Author SHA1 Message Date
yeuimu bbd925070a 部署h5 2026-08-28 15:23:54 +08:00
yeuimu 270e516f94 fix(public): media images are objects ({id,url,sortOrder}) - handle both shapes in mergeMedia 2026-08-28 11:22:53 +08:00
yeuimu d826c5bdd4 feat(public): merge secondary media gallery images with URL dedup 2026-08-28 11:19:27 +08:00
yeuimu 457792b729 feat(public): dedupe merged variants and merge specs/options from secondary origins 2026-08-28 11:05:34 +08:00
yeuimu 8233dda07a fix(admin): initial goods load also uses pageSize 1000 2026-08-28 09:49:40 +08:00
yeuimu cbdb507be9 fix(api): allow pageSize up to 1000 so admin goods tree can load full list 2026-08-28 09:36:15 +08:00
yeuimu b3bd10de06 fix(admin): load all goods in left tree (pageSize 1000) so low-priority new goods are searchable 2026-08-28 09:31:02 +08:00
yeuimu e7582bbd6e fix(deploy): add .dockerignore so host node_modules does not break image build 2026-08-27 19:13:57 +08:00
yeuimu 4c50189538 merge: multi-origin-good-merge-zll into develop 2026-08-27 18:51:28 +08:00
yeuimu 4bebb9e4b2 docs: document merged origin goods feature 2026-08-27 18:49:17 +08:00
yeuimu ac29a0c7bf feat(admin): show merged count badge on good nodes 2026-08-27 18:45:51 +08:00
yeuimu ac3a39f40d feat(admin): manage merged origin goods in good edit modal 2026-08-27 18:43:30 +08:00
yeuimu 491e74b905 feat(admin): add origin name grouping utils with vitest coverage 2026-08-27 18:40:22 +08:00
yeuimu 0aa6cbf1d9 feat(admin): suggest and merge sibling origin goods in config modal 2026-08-27 18:40:13 +08:00
yeuimu 697b82a64b fix(admin): resolve pre-existing template type errors blocking build 2026-08-27 18:40:08 +08:00
yeuimu f06dfffbda feat(public): resolve goods by secondary sds id and merge variants 2026-08-27 18:20:25 +08:00
yeuimu d9ecd04747 feat(origin-goods): include merged secondary references in tree stats 2026-08-27 18:18:29 +08:00
yeuimu 9c279ae393 feat(goods): support merged secondary origin goods in create/update/detail 2026-08-27 18:15:56 +08:00
yeuimu 848eed0b6f feat(db): add good_origin_goods junction table for merged origin goods 2026-08-27 18:09:00 +08:00
yeuimu 043d2463a6 docs(plan): add multi origin good merge design and implementation plan 2026-08-27 17:08:06 +08:00
yeuimu 005ab5b585 chore: restore files unintentionally deleted in 6c61a4e 2026-08-26 17:54:35 +08:00
yeuimu 6c61a4e871 feat(deploy): production deployment setup and fixes
- Debian-based api image (bookworm-slim), docker/debian mirrors, prisma
  binaryTargets for openssl 3.0
- nginx: admin SPA under /admin, TLS via acme.sh (ZeroSSL) + auto-renewal
  cron, http->https redirect
- prisma: add origin_goods.delisted migration, sync missing schema
  (good_image/tag_font_color/good_tags), fix users.createdAt Timestamptz
- api: CORS wildcard reflection, helmet CORP cross-origin, price
  backfill in persistProductDetail, categoryIcon ancestor fallback,
  mediaByColor per-color gallery in public goods detail
- admin: /admin base path (vite + router)
- import-data.mjs: udt_name casting, serial sequence advance fix
2026-08-26 14:23:09 +08:00
yeuimu be0b90e68f feat(security): HttpOnly cookie sessions, token revocation, and RBAC
- Add User.role (enum Role/ADMIN) and User.tokenVersion with migration
- Login now issues short-lived access token (30m default) + 7d refresh
  token, both embedding tokenVersion and a typ discriminator
- Tokens delivered via HttpOnly SameSite cookies (ir_at, ir_rt scoped
  to /auth); refresh token never leaves the cookie
- New endpoints: POST /auth/refresh (rotation), GET /auth/me,
  POST /auth/logout (bumps tokenVersion, revoking all tokens)
- JWT strategy accepts bearer or cookie, rejects refresh tokens, and
  verifies tokenVersion + user existence on every request
- Global RolesGuard: authenticated routes require ADMIN unless widened
  via @Roles(...)
- Admin SPA: session fully cookie-based, no token in localStorage;
  router guard restores session via /auth/me; axios auto-refreshes once
  on 401; stale localStorage keys cleaned up
2026-08-22 12:04:56 +08:00
yeuimu 755b40aded merge: security hardening fixes 2026-08-22 11:55:14 +08:00
yeuimu 9c1106586a fix(security): harden auth, upload, and API configuration
- Lock public registration to first-user bootstrap (403 afterwards)
- Require JwtAuthGuard on upload + whitelist png/jpg/webp/gif (SVG/XSS blocked)
- Add global throttling (login/register 5/min, upload 10/min)
- Add helmet security headers; serve uploads with nosniff
- Replace permissive CORS (origin:true+credentials) with CORS_ORIGINS whitelist
- Disable Swagger outside development; sanitize 500 error responses
- Enforce 32+ char JWT_SECRET; make token expiry configurable (TOKEN_EXPIRES_IN)
- Re-check user in DB on every JWT validation (revocation on user delete)
- Dummy bcrypt compare to prevent login user-enumeration via timing
- Map malformed BigInt inputs to 400 instead of 500
- Widen .gitignore to .env* and add apps/api/.env.example
- Disable Nuxt devtools and sourcemaps
2026-08-22 11:55:13 +08:00
yeuimu 9ed569f5bc fix(admin): simplify product forms 2026-08-21 14:54:08 +08:00
yeuimu b04623ebdd feat(goods): add editable custom products 2026-08-21 14:45:42 +08:00
yeuimu a4151607c5 fix(sync): hydrate all origin product details 2026-08-21 14:05:15 +08:00
yeuimu 4cc99f3f23 fix(docs): describe tags as grouped array 2026-08-21 11:44:25 +08:00
yeuimu 8b38d6fef7 refactor(api): group public tag filters 2026-08-21 11:34:57 +08:00
yeuimu 4963a5c463 docs: update local API startup command 2026-08-21 11:01:02 +08:00
yeuimu a43353aa98 fix(dev): support admin access over LAN 2026-08-21 10:53:47 +08:00
yeuimu 6e5f7edbb7 chore: update admin generated types and env ignore 2026-08-21 10:39:23 +08:00
yeuimu 437d9ca93b refactor(api): pair public tag filters with groups 2026-08-21 10:24:35 +08:00
yeuimu d375df810d feat(admin): manage and sync product details 2026-08-21 10:18:57 +08:00
yeuimu 7d09077f1d feat(api): add mini program catalog endpoints and product details 2026-08-21 02:11:20 +08:00
yeuimu fcbf8bb494 chore: stop tracking env files (.env, .env.development)
Credentials and per-environment config should not be committed.
Files stay on disk locally; .gitignore now covers .env.development.
2026-08-20 18:44:44 +08:00
yeuimu aed9afef92 fix(api): add sync safety guards against degenerate SDS responses
Add SYNC_GUARDS thresholds so a partial/degenerate upstream response never
triggers a destructive operation:
- skip stale category deletion when the fetched tree is suspiciously small
  vs the existing SDS category count
- skip delist detection unless both leaf-category and seen-product counts
  are healthy

Verified: 77 tests pass; live SDS returns 226 categories (guard off),
incident-case ratios (2/226, 2/2) are correctly blocked.
2026-08-20 16:37:44 +08:00
yeuimu 79fabd85f7 feat(product-center): implement Figma-designed UI, upload module, and website tests
- Redesign website homepage & product-center per Figma (fonts, logos, hero/footer/customer cases)
- Add API upload module (multer) with static serving for uploads/public assets
- Add OriginGood.delisted flag and SDS request retry logic
- Add admin ImageUpload component and goods import/upload flows
- Add vitest suite for website components and composables (32 tests)
- Add skills, docs, plans and PRODUCT.md
2026-08-20 14:32:03 +08:00
yeuimu b5fc88f3fa chore: merge website submodule fix to develop 2026-07-16 01:42:58 +08:00
yeuimu 9595030625 fix: convert apps/website from submodule to regular directory 2026-07-16 01:42:45 +08:00
616 changed files with 81266 additions and 12689 deletions
+26
View File
@@ -0,0 +1,26 @@
# 依赖与包管理缓存(容器内会重新安装,禁止从宿主机带入)
node_modules
**/node_modules
.pnpm-store
.pnpm-debug.log
# 构建产物
dist
**/dist
.turbo
# Git 与本地文件
.git
.gitignore
.dockerignore
# 测试与文档
coverage
**/*.spec.ts
**/*.test.ts
# 运行数据与本地产物
data-cleaning
deploy/backups
apps/api/uploads
*.log
-1
View File
@@ -1 +0,0 @@
DATABASE_URL=postgresql://postgres:yoyoki219765.@localhost:5432/inkreach-official
+8 -43
View File
@@ -1,45 +1,10 @@
# Dependencies node_modules/
node_modules dist/
.turbo/
# Build outputs
dist
.output
.nuxt
.nitro
.data
.cache
# TypeScript
*.tsbuildinfo
# Logs
logs
*.log *.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Environment
.env .env
.env.local .env.*
.env.*.local # Deployment runtime data (certs, ACME state, data dumps)
deploy/certbot/
# OS deploy/data-dump.json
.DS_Store uploads/
# IDE
.idea
.vscode/*
!.vscode/settings.json
!.vscode/extensions.json
# Coverage
coverage
# Nuxt
.output
.nuxt
.nitro
.cache
+1 -1
View File
@@ -4,7 +4,7 @@
### 1. 梳理需求 ### 1. 梳理需求
使用 brainstorming 进行头脑风暴, 文档存放与命名规则如下: 使用 `brainstorming` 进行头脑风暴, 文档存放与命名规则如下:
| 需求类型 | 计划目录 | 命名规则 | 示例 | | 需求类型 | 计划目录 | 命名规则 | 示例 |
| -------- | ----------------- | --------------------- | ----------------------- | | -------- | ----------------- | --------------------- | ----------------------- |
+33
View File
@@ -0,0 +1,33 @@
# Product
## Register
brand
## Users
跨境电商、POD 卖家和需要小批量定制履约能力的商家。他们通过官网了解 InkReach 的商品、生产、设计与全球配送能力,并进入 InkPOD 完成实际业务操作。
## Product Purpose
官网用于清晰展示 InkReach 的一站式 POD 能力,让访客快速浏览货盘和案例,并以最短路径进入 InkPOD 登录及商品详情页面。
## Brand Personality
直接、可靠、务实。页面应保留鲜明的橙色品牌识别,同时让商品和真实业务数据成为视觉重点。
## Anti-references
避免与 Figma 设计稿无关的通用 SaaS 模板、纯装饰性渐变、过度卡片化、被拉伸模糊的位图,以及拥挤到妨碍浏览的桌面布局。
## Design Principles
- 商品与业务信息优先于装饰。
- 关键操作即时、明确,并保持当前页面跳转语义一致。
- 宽屏增加呼吸空间,不通过无限放大素材填满画面。
- 动效用于展示连续内容,不影响用户主动操作。
- 后台配置是商品、国家、品类和标签的唯一数据来源。
## Accessibility & Inclusion
以 WCAG 2.1 AA 为基准,维持键盘可操作性、足够对比度,并为持续动画提供 `prefers-reduced-motion` 降级。
+2 -2
View File
@@ -42,7 +42,7 @@ PORT=3001
后台无需额外环境变量;Vite 代理已把 `/api/*` 转给 `http://localhost:3001` 后台无需额外环境变量;Vite 代理已把 `/api/*` 转给 `http://localhost:3001`
### 3. 启动 ### 3. 部署
启动顺序:先启动后端,再启动另两个。 启动顺序:先启动后端,再启动另两个。
@@ -51,7 +51,7 @@ PORT=3001
cd apps/api cd apps/api
pnpm prisma:generate pnpm prisma:generate
pnpm prisma:migrate pnpm prisma:migrate
pnpm start:dev pnpm --filter @inkreach/api dev
# → http://localhost:3001 · Swagger: http://localhost:3001/api/docs # → http://localhost:3001 · Swagger: http://localhost:3001/api/docs
# Terminal 2:官网 # Terminal 2:官网
-1
View File
@@ -1 +0,0 @@
VITE_API_BASE=/api
+3 -1
View File
@@ -6,7 +6,8 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vue-tsc -b && vite build", "build": "vue-tsc -b && vite build",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@element-plus/icons-vue": "^2.3.2", "@element-plus/icons-vue": "^2.3.2",
@@ -27,6 +28,7 @@
"unplugin-auto-import": "^21.0.0", "unplugin-auto-import": "^21.0.0",
"unplugin-vue-components": "^32.1.0", "unplugin-vue-components": "^32.1.0",
"vite": "^8.0.12", "vite": "^8.0.12",
"vitest": "^4.1.10",
"vue-tsc": "^3.2.8" "vue-tsc": "^3.2.8"
} }
} }
+32
View File
@@ -0,0 +1,32 @@
<svg preserveAspectRatio="xMidYMid meet" width="97" height="56" viewBox="0 0 97 56" fill="none" xmlns="http://www.w3.org/2000/svg">
<g id="Frame" clip-path="url(#clip0_0_30)">
<g id="Group">
<path id="Vector" d="M16.318 51.2332V53.8323C17.2443 53.6294 18.0909 53.4188 18.8525 53.1979L19.0969 54.0481C17.9416 54.3665 16.7117 54.6542 15.4072 54.9085L15.0341 54.1354C15.2683 54.0044 15.3866 53.8169 15.3866 53.5678V47.6478C16.632 47.4526 17.7486 47.1957 18.7341 46.8747L19.3105 47.617C18.4614 47.8918 17.463 48.1383 16.3155 48.3592V50.342H19.0171V51.2306H16.318V51.2332ZM21.4666 54.6131L21.2119 53.7142L22.0842 53.7347C22.3389 53.7347 22.465 53.5935 22.465 53.3135V48.2513H20.5378V55.9307H19.5986V47.373H23.4067V53.5087C23.4067 54.2458 23.0671 54.6131 22.3878 54.6131H21.4666Z" fill="var(--fill-0, #FF6902)"/>
<path id="Vector_2" d="M34.4941 52.1013C34.4606 52.2965 34.4221 52.4788 34.3757 52.6483H38.0474V53.5267H34.8183C35.4847 54.2895 36.7275 54.8057 38.5466 55.0805L38.0577 55.9589C35.9633 55.548 34.5893 54.8032 33.9358 53.7219C33.7325 54.0737 33.4855 54.3794 33.1922 54.6414C32.5463 55.209 31.4142 55.6584 29.7958 55.9897L29.415 55.0805C30.8173 54.834 31.8233 54.477 32.4305 54.0147C32.6209 53.858 32.783 53.6962 32.9194 53.5267H29.8755V52.6483H33.398C33.4572 52.4583 33.5086 52.2451 33.5549 52.0037L34.4941 52.1013ZM29.9733 47.8224H32.078C31.9468 47.5219 31.8079 47.2548 31.6561 47.0211L32.6338 46.8644C32.7522 47.111 32.8808 47.432 33.0249 47.8224H34.9135C35.0627 47.4962 35.1785 47.1675 35.2557 46.8362L36.254 46.962C36.1691 47.2548 36.0508 47.5425 35.9015 47.8224H37.9368V48.6623H34.4272V49.4045H37.4222V50.2058H34.4272V50.9584H38.2636V51.8188H29.6491V50.9584H33.4855V50.2058H30.5188V49.4045H33.4855V48.6623H29.9707V47.8224H29.9733Z" fill="var(--fill-0, #FF6902)"/>
<path id="Vector_3" d="M50.8993 55.756C50.5597 55.756 49.9525 55.7483 49.0776 55.7355C48.419 55.7278 47.876 55.6738 47.4541 55.5685C47.0372 55.4504 46.677 55.2244 46.3786 54.8853C46.2422 54.7235 46.111 54.6414 45.9875 54.6414C45.779 54.6414 45.4188 55.0934 44.9119 56L44.2275 55.3656C44.7241 54.5592 45.1692 54.0506 45.5681 53.8426V51.097H44.2378V50.1981H46.4609V53.9094C46.5123 53.9479 46.5612 53.9967 46.6076 54.0558C46.8623 54.3152 47.1093 54.5078 47.3512 54.6311C47.6522 54.7672 48.1076 54.8468 48.7226 54.8648C49.4919 54.8776 50.1763 54.8853 50.7784 54.8853L52.1395 54.8751C52.5898 54.8545 52.9449 54.8365 53.2073 54.816L52.9835 55.7534H50.8993V55.756ZM45.0174 47.0006C45.6838 47.5091 46.2473 48.0125 46.7105 48.5159L46.0261 49.199C45.635 48.7111 45.0869 48.182 44.3819 47.617L45.0174 47.0006ZM47.2096 49.0039H49.2938C49.3452 48.5338 49.3761 48.0561 49.3813 47.5682V46.9132H50.3101V47.3627C50.3101 47.9354 50.2818 48.4825 50.2226 49.0039H52.5718V49.9028H50.3899C50.7167 51.1073 51.5426 52.3221 52.8651 53.5472L52.2193 54.2304C51.0511 53.0644 50.2689 51.9189 49.8701 50.7914C49.4199 52.3221 48.6274 53.4676 47.4927 54.2304L46.924 53.4676C48.0664 52.7382 48.8101 51.5491 49.1548 49.9028H47.2071V49.0039H47.2096Z" fill="var(--fill-0, #FF6902)"/>
<path id="Vector_4" d="M63.6535 46.8953C64.8808 48.1589 66.2908 49.1528 67.8809 49.8745L67.4203 50.7041C66.9186 50.4627 66.4606 50.2135 66.0489 49.9516V50.8299H63.7873V52.2965H66.5378V53.1954H63.7873V54.739H67.4281V55.6481H59.215V54.739H62.8455V53.1954H60.0847V52.2965H62.8455V50.8299H60.5839V49.9516C60.167 50.2058 59.6962 50.4627 59.1738 50.7246L58.7236 49.913C60.4269 49.0989 61.8446 48.0921 62.9819 46.8953H63.6535ZM66.0309 49.9413C65.012 49.3172 64.1089 48.5801 63.319 47.7325C62.5882 48.5339 61.6851 49.271 60.607 49.9413H66.0309Z" fill="var(--fill-0, #FF6902)"/>
<path id="Vector_5" d="M73.6859 50.4319H74.7229V48.3618H73.5779V47.4911H76.7401V48.3618H75.6646V50.4319H76.5368V51.3102H75.6646V53.031C76.0505 52.8615 76.4082 52.6946 76.7401 52.5328V53.4317C75.8061 53.894 74.7769 54.2972 73.6473 54.6439L73.4132 53.7245C73.9355 53.6063 74.3729 53.4933 74.7254 53.3829V51.3128H73.6885V50.4319H73.6859ZM76.8276 48.5159H78.9812V46.9235H79.8715V48.5159H81.2017C80.9341 48.2102 80.5893 47.8815 80.1648 47.5296L80.6922 47.0211C81.2017 47.4064 81.616 47.7762 81.935 48.1358L81.5645 48.5159H82.1126V49.4045H79.8715V50.2752C80.0027 50.6861 80.1519 51.0688 80.3217 51.4284C80.7077 50.9789 81.0628 50.4832 81.3895 49.9439L82.0842 50.4627C81.634 51.1664 81.1811 51.7494 80.7231 52.2117C81.2069 53.0464 81.7986 53.7758 82.5036 54.3999L81.8861 55.1319C81.037 54.2972 80.3655 53.3212 79.8689 52.2014V54.9085C79.8689 55.5274 79.5498 55.8356 78.9092 55.8356H77.8851L77.6895 54.9573C78.0549 55.0035 78.3585 55.0266 78.6004 55.0266C78.8551 55.0266 78.9812 54.9136 78.9812 54.685V52.6714C78.3817 53.5113 77.687 54.2381 76.8971 54.8494L76.4082 54.0481C77.3679 53.4163 78.2247 52.543 78.9812 51.4309V49.4097H76.8276V48.5159ZM77.512 50.0209C77.9546 50.6733 78.2942 51.228 78.5309 51.6929L77.8851 52.1424C77.6098 51.6338 77.2496 51.0765 76.7993 50.4729L77.512 50.0209Z" fill="var(--fill-0, #FF6902)"/>
</g>
<path id="Vector_6" d="M11.1801 50.889H0.165039V51.4386H11.1801V50.889Z" fill="var(--fill-0, #FF6902)"/>
<path id="Vector_7" d="M97 50.889H85.7508V51.5671H97V50.889Z" fill="var(--fill-0, #FF6902)"/>
<g id="Group_2">
<path id="Vector_8" d="M64.2864 27.2064C55.1033 35.3686 44.6466 38.6072 40.9337 34.4414C39.4748 32.8054 39.2741 30.273 40.1207 27.304C37.5091 32.1016 36.9481 36.4293 39.0863 38.8281C42.8017 42.994 53.2585 39.7527 62.439 31.5931C68.0173 26.6362 71.8408 21.0039 73.1504 16.4117C71.2232 19.9508 68.1845 23.7443 64.2864 27.2064Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_9" d="M3.07218 12.536H0.810499C0.362795 12.536 0 12.8982 0 13.3451V15.6026C0 16.0495 0.362795 16.4117 0.810499 16.4117H3.07218C3.51988 16.4117 3.88268 16.0495 3.88268 15.6026V13.3451C3.88268 12.8982 3.51988 12.536 3.07218 12.536Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_10" d="M3.07218 17.6804H0.810499C0.362795 17.6804 0 18.0451 0 18.492V30.1702C0 30.6171 0.362795 30.9793 0.810499 30.9793H3.07218C3.51988 30.9793 3.88268 30.6171 3.88268 30.1702V18.492C3.88268 18.0451 3.51988 17.6804 3.07218 17.6804Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_11" d="M11.6889 17.6907C10.9711 17.701 10.2841 17.8397 9.64853 18.0811C9.50701 17.8422 9.24714 17.6804 8.94867 17.6804H6.5146C6.0669 17.6804 5.7041 18.0426 5.7041 18.4895V23.847V23.9806V30.2113C5.7041 30.6582 6.0669 31.0204 6.5146 31.0204H8.94867C9.39637 31.0204 9.75917 30.6582 9.75917 30.2113V23.9831V23.7571C9.75917 22.6193 10.7086 21.6973 11.8587 21.741C12.9523 21.7821 13.8039 22.7144 13.8039 23.8085V30.2447C13.8039 30.6916 14.1667 31.0538 14.6144 31.0538H17.0485C17.4962 31.0538 17.859 30.6916 17.859 30.2447V23.7571C17.8616 20.3797 15.0853 17.6393 11.6889 17.6907Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_12" d="M90.8296 17.6907C90.1606 17.701 89.5199 17.8217 88.9204 18.0349V10.6303C88.9204 10.1835 88.5576 9.82132 88.1099 9.82132H85.6758C85.2281 9.82132 84.8653 10.1835 84.8653 10.6303V22.907C84.8653 22.9969 84.873 23.0842 84.8833 23.169C84.8576 23.3924 84.8447 23.6184 84.8447 23.847V30.2113C84.8447 30.6582 85.2075 31.0204 85.6552 31.0204H88.0893C88.537 31.0204 88.8998 30.6582 88.8998 30.2113V23.7571C88.8998 22.6193 89.8492 21.6973 90.9994 21.741C92.0929 21.7821 92.9446 22.7144 92.9446 23.8085V30.2447C92.9446 30.6916 93.3074 31.0538 93.7551 31.0538H96.1891C96.6368 31.0538 96.9996 30.6916 96.9996 30.2447V23.7571C96.9996 20.3797 94.2234 17.6393 90.8296 17.6907Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_13" d="M31.0412 17.7909H28.6072C28.1595 17.7909 27.7967 18.153 27.7967 18.5999V19.4089C27.7967 20.4748 26.9656 21.3506 25.9184 21.4276C25.8386 21.4251 25.7563 21.4251 25.6765 21.4251C25.6559 21.4251 25.6379 21.4276 25.6173 21.4276C25.0898 21.3891 24.5238 21.1477 23.9886 20.6314C23.8316 20.4799 23.7416 20.2693 23.7416 20.051V10.6303C23.7416 10.1835 23.3788 9.82132 22.9311 9.82132H20.497C20.0493 9.82132 19.6865 10.1835 19.6865 10.6303V18.5999V21.985V27.5865V30.3269C19.6865 30.7738 20.0493 31.1359 20.497 31.1359H22.9311C23.3788 31.1359 23.7416 30.7738 23.7416 30.3269V30.2653V27.494C23.7416 26.4307 24.5701 25.5549 25.6147 25.4779C25.7125 25.4805 25.8103 25.4805 25.9081 25.4779C26.9759 25.5524 27.7967 26.4693 27.7967 27.5454V30.3295C27.7967 30.7764 28.1595 31.1385 28.6072 31.1385H31.0412C31.4889 31.1385 31.8517 30.7764 31.8517 30.3295V27.4966C31.8517 25.9453 31.2651 24.5302 30.3028 23.454C31.2651 22.3805 31.8517 20.9628 31.8517 19.4089V18.5999C31.8517 18.153 31.4889 17.7909 31.0412 17.7909Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_14" d="M39.8324 21.7744C39.8761 21.7769 39.9173 21.7821 39.9585 21.7846C40.7355 20.6546 41.6052 19.5271 42.5598 18.4124C41.6927 17.9604 40.7046 17.7087 39.66 17.7267C38.9807 17.7369 38.3323 17.8628 37.7277 18.0785C37.6633 17.8628 37.4678 17.7061 37.2311 17.7061H34.5062C34.0585 17.7061 33.6957 18.0682 33.6957 18.5151V23.4181C33.6855 23.5722 33.6777 23.7263 33.6777 23.883V30.2473C33.6777 30.4759 33.7729 30.6839 33.9273 30.8303C34.074 30.9818 34.2798 31.0769 34.5088 31.0769H36.9429C37.3906 31.0769 37.7534 30.7147 37.7534 30.2678V23.5285C37.8846 22.514 38.7723 21.7358 39.8324 21.7744Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_15" d="M41.5516 25.4805C41.7291 26.5746 42.1948 27.6199 42.8844 28.4854H42.8818C45.3493 31.6239 50.2304 31.891 53.4003 29.1943C53.5701 29.0504 53.5881 28.7936 53.444 28.6241L51.5709 26.4256C51.432 26.2612 51.1875 26.2381 51.0151 26.3665C49.6257 27.4016 48.1925 27.643 46.7362 26.9008L51.3316 25.0079L54.6611 23.6338C54.8695 23.5491 54.9673 23.3102 54.8798 23.1048C54.5299 22.2675 54.0847 21.1246 53.6087 20.5056C52.3685 18.7617 50.3461 17.6907 48.1488 17.6933H48.1514C44.0628 17.6624 40.8466 21.4662 41.5516 25.4805ZM45.3262 23.9215C45.4909 21.7384 48.262 20.5698 49.9164 22.0312C48.738 22.5166 46.5021 23.4386 45.3262 23.9241V23.9215Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_16" d="M77.6686 21.6125C78.5975 21.2299 79.6396 21.3352 80.4604 21.8668C80.7768 22.0723 81.1988 22.0209 81.4664 21.7538L82.9433 20.2796C83.2932 19.9303 83.2495 19.355 82.8533 19.0571C81.7006 18.1864 80.2854 17.7087 78.8213 17.7112C75.7929 17.7112 73.1401 19.7428 72.3579 22.663C71.5732 25.5832 72.852 28.6652 75.4764 30.1779C77.8256 31.5315 80.7305 31.3234 82.8507 29.7285C83.2469 29.4306 83.2932 28.8553 82.9433 28.5034L81.4664 27.0292C81.1988 26.7621 80.7794 26.7107 80.4604 26.9162C79.6396 27.4478 78.5975 27.5531 77.6686 27.1704C76.5417 26.7056 75.8084 25.6089 75.8084 24.3915C75.8084 23.1767 76.5417 22.0774 77.6686 21.6125Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_17" d="M69.361 19.617V18.1299C69.361 17.9064 69.1783 17.7241 68.9545 17.7241H65.9132C65.6893 17.7241 65.5067 17.9064 65.5067 18.1299V18.3225C64.5907 17.8936 63.564 17.665 62.4808 17.6933C58.9481 17.7909 56.0663 20.67 55.9788 24.1989C55.9145 26.7107 57.2421 28.9169 59.2465 30.1086C60.2757 29.3278 61.2921 28.488 62.2904 27.5942C62.4345 27.4632 62.5786 27.3322 62.7227 27.2012C62.7047 27.2012 62.6892 27.2038 62.6712 27.2038C60.9987 27.2038 59.6582 25.7527 59.8512 24.0448C59.9953 22.7452 61.0451 21.6973 62.347 21.5535C64.0581 21.3634 65.5118 22.699 65.5118 24.3684C65.5118 24.3889 65.5118 24.4095 65.5092 24.4326C66.9681 22.8556 68.2649 21.235 69.361 19.617Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_18" d="M65.5089 30.3166V30.9536H68.9567C69.1806 30.9536 69.3633 30.7712 69.3633 30.5478V26.102C68.0356 27.6173 67.0836 28.9066 65.5089 30.3166Z" fill="var(--fill-0, #FF6800)"/>
<path id="Vector_19" d="M48.9692 12.2458C57.8229 3.65217 68.4906 0.272244 72.7979 4.69492C74.6762 6.62374 75.0338 9.71602 74.1101 13.304C76.2791 8.46524 76.467 4.15814 74.159 1.78756C70.037 -2.44249 59.5185 1.09411 50.6674 9.6852C47.765 12.5027 45.4004 15.5153 43.6816 18.4381C45.1431 16.3372 46.9185 14.2389 48.9692 12.2458Z" fill="var(--fill-0, #FF6800)"/>
</g>
</g>
<defs>
<clipPath id="clip0_0_30">
<rect width="97" height="56" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

+16 -5
View File
@@ -1,12 +1,15 @@
import request from './request' import request from './request'
import type { import type {
Good, Good,
GoodDetail,
CreateGoodRequest, CreateGoodRequest,
UpdateGoodRequest, UpdateGoodRequest,
BatchCreateGoodsRequest, BatchCreateGoodsRequest,
UpdatePriorityRequest, BatchPriorityRequest,
GoodsFilter, GoodsFilter,
PaginatedResult, PaginatedResult,
CreateCustomGoodRequest,
UpdateCustomGoodContentRequest,
} from '@/types' } from '@/types'
export const goodsApi = { export const goodsApi = {
@@ -17,7 +20,7 @@ export const goodsApi = {
// Get good by id // Get good by id
getGoodById: (id: string) => { getGoodById: (id: string) => {
return request.get<any, Good>(`/goods/${id}`) return request.get<any, GoodDetail>(`/goods/${id}`)
}, },
// Create good // Create good
@@ -25,6 +28,14 @@ export const goodsApi = {
return request.post<any, Good>('/goods', data) return request.post<any, Good>('/goods', data)
}, },
createCustomGood: (data: CreateCustomGoodRequest) => {
return request.post<any, GoodDetail>('/goods/custom', data)
},
updateCustomGoodContent: (id: string, data: UpdateCustomGoodContentRequest) => {
return request.patch<any, GoodDetail>(`/goods/${id}/custom-content`, data)
},
// Update good // Update good
updateGood: (id: string, data: UpdateGoodRequest) => { updateGood: (id: string, data: UpdateGoodRequest) => {
return request.patch<any, Good>(`/goods/${id}`, data) return request.patch<any, Good>(`/goods/${id}`, data)
@@ -40,8 +51,8 @@ export const goodsApi = {
return request.post<any, Good[]>('/goods/batch', data) return request.post<any, Good[]>('/goods/batch', data)
}, },
// Update priority // Batch update priority
updatePriority: (data: UpdatePriorityRequest) => { batchUpdatePriority: (data: BatchPriorityRequest) => {
return request.patch<any, Good[]>('/goods/priority', data) return request.patch<any, { count: number }>('/goods/batch-priority', data)
}, },
} }
+27 -18
View File
@@ -1,5 +1,5 @@
import axios from 'axios' import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios' import type { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import router from '@/router' import router from '@/router'
@@ -9,22 +9,10 @@ const request: AxiosInstance = axios.create({
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
// Session tokens live in HttpOnly cookies — send them along.
withCredentials: true,
}) })
// Request interceptor
request.interceptors.request.use(
(config: AxiosRequestConfig) => {
const token = localStorage.getItem('token')
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error: AxiosError) => {
return Promise.reject(error)
}
)
// Response interceptor // Response interceptor
request.interceptors.response.use( request.interceptors.response.use(
(response: AxiosResponse) => { (response: AxiosResponse) => {
@@ -35,15 +23,36 @@ request.interceptors.response.use(
} }
return body return body
}, },
(error: AxiosError) => { async (error: AxiosError) => {
// Access token expired: try the refresh cookie once, then retry the
// original request. A second 401 (refresh failed) logs the user out.
const config = error.config as (InternalAxiosRequestConfig & { _retried?: boolean }) | undefined
if (
error.response?.status === 401 &&
config &&
!config._retried &&
!config.url?.includes('/auth/login') &&
!config.url?.includes('/auth/refresh')
) {
config._retried = true
try {
await axios.post(
`${import.meta.env.VITE_API_BASE || '/api'}/auth/refresh`,
{},
{ withCredentials: true },
)
return request.request(config)
} catch {
// fall through to the 401 handling below
}
}
if (error.response) { if (error.response) {
const { status, data } = error.response const { status, data } = error.response
switch (status) { switch (status) {
case 401: case 401:
ElMessage.error('Unauthorized, please login') ElMessage.error('Unauthorized, please login')
localStorage.removeItem('token')
localStorage.removeItem('user')
router.push('/login') router.push('/login')
break break
case 403: case 403:
+15 -1
View File
@@ -3,7 +3,21 @@ import type { SyncLog } from '@/types'
export const syncApi = { export const syncApi = {
syncProducts: () => { syncProducts: () => {
return request.post<any, SyncLog>('/sync/products') return request.post<any, { message: string }>('/sync/products')
},
syncCategories: () => {
return request.post<any, { message: string }>('/sync/categories')
},
syncProductDetails: () => {
return request.post<any, { message: string }>('/sync/product-details')
},
syncOneProductDetail: (goodId: string) => {
return request.post<any, { goodId: string; variants: number; detailSyncedAt: string }>(
`/sync/products/${goodId}/detail`,
)
}, },
getSyncStatus: (limit?: number) => { getSyncStatus: (limit?: number) => {
+14
View File
@@ -0,0 +1,14 @@
import request from './request'
export interface UploadResult {
url: string
filename: string
}
export const uploadApi = {
uploadImage: (file: File) => {
const formData = new FormData()
formData.append('file', file)
return request.post<any, UploadResult>('/upload/image', formData)
},
}
+10 -1
View File
@@ -11,15 +11,18 @@ export {}
/* prettier-ignore */ /* prettier-ignore */
declare module 'vue' { declare module 'vue' {
export interface GlobalComponents { export interface GlobalComponents {
ElAlert: typeof import('element-plus/es')['ElAlert']
ElAside: typeof import('element-plus/es')['ElAside'] ElAside: typeof import('element-plus/es')['ElAside']
ElBreadcrumb: typeof import('element-plus/es')['ElBreadcrumb'] ElBreadcrumb: typeof import('element-plus/es')['ElBreadcrumb']
ElBreadcrumbItem: typeof import('element-plus/es')['ElBreadcrumbItem'] ElBreadcrumbItem: typeof import('element-plus/es')['ElBreadcrumbItem']
ElButton: typeof import('element-plus/es')['ElButton'] ElButton: typeof import('element-plus/es')['ElButton']
ElCard: typeof import('element-plus/es')['ElCard']
ElCascader: typeof import('element-plus/es')['ElCascader'] ElCascader: typeof import('element-plus/es')['ElCascader']
ElCheckbox: typeof import('element-plus/es')['ElCheckbox'] ElCheckbox: typeof import('element-plus/es')['ElCheckbox']
ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup']
ElColorPicker: typeof import('element-plus/es')['ElColorPicker'] ElColorPicker: typeof import('element-plus/es')['ElColorPicker']
ElContainer: typeof import('element-plus/es')['ElContainer'] ElContainer: typeof import('element-plus/es')['ElContainer']
ElDescriptions: typeof import('element-plus/es')['ElDescriptions']
ElDescriptionsItem: typeof import('element-plus/es')['ElDescriptionsItem']
ElDialog: typeof import('element-plus/es')['ElDialog'] ElDialog: typeof import('element-plus/es')['ElDialog']
ElDropdown: typeof import('element-plus/es')['ElDropdown'] ElDropdown: typeof import('element-plus/es')['ElDropdown']
ElDropdownItem: typeof import('element-plus/es')['ElDropdownItem'] ElDropdownItem: typeof import('element-plus/es')['ElDropdownItem']
@@ -30,16 +33,20 @@ declare module 'vue' {
ElHeader: typeof import('element-plus/es')['ElHeader'] ElHeader: typeof import('element-plus/es')['ElHeader']
ElIcon: typeof import('element-plus/es')['ElIcon'] ElIcon: typeof import('element-plus/es')['ElIcon']
ElImage: typeof import('element-plus/es')['ElImage'] ElImage: typeof import('element-plus/es')['ElImage']
ElImageViewer: typeof import('element-plus/es')['ElImageViewer']
ElInput: typeof import('element-plus/es')['ElInput'] ElInput: typeof import('element-plus/es')['ElInput']
ElInputNumber: typeof import('element-plus/es')['ElInputNumber'] ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
ElMain: typeof import('element-plus/es')['ElMain'] ElMain: typeof import('element-plus/es')['ElMain']
ElMenu: typeof import('element-plus/es')['ElMenu'] ElMenu: typeof import('element-plus/es')['ElMenu']
ElMenuItem: typeof import('element-plus/es')['ElMenuItem'] ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
ElOption: typeof import('element-plus/es')['ElOption'] ElOption: typeof import('element-plus/es')['ElOption']
ElOptionGroup: typeof import('element-plus/es')['ElOptionGroup']
ElPopover: typeof import('element-plus/es')['ElPopover'] ElPopover: typeof import('element-plus/es')['ElPopover']
ElRadio: typeof import('element-plus/es')['ElRadio']
ElRadioButton: typeof import('element-plus/es')['ElRadioButton'] ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup'] ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
ElSelect: typeof import('element-plus/es')['ElSelect'] ElSelect: typeof import('element-plus/es')['ElSelect']
ElSwitch: typeof import('element-plus/es')['ElSwitch']
ElTable: typeof import('element-plus/es')['ElTable'] ElTable: typeof import('element-plus/es')['ElTable']
ElTableColumn: typeof import('element-plus/es')['ElTableColumn'] ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
ElTabPane: typeof import('element-plus/es')['ElTabPane'] ElTabPane: typeof import('element-plus/es')['ElTabPane']
@@ -47,6 +54,8 @@ declare module 'vue' {
ElTag: typeof import('element-plus/es')['ElTag'] ElTag: typeof import('element-plus/es')['ElTag']
ElTooltip: typeof import('element-plus/es')['ElTooltip'] ElTooltip: typeof import('element-plus/es')['ElTooltip']
ElTree: typeof import('element-plus/es')['ElTree'] ElTree: typeof import('element-plus/es')['ElTree']
ElUpload: typeof import('element-plus/es')['ElUpload']
ImageUpload: typeof import('./components/ImageUpload.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink'] RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView'] RouterView: typeof import('vue-router')['RouterView']
} }
+154
View File
@@ -0,0 +1,154 @@
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Loading } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { uploadApi } from '@/api/upload'
const model = defineModel<string>({ default: '' })
const props = withDefaults(defineProps<{
width?: number
height?: number
shape?: 'square' | 'circle'
label?: string
}>(), {
width: 80,
height: 80,
shape: 'square',
label: '点击上传',
})
const uploading = ref(false)
const previewVisible = ref(false)
const customUpload: UploadProps['httpRequest'] = async (options) => {
const file = options.file as File
uploading.value = true
try {
const result = await uploadApi.uploadImage(file)
model.value = result.url
} catch (e: any) {
ElMessage.error(e?.response?.data?.message || '上传失败')
} finally {
uploading.value = false
}
}
function removeImage() {
model.value = ''
}
function onImgError() {
console.warn('Image failed to load:', model.value)
}
</script>
<template>
<div class="img-upload">
<el-upload
class="img-uploader"
:show-file-list="false"
:http-request="customUpload"
accept="image/*"
>
<div v-if="model" class="img-preview-wrap" :style="{ width: width + 'px', height: height + 'px', borderRadius: shape === 'circle' ? '50%' : '8px' }">
<img :src="model" class="img-preview-img" @click.stop="previewVisible = true" @error="onImgError" />
<div class="img-overlay">
<span @click.stop="previewVisible = true">预览</span>
<span @click.stop="removeImage">删除</span>
</div>
</div>
<div v-else class="img-placeholder" :style="{ width: width + 'px', height: height + 'px', borderRadius: shape === 'circle' ? '50%' : '8px' }">
<el-icon v-if="!uploading" :size="20"><Plus /></el-icon>
<el-icon v-else :size="20" class="is-loading"><Loading /></el-icon>
<span class="img-placeholder-text">{{ uploading ? '上传中' : label }}</span>
</div>
</el-upload>
<el-image-viewer v-if="previewVisible" :url-list="[model]" @close="previewVisible = false" />
</div>
</template>
<style scoped>
.img-upload {
display: inline-block;
}
.img-uploader {
display: inline-block;
}
.img-placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
border: 1px dashed #d9d9d9;
background: #fafafa;
color: #a8abb2;
cursor: pointer;
transition: border-color 0.2s;
overflow: hidden;
}
.img-placeholder:hover {
border-color: var(--brand-color, #ff6800);
color: var(--brand-color, #ff6800);
}
.img-placeholder-text {
font-size: 12px;
}
.img-preview-wrap {
position: relative;
overflow: hidden;
cursor: pointer;
}
.img-preview-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.img-overlay {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
opacity: 0;
transition: opacity 0.2s;
}
.img-preview-wrap:hover .img-overlay {
opacity: 1;
}
.img-overlay span {
color: #fff;
font-size: 13px;
cursor: pointer;
padding: 4px 8px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.15);
}
.img-overlay span:hover {
background: rgba(255, 255, 255, 0.3);
}
.is-loading {
animation: rotating 1.5s linear infinite;
}
@keyframes rotating {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>
+12 -34
View File
@@ -71,11 +71,8 @@ function handleCommand(command: string) {
<!-- Sidebar --> <!-- Sidebar -->
<el-aside :width="collapsed ? '64px' : '240px'" class="layout-aside"> <el-aside :width="collapsed ? '64px' : '240px'" class="layout-aside">
<div class="brand" :class="{ collapsed }"> <div class="brand" :class="{ collapsed }">
<div class="brand-mark">IR</div> <img src="/logo-unified.svg" class="brand-logo" alt="InkReach" />
<div v-if="!collapsed" class="brand-text"> <span v-if="!collapsed" class="brand-text">印美达官网后台</span>
<div class="brand-name">Inkreach</div>
<div class="brand-tag">官网后台</div>
</div>
</div> </div>
<el-menu <el-menu
@@ -162,9 +159,9 @@ function handleCommand(command: string) {
.brand { .brand {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 8px;
height: 56px; height: 56px;
padding: 0 16px; padding: 0 20px;
border-bottom: 1px solid #2b2b33; border-bottom: 1px solid #2b2b33;
background: #16161a; background: #16161a;
overflow: hidden; overflow: hidden;
@@ -175,37 +172,18 @@ function handleCommand(command: string) {
padding: 0; padding: 0;
} }
.brand-mark { .brand-logo {
flex: 0 0 auto; height: 24px;
width: 32px; width: auto;
height: 32px; object-fit: contain;
border-radius: 6px; flex-shrink: 0;
background: var(--brand-color);
color: #fff;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
font-size: 13px;
letter-spacing: 0.5px;
} }
.brand-text { .brand-text {
display: flex; color: #e4e4e7;
flex-direction: column; font-size: 13px;
line-height: 1.2;
white-space: nowrap;
}
.brand-name {
color: #fff;
font-weight: 600; font-weight: 600;
font-size: 15px; white-space: nowrap;
}
.brand-tag {
color: #9ca3af;
font-size: 11px;
} }
.layout-aside :deep(.el-menu) { .layout-aside :deep(.el-menu) {
+1 -1
View File
@@ -28,7 +28,7 @@ const routes: RouteRecordRaw[] = [
] ]
const router = createRouter({ const router = createRouter({
history: createWebHistory(), history: createWebHistory('/admin/'),
routes, routes,
}) })
+23 -32
View File
@@ -4,49 +4,41 @@ import type { LoginRequest, User } from '@/types'
import { authApi } from '@/api/auth' import { authApi } from '@/api/auth'
export const useAuthStore = defineStore('auth', () => { export const useAuthStore = defineStore('auth', () => {
// Token persisted to localStorage // The session lives in HttpOnly cookies set by the API; nothing
const token = ref<string>(localStorage.getItem('token') || '') // security-relevant is stored client-side. `user` is just UI state,
// restored from the server via /auth/me on app start.
const user = ref<User | null>(null)
const sessionChecked = ref(false)
// User persisted to localStorage (parsed if available) // Tokens moved to HttpOnly cookies; clean up any stale values from the
const user = ref<User | null>(loadUser()) // previous localStorage-based session.
localStorage.removeItem('token')
localStorage.removeItem('user')
const isLoggedIn = computed(() => !!token.value) const isLoggedIn = computed(() => !!user.value)
function loadUser(): User | null { // Restore the session once per app start. The router guard awaits this
const raw = localStorage.getItem('user') // so a page refresh on a protected route does not bounce to /login.
if (!raw) return null async function ensureSessionChecked() {
if (sessionChecked.value) return
sessionChecked.value = true
try { try {
return JSON.parse(raw) as User user.value = await authApi.getCurrentUser()
} catch { } catch {
return null user.value = null
}
}
function setToken(newToken: string) {
token.value = newToken
if (newToken) {
localStorage.setItem('token', newToken)
} else {
localStorage.removeItem('token')
} }
} }
function setUser(newUser: User | null) { function setUser(newUser: User | null) {
user.value = newUser user.value = newUser
if (newUser) {
localStorage.setItem('user', JSON.stringify(newUser))
} else {
localStorage.removeItem('user')
}
} }
async function login(payload: LoginRequest) { async function login(payload: LoginRequest) {
const res = await authApi.login(payload) as any; const res = await authApi.login(payload) as any
const accessToken: string = res.accessToken ?? res.data?.accessToken ?? ''; const userData: User | null = res.user ?? res.data?.user ?? null
const userData: User | null = res.user ?? res.data?.user ?? null; sessionChecked.value = true
if (accessToken) setToken(accessToken); setUser(userData)
if (userData) setUser(userData); return res
return res;
} }
async function fetchCurrentUser() { async function fetchCurrentUser() {
@@ -61,14 +53,13 @@ export const useAuthStore = defineStore('auth', () => {
} catch { } catch {
// Ignore network errors during logout // Ignore network errors during logout
} }
setToken('')
setUser(null) setUser(null)
} }
return { return {
token,
user, user,
isLoggedIn, isLoggedIn,
ensureSessionChecked,
login, login,
fetchCurrentUser, fetchCurrentUser,
logout, logout,
+135 -7
View File
@@ -42,6 +42,89 @@ export interface Good {
position?: Position position?: Position
createdAt: string createdAt: string
updatedAt: string updatedAt: string
mergedOriginGoods?: MergedOriginGoodSummary[]
}
export interface MergedOriginGoodSummary {
id: string
sdsGoodId: string
goodName: string | null
goodImage: string | null
goodPrice: string | null
hasDetail: boolean
variantCount: number
}
export interface OriginGoodDetail {
productCode?: string | null
englishName?: string | null
productionCycleHours?: number | null
minWeightG?: string | null
productionProcess?: string | null
materialDescription?: string | null
sizeChart?: { columns?: Array<{ key: string; name: string }>; rows?: any[] } | null
packageSpecs?: { rows?: any[] } | null
syncedAt?: string | null
[key: string]: unknown
}
export interface OriginGoodVariant {
sdsVariantId: string
sku: string
sizeName?: string | null
colorName?: string | null
colorHex?: string | null
price?: string | null
enabled: boolean
[key: string]: unknown
}
export interface CustomGoodVariantRequest {
sku: string
sizeId?: string | null
sizeName?: string | null
colorId?: string | null
colorName?: string | null
colorHex?: string | null
imageUrl?: string | null
price?: string | null
originalPrice?: string | null
weightG?: string | null
boxLengthCm?: string | null
boxWidthCm?: string | null
boxHeightCm?: string | null
designData?: Record<string, unknown> | null
enabled?: boolean
sortOrder?: number
}
export interface CustomGoodDetailRequest {
productCode?: string | null
englishName?: string | null
productionCycleHours?: number | null
minWeightG?: string | null
productionProcess?: string | null
materialDescription?: string | null
blankDesignUrl?: string | null
detailsPageVideoUrl?: string | null
textureName?: string | null
reminder?: string | null
productPerformance?: string | null
applicableScenarios?: string | null
washingInstructions?: string | null
specialDescription?: string | null
designExplanation?: string | null
designArea?: string | null
pictureRequest?: string | null
sizeChart?: Record<string, unknown> | null
packageSpecs?: Record<string, unknown> | null
options?: Record<string, unknown> | null
media?: Record<string, unknown> | null
}
export interface GoodDetail extends Good {
originDetail: OriginGoodDetail | null
variants: OriginGoodVariant[]
} }
export interface CreateGoodRequest { export interface CreateGoodRequest {
@@ -53,6 +136,28 @@ export interface CreateGoodRequest {
tagIds?: number[] tagIds?: number[]
positionId?: number positionId?: number
goodPriority?: number goodPriority?: number
mergedOriginGoodIds?: number[]
}
export interface CreateCustomGoodRequest {
goodName: string
goodImage?: string
goodPrice?: string | null
countryId: number
categoryId: number
tagIds?: number[]
positionId?: number
goodPriority?: number
detail?: CustomGoodDetailRequest
variants?: CustomGoodVariantRequest[]
}
export interface UpdateCustomGoodContentRequest {
goodName?: string
goodImage?: string | null
goodPrice?: string | null
detail?: CustomGoodDetailRequest
variants?: CustomGoodVariantRequest[]
} }
export interface UpdateGoodRequest { export interface UpdateGoodRequest {
@@ -64,6 +169,7 @@ export interface UpdateGoodRequest {
tagIds?: number[] tagIds?: number[]
positionId?: number | null positionId?: number | null
goodPriority?: number goodPriority?: number
mergedOriginGoodIds?: number[]
} }
export interface BatchCreateItem { export interface BatchCreateItem {
@@ -85,6 +191,15 @@ export interface UpdatePriorityRequest {
priority: number priority: number
} }
export interface BatchPriorityItem {
id: number
priority: number
}
export interface BatchPriorityRequest {
items: BatchPriorityItem[]
}
// Country types // Country types
export interface Country { export interface Country {
id: string id: string
@@ -233,9 +348,18 @@ export interface OriginGood {
goodImage: string | null goodImage: string | null
goodPrice: string | null goodPrice: string | null
sdsGoodId: string sdsGoodId: string
source: 'SDS' | 'CUSTOM'
isCustom: boolean
sdsCategoryId: string | null sdsCategoryId: string | null
delisted?: boolean
createdAt: string createdAt: string
updatedAt: string updatedAt: string
hasDetail?: boolean
detailSyncedAt?: string | null
variantCount?: number
sizeRowCount?: number
packageRowCount?: number
productCode?: string | null
} }
// Origin Goods Tree types // Origin Goods Tree types
@@ -245,9 +369,15 @@ export interface OriginGoodsTreeNode {
goodImage: string | null goodImage: string | null
goodPrice: string | null goodPrice: string | null
sdsGoodId: string sdsGoodId: string
delisted: boolean
configuredCount: number configuredCount: number
configuredCountries: string[] configuredCountries: string[]
configuredTags: { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number }[] configuredTags: { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number }[]
hasDetail: boolean
detailSyncedAt: string | null
variantCount: number
sizeRowCount: number
packageRowCount: number
} }
export interface OriginGoodsTreeCategoryNode { export interface OriginGoodsTreeCategoryNode {
@@ -269,13 +399,11 @@ export interface OriginGoodsTreeResponse {
// Sync types // Sync types
export interface SyncLog { export interface SyncLog {
id: string id: string
type: 'CATEGORY' | 'PRODUCT' type: 'CATEGORIES' | 'PRODUCTS' | 'PRODUCT_DETAILS'
status: 'SUCCESS' | 'FAILED' status: 'RUNNING' | 'SUCCESS' | 'FAILED'
message?: string message: string | null
startTime: string startedAt: string
endTime?: string finishedAt: string | null
errorCount?: number
createdAt: string
} }
// Filter types // Filter types
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { sameOriginGroup, truncateToProcess } from './origin-name';
describe('truncateToProcess', () => {
it('keeps first 3 dash segments (drops warehouse)', () => {
expect(truncateToProcess('美国(包邮)180g纯棉T恤成人款-DG001-单面印花-美西洛杉矶一仓'))
.toBe('美国(包邮)180g纯棉T恤成人款-DG001-单面印花');
});
it('is identity for 3-segment names', () => {
expect(truncateToProcess('美国(不包邮)230g水洗炒雪花T恤-KRHM003-直喷双面'))
.toBe('美国(不包邮)230g水洗炒雪花T恤-KRHM003-直喷双面');
});
it('handles malformed names without country prefix', () => {
expect(truncateToProcess('(不包邮)230g水洗炒雪花T恤-FRTM001-双面印花'))
.toBe('(不包邮)230g水洗炒雪花T恤-FRTM001-双面印花');
});
it('returns empty for null/empty', () => {
expect(truncateToProcess(null)).toBe('');
expect(truncateToProcess('')).toBe('');
});
});
describe('sameOriginGroup', () => {
it('matches same product across warehouses', () => {
expect(sameOriginGroup(
'美国(包邮)180g纯棉T恤成人款-DG001-单面印花-美西洛杉矶一仓',
'美国(包邮)180g纯棉T恤成人款-DG001-单面印花-美中亚特兰大仓',
)).toBe(true);
});
it('does not match different SKU', () => {
expect(sameOriginGroup(
'美国(包邮)180g纯棉T恤成人款-DG001-单面印花',
'美国(包邮)180g纯棉T恤成人款-DG002-单面印花',
)).toBe(false);
});
it('does not match different country', () => {
expect(sameOriginGroup(
'美国(包邮)T恤-DG001-单面印花',
'德国(不包邮)T恤-DG001-单面印花',
)).toBe(false);
});
it('does not match empty names', () => {
expect(sameOriginGroup(null, 'x-y-z')).toBe(false);
expect(sameOriginGroup('', '')).toBe(false);
});
});
+20
View File
@@ -0,0 +1,20 @@
/**
* 原产品名匹配规则(见 data-cleaning/README.md 命名调查):
* `国家(物流备注)品名-SKU-工艺位置[-仓库名]`
* 截断到「工艺位置」= 保留按 `-` 分段的前 3 段,丢弃可选的仓库名段。
* 国家前缀在第 1 段内,天然参与比较(不同国家不合并)。
*/
const KEEP_SEGMENTS = 3;
export function truncateToProcess(name: string | null | undefined): string {
if (!name) return '';
return name.split('-').slice(0, KEEP_SEGMENTS).join('-');
}
export function sameOriginGroup(
a: string | null | undefined,
b: string | null | undefined,
): boolean {
const ka = truncateToProcess(a);
return ka !== '' && ka === truncateToProcess(b);
}
@@ -52,7 +52,6 @@ const dialogLoading = ref(false)
const dialogForm = reactive<CreateCategoryRequest & { id?: string }>({ const dialogForm = reactive<CreateCategoryRequest & { id?: string }>({
categoryName: '', categoryName: '',
categoryIcon: '', categoryIcon: '',
parentCategoryId: '',
}) })
const dialogRules = { const dialogRules = {
@@ -146,7 +145,7 @@ onMounted(fetchTree)
> >
<el-table-column prop="categoryName" label="名称" min-width="220" /> <el-table-column prop="categoryName" label="名称" min-width="220" />
<el-table-column label="图标" width="100"> <el-table-column label="图标" width="100">
<template #default="{ row }: { row: CategoryTree }"> <template #default="{ row }: any">
<el-image <el-image
v-if="row.categoryIcon" v-if="row.categoryIcon"
:src="row.categoryIcon" :src="row.categoryIcon"
@@ -158,17 +157,17 @@ onMounted(fetchTree)
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="父级"> <el-table-column label="父级">
<template #default="{ row }: { row: CategoryTree }"> <template #default="{ row }: any">
{{ row.parent?.categoryName || '-' }} {{ row.parent?.categoryName || '-' }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="子级数" width="100"> <el-table-column label="子级数" width="100">
<template #default="{ row }: { row: CategoryTree }"> <template #default="{ row }: any">
{{ row._count?.children ?? row.children?.length ?? 0 }} {{ row._count?.children ?? row.children?.length ?? 0 }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" width="180" fixed="right"> <el-table-column label="操作" width="180" fixed="right">
<template #default="{ row }: { row: CategoryTree }"> <template #default="{ row }: any">
<div class="table-actions"> <div class="table-actions">
<el-button size="small" type="primary" plain @click="openEditDialog(row)"> <el-button size="small" type="primary" plain @click="openEditDialog(row)">
<el-icon><Edit /></el-icon> <el-icon><Edit /></el-icon>
@@ -23,7 +23,7 @@ const filter = reactive<Required<CountryFilter>>({
async function fetchList() { async function fetchList() {
loading.value = true loading.value = true
try { try {
const res = await countriesApi.getCountriesList(filter) await countriesApi.getCountriesList(filter)
const data = await countriesApi.getCountriesList(filter) as any const data = await countriesApi.getCountriesList(filter) as any
const arr = Array.isArray(data) ? data : (data.items ?? []) const arr = Array.isArray(data) ? data : (data.items ?? [])
list.value = arr list.value = arr
@@ -147,7 +147,7 @@ onMounted(fetchList)
<el-table v-loading="loading" :data="list" border stripe> <el-table v-loading="loading" :data="list" border stripe>
<el-table-column label="图标" width="80"> <el-table-column label="图标" width="80">
<template #default="{ row }: { row: Country }"> <template #default="{ row }: any">
<el-image <el-image
v-if="row.countryIcon" v-if="row.countryIcon"
:src="row.countryIcon" :src="row.countryIcon"
@@ -160,12 +160,12 @@ onMounted(fetchList)
</el-table-column> </el-table-column>
<el-table-column prop="countryName" label="名称" min-width="200" /> <el-table-column prop="countryName" label="名称" min-width="200" />
<el-table-column label="创建时间" width="180"> <el-table-column label="创建时间" width="180">
<template #default="{ row }: { row: Country }"> <template #default="{ row }: any">
{{ new Date(row.createdAt).toLocaleString() }} {{ new Date(row.createdAt).toLocaleString() }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" width="180" fixed="right"> <el-table-column label="操作" width="180" fixed="right">
<template #default="{ row }: { row: Country }"> <template #default="{ row }: any">
<div class="table-actions"> <div class="table-actions">
<el-button size="small" type="primary" plain @click="openEditDialog(row)"> <el-button size="small" type="primary" plain @click="openEditDialog(row)">
<el-icon><Edit /></el-icon> <el-icon><Edit /></el-icon>
File diff suppressed because it is too large Load Diff
@@ -8,7 +8,6 @@ import type {
UpdatePositionRequest, UpdatePositionRequest,
PositionFilter, PositionFilter,
Country, Country,
Category,
CategoryTree, CategoryTree,
} from '@/types' } from '@/types'
import { positionsApi } from '@/api/positions' import { positionsApi } from '@/api/positions'
@@ -41,7 +40,7 @@ async function loadLookups() {
async function fetchList() { async function fetchList() {
loading.value = true loading.value = true
try { try {
const res = await positionsApi.getPositionsList(filter) await positionsApi.getPositionsList(filter)
const data = await positionsApi.getPositionsList(filter) as any const data = await positionsApi.getPositionsList(filter) as any
const arr = Array.isArray(data) ? data : (data.items ?? []) const arr = Array.isArray(data) ? data : (data.items ?? [])
list.value = arr list.value = arr
@@ -88,8 +87,6 @@ const dialogLoading = ref(false)
const dialogForm = reactive<CreatePositionRequest & { id?: string }>({ const dialogForm = reactive<CreatePositionRequest & { id?: string }>({
indexVal: 0, indexVal: 0,
countryId: '',
categoryId: '',
}) })
const dialogRules = { const dialogRules = {
@@ -218,17 +215,17 @@ onMounted(async () => {
<el-table v-loading="loading" :data="list" border stripe> <el-table v-loading="loading" :data="list" border stripe>
<el-table-column label="排序值" prop="indexVal" width="100" sortable /> <el-table-column label="排序值" prop="indexVal" width="100" sortable />
<el-table-column label="国家" min-width="160"> <el-table-column label="国家" min-width="160">
<template #default="{ row }: { row: Position }"> <template #default="{ row }: any">
{{ row.country?.countryName || '-' }} {{ row.country?.countryName || '-' }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="分类" min-width="200"> <el-table-column label="分类" min-width="200">
<template #default="{ row }: { row: Position }"> <template #default="{ row }: any">
{{ getCategoryName(row) }} {{ getCategoryName(row) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" width="180" fixed="right"> <el-table-column label="操作" width="180" fixed="right">
<template #default="{ row }: { row: Position }"> <template #default="{ row }: any">
<div class="table-actions"> <div class="table-actions">
<el-button size="small" type="primary" plain @click="openEditDialog(row)"> <el-button size="small" type="primary" plain @click="openEditDialog(row)">
<el-icon><Edit /></el-icon> <el-icon><Edit /></el-icon>
+398 -84
View File
@@ -1,15 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue' import { computed, onMounted, onUnmounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Box } from '@element-plus/icons-vue' import { Refresh, Box, Clock, CircleCheck, CircleClose, Loading } from '@element-plus/icons-vue'
import type { SyncLog } from '@/types' import type { SyncLog } from '@/types'
import { syncApi } from '@/api/sync' import { syncApi } from '@/api/sync'
const logs = ref<SyncLog[]>([]) const logs = ref<SyncLog[]>([])
const loading = ref(false) const loading = ref(false)
const syncing = ref(false) const syncing = ref(false)
type SyncType = 'PRODUCTS' | 'CATEGORIES' | 'PRODUCT_DETAILS'
const currentType = ref<SyncType>('PRODUCTS')
let timer: ReturnType<typeof setInterval> | null = null let timer: ReturnType<typeof setInterval> | null = null
let pollTimer: ReturnType<typeof setInterval> | null = null
async function refreshLogs() { async function refreshLogs() {
loading.value = true loading.value = true
@@ -23,138 +26,449 @@ async function refreshLogs() {
} }
} }
async function handleSync() { function syncTypeLabel(type: SyncType): string {
if (type === 'CATEGORIES') return '分类'
if (type === 'PRODUCT_DETAILS') return '全部原产品详情'
return '商品列表'
}
async function pollUntilDone(type: SyncType) {
if (pollTimer) clearInterval(pollTimer)
pollTimer = setInterval(async () => {
try {
const data = await syncApi.getSyncStatus(5) as any
const latest = Array.isArray(data) ? data : []
if (latest.length > 0) logs.value = [...latest, ...logs.value.slice(latest.length)]
const top = latest.find((l: SyncLog) => l.type === type)
if (top && top.status !== 'RUNNING') {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
syncing.value = false
if (top.status === 'SUCCESS') {
ElMessage.success(`${syncTypeLabel(type)}同步完成`)
} else {
ElMessage.error(`${syncTypeLabel(type)}同步失败`)
}
await refreshLogs()
}
} catch { /* ignore poll errors */ }
}, 3000)
}
async function handleSyncProducts() {
await doSync('PRODUCTS')
}
async function handleSyncCategories() {
await doSync('CATEGORIES')
}
async function handleSyncProductDetails() {
await doSync('PRODUCT_DETAILS')
}
async function doSync(type: SyncType) {
const label = syncTypeLabel(type)
try { try {
await ElMessageBox.confirm( await ElMessageBox.confirm(
'确定立即执行产品同步吗?此操作可能需要一些时间。', `确定立即执行${label}同步吗?${type === 'PRODUCT_DETAILS' ? '将同步全部有效原产品,耗时取决于原产品数量。' : type !== 'CATEGORIES' ? '此操作可能需要几分钟。' : ''}`,
'确认', '确认',
{ type: 'info', confirmButtonText: '执行', cancelButtonText: '取消' } { type: 'info', confirmButtonText: '执行', cancelButtonText: '取消' }
) )
} catch { return } } catch { return }
syncing.value = true syncing.value = true
currentType.value = type
try { try {
await syncApi.syncProducts() if (type === 'PRODUCTS') {
ElMessage.success('产品同步完成') await syncApi.syncProducts()
await refreshLogs() } else if (type === 'PRODUCT_DETAILS') {
await syncApi.syncProductDetails()
} else {
await syncApi.syncCategories()
}
ElMessage.info(`${label}同步已开始`)
pollUntilDone(type)
} catch { } catch {
ElMessage.error('产品同步失败') ElMessage.error(`${label}同步启动失败`)
} finally {
syncing.value = false syncing.value = false
} }
} }
function formatDate(s?: string): string { function formatTime(s?: string): string {
if (!s) return '-' if (!s) return '-'
return new Date(s).toLocaleString() const d = new Date(s)
return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
} }
function formatDuration(start?: string, end?: string): string | null {
if (!start || !end) return null
const ms = new Date(end).getTime() - new Date(start).getTime()
if (ms < 1000) return `${ms}ms`
return `${(ms / 1000).toFixed(1)}s`
}
const stats = computed(() => {
const total = logs.value.length
const success = logs.value.filter(l => l.status === 'SUCCESS').length
const failed = logs.value.filter(l => l.status === 'FAILED').length
const lastLog = logs.value[0]
return { total, success, failed, lastLog }
})
onMounted(() => { onMounted(() => {
refreshLogs() refreshLogs()
timer = setInterval(refreshLogs, 30_000) timer = setInterval(refreshLogs, 60_000)
}) })
onUnmounted(() => { onUnmounted(() => {
if (timer) clearInterval(timer) if (timer) clearInterval(timer)
if (pollTimer) clearInterval(pollTimer)
}) })
</script> </script>
<template> <template>
<div class="page-container"> <div class="sync-page" v-loading="loading">
<div class="sync-cards"> <!-- Action Card -->
<el-card class="sync-card"> <div class="sync-action-card">
<template #header> <div class="sync-action-info">
<div class="sync-card-header"> <div class="sync-action-icon">
<div class="sync-card-title"> <el-icon :size="28"><Box /></el-icon>
<el-icon><Box /></el-icon> </div>
<span>产品同步</span> <div>
</div> <h2 class="sync-action-title">数据同步</h2>
</div> <p class="sync-action-desc">分类和产品每小时自动同步全部 SDS 原产品详情每天 03:30 自动同步也可手动执行</p>
</template> </div>
<p class="sync-card-desc"> </div>
从上游拉取最新产品和原产品并与本地数据库进行同步 <div class="sync-action-buttons">
</p> <el-button
<el-button type="primary" :loading="syncing" @click="handleSync"> size="large"
<el-icon><Refresh /></el-icon> :loading="syncing && currentType === 'CATEGORIES'"
<span>执行产品同步</span> :disabled="syncing"
@click="handleSyncCategories"
>
同步分类
</el-button> </el-button>
</el-card> <el-button
</div> type="primary"
size="large"
<div class="page-card logs-card"> :loading="syncing && currentType === 'PRODUCTS'"
<div class="logs-toolbar"> :disabled="syncing"
<h3 class="logs-title">同步日志</h3> :icon="Refresh"
<el-button @click="refreshLogs"> @click="handleSyncProducts"
<el-icon><Refresh /></el-icon> >
<span>刷新</span> 同步产品
</el-button>
<el-button
type="success"
size="large"
:loading="syncing && currentType === 'PRODUCT_DETAILS'"
:disabled="syncing"
:icon="Refresh"
@click="handleSyncProductDetails"
>
同步全部原产品详情
</el-button> </el-button>
</div> </div>
</div>
<el-table v-loading="loading" :data="logs" border stripe> <!-- Stats Row -->
<el-table-column label="状态" width="100"> <div class="sync-stats">
<template #default="{ row }: { row: SyncLog }"> <div class="stat-item">
<el-tag :type="row.status === 'SUCCESS' ? 'success' : 'danger'" size="small"> <span class="stat-value">{{ stats.total }}</span>
{{ row.status === 'SUCCESS' ? '成功' : '失败' }} <span class="stat-label">总同步次数</span>
</el-tag> </div>
</template> <div class="stat-divider" />
</el-table-column> <div class="stat-item">
<el-table-column label="时间" width="200"> <span class="stat-value stat-success">{{ stats.success }}</span>
<template #default="{ row }: { row: SyncLog }"> <span class="stat-label">成功</span>
{{ formatDate(row.startTime) }} </div>
</template> <div class="stat-divider" />
</el-table-column> <div class="stat-item">
<el-table-column prop="message" label="信息" min-width="200" show-overflow-tooltip /> <span class="stat-value stat-failed">{{ stats.failed }}</span>
<template #empty> <span class="stat-label">失败</span>
<el-empty description="暂无同步记录" /> </div>
</template> <div class="stat-divider" />
</el-table> <div class="stat-item">
<span class="stat-value stat-time">{{ stats.lastLog ? formatTime(stats.lastLog.startedAt) : '-' }}</span>
<span class="stat-label">最近同步</span>
</div>
</div>
<!-- Log Timeline -->
<div class="sync-logs">
<div class="sync-logs-head">
<h3 class="sync-logs-title">同步日志</h3>
<el-button text :icon="Refresh" @click="refreshLogs">刷新</el-button>
</div>
<div v-if="logs.length === 0 && !loading" class="sync-empty">
<el-empty description="暂无同步记录" :image-size="80" />
</div>
<div v-else class="sync-timeline">
<div
v-for="log in logs"
:key="log.id"
class="timeline-item"
>
<div class="timeline-dot" :class="log.status === 'SUCCESS' ? 'is-success' : (log.status === 'RUNNING' ? 'is-running' : 'is-failed')">
<el-icon :size="12">
<Loading v-if="log.status === 'RUNNING'" />
<CircleCheck v-else-if="log.status === 'SUCCESS'" />
<CircleClose v-else />
</el-icon>
</div>
<div class="timeline-content">
<div class="timeline-header">
<span class="timeline-type">{{ syncTypeLabel(log.type) }}</span>
<span class="timeline-status" :class="log.status === 'SUCCESS' ? 'is-success' : (log.status === 'RUNNING' ? 'is-running' : 'is-failed')">
{{ log.status === 'SUCCESS' ? '成功' : log.status === 'RUNNING' ? '进行中' : '失败' }}
</span>
<span v-if="formatDuration(log.startedAt, log.finishedAt || undefined)" class="timeline-duration">
<el-icon :size="11"><Clock /></el-icon>
{{ formatDuration(log.startedAt, log.finishedAt || undefined) }}
</span>
</div>
<p v-if="log.message" class="timeline-message">{{ log.message }}</p>
<span class="timeline-time">{{ formatTime(log.startedAt) }}</span>
</div>
</div>
</div>
</div> </div>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.sync-cards { .sync-page {
display: grid; height: 100%;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); overflow-y: auto;
gap: 16px; padding: 4px;
}
/* Action Card */
.sync-action-card {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24px 28px;
background: #fff;
border-radius: 12px;
border: 1px solid #ebeef5;
margin-bottom: 16px; margin-bottom: 16px;
} }
.sync-card-header { .sync-action-info {
display: flex;
align-items: center;
gap: 16px;
}
.sync-action-icon {
width: 56px;
height: 56px;
border-radius: 12px;
background: linear-gradient(135deg, #fff2e8, #ffe0c2);
display: flex;
align-items: center;
justify-content: center;
color: var(--brand-color, #ff6800);
flex-shrink: 0;
}
.sync-action-title {
margin: 0 0 4px;
font-size: 18px;
font-weight: 700;
color: #1f2937;
}
.sync-action-desc {
margin: 0;
font-size: 13px;
color: #909399;
}
.sync-action-buttons {
display: flex;
gap: 12px;
}
/* Stats */
.sync-stats {
display: flex;
align-items: center;
gap: 0;
padding: 16px 28px;
background: #fff;
border-radius: 12px;
border: 1px solid #ebeef5;
margin-bottom: 16px;
}
.stat-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.stat-value {
font-size: 22px;
font-weight: 700;
color: #1f2937;
line-height: 1;
}
.stat-value.stat-success { color: #67c23a; }
.stat-value.stat-failed { color: #f56c6c; }
.stat-value.stat-time { font-size: 14px; font-weight: 600; color: #606266; }
.stat-label {
font-size: 12px;
color: #909399;
}
.stat-divider {
width: 1px;
height: 32px;
background: #ebeef5;
}
/* Logs */
.sync-logs {
background: #fff;
border-radius: 12px;
border: 1px solid #ebeef5;
overflow: hidden;
}
.sync-logs-head {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid #f5f5f5;
} }
.sync-card-title { .sync-logs-title {
margin: 0;
font-size: 15px;
font-weight: 600;
color: #1f2937;
}
.sync-empty {
padding: 40px 0;
}
/* Timeline */
.sync-timeline {
padding: 16px 20px;
max-height: 500px;
overflow-y: auto;
}
.timeline-item {
display: flex;
gap: 12px;
padding-bottom: 20px;
position: relative;
}
.timeline-item:not(:last-child)::before {
content: '';
position: absolute;
left: 7px;
top: 22px;
bottom: 0;
width: 2px;
background: #f0f0f0;
}
.timeline-dot {
width: 16px;
height: 16px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
z-index: 1;
margin-top: 2px;
}
.timeline-dot.is-success {
background: #f0f9eb;
color: #67c23a;
}
.timeline-dot.is-failed {
background: #fef0f0;
color: #f56c6c;
}
.timeline-dot.is-running {
background: #ecf5ff;
color: #409eff;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.timeline-content {
flex: 1;
min-width: 0;
}
.timeline-header {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
font-weight: 600; margin-bottom: 4px;
font-size: 15px;
} }
.sync-card-title :deep(.el-icon) { .timeline-status {
color: var(--brand-color);
}
.sync-card-desc {
color: #6b7280;
font-size: 13px; font-size: 13px;
margin: 0 0 16px;
min-height: 40px;
}
.logs-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.logs-title {
margin: 0;
font-size: 16px;
font-weight: 600; font-weight: 600;
} }
.timeline-status.is-success { color: #67c23a; }
.timeline-status.is-failed { color: #f56c6c; }
.timeline-status.is-running { color: #409eff; }
.timeline-type {
font-size: 12px;
font-weight: 600;
color: #606266;
background: #f5f7fa;
padding: 2px 8px;
border-radius: 4px;
}
.timeline-duration {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: 11px;
color: #909399;
background: #f5f7fa;
padding: 2px 6px;
border-radius: 8px;
}
.timeline-message {
margin: 0 0 4px;
font-size: 12px;
color: #606266;
line-height: 1.5;
word-break: break-all;
}
.timeline-time {
font-size: 11px;
color: #c0c4cc;
}
</style> </style>
+6 -7
View File
@@ -26,7 +26,7 @@ const filter = reactive<Required<TagFilter>>({
async function fetchList() { async function fetchList() {
loading.value = true loading.value = true
try { try {
const res = await tagsApi.getTagsList(filter) await tagsApi.getTagsList(filter)
const data = await tagsApi.getTagsList(filter) as any const data = await tagsApi.getTagsList(filter) as any
const arr = Array.isArray(data) ? data : (data.items ?? []) const arr = Array.isArray(data) ? data : (data.items ?? [])
list.value = arr list.value = arr
@@ -62,7 +62,6 @@ const dialogForm = reactive<CreateTagRequest & { id?: string; tagGroupId?: numbe
tagColor: '#ff6800', tagColor: '#ff6800',
tagFontColor: '#ffffff', tagFontColor: '#ffffff',
timing: '', timing: '',
tagGroupId: null,
}) })
const dialogRules = { const dialogRules = {
@@ -171,7 +170,7 @@ onMounted(() => {
<el-table v-loading="loading" :data="list" border stripe> <el-table v-loading="loading" :data="list" border stripe>
<el-table-column label="预览" width="120"> <el-table-column label="预览" width="120">
<template #default="{ row }: { row: Tag }"> <template #default="{ row }: any">
<span <span
v-if="row.tagColor" v-if="row.tagColor"
class="tag-preview" class="tag-preview"
@@ -182,7 +181,7 @@ onMounted(() => {
</el-table-column> </el-table-column>
<el-table-column prop="tagName" label="名称" min-width="200" /> <el-table-column prop="tagName" label="名称" min-width="200" />
<el-table-column label="背景色" width="140"> <el-table-column label="背景色" width="140">
<template #default="{ row }: { row: Tag }"> <template #default="{ row }: any">
<div class="color-cell"> <div class="color-cell">
<span class="color-swatch" :style="{ background: row.tagColor || '#d1d5db' }" /> <span class="color-swatch" :style="{ background: row.tagColor || '#d1d5db' }" />
<span class="color-hex">{{ row.tagColor || '-' }}</span> <span class="color-hex">{{ row.tagColor || '-' }}</span>
@@ -190,7 +189,7 @@ onMounted(() => {
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="字体色" width="140"> <el-table-column label="字体色" width="140">
<template #default="{ row }: { row: Tag }"> <template #default="{ row }: any">
<div class="color-cell"> <div class="color-cell">
<span class="color-swatch" :style="{ background: row.tagFontColor || '#d1d5db' }" /> <span class="color-swatch" :style="{ background: row.tagFontColor || '#d1d5db' }" />
<span class="color-hex">{{ row.tagFontColor || '-' }}</span> <span class="color-hex">{{ row.tagFontColor || '-' }}</span>
@@ -198,14 +197,14 @@ onMounted(() => {
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="所属分组" min-width="140"> <el-table-column label="所属分组" min-width="140">
<template #default="{ row }: { row: Tag }"> <template #default="{ row }: any">
<span v-if="row.tagGroup">{{ row.tagGroup.groupName }}</span> <span v-if="row.tagGroup">{{ row.tagGroup.groupName }}</span>
<span v-else style="color: #999;">未分组</span> <span v-else style="color: #999;">未分组</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column prop="timing" label="定时" min-width="120" /> <el-table-column prop="timing" label="定时" min-width="120" />
<el-table-column label="操作" width="180" fixed="right"> <el-table-column label="操作" width="180" fixed="right">
<template #default="{ row }: { row: Tag }"> <template #default="{ row }: any">
<div class="table-actions"> <div class="table-actions">
<el-button size="small" type="primary" plain @click="openEditDialog(row)"> <el-button size="small" type="primary" plain @click="openEditDialog(row)">
<el-icon><Edit /></el-icon> <el-icon><Edit /></el-icon>
+11 -1
View File
@@ -7,6 +7,7 @@ import { fileURLToPath, URL } from 'node:url'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
base: '/admin/',
plugins: [ plugins: [
vue(), vue(),
AutoImport({ AutoImport({
@@ -25,13 +26,22 @@ export default defineConfig({
}, },
}, },
server: { server: {
host: '0.0.0.0',
port: 5173, port: 5173,
proxy: { proxy: {
'/api': { '/api': {
target: 'http://localhost:3001', target: 'http://127.0.0.1:3001',
changeOrigin: true, changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''), rewrite: (path) => path.replace(/^\/api/, ''),
}, },
'/uploads': {
target: 'http://127.0.0.1:3001',
changeOrigin: true,
},
'/assets': {
target: 'http://127.0.0.1:3001',
changeOrigin: true,
},
}, },
}, },
}) })
+20 -6
View File
@@ -1,6 +1,20 @@
node_modules # Prisma connection string (PostgreSQL)
dist DATABASE_URL=postgresql://postgres:CHANGE_ME@localhost:5432/inkreach-official-website
coverage
*.log # JWT signing secret: generate with `node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"`
.DS_Store # Must be at least 32 characters.
.env JWT_SECRET=CHANGE_ME_TO_A_STRONG_RANDOM_SECRET
# Access token lifetime (e.g. 30m, 12h); short-lived, rotated via /auth/refresh
TOKEN_EXPIRES_IN=30m
# Refresh token lifetime (HttpOnly cookie)
REFRESH_TOKEN_EXPIRES_IN=7d
# Comma-separated list of allowed CORS origins (leave empty to disable CORS)
CORS_ORIGINS=http://localhost:5173
# Global rate limit per minute (per IP)
THROTTLE_LIMIT=120
PORT=3001
+3
View File
@@ -43,3 +43,6 @@ lerna-debug.log*
# TypeScript # TypeScript
*.tsbuildinfo *.tsbuildinfo
# Uploads
/uploads
+9 -1
View File
@@ -20,7 +20,9 @@
"test:e2e": "jest --config ./test/jest-e2e.json", "test:e2e": "jest --config ./test/jest-e2e.json",
"prisma:generate": "prisma generate", "prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev", "prisma:migrate": "prisma migrate dev",
"prisma:studio": "prisma studio" "prisma:studio": "prisma studio",
"configure:product-center-icons": "ts-node prisma/configure-product-center-icons.ts",
"import:product-detail": "ts-node prisma/import-product-detail.ts"
}, },
"dependencies": { "dependencies": {
"@nestjs/axios": "^3.0.1", "@nestjs/axios": "^3.0.1",
@@ -32,12 +34,17 @@
"@nestjs/platform-express": "^10.3.0", "@nestjs/platform-express": "^10.3.0",
"@nestjs/schedule": "^4.0.0", "@nestjs/schedule": "^4.0.0",
"@nestjs/swagger": "^7.1.17", "@nestjs/swagger": "^7.1.17",
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^5.8.0", "@prisma/client": "^5.8.0",
"@types/multer": "^2.2.0",
"axios": "^1.6.5", "axios": "^1.6.5",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.0", "class-validator": "^0.14.0",
"cookie-parser": "^1.4.7",
"express": "^4.21.0", "express": "^4.21.0",
"helmet": "^8.3.0",
"multer": "^2.2.0",
"passport": "^0.7.0", "passport": "^0.7.0",
"passport-jwt": "^4.0.1", "passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.1", "reflect-metadata": "^0.2.1",
@@ -48,6 +55,7 @@
"@nestjs/schematics": "^10.0.3", "@nestjs/schematics": "^10.0.3",
"@nestjs/testing": "^10.3.0", "@nestjs/testing": "^10.3.0",
"@types/bcrypt": "^5.0.2", "@types/bcrypt": "^5.0.2",
"@types/cookie-parser": "^1.4.10",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/jest": "^29.5.11", "@types/jest": "^29.5.11",
"@types/node": "^20.10.6", "@types/node": "^20.10.6",
@@ -0,0 +1,54 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const countryIcons: Record<string, string> = {
: '/assets/product-center/countries/us.png',
: '/assets/product-center/countries/jp.png',
西: '/assets/product-center/countries/mx.png',
西: '/assets/product-center/countries/br.png',
: '/assets/product-center/countries/middle-east.png',
: '/assets/product-center/countries/pl.png',
西: '/assets/product-center/countries/es.png',
: '/assets/product-center/countries/de.png',
: '/assets/product-center/countries/it.png',
: '/assets/product-center/countries/gb.png',
: '/assets/product-center/countries/ca.png',
: '/assets/product-center/countries/au.png',
: '/assets/product-center/countries/kr.png',
};
const categoryIcons: Record<string, string> = {
: '/assets/product-center/categories/men.svg',
: '/assets/product-center/categories/women.svg',
: '/assets/product-center/categories/children.svg',
: '/assets/product-center/categories/home.svg',
};
async function updateExistingIcons(
entries: Record<string, string>,
update: (name: string, icon: string) => Promise<{ count: number }>,
): Promise<number> {
let updated = 0;
for (const [name, icon] of Object.entries(entries)) {
const result = await update(name, icon);
updated += result.count;
}
return updated;
}
async function main(): Promise<void> {
const countries = await updateExistingIcons(countryIcons, (countryName, countryIcon) =>
prisma.country.updateMany({ where: { countryName }, data: { countryIcon } }),
);
const categories = await updateExistingIcons(categoryIcons, (categoryName, categoryIcon) =>
prisma.category.updateMany({
where: { categoryName, parentCategoryId: null },
data: { categoryIcon },
}),
);
console.log(`Configured ${countries} countries and ${categories} root categories.`);
}
main()
.finally(async () => prisma.$disconnect());
+36
View File
@@ -0,0 +1,36 @@
import { readFile } from 'fs/promises';
import { resolve } from 'path';
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../src/app.module';
import { SyncService } from '../src/sync/sync.service';
import { SdsProductDetail } from '../src/sync/sds-client.service';
async function main(): Promise<void> {
const inputPath = process.argv[2];
if (!inputPath) {
throw new Error('Usage: pnpm --filter @inkreach/api import:product-detail -- <product_detail.txt>');
}
const absolutePath = resolve(inputPath);
const raw = await readFile(absolutePath, 'utf8');
const jsonStart = raw.indexOf('{');
if (jsonStart < 0) throw new Error('No JSON object found in product detail file');
const detail = JSON.parse(raw.slice(jsonStart)) as SdsProductDetail;
const app = await NestFactory.createApplicationContext(AppModule, { logger: ['error', 'warn'] });
try {
const result = await app.get(SyncService).importProductDetail(detail);
process.stdout.write(
`Imported SDS product ${result.goodId}: ${result.variants} variants, ` +
`${result.sizeRows} size rows, ${result.packageRows} package rows, ` +
`${result.configuredGoods} configured goods\n`,
);
} finally {
await app.close();
}
}
void main().catch((error: unknown) => {
const message = error instanceof Error ? error.stack ?? error.message : String(error);
process.stderr.write(`${message}\n`);
process.exitCode = 1;
});
@@ -0,0 +1,70 @@
-- Cache SDS product details separately from website merchandising configuration.
CREATE TABLE "origin_good_details" (
"origin_good_id" BIGINT NOT NULL,
"product_code" TEXT,
"english_name" TEXT,
"blank_design_url" TEXT,
"details_page_video_url" TEXT,
"texture_name" TEXT,
"production_cycle_hours" INTEGER,
"min_weight_g" DECIMAL(12,3),
"reminder" TEXT,
"production_process" TEXT,
"material_description" TEXT,
"product_performance" TEXT,
"applicable_scenarios" TEXT,
"washing_instructions" TEXT,
"special_description" TEXT,
"design_explanation" TEXT,
"design_area" TEXT,
"picture_request" TEXT,
"size_chart" JSONB,
"package_specs" JSONB,
"options" JSONB,
"media" JSONB,
"upstream_updated_at" TIMESTAMPTZ(6),
"synced_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "origin_good_details_pkey" PRIMARY KEY ("origin_good_id")
);
CREATE TABLE "origin_good_variants" (
"origin_good_variant_id" BIGSERIAL NOT NULL,
"origin_good_id" BIGINT NOT NULL,
"sds_variant_id" TEXT NOT NULL,
"sku" TEXT NOT NULL,
"size_id" TEXT,
"size_name" TEXT,
"color_id" TEXT,
"color_name" TEXT,
"color_hex" TEXT,
"image_url" TEXT,
"price" DECIMAL(12,2),
"original_price" DECIMAL(12,2),
"weight_g" DECIMAL(12,3),
"box_length_cm" DECIMAL(12,3),
"box_width_cm" DECIMAL(12,3),
"box_height_cm" DECIMAL(12,3),
"enabled" BOOLEAN NOT NULL DEFAULT true,
"sort_order" INTEGER NOT NULL DEFAULT 0,
"design_data" JSONB,
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "origin_good_variants_pkey" PRIMARY KEY ("origin_good_variant_id")
);
CREATE UNIQUE INDEX "origin_good_variants_origin_good_id_sds_variant_id_key"
ON "origin_good_variants"("origin_good_id", "sds_variant_id");
CREATE INDEX "origin_good_variants_origin_good_id_sort_order_idx"
ON "origin_good_variants"("origin_good_id", "sort_order");
CREATE INDEX "origin_good_variants_sku_idx" ON "origin_good_variants"("sku");
ALTER TABLE "origin_good_details"
ADD CONSTRAINT "origin_good_details_origin_good_id_fkey"
FOREIGN KEY ("origin_good_id") REFERENCES "origin_goods"("origin_good_id")
ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE "origin_good_variants"
ADD CONSTRAINT "origin_good_variants_origin_good_id_fkey"
FOREIGN KEY ("origin_good_id") REFERENCES "origin_goods"("origin_good_id")
ON DELETE CASCADE ON UPDATE NO ACTION;
@@ -0,0 +1 @@
ALTER TYPE "SyncType" ADD VALUE IF NOT EXISTS 'PRODUCT_DETAILS';
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "origin_goods" ADD COLUMN "delisted" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,22 @@
-- Sync database with schema.prisma (missing columns/table from earlier iterations)
-- AlterTable
ALTER TABLE "goods" ADD COLUMN "good_image" TEXT;
-- AlterTable
ALTER TABLE "tags" ADD COLUMN "tag_font_color" TEXT;
-- CreateTable
CREATE TABLE "good_tags" (
"good_id" BIGINT NOT NULL,
"tag_id" BIGINT NOT NULL,
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "good_tags_pkey" PRIMARY KEY ("good_id","tag_id")
);
-- CreateIndex
CREATE INDEX "good_tags_tag_id_idx" ON "good_tags"("tag_id");
-- AddForeignKey
ALTER TABLE "good_tags" ADD CONSTRAINT "good_tags_good_id_fkey" FOREIGN KEY ("good_id") REFERENCES "goods"("good_id") ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE "good_tags" ADD CONSTRAINT "good_tags_tag_id_fkey" FOREIGN KEY ("tag_id") REFERENCES "tags"("tag_id") ON DELETE CASCADE ON UPDATE NO ACTION;
@@ -0,0 +1,6 @@
CREATE TYPE "OriginGoodSource" AS ENUM ('SDS', 'CUSTOM');
ALTER TABLE "origin_goods"
ADD COLUMN "source" "OriginGoodSource" NOT NULL DEFAULT 'SDS';
CREATE INDEX "origin_goods_source_idx" ON "origin_goods"("source");
@@ -0,0 +1,8 @@
-- Create enum for user roles
CREATE TYPE "Role" AS ENUM ('ADMIN');
-- Add role column, existing users become ADMIN
ALTER TABLE "users" ADD COLUMN "role" "Role" NOT NULL DEFAULT 'ADMIN';
-- Token version for JWT revocation (logout bumps it)
ALTER TABLE "users" ADD COLUMN "token_version" INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,17 @@
-- CreateTable
CREATE TABLE "good_origin_goods" (
"good_id" BIGINT NOT NULL,
"origin_good_id" BIGINT NOT NULL,
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "good_origin_goods_pkey" PRIMARY KEY ("good_id","origin_good_id")
);
-- CreateIndex
CREATE INDEX "good_origin_goods_origin_good_id_idx" ON "good_origin_goods"("origin_good_id");
-- AddForeignKey
ALTER TABLE "good_origin_goods" ADD CONSTRAINT "good_origin_goods_good_id_fkey" FOREIGN KEY ("good_id") REFERENCES "goods"("good_id") ON DELETE CASCADE ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE "good_origin_goods" ADD CONSTRAINT "good_origin_goods_origin_good_id_fkey" FOREIGN KEY ("origin_good_id") REFERENCES "origin_goods"("origin_good_id") ON DELETE CASCADE ON UPDATE NO ACTION;
+135 -34
View File
@@ -6,6 +6,7 @@
generator client { generator client {
provider = "prisma-client-js" provider = "prisma-client-js"
binaryTargets = ["native", "debian-openssl-3.0.x"]
} }
datasource db { datasource db {
@@ -14,23 +15,99 @@ datasource db {
} }
// ---------- Origin Goods ---------- // ---------- Origin Goods ----------
model OriginGood { enum OriginGoodSource {
id BigInt @id @default(autoincrement()) @map("origin_good_id") SDS
sdsGoodId String @unique @map("sds_good_id") CUSTOM
// Cached SDS product metadata (filled during sync) }
sdsCategoryId String? @map("sds_category_id")
goodName String? @map("good_name")
goodImage String? @map("good_image")
goodPrice Decimal? @map("good_price") @db.Decimal(12, 2)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
goods Good[] model OriginGood {
id BigInt @id @default(autoincrement()) @map("origin_good_id")
sdsGoodId String @unique @map("sds_good_id")
// Cached SDS product metadata (filled during sync)
sdsCategoryId String? @map("sds_category_id")
goodName String? @map("good_name")
goodImage String? @map("good_image")
goodPrice Decimal? @map("good_price") @db.Decimal(12, 2)
delisted Boolean @default(false)
source OriginGoodSource @default(SDS)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
goods Good[]
detail OriginGoodDetail?
variants OriginGoodVariant[]
mergedIntoGoods GoodOriginGood[]
@@index([sdsCategoryId]) @@index([sdsCategoryId])
@@index([source])
@@map("origin_goods") @@map("origin_goods")
} }
// ---------- Origin Good Details (cached from SDS /products/{id}) ----------
model OriginGoodDetail {
originGoodId BigInt @id @map("origin_good_id")
productCode String? @map("product_code")
englishName String? @map("english_name")
blankDesignUrl String? @map("blank_design_url")
detailsPageVideoUrl String? @map("details_page_video_url")
textureName String? @map("texture_name")
productionCycleHours Int? @map("production_cycle_hours")
minWeightG Decimal? @map("min_weight_g") @db.Decimal(12, 3)
reminder String?
productionProcess String? @map("production_process")
materialDescription String? @map("material_description")
productPerformance String? @map("product_performance")
applicableScenarios String? @map("applicable_scenarios")
washingInstructions String? @map("washing_instructions")
specialDescription String? @map("special_description")
designExplanation String? @map("design_explanation")
designArea String? @map("design_area")
pictureRequest String? @map("picture_request")
sizeChart Json? @map("size_chart")
packageSpecs Json? @map("package_specs")
options Json?
media Json?
upstreamUpdatedAt DateTime? @map("upstream_updated_at") @db.Timestamptz(6)
syncedAt DateTime @default(now()) @map("synced_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
originGood OriginGood @relation(fields: [originGoodId], references: [id], onDelete: Cascade, onUpdate: NoAction)
@@map("origin_good_details")
}
// ---------- Origin Good Variants (cached SDS child products / SKUs) ----------
model OriginGoodVariant {
id BigInt @id @default(autoincrement()) @map("origin_good_variant_id")
originGoodId BigInt @map("origin_good_id")
sdsVariantId String @map("sds_variant_id")
sku String
sizeId String? @map("size_id")
sizeName String? @map("size_name")
colorId String? @map("color_id")
colorName String? @map("color_name")
colorHex String? @map("color_hex")
imageUrl String? @map("image_url")
price Decimal? @db.Decimal(12, 2)
originalPrice Decimal? @map("original_price") @db.Decimal(12, 2)
weightG Decimal? @map("weight_g") @db.Decimal(12, 3)
boxLengthCm Decimal? @map("box_length_cm") @db.Decimal(12, 3)
boxWidthCm Decimal? @map("box_width_cm") @db.Decimal(12, 3)
boxHeightCm Decimal? @map("box_height_cm") @db.Decimal(12, 3)
enabled Boolean @default(true)
sortOrder Int @default(0) @map("sort_order")
designData Json? @map("design_data")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
originGood OriginGood @relation(fields: [originGoodId], references: [id], onDelete: Cascade, onUpdate: NoAction)
@@unique([originGoodId, sdsVariantId])
@@index([originGoodId, sortOrder])
@@index([sku])
@@map("origin_good_variants")
}
// ---------- Countries ---------- // ---------- Countries ----------
model Country { model Country {
id BigInt @id @default(autoincrement()) @map("country_id") id BigInt @id @default(autoincrement()) @map("country_id")
@@ -47,18 +124,18 @@ model Country {
// ---------- Categories (self-referential tree) ---------- // ---------- Categories (self-referential tree) ----------
model Category { model Category {
id BigInt @id @default(autoincrement()) @map("category_id") id BigInt @id @default(autoincrement()) @map("category_id")
parentCategoryId BigInt? @map("parent_category_id") parentCategoryId BigInt? @map("parent_category_id")
categoryName String @map("category_name") categoryName String @map("category_name")
categoryIcon String? @map("category_icon") categoryIcon String? @map("category_icon")
sdsCategoryId String? @unique @map("sds_category_id") sdsCategoryId String? @unique @map("sds_category_id")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6) createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6) updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
parent Category? @relation("CategoryToCategory", fields: [parentCategoryId], references: [id], onDelete: Restrict, onUpdate: NoAction) parent Category? @relation("CategoryToCategory", fields: [parentCategoryId], references: [id], onDelete: Restrict, onUpdate: NoAction)
children Category[] @relation("CategoryToCategory") children Category[] @relation("CategoryToCategory")
goods Good[] goods Good[]
positions Position[] positions Position[]
@@index([parentCategoryId]) @@index([parentCategoryId])
@@map("categories") @@map("categories")
@@ -93,7 +170,7 @@ model Tag {
goods Good[] goods Good[]
goodTags GoodTag[] goodTags GoodTag[]
tagGroup TagGroup? @relation(fields: [tagGroupId], references: [id], onDelete: SetNull, onUpdate: NoAction) tagGroup TagGroup? @relation(fields: [tagGroupId], references: [id], onDelete: SetNull, onUpdate: NoAction)
@@index([tagGroupId]) @@index([tagGroupId])
@@index([tagGroupId, sortOrder]) @@index([tagGroupId, sortOrder])
@@ -121,17 +198,17 @@ model Position {
// ---------- Goods ---------- // ---------- Goods ----------
model Good { model Good {
id BigInt @id @default(autoincrement()) @map("good_id") id BigInt @id @default(autoincrement()) @map("good_id")
originGoodId BigInt @map("origin_good_id") originGoodId BigInt @map("origin_good_id")
countryId BigInt @map("country_id") countryId BigInt @map("country_id")
categoryId BigInt @map("category_id") categoryId BigInt @map("category_id")
tagId BigInt? @map("tag_id") tagId BigInt? @map("tag_id")
positionId BigInt? @map("position_id") positionId BigInt? @map("position_id")
goodName String @map("good_name") goodName String @map("good_name")
goodImage String? @map("good_image") goodImage String? @map("good_image")
goodPriority Int @default(0) @map("good_priority") goodPriority Int @default(0) @map("good_priority")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6) createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6) updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
originGood OriginGood @relation(fields: [originGoodId], references: [id], onDelete: Restrict, onUpdate: NoAction) originGood OriginGood @relation(fields: [originGoodId], references: [id], onDelete: Restrict, onUpdate: NoAction)
country Country @relation(fields: [countryId], references: [id], onDelete: Restrict, onUpdate: NoAction) country Country @relation(fields: [countryId], references: [id], onDelete: Restrict, onUpdate: NoAction)
@@ -139,6 +216,7 @@ model Good {
tag Tag? @relation(fields: [tagId], references: [id], onDelete: SetNull, onUpdate: NoAction) tag Tag? @relation(fields: [tagId], references: [id], onDelete: SetNull, onUpdate: NoAction)
position Position? @relation(fields: [positionId], references: [id], onDelete: SetNull, onUpdate: NoAction) position Position? @relation(fields: [positionId], references: [id], onDelete: SetNull, onUpdate: NoAction)
goodTags GoodTag[] goodTags GoodTag[]
mergedOriginGoods GoodOriginGood[]
@@index([originGoodId]) @@index([originGoodId])
@@index([countryId]) @@index([countryId])
@@ -165,11 +243,33 @@ model GoodTag {
@@map("good_tags") @@map("good_tags")
} }
// ---------- Good-OriginGood Junction (merged secondary sources, M:N) ----------
// Primary source stays on goods.origin_good_id and is NOT stored here.
model GoodOriginGood {
goodId BigInt @map("good_id")
originGoodId BigInt @map("origin_good_id")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
good Good @relation(fields: [goodId], references: [id], onDelete: Cascade, onUpdate: NoAction)
originGood OriginGood @relation(fields: [originGoodId], references: [id], onDelete: Cascade, onUpdate: NoAction)
@@id([goodId, originGoodId])
@@index([originGoodId])
@@map("good_origin_goods")
}
// ---------- Users (admin authentication) ---------- // ---------- Users (admin authentication) ----------
enum Role {
ADMIN
}
model User { model User {
id BigInt @id @default(autoincrement()) id BigInt @id @default(autoincrement())
username String @unique username String @unique
passwordHash String @map("password_hash") passwordHash String @map("password_hash")
role Role @default(ADMIN)
// Bumped on logout / revocation; JWTs carrying an older version are rejected.
tokenVersion Int @default(0) @map("token_version")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6) createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6) updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
@@ -180,6 +280,7 @@ model User {
enum SyncType { enum SyncType {
CATEGORIES CATEGORIES
PRODUCTS PRODUCTS
PRODUCT_DETAILS
} }
enum SyncStatus { enum SyncStatus {
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

@@ -0,0 +1,5 @@
<svg preserveAspectRatio="none" width="100%" height="100%" overflow="visible" style="display: block;" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g id="&#230;&#175;&#155;&#230;&#175;&#175;">
<path id="Vector" d="M4.88633 1.98665C5.33119 1.97156 5.8398 1.98301 6.28931 1.98301L8.87332 1.98303L16.492 1.98247C17.189 1.98315 17.7065 2.1872 18.0772 2.81271C18.3143 3.2131 18.2842 3.61555 18.2841 4.05998L18.2832 4.9648C18.2977 4.96406 18.3123 4.96311 18.327 4.96317C18.946 4.96544 19.5651 4.96377 20.1842 4.96464C20.35 4.96487 20.5158 4.9649 20.6812 4.97965C21.3291 5.03911 21.9365 5.32106 22.4002 5.77761C22.9854 6.35146 23.2455 7.05899 23.2511 7.8691L23.2513 15.9239L23.2516 18.1581C23.2517 18.5872 23.2748 19.2749 23.1974 19.6785C23.0883 20.23 22.8164 20.7362 22.417 21.1318C22.2073 21.3409 21.9682 21.518 21.7072 21.6575C20.8557 22.1159 20.0448 22.0235 19.1195 22.0226H8.94568L6.28116 22.0228C5.66064 22.0231 4.88519 22.0568 4.28608 21.9464C3.4868 21.8008 2.74539 21.4309 2.14822 20.88C1.30557 20.1054 0.806162 19.027 0.760423 17.8834C0.744748 17.5372 0.750489 17.1759 0.750662 16.8281L0.750771 15.2893L0.750812 10.4876L0.750558 7.56548C0.750482 6.91186 0.712701 6.06771 0.837323 5.44551C0.997082 4.66425 1.36911 3.94214 1.91253 3.35852C2.68497 2.52818 3.75329 2.03535 4.88633 1.98665ZM1.50862 15.253C2.14832 14.3061 3.14214 13.6566 4.26615 13.4506C4.77379 13.3528 5.22789 13.3733 5.74026 13.3733L7.22112 13.3737L12.4984 13.3738L15.4964 13.3742L16.3552 13.3732C16.8991 13.3726 17.0379 13.3561 17.5334 13.5986V6.61544V4.56193C17.5335 4.30358 17.549 3.72192 17.5225 3.49302C17.5006 3.30198 17.4139 3.12419 17.2769 2.98926C16.9857 2.69911 16.6673 2.73987 16.2868 2.74018L15.5406 2.7411L13.0675 2.74118L5.14866 2.74166C5.07448 2.74247 5.00032 2.74432 4.92619 2.7472C3.92002 2.80855 3.077 3.17975 2.40127 3.93833C1.97103 4.42125 1.68113 5.01268 1.563 5.64857C1.47184 6.14183 1.50058 6.87789 1.50091 7.39632L1.50111 9.95416L1.50107 13.4367L1.50105 14.5679C1.50109 14.7909 1.49296 15.0324 1.50862 15.253ZM8.99453 18.9369L16.2925 18.9372L18.6071 18.9366L19.3445 18.9363C19.5484 18.9363 19.9029 18.898 20.056 19.0438C20.1299 19.1145 20.1708 19.2128 20.1691 19.3151C20.1667 19.4209 20.1207 19.5211 20.0418 19.5917C19.9477 19.6764 19.8889 19.6822 19.7676 19.6861C19.4157 19.6972 19.0567 19.6923 18.7049 19.6923L16.8063 19.6924H11.0456L6.92691 19.6928L5.64741 19.6927C5.38641 19.6927 5.09412 19.7061 4.83641 19.6802C3.90898 19.587 3.25249 18.7671 3.34189 17.8533C3.38568 17.4162 3.6029 17.0151 3.94493 16.7394C4.20443 16.5318 4.51749 16.402 4.84778 16.3651C5.04529 16.3417 5.27545 16.3472 5.47726 16.3473L6.33113 16.3475L9.20144 16.3477L14.7026 16.3475C15.6297 16.3475 16.6073 16.3314 17.5311 16.3491L17.5349 15.4343C17.535 15.2346 17.5476 14.9099 17.5039 14.73C17.4709 14.5924 17.402 14.4661 17.3042 14.3639C17.0397 14.0929 16.7182 14.1312 16.371 14.1312L15.6384 14.1317H13.1882L5.32143 14.1324C5.24029 14.1331 5.15918 14.1352 5.07812 14.1387C4.01313 14.198 3.10203 14.573 2.38161 15.3836C1.76329 16.0772 1.44917 16.99 1.50965 17.9172C1.56819 18.8651 2.00149 19.7507 2.71393 20.3786C3.22367 20.8289 3.85296 21.1221 4.52573 21.2224C4.85955 21.2734 5.19037 21.2625 5.52735 21.2625L6.74896 21.2624L11.0247 21.2619L17.3304 21.2618L19.3445 21.2623C19.7137 21.2624 20.0973 21.2727 20.4665 21.2537C21.0698 21.2227 21.64 20.8929 22.0275 20.4408C22.7492 19.599 22.6019 18.3111 21.764 17.5974C21.451 17.33 21.0641 17.164 20.6547 17.1215C20.4169 17.0944 20.0379 17.1047 19.7895 17.1046H18.3545L13.6232 17.105L7.80963 17.1052L5.98936 17.1046C5.66054 17.1045 5.3165 17.0978 4.98927 17.1128C4.72169 17.1251 4.46675 17.2485 4.29114 17.4549C4.13868 17.6329 4.06436 17.8648 4.08495 18.0982C4.10752 18.3431 4.22707 18.5688 4.41697 18.725C4.72065 18.9786 5.05403 18.9374 5.4256 18.9375H6.19901L8.99453 18.9369ZM18.2839 16.3473C18.5978 16.3331 19.0591 16.3473 19.3878 16.3477C19.8266 16.3481 20.4738 16.3234 20.8846 16.3909C21.1822 16.4405 21.4698 16.5372 21.7369 16.6773C21.9299 16.7794 22.1104 16.9035 22.2749 17.0472C22.3199 17.0859 22.4581 17.2153 22.4969 17.2411C22.5077 16.9956 22.5012 16.7118 22.501 16.4625L22.5009 15.1418L22.5006 11.0416L22.5007 8.79514C22.5011 8.43763 22.5203 7.7808 22.4675 7.45223C22.403 7.05879 22.2247 6.69285 21.9545 6.3996C21.09 5.45927 20.0243 5.7749 18.8906 5.72076C18.7008 5.71171 18.4688 5.7379 18.2855 5.71609C18.2818 6.29028 18.2808 6.8645 18.2829 7.4387L18.2832 10.5551L18.2839 16.3473Z" fill="var(--fill-0, black)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.4 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.8 KiB

@@ -0,0 +1,8 @@
<svg preserveAspectRatio="none" width="100%" height="100%" overflow="visible" style="display: block;" viewBox="0 0 16.9444 21.2465" fill="none" xmlns="http://www.w3.org/2000/svg">
<g id="Group 40">
<path id="Vector" d="M4.60937 9.39516C4.83089 9.41263 5.19797 9.40155 5.42769 9.40155L6.94956 9.40133C8.71577 9.40094 10.5191 9.38265 12.2815 9.40662C12.9508 11.3307 14.3581 13.4287 15.5839 15.0446C15.8822 15.4378 16.7974 16.3807 16.9444 16.6953C16.6383 17.2507 15.7458 17.7321 15.2033 18.0528C14.5811 18.4207 14.5649 18.082 14.2723 17.5918C14.0964 17.2971 13.9313 16.9779 13.7623 16.6745L12.1526 13.8128C11.8994 13.3696 11.5575 12.7309 11.217 12.3736C11.7063 14.5828 12.9504 16.8791 14.0188 18.8723C14.1871 19.1861 13.9309 19.3898 13.694 19.5564C13.4559 19.7238 12.6714 20.2953 12.3918 20.2153C12.2449 20.0934 12.0742 19.5867 11.9879 19.4213C11.7179 18.9037 10.0267 14.7534 9.73361 14.6621C9.63034 14.8155 9.77541 15.2831 9.80986 15.4684C10.1336 17.2094 10.7771 18.8659 11.4514 20.4962C11.5693 20.9293 9.64682 21.1744 9.30522 21.2057C8.24188 21.3076 7.16888 21.2186 6.13686 20.9428C5.9456 20.8923 5.66846 20.8251 5.5108 20.6989C5.46617 20.6631 5.41691 20.5888 5.43238 20.5306C5.54204 20.1186 5.80851 19.6085 5.95323 19.214C6.38496 18.0368 7.18965 15.777 7.16438 14.5671C6.91075 14.8989 6.6099 15.5769 6.42632 15.9742C6.019 16.8664 5.62029 17.7625 5.23025 18.6625C5.02017 19.1417 4.74544 19.823 4.49277 20.2564C4.44175 20.2465 4.39117 20.2343 4.34122 20.2198C3.94495 20.1042 2.97693 19.496 2.76767 19.1178C2.92234 18.6804 3.44618 17.8446 3.66926 17.3829C4.44438 15.7788 5.25941 14.108 5.66802 12.3696C4.94019 13.1618 2.49025 18.0769 2.21709 18.2064C2.15024 18.238 2.05775 18.2215 1.99036 18.1973C1.55572 18.0414 0.201822 17.2085 0.0193916 16.8083C-0.1163 16.5107 0.497699 15.9933 0.69442 15.7758C2.28029 14.0222 3.77967 11.6073 4.60937 9.39516Z" fill="var(--fill-0, #000000)"/>
<path id="Vector_2" d="M4.62793 0.0189548C4.95631 0.0052677 5.36925 0.0045545 5.69706 0.0201891C6.26604 0.0473438 5.85348 1.03493 6.14374 1.42184C6.3697 1.72304 6.60509 1.99478 6.84768 2.28177C7.27209 2.78427 7.69139 3.29099 8.10563 3.80189C9.04203 4.96817 9.85815 6.15223 10.759 7.30756L9.78755 7.31091L4.67883 7.30962C4.61824 6.73838 4.55875 6.30262 4.40945 5.73701C4.12639 4.6645 3.51922 3.65092 3.76517 2.51157C3.87777 1.99001 4.27615 1.65282 4.41615 1.17841C4.48472 0.946111 4.42237 0.412836 4.49314 0.150148C4.51632 0.0640753 4.55721 0.0571635 4.62793 0.0189548Z" fill="var(--fill-0, #000000)"/>
<path id="Vector_3" d="M11.061 0.016756C11.3249 0.0125319 12.1975 -0.0521733 12.3509 0.104885C12.4479 0.279115 12.3539 0.945805 12.4893 1.27531C12.6708 1.71711 12.9577 1.96767 13.086 2.42878C13.4027 3.56613 12.7585 4.65918 12.4803 5.74364C12.3332 6.31713 12.2859 6.72258 12.2107 7.30762C11.8729 7.31264 11.5351 7.31283 11.1973 7.30816C11.1476 7.22593 11.0856 7.14044 11.0303 7.06084C10.5544 6.38636 10.0687 5.71895 9.57305 5.05887C9.31283 4.71083 8.96544 4.22429 8.67958 3.91519C8.93354 3.69005 10.7286 1.47014 10.7952 1.27473C10.9056 0.950687 10.8169 0.581355 10.8834 0.247187C10.9088 0.11967 10.9592 0.085164 11.061 0.016756Z" fill="var(--fill-0, #000000)"/>
<path id="Vector_4" d="M4.75302 7.85951L12.2149 7.8591C12.2154 8.05077 12.2291 8.77411 12.2066 8.92294L12.1674 8.93525C10.0843 8.9821 7.97963 8.91638 5.8947 8.94109C5.51017 8.94565 5.11366 8.92598 4.73124 8.94817C4.77096 8.6908 4.75466 8.13501 4.75302 7.85951Z" fill="var(--fill-0, #000000)"/>
</g>
</svg>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+65
View File
@@ -0,0 +1,65 @@
/**
* Export all application tables from the local (source) database to a JSON
* file, preserving column types for the matching import-data.mjs script.
*
* Usage (from apps/api, against the local DB in .env):
* node scripts/export-data.mjs <output.json>
*/
import { PrismaClient } from '@prisma/client';
import { writeFileSync } from 'node:fs';
const TABLES = [
'users',
'countries',
'categories',
'tag_groups',
'tags',
'positions',
'origin_goods',
'origin_good_variants',
'origin_good_details',
'goods',
'good_tags',
'sync_logs',
];
const prisma = new PrismaClient();
// Serialize values losslessly; import side uses information_schema to restore types.
function serialize(value) {
if (value === null || value === undefined) return null;
if (typeof value === 'bigint') return value.toString();
if (value instanceof Date) return value.toISOString();
if (typeof value === 'object' && Buffer.isBuffer(value)) return value.toString('base64');
if (typeof value === 'object') return JSON.stringify(value); // jsonb
return value;
}
async function main() {
const out = process.argv[2];
if (!out) {
console.error('Usage: node scripts/export-data.mjs <output.json>');
process.exit(1);
}
const dump = { exportedAt: new Date().toISOString(), tables: {} };
for (const table of TABLES) {
const rows = await prisma.$queryRawUnsafe(`SELECT * FROM "${table}"`);
dump.tables[table] = rows.map((row) => {
const o = {};
for (const [k, v] of Object.entries(row)) o[k] = serialize(v);
return o;
});
console.log(`${table}: ${rows.length} rows`);
}
writeFileSync(out, JSON.stringify(dump));
console.log(`Wrote ${out}`);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(() => prisma.$disconnect());
+106
View File
@@ -0,0 +1,106 @@
/**
* Import a dump produced by export-data.mjs into the current database.
* Tables are truncated first (order-independent via session_replication_role)
* and columns are cast back to their real types using information_schema.
*
* Usage (inside the api container):
* node scripts/import-data.mjs <dump.json>
*/
import { PrismaClient, Prisma } from '@prisma/client';
import { readFileSync } from 'node:fs';
const prisma = new PrismaClient();
function toLiteral(value, udtName) {
if (value === null) return Prisma.sql`NULL`;
const target = Prisma.raw(`"${udtName}"`);
switch (udtName) {
case 'int2':
case 'int4':
case 'int8':
return Prisma.sql`${BigInt(value)}::${target}`;
case 'float4':
case 'float8':
case 'numeric':
return Prisma.sql`${Number(value)}::${target}`;
case 'bool':
return Prisma.sql`${!!value}::${target}`;
case 'timestamptz':
case 'timestamp':
return Prisma.sql`${new Date(value).toISOString()}::${target}`;
case 'date':
return Prisma.sql`${String(value)}::${target}`;
case 'jsonb':
case 'json':
return Prisma.sql`${typeof value === 'string' ? value : JSON.stringify(value)}::${target}`;
case 'bytea':
return Prisma.sql`${Buffer.from(value, 'base64')}::bytea`;
default:
// text, varchar, enums and anything else: pass as text and cast
return Prisma.sql`${String(value)}::${target}`;
}
}
async function main() {
const file = process.argv[2];
if (!file) {
console.error('Usage: node scripts/import-data.mjs <dump.json>');
process.exit(1);
}
const dump = JSON.parse(readFileSync(file, 'utf8'));
// Suspend FK checks during bulk load (postgres superuser not required for
// session_replication_role in the compose postgres where app user owns db).
await prisma.$executeRawUnsafe(`SET session_replication_role = replica`);
const summary = {};
for (const [table, rows] of Object.entries(dump.tables)) {
if (rows.length === 0) {
summary[table] = 0;
continue;
}
await prisma.$executeRawUnsafe(`TRUNCATE TABLE "${table}" CASCADE`);
const colTypes = {};
const info = await prisma.$queryRawUnsafe(
`SELECT column_name, udt_name FROM information_schema.columns WHERE table_name = '${table}'`,
);
for (const c of info) colTypes[c.column_name] = c.udt_name;
const columns = Object.keys(rows[0]);
const colList = Prisma.raw(columns.map((c) => `"${c}"`).join(', '));
const CHUNK = 200;
for (let i = 0; i < rows.length; i += CHUNK) {
const tuples = rows.slice(i, i + CHUNK).map(
(r) =>
Prisma.sql`(${Prisma.join(
columns.map((c) => toLiteral(r[c], colTypes[c])),
)})`,
);
await prisma.$executeRaw(
Prisma.sql`INSERT INTO ${Prisma.raw(`"${table}"`)} (${colList}) VALUES ${Prisma.join(tuples)}`,
);
}
// Keep sequences ahead of imported serial ids
// Keep serial sequences ahead of imported ids
const idCol = columns.find(
(c) => c === 'id' || c === `${table.replace(/s$/, '')}_id`,
);
if (idCol) {
await prisma.$executeRawUnsafe(
`SELECT setval(pg_get_serial_sequence('"${table}"', '${idCol}'), COALESCE((SELECT MAX("${idCol}") FROM "${table}"), 1))`,
);
}
summary[table] = rows.length;
}
await prisma.$executeRawUnsafe(`SET session_replication_role = DEFAULT`);
console.log('Imported:', JSON.stringify(summary, null, 2));
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(() => prisma.$disconnect());
+42
View File
@@ -0,0 +1,42 @@
/**
* Set the admin credentials for the production deployment:
* rename/disable any existing admin and create/update user `inkreach`.
*
* Usage (inside the api container): node scripts/set-admin.mjs
* Reads NEW_ADMIN_USER / NEW_ADMIN_PASSWORD from env.
*/
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcrypt';
const prisma = new PrismaClient();
async function main() {
const username = process.env.NEW_ADMIN_USER;
const password = process.env.NEW_ADMIN_PASSWORD;
if (!username || !password) {
console.error('NEW_ADMIN_USER / NEW_ADMIN_PASSWORD must be set');
process.exit(1);
}
const passwordHash = await bcrypt.hash(password, 10);
await prisma.user.upsert({
where: { username },
create: { username, passwordHash },
update: { passwordHash, tokenVersion: { increment: 1 } },
});
// Remove every other admin so only `inkreach` can sign in.
const others = await prisma.user.deleteMany({
where: { username: { not: username } },
});
const total = await prisma.user.count();
console.log(`Admin '${username}' set. Demoted ${others.count} other user(s). Total users: ${total}.`);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(() => prisma.$disconnect());
+25
View File
@@ -1,7 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { PrismaModule } from './prisma/prisma.module'; import { PrismaModule } from './prisma/prisma.module';
import { AuthModule } from './auth/auth.module'; import { AuthModule } from './auth/auth.module';
import { RolesGuard } from './auth/guards/roles.guard';
import { CountriesModule } from './countries/countries.module'; import { CountriesModule } from './countries/countries.module';
import { CategoriesModule } from './categories/categories.module'; import { CategoriesModule } from './categories/categories.module';
import { TagsModule } from './tags/tags.module'; import { TagsModule } from './tags/tags.module';
@@ -11,12 +14,21 @@ import { OriginGoodsModule } from './origin-goods/origin-goods.module';
import { GoodsModule } from './goods/goods.module'; import { GoodsModule } from './goods/goods.module';
import { SyncModule } from './sync/sync.module'; import { SyncModule } from './sync/sync.module';
import { PublicModule } from './public/public.module'; import { PublicModule } from './public/public.module';
import { UploadModule } from './upload/upload.module';
@Module({ @Module({
imports: [ imports: [
ConfigModule.forRoot({ ConfigModule.forRoot({
isGlobal: true, isGlobal: true,
}), }),
// Global rate limiting: 120 req/min per IP. Stricter limits are set
// per-endpoint with @Throttle (auth, upload).
ThrottlerModule.forRoot([
{
ttl: 60_000,
limit: Number(process.env.THROTTLE_LIMIT ?? 120),
},
]),
PrismaModule, PrismaModule,
AuthModule, AuthModule,
CountriesModule, CountriesModule,
@@ -28,6 +40,19 @@ import { PublicModule } from './public/public.module';
GoodsModule, GoodsModule,
SyncModule, SyncModule,
PublicModule, PublicModule,
UploadModule,
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
{
// Enforces the ADMIN role on every authenticated route unless the
// route widens access with @Roles(...).
provide: APP_GUARD,
useClass: RolesGuard,
},
], ],
}) })
export class AppModule {} export class AppModule {}
+108 -13
View File
@@ -1,16 +1,28 @@
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { import {
ApiOperation, Body,
ApiResponse, Controller,
ApiTags, Get,
} from '@nestjs/swagger'; HttpCode,
HttpStatus,
Post,
Req,
Res,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { LoginDto } from './dto/login.dto'; import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto'; import { RegisterDto } from './dto/register.dto';
import { import { LoginResponseDto, UserPublicDto } from './dto/auth-response.dto';
LoginResponseDto, import type { AuthenticatedUser } from './strategies/jwt.strategy';
UserPublicDto,
} from './dto/auth-response.dto'; const ACCESS_TOKEN_COOKIE = 'ir_at';
const REFRESH_TOKEN_COOKIE = 'ir_rt';
const isProd = process.env.NODE_ENV === 'production';
@ApiTags('auth') @ApiTags('auth')
@Controller('auth') @Controller('auth')
@@ -19,19 +31,102 @@ export class AuthController {
@Post('register') @Post('register')
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Register a new admin user' }) @Throttle({ default: { limit: 5, ttl: 60_000 } })
@ApiOperation({ summary: 'Register the first admin user (bootstrap only)' })
@ApiResponse({ status: 201, type: UserPublicDto }) @ApiResponse({ status: 201, type: UserPublicDto })
@ApiResponse({ status: 409, description: 'Username already exists' }) @ApiResponse({ status: 409, description: 'Username already exists' })
@ApiResponse({ status: 403, description: 'Registration is disabled once a user exists' })
register(@Body() dto: RegisterDto): Promise<UserPublicDto> { register(@Body() dto: RegisterDto): Promise<UserPublicDto> {
return this.authService.register(dto) as unknown as Promise<UserPublicDto>; return this.authService.register(dto) as unknown as Promise<UserPublicDto>;
} }
@Post('login') @Post('login')
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Login and obtain a JWT' }) @Throttle({ default: { limit: 5, ttl: 60_000 } })
@ApiOperation({ summary: 'Login and obtain access + refresh tokens' })
@ApiResponse({ status: 200, type: LoginResponseDto }) @ApiResponse({ status: 200, type: LoginResponseDto })
@ApiResponse({ status: 401, description: 'Invalid credentials' }) @ApiResponse({ status: 401, description: 'Invalid credentials' })
login(@Body() dto: LoginDto): Promise<LoginResponseDto> { async login(
return this.authService.login(dto) as unknown as Promise<LoginResponseDto>; @Body() dto: LoginDto,
@Res({ passthrough: true }) res: Response,
): Promise<LoginResponseDto> {
const result = await this.authService.login(dto);
// HttpOnly cookies are the primary session channel for the admin SPA
// (XSS cannot read them). The access token is also returned in the
// body for non-browser API clients.
res.cookie(ACCESS_TOKEN_COOKIE, result.accessToken, {
httpOnly: true,
sameSite: 'lax',
secure: isProd,
path: '/',
});
res.cookie(REFRESH_TOKEN_COOKIE, result.refreshToken, {
httpOnly: true,
sameSite: 'lax',
secure: isProd,
// Only ever sent to /auth/refresh and /auth/logout
path: '/auth',
});
// The refresh token deliberately stays HttpOnly-only.
return {
accessToken: result.accessToken,
user: result.user,
} as unknown as LoginResponseDto;
}
@Post('refresh')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 10, ttl: 60_000 } })
@ApiOperation({ summary: 'Rotate the refresh token cookie' })
@ApiResponse({ status: 200, type: LoginResponseDto })
@ApiResponse({ status: 401, description: 'Invalid refresh token' })
async refresh(
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
): Promise<LoginResponseDto> {
const token = req.cookies?.[REFRESH_TOKEN_COOKIE];
if (!token) {
res.clearCookie(REFRESH_TOKEN_COOKIE, { path: '/auth' });
throw new UnauthorizedException('Missing refresh token');
}
const result = await this.authService.refresh(token);
res.cookie(ACCESS_TOKEN_COOKIE, result.accessToken, {
httpOnly: true,
sameSite: 'lax',
secure: isProd,
path: '/',
});
res.cookie(REFRESH_TOKEN_COOKIE, result.refreshToken, {
httpOnly: true,
sameSite: 'lax',
secure: isProd,
path: '/auth',
});
return {
accessToken: result.accessToken,
user: result.user,
} as unknown as LoginResponseDto;
}
@Get('me')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Current authenticated user' })
@ApiResponse({ status: 200, type: UserPublicDto })
me(@Req() req: Request & { user: AuthenticatedUser }): Promise<UserPublicDto> {
return this.authService.me(req.user.id) as unknown as Promise<UserPublicDto>;
}
@Post('logout')
@HttpCode(HttpStatus.OK)
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Revoke all tokens of the current user' })
async logout(
@Req() req: Request & { user: AuthenticatedUser },
@Res({ passthrough: true }) res: Response,
): Promise<{ success: true }> {
await this.authService.logout(req.user.id);
res.clearCookie(ACCESS_TOKEN_COOKIE, { path: '/' });
res.clearCookie(REFRESH_TOKEN_COOKIE, { path: '/auth' });
return { success: true };
} }
} }
+6 -1
View File
@@ -17,9 +17,14 @@ import { JwtStrategy } from './strategies/jwt.strategy';
if (!secret) { if (!secret) {
throw new Error('JWT_SECRET must be configured'); throw new Error('JWT_SECRET must be configured');
} }
if (secret.length < 32) {
throw new Error('JWT_SECRET must be at least 32 characters (use a strong random value)');
}
return { return {
secret, secret,
signOptions: { expiresIn: '7d' }, signOptions: {
expiresIn: config.get<string>('TOKEN_EXPIRES_IN') ?? '7d',
},
}; };
}, },
}), }),
+119 -54
View File
@@ -1,102 +1,167 @@
import { Test } from '@nestjs/testing'; import { Test } from '@nestjs/testing';
import { JwtModule } from '@nestjs/jwt'; import { JwtModule, JwtService } from '@nestjs/jwt';
import { ConfigModule } from '@nestjs/config'; import { ConflictException, ForbiddenException, UnauthorizedException } from '@nestjs/common';
import { ConflictException, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
describe('AuthService', () => { describe('AuthService', () => {
let service: AuthService; let service: AuthService;
let prisma: PrismaService; let jwt: JwtService;
const createdUsernames: string[] = []; let prisma: {
user: {
count: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
};
const HASH = bcrypt.hashSync('plain-pwd', 10);
const dbUser = {
id: 1n,
username: 'alice',
passwordHash: HASH,
role: 'ADMIN' as const,
tokenVersion: 0,
createdAt: new Date('2026-01-01T00:00:00Z'),
};
beforeAll(async () => { beforeAll(async () => {
prisma = {
user: {
count: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
};
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
imports: [ imports: [
ConfigModule.forRoot({ isGlobal: true }),
JwtModule.register({ JwtModule.register({
secret: 'test-secret', secret: 'a'.repeat(32),
signOptions: { expiresIn: '1h' }, signOptions: { expiresIn: '1h' },
}), }),
], ],
providers: [AuthService, PrismaService], providers: [AuthService, { provide: PrismaService, useValue: prisma }],
}).compile(); }).compile();
service = moduleRef.get(AuthService); service = moduleRef.get(AuthService);
prisma = moduleRef.get(PrismaService); jwt = moduleRef.get(JwtService);
await prisma.onModuleInit();
}); });
afterAll(async () => { beforeEach(() => {
// Cleanup created test users jest.clearAllMocks();
if (createdUsernames.length) {
await prisma.user.deleteMany({
where: { username: { in: createdUsernames } },
});
}
await prisma.onModuleDestroy();
});
it('should be defined', () => {
expect(service).toBeDefined();
}); });
describe('register', () => { describe('register', () => {
it('creates a new user and stores a hashed password', async () => { it('creates the first user with a hashed password', async () => {
const username = `test_reg_${Date.now()}`; prisma.user.count.mockResolvedValueOnce(0);
createdUsernames.push(username); prisma.user.findUnique.mockResolvedValueOnce(null);
prisma.user.create.mockResolvedValueOnce(dbUser);
const user = await service.register({ username, password: 'plain-pwd' }); const user = await service.register({ username: 'alice', password: 'plain-pwd' });
expect(user.username).toBe(username); expect(user.username).toBe('alice');
expect(user.id).toBeTruthy(); const created = prisma.user.create.mock.calls[0][0].data;
expect(created.passwordHash).not.toBe('plain-pwd');
await expect(bcrypt.compare('plain-pwd', created.passwordHash)).resolves.toBe(true);
});
const stored = await prisma.user.findUnique({ where: { username } }); it('refuses registration once a user exists (bootstrap lock)', async () => {
expect(stored).not.toBeNull(); prisma.user.count.mockResolvedValueOnce(1);
expect(stored?.passwordHash).not.toBe('plain-pwd'); await expect(
const matches = await bcrypt.compare('plain-pwd', stored!.passwordHash); service.register({ username: 'mallory', password: 'evil-pwd' }),
expect(matches).toBe(true); ).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.create).not.toHaveBeenCalled();
}); });
it('throws ConflictException for duplicate usernames', async () => { it('throws ConflictException for duplicate usernames', async () => {
const username = `test_dup_${Date.now()}`; prisma.user.count.mockResolvedValueOnce(0);
createdUsernames.push(username); prisma.user.findUnique.mockResolvedValueOnce(dbUser);
await service.register({ username, password: 'pwd1234' });
await expect( await expect(
service.register({ username, password: 'pwd5678' }), service.register({ username: 'alice', password: 'pwd5678' }),
).rejects.toBeInstanceOf(ConflictException); ).rejects.toBeInstanceOf(ConflictException);
}); });
}); });
describe('login', () => { describe('login', () => {
it('returns an access token for valid credentials', async () => { it('returns access + refresh tokens with tokenVersion and type', async () => {
const username = `test_login_${Date.now()}`; prisma.user.findUnique.mockResolvedValueOnce(dbUser);
createdUsernames.push(username); const result = await service.login({ username: 'alice', password: 'plain-pwd' });
await service.register({ username, password: 'correct-pwd' });
const result = await service.login({ username, password: 'correct-pwd' }); expect(result.user.username).toBe('alice');
expect(result.accessToken).toEqual(expect.any(String)); const access = jwt.decode(result.accessToken) as Record<string, unknown>;
const parts = result.accessToken.split('.'); expect(access.typ).toBe('access');
expect(parts.length).toBe(3); expect(access.tv).toBe(0);
expect(result.user.username).toBe(username); const refresh = jwt.decode(result.refreshToken) as Record<string, unknown>;
expect(refresh.typ).toBe('refresh');
expect(refresh.tv).toBe(0);
}); });
it('throws UnauthorizedException for wrong password', async () => { it('throws UnauthorizedException for wrong password', async () => {
const username = `test_wrong_${Date.now()}`; prisma.user.findUnique.mockResolvedValueOnce(dbUser);
createdUsernames.push(username);
await service.register({ username, password: 'right-pwd' });
await expect( await expect(
service.login({ username, password: 'wrong-pwd' }), service.login({ username: 'alice', password: 'wrong-pwd' }),
).rejects.toBeInstanceOf(UnauthorizedException); ).rejects.toBeInstanceOf(UnauthorizedException);
}); });
it('throws UnauthorizedException for unknown user', async () => { it('throws UnauthorizedException for unknown user', async () => {
prisma.user.findUnique.mockResolvedValueOnce(null);
await expect( await expect(
service.login({ username: 'no-such-user-xyz', password: 'whatever' }), service.login({ username: 'no-such-user', password: 'whatever' }),
).rejects.toBeInstanceOf(UnauthorizedException); ).rejects.toBeInstanceOf(UnauthorizedException);
}); });
}); });
describe('refresh', () => {
it('rotates a valid refresh token', async () => {
const refreshToken = await jwt.signAsync({
sub: '1',
username: 'alice',
role: 'ADMIN',
tv: 0,
typ: 'refresh',
});
prisma.user.findUnique.mockResolvedValueOnce(dbUser);
const result = await service.refresh(refreshToken);
expect(result.user.username).toBe('alice');
expect(result.accessToken).not.toBe(refreshToken);
});
it('rejects access tokens used as refresh tokens', async () => {
const accessToken = await jwt.signAsync({
sub: '1',
username: 'alice',
role: 'ADMIN',
tv: 0,
typ: 'access',
});
await expect(service.refresh(accessToken)).rejects.toBeInstanceOf(UnauthorizedException);
});
it('rejects refresh tokens with a stale tokenVersion (revoked)', async () => {
const refreshToken = await jwt.signAsync({
sub: '1',
username: 'alice',
role: 'ADMIN',
tv: 0,
typ: 'refresh',
});
// User logged out elsewhere: tokenVersion bumped to 1
prisma.user.findUnique.mockResolvedValueOnce({ ...dbUser, tokenVersion: 1 });
await expect(service.refresh(refreshToken)).rejects.toBeInstanceOf(UnauthorizedException);
});
});
describe('logout', () => {
it('bumps tokenVersion to revoke all tokens', async () => {
prisma.user.update.mockResolvedValueOnce({ ...dbUser, tokenVersion: 1 });
await service.logout(1n);
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: 1n },
data: { tokenVersion: { increment: 1 } },
});
});
});
}); });
+108 -12
View File
@@ -1,5 +1,6 @@
import { import {
ConflictException, ConflictException,
ForbiddenException,
Injectable, Injectable,
UnauthorizedException, UnauthorizedException,
} from '@nestjs/common'; } from '@nestjs/common';
@@ -13,16 +14,25 @@ import type { JwtPayload } from './strategies/jwt.strategy';
export interface PublicUser { export interface PublicUser {
id: string; id: string;
username: string; username: string;
role: string;
createdAt: string; createdAt: string;
} }
export interface LoginResult { export interface LoginResult {
accessToken: string; accessToken: string;
refreshToken: string;
user: PublicUser; user: PublicUser;
} }
const BCRYPT_ROUNDS = 10; const BCRYPT_ROUNDS = 10;
const TOKEN_EXPIRES_IN = '7d'; const ACCESS_TOKEN_EXPIRES_IN = process.env.TOKEN_EXPIRES_IN ?? '30m';
const REFRESH_TOKEN_EXPIRES_IN = process.env.REFRESH_TOKEN_EXPIRES_IN ?? '7d';
/**
* Compared against when the username does not exist so that login takes
* the same time either way (prevents user enumeration via timing).
*/
const DUMMY_HASH = '$2b$10$l232BFW3u63Mhfx0BatxUOLtw.qEofG9fNYjLsh2zce7MdIKDAIR6';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
@@ -32,10 +42,15 @@ export class AuthService {
) {} ) {}
/** /**
* Registers a brand-new admin user. Throws {@link ConflictException} * Bootstrap-only registration: allowed just while the instance has no
* if the username is already taken. * users. Once an admin exists the endpoint refuses to create accounts
* (use database seeding / an operator flow instead).
*/ */
async register(dto: RegisterDto): Promise<PublicUser> { async register(dto: RegisterDto): Promise<PublicUser> {
const userCount = await this.prisma.user.count();
if (userCount > 0) {
throw new ForbiddenException('Registration is disabled');
}
const existing = await this.prisma.user.findUnique({ const existing = await this.prisma.user.findUnique({
where: { username: dto.username }, where: { username: dto.username },
}); });
@@ -50,37 +65,118 @@ export class AuthService {
} }
/** /**
* Verifies credentials and returns a signed JWT. * Verifies credentials and returns signed access + refresh tokens.
* Both tokens embed the user's tokenVersion so bumping it on the user
* row (logout / revocation) invalidates them immediately.
*/ */
async login(dto: LoginDto): Promise<LoginResult> { async login(dto: LoginDto): Promise<LoginResult> {
const user = await this.prisma.user.findUnique({ const user = await this.prisma.user.findUnique({
where: { username: dto.username }, where: { username: dto.username },
}); });
// Always run a bcrypt compare (against a dummy hash when the user is
// unknown) so response timing cannot be used to enumerate usernames.
const ok = await bcrypt.compare(dto.password, user?.passwordHash ?? DUMMY_HASH);
if (!user || !ok) {
throw new UnauthorizedException('Invalid credentials');
}
return {
accessToken: await this.signAccessToken(user),
refreshToken: await this.signRefreshToken(user),
user: this.toPublic(user),
};
}
/**
* Rotates a refresh token: the old refresh token becomes invalid as
* soon as tokenVersion is bumped (logout, revocation).
*/
async refresh(refreshToken: string): Promise<LoginResult> {
let payload: JwtPayload;
try {
payload = await this.jwt.verifyAsync(refreshToken);
} catch {
throw new UnauthorizedException('Invalid refresh token');
}
if (payload.typ !== 'refresh') {
throw new UnauthorizedException('Invalid refresh token');
}
const user = await this.prisma.user
.findUnique({ where: { id: BigInt(payload.sub) } })
.catch(() => null);
if (!user || user.tokenVersion !== payload.tv) {
throw new UnauthorizedException('Invalid refresh token');
}
return {
accessToken: await this.signAccessToken(user),
refreshToken: await this.signRefreshToken(user),
user: this.toPublic(user),
};
}
/**
* Revokes all tokens of a user by bumping tokenVersion.
*/
async logout(userId: bigint): Promise<void> {
await this.prisma.user.update({
where: { id: userId },
data: { tokenVersion: { increment: 1 } },
});
}
async me(userId: bigint): Promise<PublicUser> {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) { if (!user) {
throw new UnauthorizedException('Invalid credentials'); throw new UnauthorizedException();
}
const ok = await bcrypt.compare(dto.password, user.passwordHash);
if (!ok) {
throw new UnauthorizedException('Invalid credentials');
} }
return this.toPublic(user);
}
private async signAccessToken(user: {
id: bigint;
username: string;
role: string;
tokenVersion: number;
}): Promise<string> {
const payload: JwtPayload = { const payload: JwtPayload = {
sub: user.id.toString(), sub: user.id.toString(),
username: user.username, username: user.username,
role: user.role,
tv: user.tokenVersion,
typ: 'access',
}; };
const accessToken = await this.jwt.signAsync(payload, { return this.jwt.signAsync(payload, {
expiresIn: TOKEN_EXPIRES_IN, expiresIn: ACCESS_TOKEN_EXPIRES_IN,
});
}
private async signRefreshToken(user: {
id: bigint;
username: string;
role: string;
tokenVersion: number;
}): Promise<string> {
const payload: JwtPayload = {
sub: user.id.toString(),
username: user.username,
role: user.role,
tv: user.tokenVersion,
typ: 'refresh',
};
return this.jwt.signAsync(payload, {
expiresIn: REFRESH_TOKEN_EXPIRES_IN,
}); });
return { accessToken, user: this.toPublic(user) };
} }
private toPublic(user: { private toPublic(user: {
id: bigint; id: bigint;
username: string; username: string;
role: string;
createdAt: Date; createdAt: Date;
}): PublicUser { }): PublicUser {
return { return {
id: user.id.toString(), id: user.id.toString(),
username: user.username, username: user.username,
role: user.role,
createdAt: user.createdAt.toISOString(), createdAt: user.createdAt.toISOString(),
}; };
} }
@@ -0,0 +1,9 @@
import { SetMetadata } from '@nestjs/common';
export const ROLES_KEY = 'roles';
/**
* Restricts a route to the given roles. When omitted, any
* authenticated user with an ADMIN role passes the RolesGuard.
*/
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
@@ -0,0 +1,32 @@
import { ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RolesGuard } from './roles.guard';
describe('RolesGuard', () => {
let guard: RolesGuard;
beforeEach(() => {
guard = new RolesGuard(new Reflector());
});
const context = (user: unknown, roles?: string[]) =>
({
switchToHttp: () => ({ getRequest: () => ({ user }) }),
getHandler: () => (roles ? { __roles: roles } : {}),
getClass: () => ({}),
}) as never;
it('passes public routes (no authenticated user)', () => {
expect(guard.canActivate(context(undefined))).toBe(true);
});
it('passes ADMIN users by default', () => {
expect(guard.canActivate(context({ id: 1n, username: 'a', role: 'ADMIN' }))).toBe(true);
});
it('blocks users without the ADMIN role', () => {
expect(() => guard.canActivate(context({ id: 1n, username: 'a', role: 'VIEWER' }))).toThrow(
ForbiddenException,
);
});
});
+33
View File
@@ -0,0 +1,33 @@
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
import type { AuthenticatedUser } from '../strategies/jwt.strategy';
/**
* Role-based access control. Applied globally: any authenticated user
* reaching a protected route must hold the ADMIN role unless the route
* declares a wider set with @Roles(...). Routes without a JwtAuthGuard
* (public endpoints) have no `request.user` and are skipped here — their
* openness is decided by the controller's own guards.
*/
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<{
user?: AuthenticatedUser;
}>();
if (!request.user) {
return true; // public route — no JwtAuthGuard in front
}
const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]) ?? ['ADMIN'];
if (!required.includes(request.user.role)) {
throw new ForbiddenException('Insufficient role');
}
return true;
}
}
+46 -5
View File
@@ -2,26 +2,51 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport'; import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt'; import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../prisma/prisma.service';
export const ACCESS_TOKEN_COOKIE = 'ir_at';
export interface AuthenticatedUser {
id: bigint;
username: string;
role: string;
}
/** /**
* Shape of the JWT we issue. * Shape of the JWT we issue.
* *
* `sub` is the user ID as a string (bigints are serialized to strings in JSON). * `sub` is the user ID as a string (bigints are serialized to strings in JSON).
* `typ` distinguishes access tokens from refresh tokens; `tv` is the user's
* tokenVersion and `role` drives the RolesGuard.
*/ */
export interface JwtPayload { export interface JwtPayload {
sub: string; sub: string;
username: string; username: string;
role?: string;
tv?: number;
typ?: 'access' | 'refresh';
} }
@Injectable() @Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) { export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService) { constructor(
config: ConfigService,
private readonly prisma: PrismaService,
) {
const secret = config.get<string>('JWT_SECRET'); const secret = config.get<string>('JWT_SECRET');
if (!secret) { if (!secret) {
throw new Error('JWT_SECRET is not configured'); throw new Error('JWT_SECRET is not configured');
} }
if (secret.length < 32) {
throw new Error('JWT_SECRET must be at least 32 characters');
}
super({ super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // Access tokens are accepted from the HttpOnly cookie (browser) or
// the Authorization header (non-browser API clients).
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
(req) => req?.cookies?.[ACCESS_TOKEN_COOKIE] ?? null,
]),
ignoreExpiration: false, ignoreExpiration: false,
secretOrKey: secret, secretOrKey: secret,
}); });
@@ -29,12 +54,28 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
/** /**
* Runs on every authenticated request. The returned object becomes * Runs on every authenticated request. The returned object becomes
* `request.user` for downstream controllers. * `request.user` for downstream controllers. The user and its
* tokenVersion are re-checked in the database so tokens of deleted
* users, logged-out users, or refresh tokens stop working immediately.
*/ */
validate(payload: JwtPayload): { id: bigint; username: string } { async validate(payload: JwtPayload): Promise<AuthenticatedUser> {
if (!payload?.sub || !payload.username) { if (!payload?.sub || !payload.username) {
throw new UnauthorizedException('Invalid token payload'); throw new UnauthorizedException('Invalid token payload');
} }
return { id: BigInt(payload.sub), username: payload.username }; // Refresh tokens must never be accepted as API credentials.
if (payload.typ === 'refresh') {
throw new UnauthorizedException('Invalid token type');
}
const user = await this.prisma.user
.findUnique({ where: { id: BigInt(payload.sub) } })
.catch(() => null);
if (
!user ||
user.username !== payload.username ||
(payload.tv !== undefined && user.tokenVersion !== payload.tv)
) {
throw new UnauthorizedException('Invalid token');
}
return { id: user.id, username: user.username, role: user.role };
} }
} }
@@ -32,9 +32,24 @@ export class HttpExceptionFilter implements ExceptionFilter {
const request = ctx.getRequest<Request>(); const request = ctx.getRequest<Request>();
const status = const status =
exception instanceof HttpException exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR; // Malformed bigint/number inputs (e.g. `BigInt("abc")`) are client
// errors — map them to 400 instead of leaking a 500.
if (
status === HttpStatus.INTERNAL_SERVER_ERROR &&
exception instanceof Error &&
/Cannot convert .+ to (a BigInt|number)/i.test(exception.message)
) {
response.status(HttpStatus.BAD_REQUEST).json({
statusCode: HttpStatus.BAD_REQUEST,
message: 'Invalid numeric identifier',
error: 'BadRequestError',
timestamp: new Date().toISOString(),
path: request.url,
});
return;
}
let message: string | string[] = 'Internal server error'; let message: string | string[] = 'Internal server error';
let error = 'InternalServerError'; let error = 'InternalServerError';
@@ -51,11 +66,15 @@ export class HttpExceptionFilter implements ExceptionFilter {
message = exception.message; message = exception.message;
} }
} else if (exception instanceof Error) { } else if (exception instanceof Error) {
message = exception.message; // Unexpected errors (Prisma, driver, ...) may contain SQL or
error = exception.name; // connection details — never send them to the client.
this.logger.error(
`${request.method} ${request.url} -> ${status} ${exception.message}`,
exception.stack,
);
} }
if (status >= 500) { if (status >= 500 && exception instanceof HttpException) {
this.logger.error( this.logger.error(
`${request.method} ${request.url} -> ${status} ${message}`, `${request.method} ${request.url} -> ${status} ${message}`,
exception instanceof Error ? exception.stack : undefined, exception instanceof Error ? exception.stack : undefined,
@@ -15,6 +15,13 @@ export class BatchCreateItemDto {
@Min(1) @Min(1)
originGoodId!: number; originGoodId!: number;
@ApiProperty({ required: false, nullable: true, type: [Number], description: '副源原产品 ID,不含主源' })
@IsOptional()
@IsArray()
@IsInt({ each: true })
@Min(1, { each: true })
mergedOriginGoodIds?: number[];
@ApiProperty({ required: false }) @ApiProperty({ required: false })
@IsOptional() @IsOptional()
@IsInt() @IsInt()
@@ -20,6 +20,13 @@ export class CreateGoodDto {
@Min(1) @Min(1)
originGoodId!: number; originGoodId!: number;
@ApiProperty({ required: false, nullable: true, type: [Number], description: '副源原产品 ID,不含主源' })
@IsOptional()
@IsArray()
@IsInt({ each: true })
@Min(1, { each: true })
mergedOriginGoodIds?: number[];
@ApiProperty() @ApiProperty()
@IsInt() @IsInt()
@Min(1) @Min(1)
+236
View File
@@ -0,0 +1,236 @@
import { ApiProperty, OmitType, PartialType } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
IsArray,
IsBoolean,
IsInt,
IsNumberString,
IsObject,
IsOptional,
IsString,
Min,
ValidateNested,
} from 'class-validator';
import { CreateGoodDto } from './create-good.dto';
export class CustomGoodDetailDto {
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
productCode?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
englishName?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
blankDesignUrl?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
detailsPageVideoUrl?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
textureName?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsInt()
@Min(0)
productionCycleHours?: number | null;
@ApiProperty({ required: false, nullable: true, example: '208.000' })
@IsOptional()
@IsNumberString()
minWeightG?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
productionProcess?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
materialDescription?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
reminder?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
productPerformance?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
applicableScenarios?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
washingInstructions?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
specialDescription?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
designExplanation?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
designArea?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
pictureRequest?: string | null;
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
sizeChart?: Record<string, unknown> | null;
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
packageSpecs?: Record<string, unknown> | null;
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
options?: Record<string, unknown> | null;
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
media?: Record<string, unknown> | null;
}
export class CustomGoodVariantDto {
@ApiProperty()
@IsString()
sku!: string;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
sizeName?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
sizeId?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
colorName?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
colorHex?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
colorId?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsString()
imageUrl?: string | null;
@ApiProperty({ required: false, nullable: true, example: '28.00' })
@IsOptional()
@IsNumberString()
price?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsNumberString()
originalPrice?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsNumberString()
weightG?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsNumberString()
boxLengthCm?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsNumberString()
boxWidthCm?: string | null;
@ApiProperty({ required: false, nullable: true })
@IsOptional()
@IsNumberString()
boxHeightCm?: string | null;
@ApiProperty({ required: false, nullable: true, type: Object })
@IsOptional()
@IsObject()
designData?: Record<string, unknown> | null;
@ApiProperty({ required: false, default: true })
@IsOptional()
@IsBoolean()
enabled?: boolean;
@ApiProperty({ required: false, default: 0 })
@IsOptional()
@IsInt()
@Min(0)
sortOrder?: number;
}
export class CreateCustomGoodDto extends OmitType(CreateGoodDto, [
'originGoodId',
] as const) {
@ApiProperty({ required: false, nullable: true, example: '28.00' })
@IsOptional()
@IsNumberString()
goodPrice?: string | null;
@ApiProperty({ required: false, type: CustomGoodDetailDto })
@IsOptional()
@ValidateNested()
@Type(() => CustomGoodDetailDto)
detail?: CustomGoodDetailDto;
@ApiProperty({ required: false, type: [CustomGoodVariantDto] })
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => CustomGoodVariantDto)
variants?: CustomGoodVariantDto[];
}
export class UpdateCustomGoodContentDto extends PartialType(
OmitType(CreateCustomGoodDto, [
'countryId',
'categoryId',
'tagIds',
'positionId',
'goodPriority',
] as const),
) {}
+131
View File
@@ -9,11 +9,55 @@ export interface GoodRelations {
originGood?: { originGood?: {
id: bigint; id: bigint;
sdsGoodId: string; sdsGoodId: string;
source: 'SDS' | 'CUSTOM';
goodName: string | null; goodName: string | null;
goodImage: string | null; goodImage: string | null;
goodPrice: unknown; goodPrice: unknown;
detail?: {
productCode: string | null;
syncedAt: Date;
sizeChart: unknown;
packageSpecs: unknown;
[key: string]: unknown;
} | null;
variants?: Array<{
sdsVariantId: string;
sku: string;
sizeName: string | null;
colorName: string | null;
colorHex: string | null;
price: unknown;
enabled: boolean;
[key: string]: unknown;
}>;
_count?: { variants: number };
} | null; } | null;
goodTags?: { tag: { id: bigint; tagName: string; tagColor: string | null; tagFontColor: string | null } }[]; goodTags?: { tag: { id: bigint; tagName: string; tagColor: string | null; tagFontColor: string | null } }[];
mergedOriginGoods?: Array<{
originGood: {
id: bigint;
sdsGoodId: string;
source: 'SDS' | 'CUSTOM';
goodName: string | null;
goodImage: string | null;
goodPrice: unknown;
detail?: { syncedAt: Date } | Record<string, unknown> | null;
variants?: Array<{ [key: string]: unknown }>;
_count?: { variants: number };
};
}>;
}
export interface MergedOriginGoodSummary {
id: string;
sdsGoodId: string;
source: 'SDS' | 'CUSTOM';
isCustom: boolean;
goodName: string | null;
goodImage: string | null;
goodPrice: string | null;
hasDetail: boolean;
variantCount: number;
} }
export class GoodDto { export class GoodDto {
@@ -62,6 +106,9 @@ export class GoodDto {
@ApiProperty({ required: false, type: Array }) @ApiProperty({ required: false, type: Array })
tags!: Array<{ id: string; tagName: string; tagColor: string | null; tagFontColor: string | null }>; tags!: Array<{ id: string; tagName: string; tagColor: string | null; tagFontColor: string | null }>;
@ApiProperty({ required: false, type: Array })
mergedOriginGoods!: MergedOriginGoodSummary[];
@ApiProperty({ required: false, nullable: true }) @ApiProperty({ required: false, nullable: true })
position?: { id: string; indexVal: number } | null; position?: { id: string; indexVal: number } | null;
@@ -69,9 +116,17 @@ export class GoodDto {
originGood?: { originGood?: {
id: string; id: string;
sdsGoodId: string; sdsGoodId: string;
source: 'SDS' | 'CUSTOM';
isCustom: boolean;
goodName: string | null; goodName: string | null;
goodImage: string | null; goodImage: string | null;
goodPrice: string | null; goodPrice: string | null;
hasDetail: boolean;
detailSyncedAt: string | null;
variantCount: number;
sizeRowCount: number;
packageRowCount: number;
productCode: string | null;
} | null; } | null;
static from( static from(
@@ -120,6 +175,21 @@ export class GoodDto {
tagFontColor: gt.tag.tagFontColor, tagFontColor: gt.tag.tagFontColor,
})) }))
: [], : [],
mergedOriginGoods: (rel.mergedOriginGoods ?? []).map((m) => ({
id: m.originGood.id.toString(),
sdsGoodId: m.originGood.sdsGoodId,
source: m.originGood.source,
isCustom: m.originGood.source === 'CUSTOM',
goodName: m.originGood.goodName,
goodImage: m.originGood.goodImage,
goodPrice:
m.originGood.goodPrice === null || m.originGood.goodPrice === undefined
? null
: (m.originGood.goodPrice as { toString(): string }).toString(),
hasDetail: Boolean(m.originGood.detail),
variantCount:
m.originGood._count?.variants ?? m.originGood.variants?.length ?? 0,
})),
position: rel.position position: rel.position
? { ? {
id: rel.position.id.toString(), id: rel.position.id.toString(),
@@ -130,6 +200,8 @@ export class GoodDto {
? { ? {
id: rel.originGood.id.toString(), id: rel.originGood.id.toString(),
sdsGoodId: rel.originGood.sdsGoodId, sdsGoodId: rel.originGood.sdsGoodId,
source: rel.originGood.source,
isCustom: rel.originGood.source === 'CUSTOM',
goodName: rel.originGood.goodName, goodName: rel.originGood.goodName,
goodImage: rel.originGood.goodImage, goodImage: rel.originGood.goodImage,
goodPrice: goodPrice:
@@ -137,10 +209,69 @@ export class GoodDto {
rel.originGood.goodPrice === undefined rel.originGood.goodPrice === undefined
? null ? null
: (rel.originGood.goodPrice as { toString(): string }).toString(), : (rel.originGood.goodPrice as { toString(): string }).toString(),
hasDetail: Boolean(rel.originGood.detail),
detailSyncedAt: rel.originGood.detail?.syncedAt.toISOString() ?? null,
variantCount: rel.originGood._count?.variants ?? rel.originGood.variants?.length ?? 0,
sizeRowCount: GoodDto.jsonRows(rel.originGood.detail?.sizeChart),
packageRowCount: GoodDto.jsonRows(rel.originGood.detail?.packageSpecs),
productCode: rel.originGood.detail?.productCode ?? null,
} }
: null, : null,
}; };
} }
private static jsonRows(value: unknown): number {
if (!value || typeof value !== 'object' || !('rows' in value)) return 0;
const rows = (value as { rows?: unknown }).rows;
return Array.isArray(rows) ? rows.length : 0;
}
}
export class GoodDetailDto extends GoodDto {
@ApiProperty({ nullable: true, type: Object })
originDetail!: Record<string, unknown> | null;
@ApiProperty({ type: Array })
variants!: Array<Record<string, unknown>>;
static fromGood(good: PrismaGood, rel: GoodRelations): GoodDetailDto {
const base = GoodDto.from(good, rel);
const detail = rel.originGood?.detail;
const toAnnotated = (
variant: Record<string, unknown>,
originGoodId: string,
originGoodName: string | null,
) => ({
...variant,
price:
variant.price === null || variant.price === undefined
? null
: (variant.price as unknown as { toString(): string }).toString(),
originGoodId,
originGoodName,
});
const primaryId = good.originGoodId.toString();
const primaryName = rel.originGood?.goodName ?? null;
const mergedVariants = [
...(rel.originGood?.variants ?? []).map((variant) =>
toAnnotated(variant as Record<string, unknown>, primaryId, primaryName),
),
...(rel.mergedOriginGoods ?? []).flatMap((m) =>
(m.originGood.variants ?? []).map((variant) =>
toAnnotated(
variant,
m.originGood.id.toString(),
m.originGood.goodName,
),
),
),
];
return {
...base,
originDetail: detail ? { ...detail, syncedAt: detail.syncedAt.toISOString() } : null,
variants: mergedVariants,
};
}
} }
export interface PaginatedGoods { export interface PaginatedGoods {
+1 -1
View File
@@ -21,7 +21,7 @@ export class QueryGoodDto {
@Type(() => Number) @Type(() => Number)
@IsInt() @IsInt()
@Min(1) @Min(1)
@Max(200) @Max(1000)
pageSize: number = 20; pageSize: number = 20;
@ApiProperty({ required: false }) @ApiProperty({ required: false })
@@ -19,6 +19,13 @@ export class UpdateGoodDto {
@Min(1) @Min(1)
originGoodId?: number; originGoodId?: number;
@ApiProperty({ required: false, nullable: true, type: [Number], description: '副源原产品 ID 全量覆盖,不含主源' })
@IsOptional()
@IsArray()
@IsInt({ each: true })
@Min(1, { each: true })
mergedOriginGoodIds?: number[];
@ApiProperty({ required: false }) @ApiProperty({ required: false })
@IsOptional() @IsOptional()
@IsInt() @IsInt()
+37 -18
View File
@@ -22,6 +22,10 @@ import { UpdateGoodDto } from './dto/update-good.dto';
import { QueryGoodDto } from './dto/query-good.dto'; import { QueryGoodDto } from './dto/query-good.dto';
import { BatchCreateGoodDto } from './dto/batch-create-good.dto'; import { BatchCreateGoodDto } from './dto/batch-create-good.dto';
import { BatchPriorityDto } from './dto/batch-priority.dto'; import { BatchPriorityDto } from './dto/batch-priority.dto';
import {
CreateCustomGoodDto,
UpdateCustomGoodContentDto,
} from './dto/custom-good.dto';
@ApiTags('goods') @ApiTags('goods')
@ApiBearerAuth() @ApiBearerAuth()
@@ -36,18 +40,45 @@ export class GoodsController {
return this.service.findAll(query); return this.service.findAll(query);
} }
@Get(':id')
@ApiOperation({ summary: 'Get one good with relations' })
findOne(@Param('id', ParseIntPipe) id: string) {
return this.service.findOne(BigInt(id));
}
@Post() @Post()
@ApiOperation({ summary: 'Create a good' }) @ApiOperation({ summary: 'Create a good' })
create(@Body() dto: CreateGoodDto) { create(@Body() dto: CreateGoodDto) {
return this.service.create(dto); return this.service.create(dto);
} }
@Patch('batch-priority')
@ApiOperation({ summary: 'Batch update good priorities (transaction)' })
batchPriority(@Body() dto: BatchPriorityDto) {
return this.service.batchUpdatePriority(dto);
}
@Post('batch')
@ApiOperation({ summary: 'Batch create goods from origin goods (transaction)' })
batchCreate(@Body() dto: BatchCreateGoodDto) {
return this.service.batchCreate(dto);
}
@Post('custom')
@ApiOperation({ summary: 'Create a fully editable custom product' })
createCustom(@Body() dto: CreateCustomGoodDto) {
return this.service.createCustom(dto);
}
@Patch(':id/custom-content')
@ApiOperation({ summary: 'Update editable content for a custom product' })
updateCustomContent(
@Param('id', ParseIntPipe) id: string,
@Body() dto: UpdateCustomGoodContentDto,
) {
return this.service.updateCustomContent(BigInt(id), dto);
}
@Get(':id')
@ApiOperation({ summary: 'Get one good with relations' })
findOne(@Param('id', ParseIntPipe) id: string) {
return this.service.findOne(BigInt(id));
}
@Patch(':id') @Patch(':id')
@ApiOperation({ summary: 'Update a good' }) @ApiOperation({ summary: 'Update a good' })
update( update(
@@ -62,16 +93,4 @@ export class GoodsController {
remove(@Param('id', ParseIntPipe) id: string) { remove(@Param('id', ParseIntPipe) id: string) {
return this.service.remove(BigInt(id)); return this.service.remove(BigInt(id));
} }
@Patch('batch-priority')
@ApiOperation({ summary: 'Batch update good priorities (transaction)' })
batchPriority(@Body() dto: BatchPriorityDto) {
return this.service.batchUpdatePriority(dto);
}
@Post('batch')
@ApiOperation({ summary: 'Batch create goods from origin goods (transaction)' })
batchCreate(@Body() dto: BatchCreateGoodDto) {
return this.service.batchCreate(dto);
}
} }
+2
View File
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { GoodsController } from './goods.controller'; import { GoodsController } from './goods.controller';
import { GoodsService } from './goods.service'; import { GoodsService } from './goods.service';
import { SyncModule } from '../sync/sync.module';
@Module({ @Module({
imports: [SyncModule],
controllers: [GoodsController], controllers: [GoodsController],
providers: [GoodsService], providers: [GoodsService],
exports: [GoodsService], exports: [GoodsService],
+183 -1
View File
@@ -5,6 +5,7 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { GoodsService } from './goods.service'; import { GoodsService } from './goods.service';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { SyncService } from '../sync/sync.service';
describe('GoodsService', () => { describe('GoodsService', () => {
let service: GoodsService; let service: GoodsService;
@@ -22,7 +23,14 @@ describe('GoodsService', () => {
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
providers: [GoodsService, PrismaService], providers: [
GoodsService,
PrismaService,
{
provide: SyncService,
useValue: { queueProductDetailSync: jest.fn() },
},
],
}).compile(); }).compile();
service = moduleRef.get(GoodsService); service = moduleRef.get(GoodsService);
prisma = moduleRef.get(PrismaService); prisma = moduleRef.get(PrismaService);
@@ -111,6 +119,51 @@ describe('GoodsService', () => {
expect(fetched.goodName).toBe(`Goods Test ${stamp} basic`); expect(fetched.goodName).toBe(`Goods Test ${stamp} basic`);
}); });
it('creates, edits, and removes a fully editable custom good', async () => {
const created = await service.createCustom({
goodName: `Goods Test ${stamp} custom`,
goodImage: 'https://example.com/custom.png',
goodPrice: '29.90',
countryId: Number(countryId),
categoryId: Number(categoryId),
tagIds: [Number(tagId)],
detail: {
productCode: `CUSTOM-${stamp}`,
materialDescription: 'Cotton',
sizeChart: { columns: [], rows: [] },
packageSpecs: { rows: [] },
},
variants: [
{ sku: `CUSTOM-SKU-${stamp}`, sizeName: 'S', price: '29.90' },
],
});
expect(created.originGood?.source).toBe('CUSTOM');
expect(created.originGood?.isCustom).toBe(true);
expect(created.originGood?.goodPrice).toBe('29.9');
expect(created.variants).toHaveLength(1);
const updated = await service.updateCustomContent(BigInt(created.id), {
goodName: `Goods Test ${stamp} custom edited`,
goodPrice: '39.90',
detail: { materialDescription: 'Organic cotton' },
variants: [
{ sku: `CUSTOM-SKU-${stamp}-M`, sizeName: 'M', price: '39.90' },
],
});
expect(updated.goodName).toContain('custom edited');
expect(updated.originGood?.goodPrice).toBe('39.9');
expect(updated.originDetail?.materialDescription).toBe('Organic cotton');
expect(updated.originDetail?.productCode).toBe(`CUSTOM-${stamp}`);
expect(updated.variants[0]?.sizeName).toBe('M');
const customOriginId = BigInt(updated.originGoodId);
await service.remove(BigInt(updated.id));
await expect(
prisma.originGood.findUnique({ where: { id: customOriginId } }),
).resolves.toBeNull();
});
it('filters by countryId, tagId, positionId and keyword', async () => { it('filters by countryId, tagId, positionId and keyword', async () => {
const result = await service.findAll({ const result = await service.findAll({
page: 1, page: 1,
@@ -208,6 +261,135 @@ describe('GoodsService', () => {
expect(after.total).toBe(before.total); expect(after.total).toBe(before.total);
}); });
describe('merged origin goods', () => {
it('creates a good with merged origin goods and reads them back', async () => {
const created = await service.create({
goodName: `Goods Test ${stamp} merged`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [Number(originGoodIds[2]), Number(originGoodIds[3])],
countryId: Number(countryId),
categoryId: Number(categoryId),
});
expect(created.mergedOriginGoods.map((m) => m.id).sort()).toEqual(
[originGoodIds[2].toString(), originGoodIds[3].toString()].sort(),
);
const fetched = await service.findOne(BigInt(created.id));
expect(fetched.mergedOriginGoods.length).toBe(2);
});
it('rejects mergedOriginGoodIds containing the primary', async () => {
await expect(
service.create({
goodName: `Goods Test ${stamp} bad-primary`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [Number(originGoodIds[1])],
countryId: Number(countryId),
categoryId: Number(categoryId),
}),
).rejects.toThrow(BadRequestException);
});
it('rejects mergedOriginGoodIds that do not exist', async () => {
await expect(
service.create({
goodName: `Goods Test ${stamp} bad-missing`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [999999999],
countryId: Number(countryId),
categoryId: Number(categoryId),
}),
).rejects.toThrow(BadRequestException);
});
it('replaces merged origin goods on update', async () => {
const created = await service.create({
goodName: `Goods Test ${stamp} replace`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [Number(originGoodIds[2])],
countryId: Number(countryId),
categoryId: Number(categoryId),
});
const updated = await service.update(BigInt(created.id), {
mergedOriginGoodIds: [Number(originGoodIds[3]), Number(originGoodIds[4])],
});
expect(updated.mergedOriginGoods.map((m) => m.id).sort()).toEqual(
[originGoodIds[3].toString(), originGoodIds[4].toString()].sort(),
);
});
it('moves old primary into merged list when switching primary', async () => {
const created = await service.create({
goodName: `Goods Test ${stamp} switch`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [Number(originGoodIds[2])],
countryId: Number(countryId),
categoryId: Number(categoryId),
});
const updated = await service.update(BigInt(created.id), {
originGoodId: Number(originGoodIds[2]),
mergedOriginGoodIds: [Number(originGoodIds[1]), Number(originGoodIds[3])],
});
expect(updated.originGoodId).toBe(originGoodIds[2].toString());
expect(updated.mergedOriginGoods.map((m) => m.id).sort()).toEqual(
[originGoodIds[1].toString(), originGoodIds[3].toString()].sort(),
);
});
it('cascades merged rows on good removal', async () => {
const created = await service.create({
goodName: `Goods Test ${stamp} cascade`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [Number(originGoodIds[2])],
countryId: Number(countryId),
categoryId: Number(categoryId),
});
await service.remove(BigInt(created.id));
const rows = await prisma.goodOriginGood.count({
where: { goodId: BigInt(created.id) },
});
expect(rows).toBe(0);
});
it('returns merged variants with source annotation in detail', async () => {
const v1 = await prisma.originGoodVariant.create({
data: {
originGoodId: originGoodIds[1],
sdsVariantId: `mv-pri-${stamp}`,
sku: `MV-PRI-${stamp}`,
colorName: '黑色',
},
});
const v2 = await prisma.originGoodVariant.create({
data: {
originGoodId: originGoodIds[2],
sdsVariantId: `mv-sec-${stamp}`,
sku: `MV-SEC-${stamp}`,
colorName: '白色',
},
});
try {
const created = await service.create({
goodName: `Goods Test ${stamp} variants`,
originGoodId: Number(originGoodIds[1]),
mergedOriginGoodIds: [Number(originGoodIds[2])],
countryId: Number(countryId),
categoryId: Number(categoryId),
});
const detail = await service.findOne(BigInt(created.id));
const sources = new Set(
detail.variants.map((v) => v['originGoodId'] as string),
);
expect(sources.has(originGoodIds[1].toString())).toBe(true);
expect(sources.has(originGoodIds[2].toString())).toBe(true);
expect(detail.variants).toHaveLength(2);
expect(detail.mergedOriginGoods.find((m) => m.id === originGoodIds[2].toString())?.variantCount).toBe(1);
} finally {
await prisma.originGoodVariant.delete({ where: { id: v1.id } });
await prisma.originGoodVariant.delete({ where: { id: v2.id } });
}
});
});
it('throws NotFoundException for unknown id', async () => { it('throws NotFoundException for unknown id', async () => {
await expect(service.findOne(BigInt(99999999))).rejects.toBeInstanceOf( await expect(service.findOne(BigInt(99999999))).rejects.toBeInstanceOf(
NotFoundException, NotFoundException,
+357 -11
View File
@@ -10,20 +10,49 @@ import { UpdateGoodDto } from './dto/update-good.dto';
import { QueryGoodDto } from './dto/query-good.dto'; import { QueryGoodDto } from './dto/query-good.dto';
import { BatchCreateGoodDto } from './dto/batch-create-good.dto'; import { BatchCreateGoodDto } from './dto/batch-create-good.dto';
import { BatchPriorityDto } from './dto/batch-priority.dto'; import { BatchPriorityDto } from './dto/batch-priority.dto';
import { GoodDto, PaginatedGoods } from './dto/good.dto'; import { GoodDetailDto, GoodDto, PaginatedGoods } from './dto/good.dto';
import { SyncService } from '../sync/sync.service';
import { randomUUID } from 'crypto';
import {
CreateCustomGoodDto,
CustomGoodDetailDto,
CustomGoodVariantDto,
UpdateCustomGoodContentDto,
} from './dto/custom-good.dto';
const GOOD_INCLUDE = { const GOOD_INCLUDE = {
country: true, country: true,
category: true, category: true,
tag: true, tag: true,
position: true, position: true,
originGood: true, originGood: {
include: {
detail: true,
variants: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }] },
_count: { select: { variants: true } },
},
},
goodTags: { include: { tag: true } }, goodTags: { include: { tag: true } },
mergedOriginGoods: {
orderBy: { createdAt: 'asc' },
include: {
originGood: {
include: {
detail: true,
variants: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }] },
_count: { select: { variants: true } },
},
},
},
},
} satisfies Prisma.GoodInclude; } satisfies Prisma.GoodInclude;
@Injectable() @Injectable()
export class GoodsService { export class GoodsService {
constructor(private readonly prisma: PrismaService) {} constructor(
private readonly prisma: PrismaService,
private readonly syncService: SyncService,
) {}
async findAll(query: QueryGoodDto): Promise<PaginatedGoods> { async findAll(query: QueryGoodDto): Promise<PaginatedGoods> {
const { page, pageSize, countryId, categoryId, tagId, positionId, keyword } = query; const { page, pageSize, countryId, categoryId, tagId, positionId, keyword } = query;
@@ -58,6 +87,7 @@ export class GoodsService {
position: g.position, position: g.position,
originGood: g.originGood, originGood: g.originGood,
goodTags: g.goodTags, goodTags: g.goodTags,
mergedOriginGoods: g.mergedOriginGoods,
})), })),
total, total,
page, page,
@@ -65,25 +95,31 @@ export class GoodsService {
}; };
} }
async findOne(id: bigint): Promise<GoodDto> { async findOne(id: bigint): Promise<GoodDetailDto> {
const good = await this.prisma.good.findUnique({ const good = await this.prisma.good.findUnique({
where: { id }, where: { id },
include: GOOD_INCLUDE, include: GOOD_INCLUDE,
}); });
if (!good) throw new NotFoundException(`Good ${id} not found`); if (!good) throw new NotFoundException(`Good ${id} not found`);
return GoodDto.from(good, { return GoodDetailDto.fromGood(good, {
country: good.country, country: good.country,
category: good.category, category: good.category,
tag: good.tag, tag: good.tag,
position: good.position, position: good.position,
originGood: good.originGood, originGood: good.originGood,
goodTags: good.goodTags, goodTags: good.goodTags,
mergedOriginGoods: good.mergedOriginGoods,
}); });
} }
async create(dto: CreateGoodDto): Promise<GoodDto> { async create(dto: CreateGoodDto): Promise<GoodDto> {
await this.ensureReferences(dto); await this.ensureReferences(dto);
return this.prisma.$transaction(async (tx) => { const mergedIds = this.dedupeMergedIds(
BigInt(dto.originGoodId),
dto.mergedOriginGoodIds,
);
await this.ensureMergedOriginGoods(mergedIds);
const result = await this.prisma.$transaction(async (tx) => {
const created = await tx.good.create({ const created = await tx.good.create({
data: { data: {
goodName: dto.goodName, goodName: dto.goodName,
@@ -103,6 +139,14 @@ export class GoodsService {
})), })),
}); });
} }
if (mergedIds.length > 0) {
await tx.goodOriginGood.createMany({
data: mergedIds.map((originGoodId) => ({
goodId: created.id,
originGoodId,
})),
});
}
const result = await tx.good.findUniqueOrThrow({ const result = await tx.good.findUniqueOrThrow({
where: { id: created.id }, where: { id: created.id },
include: GOOD_INCLUDE, include: GOOD_INCLUDE,
@@ -114,12 +158,133 @@ export class GoodsService {
position: result.position, position: result.position,
originGood: result.originGood, originGood: result.originGood,
goodTags: result.goodTags, goodTags: result.goodTags,
mergedOriginGoods: result.mergedOriginGoods,
}); });
}); });
if (
result.originGood?.source === 'SDS' &&
result.originGood.sdsGoodId &&
!result.originGood.hasDetail
) {
this.syncService.queueProductDetailSync(result.originGood.sdsGoodId);
}
return result;
}
async createCustom(dto: CreateCustomGoodDto): Promise<GoodDetailDto> {
await this.ensureCountry(dto.countryId);
await this.ensureCategory(dto.categoryId);
if (dto.positionId !== undefined) await this.ensurePosition(dto.positionId);
for (const tagId of dto.tagIds ?? []) await this.ensureTag(tagId);
const goodId = await this.prisma.$transaction(async (tx) => {
const originGood = await tx.originGood.create({
data: {
source: 'CUSTOM',
sdsGoodId: `custom-${randomUUID()}`,
goodName: dto.goodName,
goodImage: dto.goodImage ?? null,
goodPrice: this.decimal(dto.goodPrice),
detail: {
create: this.customDetailData(
dto.detail ?? {},
) as Prisma.OriginGoodDetailUncheckedCreateWithoutOriginGoodInput,
},
},
});
if (dto.variants?.length) {
await this.replaceCustomVariants(tx, originGood.id, dto.variants);
}
const good = await tx.good.create({
data: {
originGoodId: originGood.id,
countryId: BigInt(dto.countryId),
categoryId: BigInt(dto.categoryId),
positionId:
dto.positionId === undefined ? null : BigInt(dto.positionId),
goodName: dto.goodName,
goodImage: dto.goodImage ?? null,
goodPriority: dto.goodPriority ?? 0,
},
});
if (dto.tagIds?.length) {
await tx.goodTag.createMany({
data: dto.tagIds.map((tagId) => ({
goodId: good.id,
tagId: BigInt(tagId),
})),
});
}
return good.id;
});
return this.findOne(goodId);
}
async updateCustomContent(
id: bigint,
dto: UpdateCustomGoodContentDto,
): Promise<GoodDetailDto> {
const existing = await this.prisma.good.findUnique({
where: { id },
include: { originGood: true },
});
if (!existing) throw new NotFoundException(`Good ${id} not found`);
if (existing.originGood.source !== 'CUSTOM') {
throw new BadRequestException('SDS 映射商品的上游信息不可修改');
}
await this.prisma.$transaction(async (tx) => {
await tx.originGood.update({
where: { id: existing.originGoodId },
data: {
goodName: dto.goodName,
goodImage: dto.goodImage,
goodPrice:
dto.goodPrice === undefined ? undefined : this.decimal(dto.goodPrice),
},
});
if (dto.detail !== undefined) {
await tx.originGoodDetail.upsert({
where: { originGoodId: existing.originGoodId },
create: {
originGoodId: existing.originGoodId,
...(this.customDetailData(
dto.detail,
) as Prisma.OriginGoodDetailUncheckedCreateWithoutOriginGoodInput),
},
update: this.customDetailData(dto.detail, true),
});
}
if (dto.variants !== undefined) {
await this.replaceCustomVariants(
tx,
existing.originGoodId,
dto.variants,
);
}
const goodData: Prisma.GoodUpdateInput = {};
if (dto.goodName !== undefined) goodData.goodName = dto.goodName;
if (dto.goodImage !== undefined) goodData.goodImage = dto.goodImage;
if (Object.keys(goodData).length) {
await tx.good.update({ where: { id }, data: goodData });
}
});
return this.findOne(id);
} }
async update(id: bigint, dto: UpdateGoodDto): Promise<GoodDto> { async update(id: bigint, dto: UpdateGoodDto): Promise<GoodDto> {
await this.findOne(id); await this.findOne(id);
let mergedIds: bigint[] | undefined;
if (dto.mergedOriginGoodIds !== undefined || dto.originGoodId !== undefined) {
const current = await this.prisma.good.findUniqueOrThrow({
where: { id },
select: { originGoodId: true },
});
const primaryId =
dto.originGoodId !== undefined ? BigInt(dto.originGoodId) : current.originGoodId;
mergedIds = this.dedupeMergedIds(primaryId, dto.mergedOriginGoodIds);
await this.ensureMergedOriginGoods(mergedIds);
}
const data: Prisma.GoodUpdateInput = {}; const data: Prisma.GoodUpdateInput = {};
if (dto.goodName !== undefined) data.goodName = dto.goodName; if (dto.goodName !== undefined) data.goodName = dto.goodName;
if (dto.originGoodId !== undefined) { if (dto.originGoodId !== undefined) {
@@ -148,7 +313,7 @@ export class GoodsService {
} }
} }
return this.prisma.$transaction(async (tx) => { const result = await this.prisma.$transaction(async (tx) => {
if (dto.tagIds !== undefined) { if (dto.tagIds !== undefined) {
await tx.goodTag.deleteMany({ where: { goodId: id } }); await tx.goodTag.deleteMany({ where: { goodId: id } });
if (dto.tagIds.length > 0) { if (dto.tagIds.length > 0) {
@@ -160,6 +325,17 @@ export class GoodsService {
}); });
} }
} }
if (mergedIds !== undefined) {
await tx.goodOriginGood.deleteMany({ where: { goodId: id } });
if (mergedIds.length > 0) {
await tx.goodOriginGood.createMany({
data: mergedIds.map((originGoodId) => ({
goodId: id,
originGoodId,
})),
});
}
}
const updated = await tx.good.update({ const updated = await tx.good.update({
where: { id }, where: { id },
data, data,
@@ -172,13 +348,36 @@ export class GoodsService {
position: updated.position, position: updated.position,
originGood: updated.originGood, originGood: updated.originGood,
goodTags: updated.goodTags, goodTags: updated.goodTags,
mergedOriginGoods: updated.mergedOriginGoods,
}); });
}); });
if (
result.originGood?.source === 'SDS' &&
result.originGood.sdsGoodId &&
!result.originGood.hasDetail
) {
this.syncService.queueProductDetailSync(result.originGood.sdsGoodId);
}
return result;
} }
async remove(id: bigint): Promise<{ id: string }> { async remove(id: bigint): Promise<{ id: string }> {
await this.findOne(id); const good = await this.prisma.good.findUnique({
await this.prisma.good.delete({ where: { id } }); where: { id },
include: { originGood: true },
});
if (!good) throw new NotFoundException(`Good ${id} not found`);
await this.prisma.$transaction(async (tx) => {
await tx.good.delete({ where: { id } });
if (good.originGood.source === 'CUSTOM') {
const remaining = await tx.good.count({
where: { originGoodId: good.originGoodId },
});
if (remaining === 0) {
await tx.originGood.delete({ where: { id: good.originGoodId } });
}
}
});
return { id: id.toString() }; return { id: id.toString() };
} }
@@ -187,7 +386,7 @@ export class GoodsService {
* or none do. * or none do.
*/ */
async batchUpdatePriority(dto: BatchPriorityDto): Promise<{ count: number }> { async batchUpdatePriority(dto: BatchPriorityDto): Promise<{ count: number }> {
return this.prisma.$transaction(async (tx) => { const result = await this.prisma.$transaction(async (tx) => {
for (const item of dto.items) { for (const item of dto.items) {
await tx.good.update({ await tx.good.update({
where: { id: BigInt(item.id) }, where: { id: BigInt(item.id) },
@@ -196,6 +395,7 @@ export class GoodsService {
} }
return { count: dto.items.length }; return { count: dto.items.length };
}); });
return result;
} }
/** /**
@@ -209,7 +409,7 @@ export class GoodsService {
await this.ensureTag(tagId); await this.ensureTag(tagId);
} }
} }
return this.prisma.$transaction(async (tx) => { const result = await this.prisma.$transaction(async (tx) => {
const created: GoodDto[] = []; const created: GoodDto[] = [];
for (const item of dto.items) { for (const item of dto.items) {
const og = await tx.originGood.findUnique({ const og = await tx.originGood.findUnique({
@@ -239,6 +439,24 @@ export class GoodsService {
})), })),
}); });
} }
const itemMerged = this.dedupeMergedIds(og.id, item.mergedOriginGoodIds);
if (itemMerged.length > 0) {
const existRows = await tx.originGood.findMany({
where: { id: { in: itemMerged } },
select: { id: true },
});
if (existRows.length !== itemMerged.length) {
const found = new Set(existRows.map((r) => r.id.toString()));
const missing = itemMerged.find((mid) => !found.has(mid.toString()));
throw new BadRequestException(`Origin good ${missing} not found`);
}
await tx.goodOriginGood.createMany({
data: itemMerged.map((originGoodId) => ({
goodId: row.id,
originGoodId,
})),
});
}
const result = await tx.good.findUniqueOrThrow({ const result = await tx.good.findUniqueOrThrow({
where: { id: row.id }, where: { id: row.id },
include: GOOD_INCLUDE, include: GOOD_INCLUDE,
@@ -250,10 +468,24 @@ export class GoodsService {
position: result.position, position: result.position,
originGood: result.originGood, originGood: result.originGood,
goodTags: result.goodTags, goodTags: result.goodTags,
mergedOriginGoods: result.mergedOriginGoods,
})); }));
} }
return created; return created;
}); });
for (const goodId of new Set(
result
.filter(
(item) =>
item.originGood?.source === 'SDS' &&
!item.originGood.hasDetail,
)
.map((item) => item.originGood?.sdsGoodId)
.filter((id): id is string => Boolean(id)),
)) {
this.syncService.queueProductDetailSync(goodId);
}
return result;
} }
/** /**
@@ -284,6 +516,31 @@ export class GoodsService {
if (!og) throw new BadRequestException(`Origin good ${id} not found`); if (!og) throw new BadRequestException(`Origin good ${id} not found`);
} }
/** Dedupe merged ids and reject any that equals the primary source. */
private dedupeMergedIds(primaryId: bigint, ids?: number[]): bigint[] {
if (!ids || ids.length === 0) return [];
const unique = [...new Set(ids.map((id) => BigInt(id)))];
if (unique.includes(primaryId)) {
throw new BadRequestException(
'mergedOriginGoodIds 不能包含主源 originGoodId',
);
}
return unique;
}
private async ensureMergedOriginGoods(ids: bigint[]) {
if (ids.length === 0) return;
const rows = await this.prisma.originGood.findMany({
where: { id: { in: ids } },
select: { id: true },
});
if (rows.length !== ids.length) {
const found = new Set(rows.map((r) => r.id.toString()));
const missing = ids.find((id) => !found.has(id.toString()));
throw new BadRequestException(`Origin good ${missing} not found`);
}
}
private async ensureCountry(id: number) { private async ensureCountry(id: number) {
const c = await this.prisma.country.findUnique({ where: { id: BigInt(id) } }); const c = await this.prisma.country.findUnique({ where: { id: BigInt(id) } });
if (!c) throw new BadRequestException(`Country ${id} not found`); if (!c) throw new BadRequestException(`Country ${id} not found`);
@@ -313,4 +570,93 @@ export class GoodsService {
if (!p) throw new BadRequestException(`Position ${dto.positionId} not found`); if (!p) throw new BadRequestException(`Position ${dto.positionId} not found`);
} }
} }
private async ensurePosition(id: number) {
const position = await this.prisma.position.findUnique({
where: { id: BigInt(id) },
});
if (!position) throw new BadRequestException(`Position ${id} not found`);
}
private decimal(value: string | null | undefined): Prisma.Decimal | null {
return value === undefined || value === null || value === ''
? null
: new Prisma.Decimal(value);
}
private customDetailData(
detail: CustomGoodDetailDto,
preserveMissing = false,
): Prisma.OriginGoodDetailUncheckedUpdateInput {
const nullable = <T>(value: T | null | undefined): T | null | undefined =>
preserveMissing && value === undefined ? undefined : value ?? null;
const decimal = (value: string | null | undefined) =>
preserveMissing && value === undefined ? undefined : this.decimal(value);
const json = (
value: Record<string, unknown> | null | undefined,
): Prisma.InputJsonValue | Prisma.NullTypes.DbNull | undefined =>
preserveMissing && value === undefined
? undefined
: value === null || value === undefined
? Prisma.DbNull
: (value as Prisma.InputJsonValue);
return {
productCode: nullable(detail.productCode),
englishName: nullable(detail.englishName),
blankDesignUrl: nullable(detail.blankDesignUrl),
detailsPageVideoUrl: nullable(detail.detailsPageVideoUrl),
textureName: nullable(detail.textureName),
productionCycleHours: nullable(detail.productionCycleHours),
minWeightG: decimal(detail.minWeightG),
reminder: nullable(detail.reminder),
productionProcess: nullable(detail.productionProcess),
materialDescription: nullable(detail.materialDescription),
productPerformance: nullable(detail.productPerformance),
applicableScenarios: nullable(detail.applicableScenarios),
washingInstructions: nullable(detail.washingInstructions),
specialDescription: nullable(detail.specialDescription),
designExplanation: nullable(detail.designExplanation),
designArea: nullable(detail.designArea),
pictureRequest: nullable(detail.pictureRequest),
sizeChart: json(detail.sizeChart),
packageSpecs: json(detail.packageSpecs),
options: json(detail.options),
media: json(detail.media),
};
}
private async replaceCustomVariants(
tx: Prisma.TransactionClient,
originGoodId: bigint,
variants: CustomGoodVariantDto[],
): Promise<void> {
await tx.originGoodVariant.deleteMany({ where: { originGoodId } });
for (const variant of variants) {
await tx.originGoodVariant.create({
data: {
originGoodId,
sdsVariantId: `custom-${randomUUID()}`,
sku: variant.sku,
sizeId: variant.sizeId ?? null,
sizeName: variant.sizeName ?? null,
colorId: variant.colorId ?? null,
colorName: variant.colorName ?? null,
colorHex: variant.colorHex ?? null,
imageUrl: variant.imageUrl ?? null,
price: this.decimal(variant.price),
originalPrice: this.decimal(variant.originalPrice),
weightG: this.decimal(variant.weightG),
boxLengthCm: this.decimal(variant.boxLengthCm),
boxWidthCm: this.decimal(variant.boxWidthCm),
boxHeightCm: this.decimal(variant.boxHeightCm),
enabled: variant.enabled ?? true,
sortOrder: variant.sortOrder ?? 0,
designData:
variant.designData === null || variant.designData === undefined
? Prisma.DbNull
: (variant.designData as Prisma.InputJsonValue),
},
});
}
}
} }
+55 -17
View File
@@ -1,13 +1,17 @@
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common'; import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import helmet from 'helmet';
import * as cookieParserModule from 'cookie-parser';
import { json } from 'express'; import { json } from 'express';
import { join } from 'path';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter'; import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor'; import { TransformInterceptor } from './common/interceptors/transform.interceptor';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule, { bodyParser: false }); const app = await NestFactory.create<NestExpressApplication>(AppModule, { bodyParser: false });
// Replace Express's JSON parser with one that stringifies BigInt. // Replace Express's JSON parser with one that stringifies BigInt.
// Express's default `json()` throws "Do not know how to serialize a BigInt". // Express's default `json()` throws "Do not know how to serialize a BigInt".
@@ -26,10 +30,42 @@ async function bootstrap() {
}), }),
); );
// CORS // Security headers (X-Content-Type-Options, X-Frame-Options, CSP, HSTS, ...)
app.enableCors({ // Static assets (/uploads, /assets) are embedded cross-origin by other
origin: ['http://localhost:5173', 'http://localhost:3000'], // sites, so CORP must allow cross-origin reads.
credentials: true, app.use(helmet({ crossOriginResourcePolicy: { policy: 'cross-origin' } }));
// Parse auth cookies (HttpOnly access/refresh tokens). Resolve both the
// namespace and its `default` interop shape so it works regardless of
// the compiled module interop mode.
const cookieParser = (
cookieParserModule as unknown as {
default?: typeof cookieParserModule;
}
).default ?? cookieParserModule;
app.use(cookieParser());
// CORS: only origins listed in CORS_ORIGINS (comma-separated) are
// allowed. Credentials are enabled because the session lives in
// HttpOnly cookies. "*" disables the allowlist and reflects any origin
// (reflected origins are required when credentials are enabled).
const corsOrigins = (process.env.CORS_ORIGINS ?? '')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
const origin = corsOrigins.includes('*') ? true : corsOrigins;
app.enableCors(corsOrigins.length > 0 ? { origin, credentials: true } : undefined);
// Serve uploaded files. nosniff prevents browsers from sniffing a
// non-image content type out of an uploaded file.
app.useStaticAssets(join(process.cwd(), 'uploads'), {
prefix: '/uploads/',
setHeaders: (res) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
},
});
app.useStaticAssets(join(process.cwd(), 'public'), {
prefix: '/assets/',
}); });
// Global pipes // Global pipes
@@ -45,21 +81,23 @@ async function bootstrap() {
app.useGlobalFilters(new HttpExceptionFilter()); app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalInterceptors(new TransformInterceptor()); app.useGlobalInterceptors(new TransformInterceptor());
// Swagger // Swagger is only exposed outside production to avoid leaking the
const config = new DocumentBuilder() // full admin API surface.
.setTitle('InkReach Product Center API') if (process.env.NODE_ENV !== 'production') {
.setDescription('Backend API for InkReach Product Center') const config = new DocumentBuilder()
.setVersion('1.0') .setTitle('InkReach Product Center API')
.addBearerAuth() .setDescription('Backend API for InkReach Product Center')
.build(); .setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config); const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document); SwaggerModule.setup('api/docs', app, document);
}
const port = process.env.PORT ?? 3001; const port = process.env.PORT ?? 3001;
await app.listen(port); await app.listen(port, '0.0.0.0');
console.log(`🚀 Application is running on: http://localhost:${port}`); console.log(`🚀 Application is running on: http://0.0.0.0:${port}`);
console.log(`📚 Swagger documentation: http://localhost:${port}/api/docs`);
} }
// Make JSON.stringify aware of BigInt so outgoing responses containing // Make JSON.stringify aware of BigInt so outgoing responses containing
@@ -77,4 +77,69 @@ describe('OriginGoodsService', () => {
expect(result.total).toBe(0); expect(result.total).toBe(0);
expect(result.items.length).toBe(0); expect(result.items.length).toBe(0);
}); });
describe('getTree merged references', () => {
/* eslint-disable @typescript-eslint/no-explicit-any */
function findOgNode(
treeResponse: { tree: any[] },
ogId: string,
): { configuredCount: number; configuredCountries: string[] } {
let found: { configuredCount: number; configuredCountries: string[] } | null = null;
const walk = (nodes: any[]) => {
for (const n of nodes) {
const hit = (n.originGoods ?? []).find((o: any) => o.id === ogId);
if (hit) {
found = hit;
return;
}
if (n.children?.length) walk(n.children);
}
};
walk(treeResponse.tree);
if (!found) throw new Error(`og node ${ogId} not found in tree`);
return found;
}
it('counts secondary references as configured', async () => {
const sdsCat = `tree-cat-${stamp}`;
await prisma.originGood.createMany({
data: [
{ sdsGoodId: `tree-a-${stamp}`, goodName: `Tree A ${stamp}`, sdsCategoryId: sdsCat },
{ sdsGoodId: `tree-b-${stamp}`, goodName: `Tree B ${stamp}`, sdsCategoryId: sdsCat },
],
});
createdSds.push(`tree-a-${stamp}`, `tree-b-${stamp}`);
const originA = await prisma.originGood.findUniqueOrThrow({ where: { sdsGoodId: `tree-a-${stamp}` } });
const originB = await prisma.originGood.findUniqueOrThrow({ where: { sdsGoodId: `tree-b-${stamp}` } });
const cat = await prisma.category.create({
data: { categoryName: `Tree Cat ${stamp}`, sdsCategoryId: sdsCat },
});
const country = await prisma.country.create({
data: { countryName: `Tree Country ${stamp}` },
});
const good = await prisma.good.create({
data: {
goodName: `Tree Good ${stamp}`,
originGoodId: originA.id,
countryId: country.id,
categoryId: cat.id,
},
});
await prisma.goodOriginGood.create({
data: { goodId: good.id, originGoodId: originB.id },
});
try {
const tree = await service.getTree();
const nodeB = findOgNode(tree, originB.id.toString());
expect(nodeB.configuredCount).toBeGreaterThanOrEqual(1);
expect(nodeB.configuredCountries).toContain(`Tree Country ${stamp}`);
} finally {
await prisma.good.delete({ where: { id: good.id } }).catch(() => undefined);
await prisma.country.delete({ where: { id: country.id } }).catch(() => undefined);
await prisma.category.delete({ where: { id: cat.id } }).catch(() => undefined);
}
});
});
}); });
@@ -13,6 +13,9 @@ export interface PaginatedOriginGoods {
sdsCategoryId: string | null; sdsCategoryId: string | null;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
hasDetail: boolean;
detailSyncedAt: string | null;
variantCount: number;
}>; }>;
total: number; total: number;
page: number; page: number;
@@ -29,9 +32,15 @@ export interface OriginGoodsTreeNode {
goodImage: string | null; goodImage: string | null;
goodPrice: string | null; goodPrice: string | null;
sdsGoodId: string; sdsGoodId: string;
delisted: boolean;
configuredCount: number; configuredCount: number;
configuredCountries: string[]; configuredCountries: string[];
configuredTags: { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number }[]; configuredTags: { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number }[];
hasDetail: boolean;
detailSyncedAt: string | null;
variantCount: number;
sizeRowCount: number;
packageRowCount: number;
} }
/** A category node in the hierarchical tree, with origin goods as leaves. */ /** A category node in the hierarchical tree, with origin goods as leaves. */
@@ -58,15 +67,19 @@ export class OriginGoodsService {
async findAll(query: QueryOriginGoodDto): Promise<PaginatedOriginGoods> { async findAll(query: QueryOriginGoodDto): Promise<PaginatedOriginGoods> {
const { page, pageSize, keyword } = query; const { page, pageSize, keyword } = query;
const where: Prisma.OriginGoodWhereInput = keyword const where: Prisma.OriginGoodWhereInput = {
? { goodName: { contains: keyword, mode: 'insensitive' } } source: 'SDS',
: {}; ...(keyword
? { goodName: { contains: keyword, mode: 'insensitive' as const } }
: {}),
};
const [total, rows] = await this.prisma.$transaction([ const [total, rows] = await this.prisma.$transaction([
this.prisma.originGood.count({ where }), this.prisma.originGood.count({ where }),
this.prisma.originGood.findMany({ this.prisma.originGood.findMany({
where, where,
orderBy: { id: 'desc' }, orderBy: { id: 'desc' },
include: { detail: true, _count: { select: { variants: true } } },
skip: (page - 1) * pageSize, skip: (page - 1) * pageSize,
take: pageSize, take: pageSize,
}), }),
@@ -82,6 +95,9 @@ export class OriginGoodsService {
sdsCategoryId: r.sdsCategoryId, sdsCategoryId: r.sdsCategoryId,
createdAt: r.createdAt.toISOString(), createdAt: r.createdAt.toISOString(),
updatedAt: r.updatedAt.toISOString(), updatedAt: r.updatedAt.toISOString(),
hasDetail: Boolean(r.detail),
detailSyncedAt: r.detail?.syncedAt.toISOString() ?? null,
variantCount: r._count.variants,
})), })),
total, total,
page, page,
@@ -98,7 +114,7 @@ export class OriginGoodsService {
* under a synthetic "未分类" root node. * under a synthetic "未分类" root node.
*/ */
async getTree(): Promise<OriginGoodsTreeResponse> { async getTree(): Promise<OriginGoodsTreeResponse> {
const [allCategories, allOriginGoods, configCounts, goodsWithCountries, goodsWithTags] = const [allCategories, allOriginGoods, configCounts, goodsWithCountries, goodsWithTags, mergedCounts, mergedWithCountries] =
await Promise.all([ await Promise.all([
this.prisma.category.findMany({ this.prisma.category.findMany({
where: { sdsCategoryId: { not: null } }, where: { sdsCategoryId: { not: null } },
@@ -110,7 +126,11 @@ export class OriginGoodsService {
parentCategoryId: true, parentCategoryId: true,
}, },
}), }),
this.prisma.originGood.findMany({ orderBy: { goodName: 'asc' } }), this.prisma.originGood.findMany({
where: { delisted: false, source: 'SDS' },
orderBy: { goodName: 'asc' },
include: { detail: true, _count: { select: { variants: true } } },
}),
this.prisma.good.groupBy({ this.prisma.good.groupBy({
by: ['originGoodId'], by: ['originGoodId'],
_count: { _all: true }, _count: { _all: true },
@@ -124,7 +144,12 @@ export class OriginGoodsService {
}), }),
this.prisma.goodTag.findMany({ this.prisma.goodTag.findMany({
select: { select: {
good: { select: { originGoodId: true } }, good: {
select: {
originGoodId: true,
mergedOriginGoods: { select: { originGoodId: true } },
},
},
tag: { tag: {
select: { select: {
tagName: true, tagName: true,
@@ -137,26 +162,57 @@ export class OriginGoodsService {
}, },
}, },
}), }),
// Secondary-source references (good_origin_goods)
this.prisma.goodOriginGood.groupBy({
by: ['originGoodId'],
_count: { _all: true },
}),
this.prisma.goodOriginGood.findMany({
select: {
originGoodId: true,
good: { select: { country: { select: { countryName: true } } } },
},
}),
]); ]);
const countMap = new Map<string, number>(); const countMap = new Map<string, number>();
configCounts.forEach((c) => configCounts.forEach((c) =>
countMap.set(c.originGoodId.toString(), c._count._all), countMap.set(c.originGoodId.toString(), c._count._all),
); );
// Secondary (merged) references count towards configured status too.
const countryMap = new Map<string, string[]>(); mergedCounts.forEach((c) => {
goodsWithCountries.forEach((g) => { const key = c.originGoodId.toString();
const key = g.originGoodId.toString(); countMap.set(key, (countMap.get(key) ?? 0) + c._count._all);
const name = g.country?.countryName;
if (!name) return;
const arr = countryMap.get(key);
if (arr) arr.push(name);
else countryMap.set(key, [name]);
}); });
const countryMap = new Map<string, string[]>();
const addCountry = (key: string, name?: string | null) => {
if (!name) return;
const arr = countryMap.get(key);
if (!arr?.includes(name)) {
countryMap.set(key, [...(arr ?? []), name]);
}
};
goodsWithCountries.forEach((g) =>
addCountry(g.originGoodId.toString(), g.country?.countryName),
);
mergedWithCountries.forEach((m) =>
addCountry(m.originGoodId.toString(), m.good.country?.countryName),
);
const tagMap = new Map<string, { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number }[]>(); const tagMap = new Map<string, { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number }[]>();
const addTag = (
key: string,
tagInfo: { tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroupId: string | null; tagGroupName: string | null; sortOrder: number },
) => {
const arr = tagMap.get(key);
if (arr) {
if (!arr.some((t) => t.tagName === tagInfo.tagName)) arr.push(tagInfo);
} else {
tagMap.set(key, [tagInfo]);
}
};
goodsWithTags.forEach((gt) => { goodsWithTags.forEach((gt) => {
const key = gt.good.originGoodId.toString();
const tagInfo = { const tagInfo = {
tagName: gt.tag.tagName, tagName: gt.tag.tagName,
tagColor: gt.tag.tagColor, tagColor: gt.tag.tagColor,
@@ -165,11 +221,10 @@ export class OriginGoodsService {
tagGroupName: gt.tag.tagGroup?.groupName ?? null, tagGroupName: gt.tag.tagGroup?.groupName ?? null,
sortOrder: gt.tag.sortOrder, sortOrder: gt.tag.sortOrder,
}; };
const arr = tagMap.get(key); addTag(gt.good.originGoodId.toString(), tagInfo);
if (arr) { // A good's tags also mark its secondary origin goods as configured.
if (!arr.some((t) => t.tagName === tagInfo.tagName)) arr.push(tagInfo); for (const m of gt.good.mergedOriginGoods) {
} else { addTag(m.originGoodId.toString(), tagInfo);
tagMap.set(key, [tagInfo]);
} }
}); });
@@ -194,7 +249,9 @@ export class OriginGoodsService {
const childrenCats = allCategories.filter( const childrenCats = allCategories.filter(
(c) => c.parentCategoryId !== null && c.parentCategoryId === cat.id, (c) => c.parentCategoryId !== null && c.parentCategoryId === cat.id,
); );
const childNodes = childrenCats.map(buildNode); const childNodes = childrenCats
.map(buildNode)
.filter((n) => n.totalCount > 0);
const ogsForThisCat = allOriginGoods.filter( const ogsForThisCat = allOriginGoods.filter(
(og) => ogToCategory.get(og.id.toString()) === cat.id.toString(), (og) => ogToCategory.get(og.id.toString()) === cat.id.toString(),
@@ -205,9 +262,15 @@ export class OriginGoodsService {
goodImage: og.goodImage, goodImage: og.goodImage,
goodPrice: og.goodPrice?.toString() ?? null, goodPrice: og.goodPrice?.toString() ?? null,
sdsGoodId: og.sdsGoodId, sdsGoodId: og.sdsGoodId,
delisted: og.delisted,
configuredCount: countMap.get(og.id.toString()) ?? 0, configuredCount: countMap.get(og.id.toString()) ?? 0,
configuredCountries: countryMap.get(og.id.toString()) ?? [], configuredCountries: countryMap.get(og.id.toString()) ?? [],
configuredTags: tagMap.get(og.id.toString()) ?? [], configuredTags: tagMap.get(og.id.toString()) ?? [],
hasDetail: Boolean(og.detail),
detailSyncedAt: og.detail?.syncedAt.toISOString() ?? null,
variantCount: og._count.variants,
sizeRowCount: this.jsonRows(og.detail?.sizeChart),
packageRowCount: this.jsonRows(og.detail?.packageSpecs),
})); }));
const childTotal = childNodes.reduce((s, n) => s + n.totalCount, 0); const childTotal = childNodes.reduce((s, n) => s + n.totalCount, 0);
@@ -229,7 +292,7 @@ export class OriginGoodsService {
}; };
const roots = allCategories.filter((c) => c.parentCategoryId === null); const roots = allCategories.filter((c) => c.parentCategoryId === null);
const tree = roots.map(buildNode); const tree = roots.map(buildNode).filter((n) => n.totalCount > 0);
const unmapped = allOriginGoods.filter( const unmapped = allOriginGoods.filter(
(og) => !ogToCategory.has(og.id.toString()), (og) => !ogToCategory.has(og.id.toString()),
@@ -250,9 +313,15 @@ export class OriginGoodsService {
goodImage: og.goodImage, goodImage: og.goodImage,
goodPrice: og.goodPrice?.toString() ?? null, goodPrice: og.goodPrice?.toString() ?? null,
sdsGoodId: og.sdsGoodId, sdsGoodId: og.sdsGoodId,
delisted: og.delisted,
configuredCount: countMap.get(og.id.toString()) ?? 0, configuredCount: countMap.get(og.id.toString()) ?? 0,
configuredCountries: countryMap.get(og.id.toString()) ?? [], configuredCountries: countryMap.get(og.id.toString()) ?? [],
configuredTags: tagMap.get(og.id.toString()) ?? [], configuredTags: tagMap.get(og.id.toString()) ?? [],
hasDetail: Boolean(og.detail),
detailSyncedAt: og.detail?.syncedAt.toISOString() ?? null,
variantCount: og._count.variants,
sizeRowCount: this.jsonRows(og.detail?.sizeChart),
packageRowCount: this.jsonRows(og.detail?.packageSpecs),
})), })),
}); });
} }
@@ -269,4 +338,10 @@ export class OriginGoodsService {
configuredCount: totalConfigured, configuredCount: totalConfigured,
}; };
} }
private jsonRows(value: unknown): number {
if (!value || typeof value !== 'object' || !('rows' in value)) return 0;
const rows = (value as { rows?: unknown }).rows;
return Array.isArray(rows) ? rows.length : 0;
}
} }
@@ -17,6 +17,9 @@ export class PublicCategoryNodeDto {
@ApiProperty({ type: [PublicCategoryNodeDto] }) @ApiProperty({ type: [PublicCategoryNodeDto] })
children!: PublicCategoryNodeDto[]; children!: PublicCategoryNodeDto[];
@ApiProperty({ description: '当前节点及其后代分类的商品数量' })
productCount!: number;
static from(category: PrismaCategory, children: PublicCategoryNodeDto[] = []): PublicCategoryNodeDto { static from(category: PrismaCategory, children: PublicCategoryNodeDto[] = []): PublicCategoryNodeDto {
return { return {
id: category.id.toString(), id: category.id.toString(),
@@ -26,6 +29,7 @@ export class PublicCategoryNodeDto {
? category.parentCategoryId.toString() ? category.parentCategoryId.toString()
: null, : null,
children, children,
productCount: 0,
}; };
} }
} }
@@ -0,0 +1,89 @@
import { ApiProperty } from '@nestjs/swagger';
import { PublicGoodDto } from './public-good.dto';
export class PublicGoodDetailDto extends PublicGoodDto {
@ApiProperty({ nullable: true })
productCode!: string | null;
@ApiProperty({ nullable: true })
englishName!: string | null;
@ApiProperty({ nullable: true })
productionCycleHours!: number | null;
@ApiProperty({ nullable: true })
minWeightG!: string | null;
@ApiProperty({ type: Object })
details!: Record<string, string | null>;
@ApiProperty({ nullable: true, type: Object })
media!: Record<string, unknown> | null;
@ApiProperty({ type: Array, description: 'Variant images grouped by color' })
mediaByColor!: Array<{
colorId: string | null;
colorName: string | null;
colorHex: string | null;
images: string[];
}>;
@ApiProperty({ nullable: true, type: Object })
options!: Record<string, unknown> | null;
@ApiProperty({ nullable: true, type: Object })
sizeChart!: Record<string, unknown> | null;
@ApiProperty({ nullable: true, type: Object })
packageSpecs!: Record<string, unknown> | null;
@ApiProperty({ type: Array })
variants!: Array<{
id: string;
sku: string;
sizeId: string | null;
sizeName: string | null;
colorId: string | null;
colorName: string | null;
colorHex: string | null;
imageUrl: string | null;
price: string | null;
originalPrice: string | null;
weightG: string | null;
boxLengthCm: string | null;
boxWidthCm: string | null;
boxHeightCm: string | null;
enabled: boolean;
sortOrder: number;
}>;
@ApiProperty({ nullable: true })
detailSyncedAt!: string | null;
}
export class PublicTagGroupFilterDto {
@ApiProperty()
id!: string;
@ApiProperty()
groupName!: string;
@ApiProperty({ nullable: true })
groupIcon!: string | null;
@ApiProperty({ nullable: true })
groupColor!: string | null;
@ApiProperty()
sortOrder!: number;
@ApiProperty({ type: Array })
tags!: Array<{
id: string;
tagName: string;
tagColor: string | null;
tagFontColor: string | null;
sortOrder: number;
productCount: number;
}>;
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { ApiProperty } from '@nestjs/swagger';
export class PublicGoodDto { export class PublicGoodDto {
@ApiProperty() @ApiProperty()
id!: string; goodId!: string;
@ApiProperty() @ApiProperty()
goodName!: string; goodName!: string;
@@ -0,0 +1,35 @@
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import {
PublicQueryGoodDto,
PublicTagFilterDto,
} from './public-query-good.dto';
describe('PublicQueryGoodDto', () => {
it('parses tags from a JSON query parameter into nested DTOs', async () => {
const dto = plainToInstance(PublicQueryGoodDto, {
tags: JSON.stringify([
{ tagGroupId: '1', tagIds: ['11', '12'] },
{ tagGroupId: '2', tagIds: ['25'] },
]),
});
expect(dto.tags).toHaveLength(2);
expect(dto.tags?.[0]).toBeInstanceOf(PublicTagFilterDto);
expect(dto.tags?.[0]).toEqual({
tagGroupId: '1',
tagIds: ['11', '12'],
});
await expect(validate(dto)).resolves.toHaveLength(0);
});
it('rejects malformed group and tag ids', async () => {
const dto = plainToInstance(PublicQueryGoodDto, {
tags: JSON.stringify([
{ tagGroupId: 'craft', tagIds: ['11', 'bad'] },
]),
});
expect(await validate(dto)).not.toHaveLength(0);
});
});
@@ -1,13 +1,53 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { plainToInstance, Transform, Type } from 'class-transformer';
import { import {
IsArray,
IsIn,
IsInt, IsInt,
IsNumberString,
IsOptional, IsOptional,
IsString, IsString,
ValidateNested,
ArrayNotEmpty,
Max, Max,
Min, Min,
} from 'class-validator'; } from 'class-validator';
const stringList = ({ value }: { value: unknown }): string[] | undefined => {
if (value === undefined || value === null || value === '') return undefined;
const values = Array.isArray(value) ? value : [value];
return values
.flatMap((item) => String(item).split(','))
.map((item) => item.trim())
.filter(Boolean);
};
const tagFilters = ({ value }: { value: unknown }): unknown => {
if (value === undefined || value === null || value === '') return undefined;
const values = Array.isArray(value) ? value : [value];
try {
return values.flatMap((item) => {
if (typeof item !== 'string') return [item];
const parsed = JSON.parse(item) as unknown;
return Array.isArray(parsed) ? parsed : [parsed];
}).map((item) => plainToInstance(PublicTagFilterDto, item));
} catch {
return value;
}
};
export class PublicTagFilterDto {
@ApiProperty({ example: '1' })
@IsNumberString()
tagGroupId!: string;
@ApiProperty({ type: [String], example: ['11', '12', '13'] })
@IsArray()
@ArrayNotEmpty()
@IsNumberString({}, { each: true })
tagIds!: string[];
}
export class PublicQueryGoodDto { export class PublicQueryGoodDto {
@ApiProperty({ required: false, default: 1 }) @ApiProperty({ required: false, default: 1 })
@IsOptional() @IsOptional()
@@ -16,7 +56,7 @@ export class PublicQueryGoodDto {
@Min(1) @Min(1)
page: number = 1; page: number = 1;
@ApiProperty({ required: false, default: 20 }) @ApiProperty({ required: false, default: 20, maximum: 200 })
@IsOptional() @IsOptional()
@Type(() => Number) @Type(() => Number)
@IsInt() @IsInt()
@@ -24,25 +64,57 @@ export class PublicQueryGoodDto {
@Max(200) @Max(200)
pageSize: number = 20; pageSize: number = 20;
@ApiProperty({ required: false }) @ApiProperty({ required: false, type: String, description: '不传表示全部国家' })
@IsOptional() @IsOptional()
@Type(() => Number) @IsNumberString()
@IsInt() countryId?: string;
countryId?: number;
@ApiProperty({ required: false, type: String })
@IsOptional()
@IsNumberString()
categoryId?: string;
@ApiHideProperty()
@IsOptional()
@Transform(tagFilters)
@IsArray()
@ValidateNested({ each: true })
tags?: PublicTagFilterDto[];
@ApiProperty({ required: false }) @ApiProperty({ required: false })
@IsOptional() @IsOptional()
@Type(() => Number)
@IsInt()
categoryId?: number;
@ApiProperty({ required: false, description: 'Comma-separated tag IDs, e.g. "30,34"' })
@IsOptional()
@IsString() @IsString()
tagIds?: string; minPrice?: string;
@ApiProperty({ required: false })
@IsOptional()
@IsString()
maxPrice?: string;
@ApiProperty({ required: false, enum: ['DEFAULT', 'PRICE_ASC', 'PRICE_DESC', 'NEWEST'] })
@IsOptional()
@IsIn(['DEFAULT', 'PRICE_ASC', 'PRICE_DESC', 'NEWEST'])
sort?: 'DEFAULT' | 'PRICE_ASC' | 'PRICE_DESC' | 'NEWEST';
@ApiProperty({ required: false }) @ApiProperty({ required: false })
@IsOptional() @IsOptional()
@IsString() @IsString()
keyword?: string; keyword?: string;
} }
export class PublicCountryQueryDto {
@ApiProperty({ required: false, type: String, description: '不传表示全部国家' })
@IsOptional()
@IsNumberString()
countryId?: string;
}
export class PublicHomeGoodsQueryDto extends PublicCountryQueryDto {
@ApiProperty({ required: false, default: 10, maximum: 50 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(50)
limit: number = 10;
}
+57 -15
View File
@@ -2,24 +2,38 @@ import {
Controller, Controller,
Get, Get,
Param, Param,
ParseIntPipe,
Query, Query,
} from '@nestjs/common'; } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger'; import {
ApiExtraModels,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiQuery,
ApiTags,
getSchemaPath,
} from '@nestjs/swagger';
import { PublicService } from './public.service'; import { PublicService } from './public.service';
import { PublicQueryGoodDto } from './dto/public-query-good.dto'; import {
PublicCountryQueryDto,
PublicHomeGoodsQueryDto,
PublicQueryGoodDto,
PublicTagFilterDto,
} from './dto/public-query-good.dto';
import { PublicTagDto } from './dto/public-tag.dto'; import { PublicTagDto } from './dto/public-tag.dto';
import { PublicTagGroupDto } from './dto/public-tag-group.dto'; import { PublicGoodDetailDto, PublicTagGroupFilterDto } from './dto/public-good-detail.dto';
import { PublicGoodDto } from './dto/public-good.dto';
@ApiTags('public') @ApiTags('public')
@ApiExtraModels(PublicTagFilterDto)
@Controller('public') @Controller('public')
export class PublicController { export class PublicController {
constructor(private readonly service: PublicService) {} constructor(private readonly service: PublicService) {}
@Get('categories') @Get('categories')
@ApiOperation({ summary: 'Public list of categories that have goods' }) @ApiOperation({ summary: '获取商品分类树;countryId 不传时返回全部国家' })
getCategories() { getCategories(@Query() query: PublicCountryQueryDto) {
return this.service.getCategoriesTree(); return this.service.getCategoriesTree(query.countryId);
} }
@Get('countries') @Get('countries')
@@ -35,20 +49,48 @@ export class PublicController {
} }
@Get('tag-groups') @Get('tag-groups')
@ApiOperation({ summary: 'Public list of tag groups that have goods' }) @ApiOperation({ summary: '获取标签组及标签筛选项;countryId 不传时返回全部国家' })
getTagGroups(): Promise<PublicTagGroupDto[]> { @ApiOkResponse({ type: [PublicTagGroupFilterDto] })
return this.service.getTagGroups(); getTagGroups(@Query() query: PublicCountryQueryDto): Promise<PublicTagGroupFilterDto[]> {
return this.service.getTagGroups(query.countryId);
} }
@Get('goods') @Get('goods')
@ApiOperation({ summary: 'Public paginated goods with filters' }) @ApiOperation({ summary: '分页获取商品' })
@ApiQuery({
name: 'tags',
required: false,
description:
'标签筛选分组。参数值为 JSON 数组;同组 tagIds 按 OR 匹配,不同标签组按 AND 匹配',
content: {
'application/json': {
schema: {
type: 'array',
items: { $ref: getSchemaPath(PublicTagFilterDto) },
},
example: [
{ tagGroupId: '1', tagIds: ['11', '12'] },
{ tagGroupId: '2', tagIds: ['25'] },
],
},
},
})
getGoods(@Query() query: PublicQueryGoodDto) { getGoods(@Query() query: PublicQueryGoodDto) {
return this.service.getGoods(query); return this.service.getGoods(query);
} }
@Get('goods/:id') @Get('goods/:goodId')
@ApiOperation({ summary: 'Public good detail' }) @ApiOperation({ summary: '获取商品完整详情' })
getGood(@Param('id', ParseIntPipe) id: string) { @ApiParam({ name: 'goodId', type: String, example: '168746' })
return this.service.getGood(BigInt(id)); @ApiOkResponse({ type: PublicGoodDetailDto })
getGood(@Param('goodId') goodId: string): Promise<PublicGoodDetailDto> {
return this.service.getGood(goodId);
}
@Get('home-goods')
@ApiOperation({ summary: '获取首页商品;可按国家返回' })
@ApiOkResponse({ type: [PublicGoodDto] })
getHomeGoods(@Query() query: PublicHomeGoodsQueryDto): Promise<PublicGoodDto[]> {
return this.service.getHomeGoods(query);
} }
} }
+281 -8
View File
@@ -1,5 +1,5 @@
import { Test } from '@nestjs/testing'; import { Test } from '@nestjs/testing';
import { NotFoundException } from '@nestjs/common'; import { BadRequestException, NotFoundException } from '@nestjs/common';
import { PublicService } from './public.service'; import { PublicService } from './public.service';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
@@ -12,6 +12,8 @@ describe('PublicService', () => {
let childCategoryId: bigint; let childCategoryId: bigint;
let otherCategoryId: bigint; let otherCategoryId: bigint;
let tagId: bigint; let tagId: bigint;
let filterGroupIds: bigint[] = [];
let filterTagIds: bigint[] = [];
let originGoodId: bigint; let originGoodId: bigint;
let goodIds: bigint[] = []; let goodIds: bigint[] = [];
@@ -98,6 +100,50 @@ describe('PublicService', () => {
}); });
goodIds = [g1.id, g2.id, g3.id]; goodIds = [g1.id, g2.id, g3.id];
const craftGroup = await prisma.tagGroup.create({
data: { groupName: `Pub Craft ${stamp}`, sortOrder: 100 },
});
const materialGroup = await prisma.tagGroup.create({
data: { groupName: `Pub Material ${stamp}`, sortOrder: 101 },
});
filterGroupIds = [craftGroup.id, materialGroup.id];
const craftA = await prisma.tag.create({
data: { tagName: `Pub Craft A ${stamp}`, tagGroupId: craftGroup.id },
});
const craftB = await prisma.tag.create({
data: { tagName: `Pub Craft B ${stamp}`, tagGroupId: craftGroup.id },
});
const cotton = await prisma.tag.create({
data: { tagName: `Pub Cotton ${stamp}`, tagGroupId: materialGroup.id },
});
filterTagIds = [craftA.id, craftB.id, cotton.id];
await prisma.goodTag.createMany({
data: [
{ goodId: g1.id, tagId: craftA.id },
{ goodId: g1.id, tagId: cotton.id },
{ goodId: g2.id, tagId: craftB.id },
],
});
await prisma.originGoodDetail.create({
data: {
originGoodId,
productCode: 'OZ10827003',
productionProcess: '白墨烫画',
sizeChart: { columns: [], rows: [{ sizeId: 'size_0', sizeName: 'S', measurements: [] }] },
packageSpecs: { rows: [{ sizeId: 'size_0', sizeName: 'S' }] },
},
});
await prisma.originGoodVariant.create({
data: {
originGoodId,
sdsVariantId: `pub-variant-${stamp}`,
sku: `OZ${stamp}`,
sizeName: 'S',
price: 38,
},
});
// Seed a good in `otherCategory` so the "onlyHaveGoods" filter // Seed a good in `otherCategory` so the "onlyHaveGoods" filter
// returns more than one category. // returns more than one category.
await prisma.good.create({ await prisma.good.create({
@@ -134,6 +180,8 @@ describe('PublicService', () => {
where: { countryId }, where: { countryId },
}); });
await prisma.tag.delete({ where: { id: tagId } }); await prisma.tag.delete({ where: { id: tagId } });
await prisma.tag.deleteMany({ where: { id: { in: filterTagIds } } });
await prisma.tagGroup.deleteMany({ where: { id: { in: filterGroupIds } } });
await prisma.originGood.delete({ where: { id: originGoodId } }); await prisma.originGood.delete({ where: { id: originGoodId } });
// Delete children before parent (FK self-relation is RESTRICT). // Delete children before parent (FK self-relation is RESTRICT).
await prisma.category.delete({ where: { id: childCategoryId } }); await prisma.category.delete({ where: { id: childCategoryId } });
@@ -172,8 +220,8 @@ describe('PublicService', () => {
const filtered = await service.getGoods({ const filtered = await service.getGoods({
page: 1, page: 1,
pageSize: 50, pageSize: 50,
countryId: Number(countryId), countryId: countryId.toString(),
categoryId: Number(categoryId), // includes child categoryId: categoryId.toString(), // includes child
keyword: `Pub `, keyword: `Pub `,
}); });
expect(filtered.total).toBeGreaterThanOrEqual(4); // High, Mid, NoPos, ChildGood expect(filtered.total).toBeGreaterThanOrEqual(4); // High, Mid, NoPos, ChildGood
@@ -184,7 +232,7 @@ describe('PublicService', () => {
const result = await service.getGoods({ const result = await service.getGoods({
page: 1, page: 1,
pageSize: 50, pageSize: 50,
countryId: Number(countryId), countryId: countryId.toString(),
keyword: `Pub `, keyword: `Pub `,
}); });
const priorities = result.items.map((g) => g.goodPriority); const priorities = result.items.map((g) => g.goodPriority);
@@ -193,18 +241,118 @@ describe('PublicService', () => {
expect(priorities).toEqual(sorted); expect(priorities).toEqual(sorted);
}); });
it('uses OR within one tag group and AND across tag groups', async () => {
const sameGroup = await service.getGoods({
page: 1,
pageSize: 50,
countryId: countryId.toString(),
keyword: `Pub `,
tags: [
{
tagGroupId: filterGroupIds[0].toString(),
tagIds: filterTagIds.slice(0, 2).map(String),
},
],
});
expect(sameGroup.items.map((item) => item.goodName)).toEqual(
expect.arrayContaining([`Pub High ${stamp}`, `Pub Mid ${stamp}`]),
);
const acrossGroups = await service.getGoods({
page: 1,
pageSize: 50,
countryId: countryId.toString(),
keyword: `Pub `,
tags: [
{
tagGroupId: filterGroupIds[0].toString(),
tagIds: filterTagIds.slice(0, 2).map(String),
},
{
tagGroupId: filterGroupIds[1].toString(),
tagIds: [filterTagIds[2].toString()],
},
],
});
expect(acrossGroups.items.map((item) => item.goodName)).toContain(`Pub High ${stamp}`);
expect(acrossGroups.items.map((item) => item.goodName)).not.toContain(`Pub Mid ${stamp}`);
});
it('rejects a tag paired with the wrong tag group', async () => {
await expect(
service.getGoods({
page: 1,
pageSize: 20,
tags: [
{
tagGroupId: filterGroupIds[1].toString(),
tagIds: [filterTagIds[0].toString()],
},
],
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('returns the SDS product id as the public product id', async () => {
const result = await service.getGoods({
page: 1,
pageSize: 1,
countryId: countryId.toString(),
keyword: `Pub High ${stamp}`,
});
expect(result.items).toHaveLength(1);
expect(result.items[0].goodId).toBe(`pub-sds-${stamp}`);
expect(result.items[0].goodId).not.toBe(goodIds[0].toString());
});
it('returns custom goods through the same public product contract', async () => {
const customPublicId = `custom-public-${stamp}`;
const origin = await prisma.originGood.create({
data: {
source: 'CUSTOM',
sdsGoodId: customPublicId,
goodName: `Pub Custom ${stamp}`,
goodPrice: 42,
detail: { create: { productCode: `CUSTOM-${stamp}` } },
},
});
const good = await prisma.good.create({
data: {
originGoodId: origin.id,
countryId,
categoryId,
goodName: `Pub Custom ${stamp}`,
},
});
try {
const detail = await service.getGood(customPublicId);
expect(detail.goodId).toBe(customPublicId);
expect(detail.goodName).toBe(`Pub Custom ${stamp}`);
expect(detail.productCode).toBe(`CUSTOM-${stamp}`);
} finally {
await prisma.good.delete({ where: { id: good.id } });
await prisma.originGood.delete({ where: { id: origin.id } });
}
});
it('getGood returns detail and 404 for unknown id', async () => { it('getGood returns detail and 404 for unknown id', async () => {
const first = await service.getGoods({ const first = await service.getGoods({
page: 1, page: 1,
pageSize: 1, pageSize: 1,
countryId: Number(countryId), countryId: countryId.toString(),
keyword: `Pub `, keyword: `Pub `,
}); });
expect(first.items.length).toBe(1); expect(first.items.length).toBe(1);
const detail = await service.getGood(BigInt(first.items[0].id)); const detail = await service.getGood(`pub-sds-${stamp}`);
expect(detail.id).toBe(first.items[0].id); expect(detail.goodId).toBe(first.items[0].goodId);
expect(detail.productCode).toBe('OZ10827003');
expect(detail.details.productionProcess).toBe('白墨烫画');
expect((detail.sizeChart?.rows as unknown[])).toHaveLength(1);
expect((detail.packageSpecs?.rows as unknown[])).toHaveLength(1);
expect(detail.variants).toHaveLength(1);
await expect(service.getGood(BigInt(99999999))).rejects.toBeInstanceOf( await expect(service.getGood('99999999')).rejects.toBeInstanceOf(
NotFoundException, NotFoundException,
); );
}); });
@@ -231,4 +379,129 @@ describe('PublicService', () => {
const sortOrders = groups.map((g) => g.sortOrder); const sortOrders = groups.map((g) => g.sortOrder);
expect([...sortOrders].sort((a, b) => a - b)).toEqual(sortOrders); expect([...sortOrders].sort((a, b) => a - b)).toEqual(sortOrders);
}); });
describe('merged secondary origin goods', () => {
it('resolves a good by secondary sdsGoodId with merged variants', async () => {
const secondary = await prisma.originGood.create({
data: { sdsGoodId: `pub-secondary-${stamp}`, goodName: `Pub Secondary ${stamp}` },
});
const secVariant = await prisma.originGoodVariant.create({
data: {
originGoodId: secondary.id,
sdsVariantId: `pub-var-sec-${stamp}`,
sku: `PUB-SEC-${stamp}`,
colorId: 'black',
colorName: '黑色',
imageUrl: 'http://img/black-sec',
},
});
// Attach as secondary source of the highest-priority fixture good.
await prisma.goodOriginGood.create({
data: { goodId: goodIds[0], originGoodId: secondary.id },
});
try {
const detail = await service.getGood(`pub-secondary-${stamp}`);
expect(detail.goodId).toBe(`pub-sds-${stamp}`); // 对外 goodId 仍是主源
expect(detail.variants.length).toBeGreaterThanOrEqual(2);
const black = detail.mediaByColor.find((g) => g.colorName === '黑色');
expect(black).toBeTruthy();
expect(black!.images).toContain('http://img/black-sec');
} finally {
await prisma.goodOriginGood.deleteMany({ where: { originGoodId: secondary.id } });
await prisma.originGoodVariant.delete({ where: { id: secVariant.id } }).catch(() => undefined);
await prisma.originGood.delete({ where: { id: secondary.id } }).catch(() => undefined);
}
});
it('dedupes variants by color+size (primary wins) and merges specs/options', async () => {
const stamp2 = `${stamp}-merge2`;
const primaryOg = await prisma.originGood.create({
data: { sdsGoodId: `pub-pri-${stamp2}`, goodName: `Pub Pri ${stamp2}` },
});
const secondaryOg = await prisma.originGood.create({
data: { sdsGoodId: `pub-sec-${stamp2}`, goodName: `Pub Sec ${stamp2}` },
});
// Primary: Black|S and Black|M, size chart S/M, package S, options S/M.
await prisma.originGoodVariant.createMany({
data: [
{ originGoodId: primaryOg.id, sdsVariantId: `v1-${stamp2}`, sku: `SK1-${stamp2}`, colorName: 'Black', sizeName: 'S', price: 16 },
{ originGoodId: primaryOg.id, sdsVariantId: `v2-${stamp2}`, sku: `SK2-${stamp2}`, colorName: 'black', sizeName: 'M', price: 16 },
],
});
await prisma.originGoodDetail.create({
data: {
originGoodId: primaryOg.id,
sizeChart: { rows: [{ sizeName: 'S', measurements: [{ key: 'chest', cm: '94' }] }, { sizeName: 'M', measurements: [{ key: 'chest', cm: '100' }] }] },
packageSpecs: { rows: [{ sizeName: 'S' }] },
options: { sizes: [{ name: 'S' }, { name: 'M' }] },
media: { images: [{ id: 'i1', url: 'http://img/pri-a', sortOrder: 0 }, { id: 'i2', url: 'http://img/pri-b', sortOrder: 1 }], primaryImageUrl: 'http://img/pri-a' },
},
});
// Secondary: duplicate Black|S with a DIFFERENT price (must be dropped,
// primary wins), plus a unique color Kelly|S; specs add XXXL rows.
await prisma.originGoodVariant.createMany({
data: [
{ originGoodId: secondaryOg.id, sdsVariantId: `v3-${stamp2}`, sku: `SK3-${stamp2}`, colorName: 'Black', sizeName: 'S', price: 20 },
{ originGoodId: secondaryOg.id, sdsVariantId: `v4-${stamp2}`, sku: `SK4-${stamp2}`, colorName: 'Kelly', sizeName: 'S', price: 22 },
],
});
await prisma.originGoodDetail.create({
data: {
originGoodId: secondaryOg.id,
sizeChart: { rows: [{ sizeName: 'XXXL', measurements: [{ key: 'chest', cm: '120' }] }] },
packageSpecs: { rows: [{ sizeName: 'M' }, { sizeName: 'XXXL' }] },
options: { sizes: [{ name: 'XXXL' }] },
media: { images: [{ id: 'i1', url: 'http://img/pri-a', sortOrder: 0 }, { id: 'i9', url: 'http://img/sec-x', sortOrder: 0 }], primaryImageUrl: 'http://img/pri-a' },
},
});
const mergedGood = await prisma.good.create({
data: {
goodName: `Pub Merged ${stamp2}`,
originGoodId: primaryOg.id,
countryId,
categoryId,
},
});
await prisma.goodOriginGood.create({
data: { goodId: mergedGood.id, originGoodId: secondaryOg.id },
});
try {
const detail = await service.getGood(`pub-pri-${stamp2}`);
// Variants: 3 unique color+size combos (case-insensitive); duplicate
// Black|S from the secondary deduped.
expect(
detail.variants.map((v) => `${v.colorName}/${v.sizeName}`.toLowerCase()).sort(),
).toEqual(['black/m', 'black/s', 'kelly/s']);
const blackS = detail.variants.find((v) => v.colorName === 'Black' && v.sizeName === 'S');
expect(blackS!.price).toBe('16'); // primary price wins over secondary 20
// Size chart: S/M from primary, XXXL appended from secondary.
const chartSizes = (detail.sizeChart as any).rows.map((r: any) => r.sizeName).sort();
expect(chartSizes).toEqual(['M', 'S', 'XXXL']);
// Package specs: S from primary, M/XXXL appended from secondary.
const pkgSizes = (detail.packageSpecs as any).rows.map((r: any) => r.sizeName).sort();
expect(pkgSizes).toEqual(['M', 'S', 'XXXL']);
// Options: sizes unioned S/M + XXXL.
const optSizes = (detail.options as any).sizes.map((s: any) => s.name).sort();
expect(optSizes).toEqual(['M', 'S', 'XXXL']);
// Media gallery: primary images first, secondary-only URL appended,
// duplicate URL (pri-a) kept once. Entries keep their object shape.
const media = detail.media as any;
expect(media.images.map((i: any) => i.url)).toEqual([
'http://img/pri-a',
'http://img/pri-b',
'http://img/sec-x',
]);
expect(media.primaryImageUrl).toBe('http://img/pri-a');
} finally {
await prisma.goodOriginGood.deleteMany({ where: { goodId: mergedGood.id } });
await prisma.good.delete({ where: { id: mergedGood.id } });
await prisma.originGoodVariant.deleteMany({ where: { originGoodId: { in: [primaryOg.id, secondaryOg.id] } } });
await prisma.originGoodDetail.deleteMany({ where: { originGoodId: { in: [primaryOg.id, secondaryOg.id] } } });
await prisma.originGood.delete({ where: { id: primaryOg.id } });
await prisma.originGood.delete({ where: { id: secondaryOg.id } }).catch(() => undefined);
}
});
});
}); });
+481 -97
View File
@@ -1,12 +1,20 @@
import { Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Category as PrismaCategory, Prisma } from '@prisma/client'; import { Category as PrismaCategory, Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { PublicQueryGoodDto } from './dto/public-query-good.dto'; import {
PublicHomeGoodsQueryDto,
PublicQueryGoodDto,
PublicTagFilterDto,
} from './dto/public-query-good.dto';
import { PublicCategoryNodeDto } from './dto/public-category.dto'; import { PublicCategoryNodeDto } from './dto/public-category.dto';
import { PublicCountryDto } from './dto/public-country.dto'; import { PublicCountryDto } from './dto/public-country.dto';
import { PublicTagDto } from './dto/public-tag.dto'; import { PublicTagDto } from './dto/public-tag.dto';
import { PublicTagGroupDto } from './dto/public-tag-group.dto'; import { PublicTagGroupDto } from './dto/public-tag-group.dto';
import { PublicGoodDto } from './dto/public-good.dto'; import { PublicGoodDto } from './dto/public-good.dto';
import {
PublicGoodDetailDto,
PublicTagGroupFilterDto,
} from './dto/public-good-detail.dto';
export interface PublicPaginatedGoods { export interface PublicPaginatedGoods {
items: PublicGoodDto[]; items: PublicGoodDto[];
@@ -20,17 +28,39 @@ const PUBLIC_GOOD_INCLUDE = {
category: true, category: true,
tag: { include: { tagGroup: true } }, tag: { include: { tagGroup: true } },
position: true, position: true,
originGood: true, originGood: {
include: {
detail: true,
variants: { orderBy: [{ sortOrder: 'asc' as const }, { id: 'asc' as const }] },
},
},
mergedOriginGoods: {
orderBy: { createdAt: 'asc' as const },
include: {
originGood: {
include: {
detail: true,
variants: { orderBy: [{ sortOrder: 'asc' as const }, { id: 'asc' as const }] },
},
},
},
},
goodTags: { include: { tag: { include: { tagGroup: true } } } }, goodTags: { include: { tag: { include: { tagGroup: true } } } },
} satisfies Prisma.GoodInclude; } satisfies Prisma.GoodInclude;
type PublicGoodRow = Prisma.GoodGetPayload<{ include: typeof PUBLIC_GOOD_INCLUDE }>;
@Injectable() @Injectable()
export class PublicService { export class PublicService {
constructor(private readonly prisma: PrismaService) {} constructor(private readonly prisma: PrismaService) {}
async getCategoriesTree(): Promise<PublicCategoryNodeDto[]> { async getCategoriesTree(countryId?: string): Promise<PublicCategoryNodeDto[]> {
const goodsWhere: Prisma.GoodWhereInput = {
originGood: { delisted: false },
...(countryId ? { countryId: BigInt(countryId) } : {}),
};
const leafCategories = await this.prisma.category.findMany({ const leafCategories = await this.prisma.category.findMany({
where: { goods: { some: {} } }, where: { goods: { some: goodsWhere } },
orderBy: { id: 'asc' }, orderBy: { id: 'asc' },
}); });
const ancestorIds = new Set<bigint>(); const ancestorIds = new Set<bigint>();
@@ -46,22 +76,30 @@ export class PublicService {
cursor = parent.parentCategoryId; cursor = parent.parentCategoryId;
} }
} }
const ancestorRows = ancestorIds.size > 0 const ancestorRows = ancestorIds.size
? await this.prisma.category.findMany({ ? await this.prisma.category.findMany({
where: { id: { in: [...ancestorIds] } }, where: { id: { in: [...ancestorIds] } },
orderBy: { id: 'asc' }, orderBy: { id: 'asc' },
}) })
: []; : [];
const allRows = [...leafCategories, ...ancestorRows].filter( const allRows = [...leafCategories, ...ancestorRows].filter(
(row, idx, arr) => arr.findIndex((r) => r.id === row.id) === idx, (row, index, rows) => rows.findIndex((item) => item.id === row.id) === index,
); );
allRows.sort((a, b) => Number(a.id - b.id)); allRows.sort((a, b) => Number(a.id - b.id));
return this.buildTree(allRows); const directCounts = await this.prisma.good.groupBy({
by: ['categoryId'],
where: goodsWhere,
_count: { _all: true },
});
return this.buildTree(
allRows,
new Map(directCounts.map((row) => [row.categoryId, row._count._all])),
);
} }
async getCountries(): Promise<PublicCountryDto[]> { async getCountries(): Promise<PublicCountryDto[]> {
const rows = await this.prisma.country.findMany({ const rows = await this.prisma.country.findMany({
where: { goods: { some: {} } }, where: { goods: { some: { originGood: { delisted: false } } } },
orderBy: { id: 'asc' }, orderBy: { id: 'asc' },
}); });
return rows.map(PublicCountryDto.from); return rows.map(PublicCountryDto.from);
@@ -69,7 +107,7 @@ export class PublicService {
async getTags(): Promise<PublicTagDto[]> { async getTags(): Promise<PublicTagDto[]> {
const rows = await this.prisma.tag.findMany({ const rows = await this.prisma.tag.findMany({
where: { goodTags: { some: {} } }, where: { goodTags: { some: { good: { originGood: { delisted: false } } } } },
orderBy: [ orderBy: [
{ tagGroup: { sortOrder: 'asc' } }, { tagGroup: { sortOrder: 'asc' } },
{ sortOrder: 'asc' }, { sortOrder: 'asc' },
@@ -80,96 +118,144 @@ export class PublicService {
return rows.map(PublicTagDto.from); return rows.map(PublicTagDto.from);
} }
async getTagGroups(): Promise<PublicTagGroupDto[]> { async getTagGroups(countryId?: string): Promise<PublicTagGroupFilterDto[]> {
const goodWhere: Prisma.GoodWhereInput = {
originGood: { delisted: false },
...(countryId ? { countryId: BigInt(countryId) } : {}),
};
const rows = await this.prisma.tagGroup.findMany({ const rows = await this.prisma.tagGroup.findMany({
where: { tags: { some: { goodTags: { some: {} } } } }, where: { tags: { some: { goodTags: { some: { good: goodWhere } } } } },
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
include: {
tags: {
where: { goodTags: { some: { good: goodWhere } } },
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
include: {
_count: { select: { goodTags: { where: { good: goodWhere } } } },
},
},
},
}); });
return rows.map(PublicTagGroupDto.from); return rows.map((group) => ({
...PublicTagGroupDto.from(group),
tags: group.tags.map((tag) => ({
id: tag.id.toString(),
tagName: tag.tagName,
tagColor: tag.tagColor,
tagFontColor: tag.tagFontColor,
sortOrder: tag.sortOrder,
productCount: tag._count.goodTags,
})),
}));
} }
async getGoods(query: PublicQueryGoodDto): Promise<PublicPaginatedGoods> { async getGoods(query: PublicQueryGoodDto): Promise<PublicPaginatedGoods> {
const where: Prisma.GoodWhereInput = {}; const where: Prisma.GoodWhereInput = { originGood: { delisted: false } };
if (query.countryId !== undefined) where.countryId = BigInt(query.countryId); if (query.countryId) where.countryId = BigInt(query.countryId);
if (query.tagIds) { if (query.keyword) where.goodName = { contains: query.keyword, mode: 'insensitive' };
const ids = query.tagIds if (query.categoryId) {
.split(',') where.categoryId = { in: await this.collectCategoryDescendants(BigInt(query.categoryId)) };
.map((s) => s.trim())
.filter(Boolean)
.map((s) => BigInt(s));
if (ids.length > 0) {
// AND logic: 商品必须同时具备所有选中的 tag
where.AND = ids.map((id) => ({ goodTags: { some: { tagId: id } } }));
}
} }
if (query.keyword) {
where.goodName = { contains: query.keyword, mode: 'insensitive' }; const tagFilters = await this.buildTagGroupFilters(query.tags ?? []);
if (tagFilters.length) where.AND = tagFilters;
const minPrice = this.parsePrice(query.minPrice, 'minPrice');
const maxPrice = this.parsePrice(query.maxPrice, 'maxPrice');
if (minPrice !== null && maxPrice !== null && minPrice > maxPrice) {
throw new BadRequestException('minPrice 不能大于 maxPrice');
} }
if (query.categoryId !== undefined) { if (minPrice !== null || maxPrice !== null) {
const ids = await this.collectCategoryDescendants(BigInt(query.categoryId)); where.originGood = {
where.categoryId = { in: ids }; delisted: false,
goodPrice: {
...(minPrice !== null ? { gte: minPrice } : {}),
...(maxPrice !== null ? { lte: maxPrice } : {}),
},
};
} }
const orderBy: Prisma.GoodOrderByWithRelationInput[] =
query.sort === 'PRICE_ASC'
? [{ originGood: { goodPrice: 'asc' } }, { id: 'asc' }]
: query.sort === 'PRICE_DESC'
? [{ originGood: { goodPrice: 'desc' } }, { id: 'asc' }]
: query.sort === 'NEWEST'
? [{ createdAt: 'desc' }, { id: 'asc' }]
: [
{ goodPriority: 'desc' },
{ position: { indexVal: 'asc' } },
{ createdAt: 'desc' },
{ id: 'asc' },
];
const [total, rows] = await this.prisma.$transaction([ const [total, rows] = await this.prisma.$transaction([
this.prisma.good.count({ where }), this.prisma.good.count({ where }),
this.prisma.good.findMany({ this.prisma.good.findMany({
where, where,
include: PUBLIC_GOOD_INCLUDE, include: PUBLIC_GOOD_INCLUDE,
// Server-side primary sort; PublicGoodDto retains original indexes orderBy,
// for stable pagination but the final ORDER BY is mirrored below.
orderBy: [
{ goodPriority: 'desc' },
{ position: { indexVal: 'asc' } },
{ createdAt: 'desc' },
],
skip: (query.page - 1) * query.pageSize, skip: (query.page - 1) * query.pageSize,
take: query.pageSize, take: query.pageSize,
}), }),
]); ]);
return { return {
items: rows.map((g) => this.toPublicGood(g)), items: rows.map((good) => this.toPublicGood(good)),
total, total,
page: query.page, page: query.page,
pageSize: query.pageSize, pageSize: query.pageSize,
}; };
} }
async getGood(id: bigint): Promise<PublicGoodDto> { async getGood(goodId: string): Promise<PublicGoodDetailDto> {
const good = await this.prisma.good.findUnique({ const good = await this.prisma.good.findFirst({
where: { id }, where: {
OR: [
{ originGood: { sdsGoodId: goodId, delisted: false } },
// Merged secondary sources also resolve to the same good.
{
mergedOriginGoods: {
some: { originGood: { sdsGoodId: goodId, delisted: false } },
},
},
],
},
include: PUBLIC_GOOD_INCLUDE, include: PUBLIC_GOOD_INCLUDE,
orderBy: [{ goodPriority: 'desc' }, { id: 'asc' }],
}); });
if (!good) throw new NotFoundException(`Good ${id} not found`); if (!good) {
return this.toPublicGood(good); throw new NotFoundException({ message: '不存在商品', error: 'PRODUCT_NOT_FOUND' });
}
const dto = this.toPublicGoodDetail(good);
dto.category.categoryIcon = await this.resolveCategoryIcon(good.category);
return dto;
} }
private toPublicGood(good: { async getHomeGoods(query: PublicHomeGoodsQueryDto): Promise<PublicGoodDto[]> {
id: bigint; const rows = await this.prisma.good.findMany({
goodName: string; where: {
goodImage: string | null; positionId: { not: null },
goodPriority: number; originGood: { delisted: false },
country: { id: bigint; countryName: string; countryIcon: string | null }; ...(query.countryId ? { countryId: BigInt(query.countryId) } : {}),
category: { id: bigint; categoryName: string; categoryIcon: string | null }; },
tag: { id: bigint; tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroup: { id: bigint; groupName: string; sortOrder: number } | null } | null; include: PUBLIC_GOOD_INCLUDE,
position: { id: bigint; indexVal: number } | null; orderBy: [
originGood: { { position: { indexVal: 'asc' } },
goodImage: string | null; { goodPriority: 'desc' },
goodPrice: { toString(): string } | null; { id: 'asc' },
} | null; ],
goodTags: { tag: { id: bigint; tagName: string; tagColor: string | null; tagFontColor: string | null; tagGroup: { id: bigint; groupName: string; sortOrder: number } | null } }[]; take: query.limit,
createdAt: Date; });
}): PublicGoodDto { return rows.map((good) => this.toPublicGood(good));
const formatGroup = (g: { id: bigint; groupName: string; sortOrder: number } | null) => }
g
? { private toPublicGood(good: PublicGoodRow): PublicGoodDto {
id: g.id.toString(), const formatGroup = (group: { id: bigint; groupName: string; sortOrder: number } | null) =>
groupName: g.groupName, group
sortOrder: g.sortOrder, ? { id: group.id.toString(), groupName: group.groupName, sortOrder: group.sortOrder }
}
: null; : null;
return { return {
id: good.id.toString(), goodId: good.originGood.sdsGoodId,
goodName: good.goodName, goodName: good.goodName,
goodPriority: good.goodPriority, goodPriority: good.goodPriority,
country: { country: {
@@ -191,63 +277,361 @@ export class PublicService {
group: formatGroup(good.tag.tagGroup), group: formatGroup(good.tag.tagGroup),
} }
: null, : null,
tags: good.goodTags.map((gt) => ({ tags: good.goodTags.map(({ tag }) => ({
id: gt.tag.id.toString(), id: tag.id.toString(),
tagName: gt.tag.tagName, tagName: tag.tagName,
tagColor: gt.tag.tagColor, tagColor: tag.tagColor,
tagFontColor: gt.tag.tagFontColor, tagFontColor: tag.tagFontColor,
group: formatGroup(gt.tag.tagGroup), group: formatGroup(tag.tagGroup),
})), })),
position: good.position position: good.position
? { ? { id: good.position.id.toString(), indexVal: good.position.indexVal }
id: good.position.id.toString(),
indexVal: good.position.indexVal,
}
: null, : null,
image: good.goodImage ?? good.originGood?.goodImage ?? null, image: good.goodImage ?? good.originGood.goodImage,
price: price: good.originGood.goodPrice?.toString() ?? null,
good.originGood?.goodPrice === null ||
good.originGood?.goodPrice === undefined
? null
: good.originGood.goodPrice.toString(),
createdAt: good.createdAt.toISOString(), createdAt: good.createdAt.toISOString(),
}; };
} }
/** Group distinct variant images by color so the frontend can switch media per color.
* Only color-specific photos are included (main / result / detail images);
* design-layer素材图 and the product-level blank garment photo are excluded
* because they are not per-color gallery photos. */
private groupImagesByColor(
variants: Array<PublicGoodRow['originGood']['variants'][number]>,
): Array<{ colorId: string | null; colorName: string | null; colorHex: string | null; images: string[] }> {
const groups = new Map<string, {
colorId: string | null;
colorName: string | null;
colorHex: string | null;
images: string[];
}>();
for (const variant of variants) {
const key = variant.colorId ?? `variant:${variant.sdsVariantId}`;
let group = groups.get(key);
if (!group) {
group = {
colorId: variant.colorId,
colorName: variant.colorName,
colorHex: variant.colorHex,
images: [],
};
groups.set(key, group);
}
const design = (variant.designData ?? {}) as {
detailImgUrls?: Array<{ imageUrl?: unknown }>;
prototypeResultGroups?: Array<{ resultImage?: unknown }>;
};
const urls: unknown[] = [
variant.imageUrl,
...(design.prototypeResultGroups ?? []).map((item) => item?.resultImage),
...(design.detailImgUrls ?? []).map((image) => image?.imageUrl),
];
for (const url of urls) {
const value = typeof url === 'string' ? url.trim() : '';
if (value && !group.images.includes(value)) {
group.images.push(value);
}
}
}
return [...groups.values()];
}
/** Leaf categories often have no icon upstream; fall back to the nearest ancestor that has one. */
private async resolveCategoryIcon(category: PublicGoodRow['category']): Promise<string | null> {
if (category.categoryIcon) return category.categoryIcon;
let cursor = category.parentCategoryId;
for (let depth = 0; cursor !== null && depth < 10; depth++) {
const parent = await this.prisma.category.findUnique({
where: { id: cursor },
select: { categoryIcon: true, parentCategoryId: true },
});
if (!parent) break;
if (parent.categoryIcon) return parent.categoryIcon;
cursor = parent.parentCategoryId;
}
return null;
}
private toPublicGoodDetail(good: PublicGoodRow): PublicGoodDetailDto {
const base = this.toPublicGood(good);
const detail = good.originGood.detail;
// Merge primary and secondary origin goods: variants deduped by
// color+size (primary wins), detail specs filled from secondaries
// for sizes/options the primary does not have.
const secondaryDetails = good.mergedOriginGoods
.map((m) => m.originGood.detail)
.filter((d): d is NonNullable<typeof d> => Boolean(d));
const secondaryVariantLists = good.mergedOriginGoods.map((m) => m.originGood.variants);
const allVariants = this.dedupeVariants([
...good.originGood.variants,
...secondaryVariantLists.flat(),
]);
return {
...base,
productCode: detail?.productCode ?? null,
englishName: detail?.englishName ?? null,
productionCycleHours: detail?.productionCycleHours ?? null,
minWeightG: detail?.minWeightG?.toString() ?? null,
details: {
reminder: detail?.reminder ?? null,
productionProcess: detail?.productionProcess ?? null,
materialDescription: detail?.materialDescription ?? null,
productPerformance: detail?.productPerformance ?? null,
applicableScenarios: detail?.applicableScenarios ?? null,
washingInstructions: detail?.washingInstructions ?? null,
specialDescription: detail?.specialDescription ?? null,
designExplanation: detail?.designExplanation ?? null,
designArea: detail?.designArea ?? null,
pictureRequest: detail?.pictureRequest ?? null,
},
media: this.mergeMedia(detail, secondaryDetails),
mediaByColor: this.groupImagesByColor(allVariants),
options: this.mergeOptions(detail, secondaryDetails),
sizeChart: this.mergeRowsByKey(detail, secondaryDetails, 'sizeChart'),
packageSpecs: this.mergeRowsByKey(detail, secondaryDetails, 'packageSpecs'),
variants: allVariants.map((variant) => ({
id: variant.sdsVariantId,
sku: variant.sku,
sizeId: variant.sizeId,
sizeName: variant.sizeName,
colorId: variant.colorId,
colorName: variant.colorName,
colorHex: variant.colorHex,
imageUrl: variant.imageUrl,
price: variant.price?.toString() ?? null,
originalPrice: variant.originalPrice?.toString() ?? null,
weightG: variant.weightG?.toString() ?? null,
boxLengthCm: variant.boxLengthCm?.toString() ?? null,
boxWidthCm: variant.boxWidthCm?.toString() ?? null,
boxHeightCm: variant.boxHeightCm?.toString() ?? null,
enabled: variant.enabled,
sortOrder: variant.sortOrder,
})),
detailSyncedAt: detail?.syncedAt.toISOString() ?? null,
};
}
/** Norm key for variant/dedupe matching: case-insensitive, trimmed. */
private static normName(value: string | null | undefined): string {
return (value ?? '').trim().toLowerCase();
}
/** Dedupe variants by color+size (case-insensitive); first (primary) wins. */
private dedupeVariants(variants: PublicGoodRow['originGood']['variants']) {
const seen = new Set<string>();
const result: PublicGoodRow['originGood']['variants'] = [];
for (const variant of variants) {
const key = `${PublicService.normName(variant.colorName)}|${PublicService.normName(variant.sizeName)}`;
if (seen.has(key)) continue;
seen.add(key);
result.push(variant);
}
return result;
}
/**
* Merge a `{ rows: [...] }` spec (sizeChart / packageSpecs) across primary
* and secondary details: primary rows win, rows for sizes the primary
* lacks are appended from secondaries in order.
*/
private mergeRowsByKey(
primary: PublicGoodRow['originGood']['detail'],
secondaries: NonNullable<PublicGoodRow['originGood']['detail']>[],
field: 'sizeChart' | 'packageSpecs',
): Record<string, unknown> | null {
const primaryRows = (primary?.[field] as { rows?: Array<Record<string, unknown>> } | null)?.rows;
if (!Array.isArray(primaryRows) && secondaries.length === 0) return null;
const rows: Array<Record<string, unknown>> = Array.isArray(primaryRows) ? [...primaryRows] : [];
const seen = new Set(rows.map((r) => PublicService.normName(String(r?.sizeName ?? ''))));
for (const sec of secondaries) {
const secRows = (sec[field] as { rows?: Array<Record<string, unknown>> } | null)?.rows;
if (!Array.isArray(secRows)) continue;
for (const row of secRows) {
const key = PublicService.normName(String(row?.sizeName ?? ''));
if (seen.has(key)) continue;
seen.add(key);
rows.push(row);
}
}
if (rows.length === 0) return null;
return { ...(primary?.[field] as Record<string, unknown> | null ?? {}), rows };
}
/**
* Merge options across details: sizes/colors are unioned by name,
* primary entries win and secondary-only ones are appended.
*/
private mergeOptions(
primary: PublicGoodRow['originGood']['detail'],
secondaries: NonNullable<PublicGoodRow['originGood']['detail']>[],
): Record<string, unknown> | null {
const primaryOptions = primary?.options as
| { sizes?: Array<Record<string, unknown>>; colors?: Array<Record<string, unknown>> }
| null;
if (!primaryOptions && secondaries.length === 0) return null;
const merged: Record<string, unknown> = { ...(primaryOptions ?? {}) };
for (const listKey of ['sizes', 'colors'] as const) {
const base = Array.isArray(primaryOptions?.[listKey])
? [...(primaryOptions![listKey] as Array<Record<string, unknown>>)]
: null;
if (!base && secondaries.length === 0) continue;
const rows = base ?? [];
const seen = new Set(rows.map((r) => PublicService.normName(String(r?.name ?? ''))));
for (const sec of secondaries) {
const secOptions = sec.options as
| { sizes?: Array<Record<string, unknown>>; colors?: Array<Record<string, unknown>> }
| null;
const secRows = secOptions?.[listKey];
if (!Array.isArray(secRows)) continue;
for (const row of secRows) {
const key = PublicService.normName(String(row?.name ?? ''));
if (seen.has(key)) continue;
seen.add(key);
rows.push(row);
}
}
merged[listKey] = rows;
}
return merged;
}
/**
* Merge the gallery `media` across details: primary images first,
* secondary-only image URLs appended (URL-deduped). `primaryImageUrl`
* stays the primary's. Image entries keep their original shape
* (`{id,url,sortOrder}` objects or plain strings).
*/
private mergeMedia(
primary: PublicGoodRow['originGood']['detail'],
secondaries: NonNullable<PublicGoodRow['originGood']['detail']>[],
): Record<string, unknown> | null {
const imageUrl = (img: unknown): string | null => {
if (typeof img === 'string') return img;
if (img && typeof img === 'object' && typeof (img as { url?: unknown }).url === 'string') {
return (img as { url: string }).url;
}
return null;
};
const primaryMedia = (primary?.media as Record<string, unknown> | null) ?? null;
const primaryImages = Array.isArray(primaryMedia?.images)
? (primaryMedia!.images as unknown[])
: null;
if (!primaryImages && secondaries.length === 0) return null;
const images: unknown[] = primaryImages ? [...primaryImages] : [];
const seen = new Set(images.map(imageUrl).filter((u): u is string => Boolean(u)));
for (const sec of secondaries) {
const secMedia = sec.media as { images?: unknown } | null;
if (!Array.isArray(secMedia?.images)) continue;
for (const img of secMedia!.images as unknown[]) {
const url = imageUrl(img);
if (!url || seen.has(url)) continue;
seen.add(url);
images.push(img);
}
}
if (images.length === 0) return null;
return { ...(primaryMedia ?? {}), images };
}
private async buildTagGroupFilters(
selectedGroups: PublicTagFilterDto[],
): Promise<Prisma.GoodWhereInput[]> {
const selections = selectedGroups.flatMap((group) => {
if (!/^\d+$/.test(group.tagGroupId) || !Array.isArray(group.tagIds)) {
throw new BadRequestException(
'tags 每个元素必须包含合法的 tagGroupId 和 tagIds',
);
}
return group.tagIds.map((tagId) => {
if (!/^\d+$/.test(tagId)) {
throw new BadRequestException('tagIds 必须全部为数字字符串');
}
return { tagGroupId: group.tagGroupId, tagId };
});
});
const uniqueTagIds = [...new Set(selections.map((item) => item.tagId))];
const selected = uniqueTagIds.length
? await this.prisma.tag.findMany({
where: { id: { in: uniqueTagIds.map((id) => BigInt(id)) } },
select: { id: true, tagGroupId: true },
})
: [];
if (selected.length !== uniqueTagIds.length) {
throw new BadRequestException('包含不存在的标签 ID');
}
const actualGroups = new Map(
selected.map((tag) => [
tag.id.toString(),
tag.tagGroupId?.toString() ?? null,
]),
);
for (const selection of selections) {
if (actualGroups.get(selection.tagId) !== selection.tagGroupId) {
throw new BadRequestException(
`标签 ${selection.tagId} 不属于标签组 ${selection.tagGroupId}`,
);
}
}
const byGroup = new Map<string, bigint[]>();
for (const selection of selections) {
const key = selection.tagGroupId;
const ids = byGroup.get(key) ?? [];
const id = BigInt(selection.tagId);
if (!ids.includes(id)) ids.push(id);
byGroup.set(key, ids);
}
return [...byGroup.values()].map((ids) => ({
goodTags: { some: { tagId: { in: ids } } },
}));
}
private parsePrice(value: string | undefined, field: string): number | null {
if (value === undefined || value === '') return null;
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
throw new BadRequestException(`${field} 必须是大于等于 0 的金额`);
}
return parsed;
}
private async collectCategoryDescendants(rootId: bigint): Promise<bigint[]> { private async collectCategoryDescendants(rootId: bigint): Promise<bigint[]> {
const ids: bigint[] = [rootId]; const ids: bigint[] = [rootId];
let frontier: bigint[] = [rootId]; let frontier: bigint[] = [rootId];
while (frontier.length > 0) { while (frontier.length) {
const children = await this.prisma.category.findMany({ const children = await this.prisma.category.findMany({
where: { parentCategoryId: { in: frontier } }, where: { parentCategoryId: { in: frontier } },
select: { id: true }, select: { id: true },
}); });
if (children.length === 0) break; if (!children.length) break;
const childIds = children.map((c) => c.id); frontier = children.map((child) => child.id);
ids.push(...childIds); ids.push(...frontier);
frontier = childIds;
} }
return ids; return ids;
} }
private buildTree( private buildTree(
rows: PrismaCategory[], rows: PrismaCategory[],
directCounts: Map<bigint, number>,
): PublicCategoryNodeDto[] { ): PublicCategoryNodeDto[] {
const byId = new Map<bigint, PublicCategoryNodeDto>(); const byId = new Map<bigint, PublicCategoryNodeDto>();
for (const row of rows) { for (const row of rows) {
byId.set(row.id, PublicCategoryNodeDto.from(row, [])); const node = PublicCategoryNodeDto.from(row, []);
node.productCount = directCounts.get(row.id) ?? 0;
byId.set(row.id, node);
} }
const roots: PublicCategoryNodeDto[] = []; const roots: PublicCategoryNodeDto[] = [];
for (const row of rows) { for (const row of rows) {
const node = byId.get(row.id)!; const node = byId.get(row.id)!;
if (row.parentCategoryId === null) { const parent = row.parentCategoryId === null ? null : byId.get(row.parentCategoryId);
roots.push(node); if (parent) parent.children.push(node);
} else { else roots.push(node);
const parent = byId.get(row.parentCategoryId);
if (parent) parent.children.push(node);
else roots.push(node);
}
} }
const total = (node: PublicCategoryNodeDto): number => {
node.productCount += node.children.reduce((sum, child) => sum + total(child), 0);
return node.productCount;
};
roots.forEach(total);
return roots; return roots;
} }
} }
+1 -1
View File
@@ -6,7 +6,7 @@ export class SyncLogDto {
id!: string; id!: string;
@ApiProperty() @ApiProperty()
type!: 'CATEGORIES' | 'PRODUCTS'; type!: 'CATEGORIES' | 'PRODUCTS' | 'PRODUCT_DETAILS';
@ApiProperty() @ApiProperty()
status!: 'RUNNING' | 'SUCCESS' | 'FAILED'; status!: 'RUNNING' | 'SUCCESS' | 'FAILED';
@@ -0,0 +1,55 @@
import { Test } from '@nestjs/testing';
import { of } from 'rxjs';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { SdsClientService } from './sds-client.service';
describe('SdsClientService', () => {
let service: SdsClientService;
let http: { post: jest.Mock; get: jest.Mock };
beforeEach(async () => {
http = { post: jest.fn(), get: jest.fn() };
const moduleRef = await Test.createTestingModule({
providers: [
SdsClientService,
{ provide: HttpService, useValue: http },
{ provide: ConfigService, useValue: { get: jest.fn(() => undefined) } },
],
}).compile();
service = moduleRef.get(SdsClientService);
});
describe('fetchCategoryTree', () => {
it('throws when the upstream returns a degenerate small tree', async () => {
http.post.mockReturnValue(of({ data: [{ id: 1, name: 'Only' }] }));
await expect(service.fetchCategoryTree()).rejects.toThrow(/degenerate/i);
});
it('returns the tree when it is healthy', async () => {
const tree = Array.from({ length: 20 }, (_, i) => ({ id: i + 1, name: `C${i}` }));
http.post.mockReturnValue(of({ data: tree }));
const result = await service.fetchCategoryTree();
expect(result).toHaveLength(20);
});
});
describe('fetchProductDetail', () => {
it('requests /products/{goodId} and validates the returned id', async () => {
http.get.mockReturnValue(of({ data: { id: 168746, sku: 'OZ10827003' } }));
const result = await service.fetchProductDetail('168746');
expect(result.sku).toBe('OZ10827003');
expect(http.get).toHaveBeenCalledWith(
'https://mapi.sdspod.com/products/168746',
expect.objectContaining({ headers: expect.any(Object) }),
);
});
it('rejects a mismatched product response', async () => {
http.get.mockReturnValue(of({ data: { id: 1 } }));
await expect(service.fetchProductDetail('168746')).rejects.toThrow(/id mismatch/i);
});
});
});
+149 -18
View File
@@ -9,6 +9,13 @@ const POD_HEADERS = {
Referer: 'https://inkpod.vip/', Referer: 'https://inkpod.vip/',
} as const; } as const;
/**
* Minimum number of category nodes a healthy `category/tree/3` response contains.
* Below this the response is treated as degenerate and rejected so the caller
* never runs a destructive sync against a partial tree.
*/
export const MIN_SDS_CATEGORY_NODES = 10;
export interface SdsCategoryTreeNode { export interface SdsCategoryTreeNode {
id: number | string | null; id: number | string | null;
name?: string; name?: string;
@@ -45,6 +52,86 @@ export interface SdsProductsPage {
[key: string]: unknown; [key: string]: unknown;
} }
export interface SdsProductVariant extends Record<string, unknown> {
id?: number | string;
sku?: string;
size?: string;
sizeId?: number | string;
sizeDto?: { id?: number | string; sizeName?: string };
colorId?: number | string;
color_name?: string;
color?: {
colorId?: number | string;
color?: string;
color_name?: string;
chineseName?: string;
};
currentPrice?: number | string;
originalPrice?: number | string;
unit_price?: number | string;
min_price?: number | string;
weight?: number | string;
box_length?: number | string;
box_width?: number | string;
box_height?: number | string;
status?: number | string;
delFlag?: number | string;
size_sort?: number | string;
attribute_sort?: string;
psd_img_url?: string;
img_url?: string;
blankDesignUrl?: string;
designPrototype?: {
detailImgUrls?: Array<{ imageUrl?: string }>;
prototypeResultGroups?: Array<{ resultImage?: string }>;
[key: string]: unknown;
};
}
export interface SdsProductDetail extends Record<string, unknown> {
id: number | string;
name?: string;
sku?: string;
english_name?: string;
blankDesignUrl?: string;
detailsPageVideoUrl?: string;
productionCycle?: number | string;
minWeight?: number | string;
min_price?: number | string;
updateTime?: number | string;
psd_img_url?: string;
img_url?: string;
texture?: { name?: string };
product_details?: {
reminder?: string;
production_process?: string;
material_description?: string;
product_performance?: string;
applicable_scenarios?: string;
washing_instructions?: string;
special_description?: string;
design_explanation?: string;
design_area?: string;
picture_request?: string;
product_size?: string;
packaging_specification?: string;
};
subproducts?: {
attributers?: Array<{
size?: string;
sizeId?: number | string;
colors?: Array<{
colorId?: number | string;
color?: string;
color_name?: string;
chineseName?: string;
colorSort?: number | string;
}>;
}>;
items?: SdsProductVariant[];
};
}
/** /**
* Thin wrapper around the SDS (mapi.sdspod.com) endpoints that the * Thin wrapper around the SDS (mapi.sdspod.com) endpoints that the
* `SyncService` consumes. * `SyncService` consumes.
@@ -65,10 +152,39 @@ export class SdsClientService {
'https://mapi.sdspod.com'; 'https://mapi.sdspod.com';
} }
/** private async request<T>(
* Fetches the SDS category tree of type 3 (products category). method: 'post' | 'get',
* Body matches the legacy inkpod client. url: string,
*/ body?: unknown,
params?: Record<string, unknown>,
): Promise<T> {
const MAX_RETRIES = 3;
let lastError: unknown;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
const config = {
headers: POD_HEADERS,
timeout: 30000,
...(params ? { params } : {}),
};
const obs =
method === 'post'
? this.http.post<T>(url, body, config)
: this.http.get<T>(url, config);
const { data } = await firstValueFrom(obs);
return data as T;
} catch (err) {
lastError = err;
const msg = err instanceof Error ? err.message : String(err);
if (attempt < MAX_RETRIES) {
this.logger.warn(`SDS request attempt ${attempt}/${MAX_RETRIES} failed: ${msg}`);
await new Promise((r) => setTimeout(r, 1000 * attempt));
}
}
}
throw lastError;
}
async fetchCategoryTree(): Promise<SdsCategoryTreeNode[]> { async fetchCategoryTree(): Promise<SdsCategoryTreeNode[]> {
const url = `${this.baseUrl}/category/tree/3`; const url = `${this.baseUrl}/category/tree/3`;
const body = { const body = {
@@ -76,27 +192,42 @@ export class SdsClientService {
withPrivate: true, withPrivate: true,
onlyHaveProduct: true, onlyHaveProduct: true,
}; };
const { data } = await firstValueFrom( const data = await this.request<unknown>('post', url, body);
this.http.post<SdsCategoryTreeNode[]>(url, body, { headers: POD_HEADERS }), if (!Array.isArray(data)) {
); throw new Error(`SDS category tree returned ${typeof data}, expected array`);
return Array.isArray(data) ? data : []; }
if (data.length < MIN_SDS_CATEGORY_NODES) {
throw new Error(
`SDS category tree is degenerate (${data.length} nodes < ${MIN_SDS_CATEGORY_NODES}) — ` +
`aborting to avoid destructive sync`,
);
}
return data as SdsCategoryTreeNode[];
} }
/**
* Fetches one page of products for a given SDS category.
*/
async fetchProductsPage( async fetchProductsPage(
categoryId: string | number, categoryId: string | number,
page = 1, page = 1,
size = 50, size = 50,
): Promise<SdsProductsPage> { ): Promise<SdsProductsPage> {
const url = `${this.baseUrl}/products/page`; const url = `${this.baseUrl}/products/page`;
const { data } = await firstValueFrom( const data = await this.request<unknown>('get', url, undefined, { categoryId, page, size });
this.http.get<SdsProductsPage>(url, { if (!data || typeof data !== 'object') {
headers: POD_HEADERS, throw new Error(`SDS products page returned ${typeof data}, expected object`);
params: { categoryId, page, size }, }
}), return data as SdsProductsPage;
); }
return data ?? {};
async fetchProductDetail(goodId: string | number): Promise<SdsProductDetail> {
const url = `${this.baseUrl}/products/${encodeURIComponent(String(goodId))}`;
const data = await this.request<unknown>('get', url);
if (!data || typeof data !== 'object' || Array.isArray(data)) {
throw new Error(`SDS product detail returned ${typeof data}, expected object`);
}
const detail = data as SdsProductDetail;
if (String(detail.id) !== String(goodId)) {
throw new Error(`SDS product detail id mismatch: expected ${goodId}, got ${String(detail.id)}`);
}
return detail;
} }
} }
@@ -0,0 +1,86 @@
import {
normalizeProductDetail,
parsePackageSpecs,
parseSizeChart,
} from './sds-product-detail.mapper';
const sizeTable = JSON.stringify([
['尺码', '衣长(cm/in)', '胸围(cm/in)', '肩宽(cm/in)', '袖长(cm/in)'].map((content) => ({ content, remark: '' })),
['S', '71', '92', '43', '22'].map((content) => ({ content, remark: '' })),
['M', '74', '102', '45', '22'].map((content) => ({ content, remark: '' })),
['L', '76', '112', '48', '23'].map((content) => ({ content, remark: '' })),
['XL', '79', '122', '51', '23'].map((content) => ({ content, remark: '' })),
['2XL', '82', '132', '53', '25'].map((content) => ({ content, remark: '' })),
['3XL', '84', '142', '56', '25'].map((content) => ({ content, remark: '' })),
]);
const packageTable = JSON.stringify([
['尺码', '包装尺寸(cm', '包装尺寸(in', '包装体积(cm³)', '包装体积(in³)', '含包装重量(g', '含包装重量(lb'].map((content) => ({ content })),
['S', '36.0*26.0*1.0\t', '14.17*10.24*0.39\t', '936.00', '57.12', '208.00', '0.46'].map((content) => ({ content })),
['M', '36.0*26.0*1.0', '14.17*10.24*0.39', '936.00', '57.12', '218.00', '0.48'].map((content) => ({ content })),
]);
describe('SDS product detail mapper', () => {
it('parses the product_detail.txt size table into structured rows', () => {
const chart = parseSizeChart(sizeTable) as any;
expect(chart.columns.map((column: any) => column.key)).toEqual([
'bodyLength',
'chest',
'shoulder',
'sleeveLength',
]);
expect(chart.rows).toHaveLength(6);
expect(chart.rows[0].measurements[0]).toEqual({ key: 'bodyLength', cm: '71', in: '27.95' });
});
it('parses packaging dimensions and weights', () => {
const specs = parsePackageSpecs(packageTable) as any;
expect(specs.rows).toHaveLength(2);
expect(specs.rows[0].dimensionsCm).toEqual({ length: '36.0', width: '26.0', height: '1.0' });
expect(specs.rows[0].grossWeightG).toBe('208.00');
});
it('normalizes detail text, options and variants', () => {
const normalized = normalizeProductDetail({
id: 168746,
sku: 'OZ10827003',
english_name: 't-shirt',
productionCycle: 24,
minWeight: 250,
product_details: {
production_process: '白墨烫画',
material_description: '100%纯棉',
product_size: sizeTable,
packaging_specification: packageTable,
},
subproducts: {
attributers: [{
size: 'S',
sizeId: 1922304,
colors: [{ colorId: 1139383, color: '#000300', color_name: 'black', colorSort: 1 }],
}],
items: [{
id: 168747,
sku: 'OZ10827003001',
size: 'S',
sizeId: 1922304,
colorId: 1139383,
color: { colorId: 1139383, color: '#000300', color_name: 'black' },
currentPrice: 38,
originalPrice: 38,
weight: 250,
box_length: 30,
box_width: 20,
box_height: 5,
status: 1,
delFlag: '0',
}],
},
});
expect(normalized.productCode).toBe('OZ10827003');
expect(normalized.productionProcess).toBe('白墨烫画');
expect(normalized.variants[0].sku).toBe('OZ10827003001');
expect(normalized.variants[0].price?.toString()).toBe('38');
});
});
@@ -0,0 +1,261 @@
import { Prisma } from '@prisma/client';
import { SdsProductDetail, SdsProductVariant } from './sds-client.service';
type TableCell = { content?: unknown; remark?: unknown };
type Table = TableCell[][];
export interface NormalizedVariant {
sdsVariantId: string;
sku: string;
sizeId: string | null;
sizeName: string | null;
colorId: string | null;
colorName: string | null;
colorHex: string | null;
imageUrl: string | null;
price: Prisma.Decimal | null;
originalPrice: Prisma.Decimal | null;
weightG: Prisma.Decimal | null;
boxLengthCm: Prisma.Decimal | null;
boxWidthCm: Prisma.Decimal | null;
boxHeightCm: Prisma.Decimal | null;
enabled: boolean;
sortOrder: number;
designData: Prisma.InputJsonValue | null;
}
export interface NormalizedProductDetail {
productCode: string | null;
englishName: string | null;
blankDesignUrl: string | null;
detailsPageVideoUrl: string | null;
textureName: string | null;
productionCycleHours: number | null;
minWeightG: Prisma.Decimal | null;
reminder: string | null;
productionProcess: string | null;
materialDescription: string | null;
productPerformance: string | null;
applicableScenarios: string | null;
washingInstructions: string | null;
specialDescription: string | null;
designExplanation: string | null;
designArea: string | null;
pictureRequest: string | null;
sizeChart: Prisma.InputJsonValue | null;
packageSpecs: Prisma.InputJsonValue | null;
options: Prisma.InputJsonValue | null;
media: Prisma.InputJsonValue | null;
upstreamUpdatedAt: Date | null;
variants: NormalizedVariant[];
}
const text = (value: unknown): string | null => {
if (value === undefined || value === null) return null;
const normalized = String(value).trim();
return normalized.length > 0 ? normalized : null;
};
const decimal = (value: unknown): Prisma.Decimal | null => {
if (value === undefined || value === null || value === '') return null;
const n = Number(value);
return Number.isFinite(n) ? new Prisma.Decimal(n) : null;
};
const integer = (value: unknown): number | null => {
const n = Number(value);
return Number.isInteger(n) ? n : null;
};
function parseTable(raw: unknown): Table | null {
if (typeof raw !== 'string' || raw.trim() === '') return null;
try {
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed) || parsed.length < 2) return null;
const rows = parsed.filter(Array.isArray) as Table;
return rows.length >= 2 ? rows : null;
} catch {
return null;
}
}
const cell = (row: TableCell[], index: number): string =>
text(row[index]?.content)?.replace(/\t/g, '').trim() ?? '';
const measurementKey = (header: string, index: number): string => {
if (header.includes('衣长')) return 'bodyLength';
if (header.includes('胸围')) return 'chest';
if (header.includes('肩宽')) return 'shoulder';
if (header.includes('袖长')) return 'sleeveLength';
return `measurement${index}`;
};
export function parseSizeChart(raw: unknown): Prisma.InputJsonValue | null {
const table = parseTable(raw);
if (!table) return null;
const [header, ...body] = table;
const columns = header.slice(1).map((item, index) => {
const name = text(item.content)?.replace(/\s*\(cm\/in\)\s*/i, '') ?? `规格${index + 1}`;
return { key: measurementKey(name, index + 1), name };
});
const rows = body
.map((row, rowIndex) => {
const sizeName = cell(row, 0);
if (!sizeName) return null;
return {
sizeId: `size_${rowIndex}`,
sizeName,
measurements: columns.map((column, index) => {
const cm = cell(row, index + 1);
const cmNumber = Number(cm);
return {
key: column.key,
cm: cm || null,
in: Number.isFinite(cmNumber) ? (cmNumber / 2.54).toFixed(2) : null,
};
}),
};
})
.filter((row): row is NonNullable<typeof row> => row !== null);
return { columns, rows } as Prisma.InputJsonValue;
}
function dimensions(value: string): { length: string; width: string; height: string } | null {
const parts = value
.replace(/[×x]/gi, '*')
.split('*')
.map((part) => part.trim());
if (parts.length !== 3 || parts.some((part) => !Number.isFinite(Number(part)))) return null;
return { length: parts[0], width: parts[1], height: parts[2] };
}
export function parsePackageSpecs(raw: unknown): Prisma.InputJsonValue | null {
const table = parseTable(raw);
if (!table) return null;
const rows = table.slice(1)
.map((row, rowIndex) => {
const sizeName = cell(row, 0);
if (!sizeName) return null;
return {
sizeId: `size_${rowIndex}`,
sizeName,
dimensionsCm: dimensions(cell(row, 1)),
dimensionsIn: dimensions(cell(row, 2)),
volumeCm3: cell(row, 3) || null,
volumeIn3: cell(row, 4) || null,
grossWeightG: cell(row, 5) || null,
grossWeightLb: cell(row, 6) || null,
};
})
.filter((row): row is NonNullable<typeof row> => row !== null);
return { rows } as Prisma.InputJsonValue;
}
function normalizeOptions(detail: SdsProductDetail): Prisma.InputJsonValue | null {
const attributers = detail.subproducts?.attributers;
if (!Array.isArray(attributers)) return null;
const sizeMap = new Map<string, { id: string; name: string; sortOrder: number; enabled: boolean }>();
const colorMap = new Map<string, { id: string; name: string; hex: string | null; sortOrder: number; enabled: boolean }>();
attributers.forEach((attribute, sizeIndex) => {
const sizeName = text(attribute.size);
const sizeId = text(attribute.sizeId) ?? `size_${sizeIndex}`;
if (sizeName) sizeMap.set(sizeId, { id: sizeId, name: sizeName, sortOrder: sizeIndex, enabled: true });
if (Array.isArray(attribute.colors)) {
attribute.colors.forEach((color, colorIndex) => {
const colorId = text(color.colorId) ?? `color_${colorIndex}`;
if (!colorMap.has(colorId)) {
colorMap.set(colorId, {
id: colorId,
name: text(color.chineseName) ?? text(color.color_name) ?? colorId,
hex: text(color.color),
sortOrder: integer(color.colorSort) ?? colorIndex,
enabled: true,
});
}
});
}
});
return { sizes: [...sizeMap.values()], colors: [...colorMap.values()] } as Prisma.InputJsonValue;
}
function normalizeMedia(detail: SdsProductDetail, variants: SdsProductVariant[]): Prisma.InputJsonValue | null {
const urls: string[] = [];
const add = (value: unknown) => {
const url = text(value);
if (url && !urls.includes(url)) urls.push(url);
};
add(detail.blankDesignUrl);
add(detail.psd_img_url);
add(detail.img_url);
for (const variant of variants) {
add(variant.psd_img_url);
add(variant.img_url);
add(variant.blankDesignUrl);
for (const image of variant.designPrototype?.detailImgUrls ?? []) add(image.imageUrl);
for (const image of variant.designPrototype?.prototypeResultGroups ?? []) add(image.resultImage);
}
if (urls.length === 0) return null;
return {
primaryImageUrl: urls[0],
images: urls.map((url, index) => ({ id: `image_${index}`, url, sortOrder: index })),
} as Prisma.InputJsonValue;
}
function normalizeVariant(variant: SdsProductVariant, index: number): NormalizedVariant | null {
const sdsVariantId = text(variant.id);
const sku = text(variant.sku);
if (!sdsVariantId || !sku) return null;
return {
sdsVariantId,
sku,
sizeId: text(variant.sizeId) ?? text(variant.sizeDto?.id),
sizeName: text(variant.size) ?? text(variant.sizeDto?.sizeName),
colorId: text(variant.colorId) ?? text(variant.color?.colorId),
colorName: text(variant.color?.chineseName) ?? text(variant.color_name) ?? text(variant.color?.color_name),
colorHex: text(variant.color?.color),
imageUrl: text(variant.psd_img_url) ?? text(variant.img_url) ?? text(variant.blankDesignUrl),
price: decimal(variant.currentPrice ?? variant.unit_price ?? variant.min_price),
originalPrice: decimal(variant.originalPrice),
weightG: decimal(variant.weight),
boxLengthCm: decimal(variant.box_length),
boxWidthCm: decimal(variant.box_width),
boxHeightCm: decimal(variant.box_height),
enabled: Number(variant.status ?? 1) === 1 && String(variant.delFlag ?? '0') === '0',
sortOrder: integer(variant.attribute_sort?.split('-')[0]) ?? integer(variant.size_sort) ?? index,
designData: variant.designPrototype ? (variant.designPrototype as Prisma.InputJsonValue) : null,
};
}
export function normalizeProductDetail(detail: SdsProductDetail): NormalizedProductDetail {
const productDetails = detail.product_details ?? {};
const sourceVariants = Array.isArray(detail.subproducts?.items) ? detail.subproducts!.items! : [];
const variants = sourceVariants
.map(normalizeVariant)
.filter((variant): variant is NormalizedVariant => variant !== null);
const updatedAt = Number(detail.updateTime);
return {
productCode: text(detail.sku),
englishName: text(detail.english_name),
blankDesignUrl: text(detail.blankDesignUrl),
detailsPageVideoUrl: text(detail.detailsPageVideoUrl),
textureName: text(detail.texture?.name),
productionCycleHours: integer(detail.productionCycle),
minWeightG: decimal(detail.minWeight),
reminder: text(productDetails.reminder),
productionProcess: text(productDetails.production_process),
materialDescription: text(productDetails.material_description),
productPerformance: text(productDetails.product_performance),
applicableScenarios: text(productDetails.applicable_scenarios),
washingInstructions: text(productDetails.washing_instructions),
specialDescription: text(productDetails.special_description),
designExplanation: text(productDetails.design_explanation),
designArea: text(productDetails.design_area),
pictureRequest: text(productDetails.picture_request),
sizeChart: parseSizeChart(productDetails.product_size),
packageSpecs: parsePackageSpecs(productDetails.packaging_specification),
options: normalizeOptions(detail),
media: normalizeMedia(detail, sourceVariants),
upstreamUpdatedAt: Number.isFinite(updatedAt) ? new Date(updatedAt) : null,
variants,
};
}
+19 -6
View File
@@ -2,6 +2,7 @@ import {
Controller, Controller,
DefaultValuePipe, DefaultValuePipe,
Get, Get,
Param,
ParseIntPipe, ParseIntPipe,
Post, Post,
Query, Query,
@@ -25,15 +26,27 @@ export class SyncController {
constructor(private readonly service: SyncService) {} constructor(private readonly service: SyncService) {}
@Post('categories') @Post('categories')
@ApiOperation({ summary: 'Manually trigger category sync' }) @ApiOperation({ summary: 'Manually trigger category sync (async)' })
syncCategories() { async syncCategories() {
return this.service.syncCategories(); return this.service.startCategorySync();
} }
@Post('products') @Post('products')
@ApiOperation({ summary: 'Manually trigger product sync' }) @ApiOperation({ summary: 'Manually trigger product sync (async)' })
syncProducts() { async syncProducts() {
return this.service.syncProducts(); return this.service.startProductSync();
}
@Post('product-details')
@ApiOperation({ summary: 'Manually sync details for all active origin products (async)' })
async syncProductDetails() {
return this.service.startProductDetailSync();
}
@Post('products/:goodId/detail')
@ApiOperation({ summary: 'Immediately sync one SDS product detail' })
async syncOneProductDetail(@Param('goodId') goodId: string) {
return this.service.syncOneProductDetail(goodId);
} }
@Get('status') @Get('status')
+165 -1
View File
@@ -1,6 +1,10 @@
import { Test } from '@nestjs/testing'; import { Test } from '@nestjs/testing';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { SyncService } from './sync.service'; import {
SyncService,
shouldRunDelistDetection,
shouldSkipStaleDeletion,
} from './sync.service';
import { SdsClientService } from './sds-client.service'; import { SdsClientService } from './sds-client.service';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
@@ -15,6 +19,7 @@ describe('SyncService', () => {
const sdsMock: Partial<SdsClientService> = { const sdsMock: Partial<SdsClientService> = {
fetchCategoryTree: jest.fn(), fetchCategoryTree: jest.fn(),
fetchProductsPage: jest.fn(), fetchProductsPage: jest.fn(),
fetchProductDetail: jest.fn(async (goodId: string | number) => ({ id: goodId })),
}; };
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
imports: [ConfigModule.forRoot({ isGlobal: true })], imports: [ConfigModule.forRoot({ isGlobal: true })],
@@ -25,6 +30,9 @@ describe('SyncService', () => {
], ],
}).compile(); }).compile();
service = moduleRef.get(SyncService); service = moduleRef.get(SyncService);
jest
.spyOn(service, 'syncConfiguredProductDetails')
.mockResolvedValue({ synced: 0, failed: 0 });
sds = moduleRef.get(SdsClientService) as jest.Mocked<SdsClientService>; sds = moduleRef.get(SdsClientService) as jest.Mocked<SdsClientService>;
prisma = moduleRef.get(PrismaService); prisma = moduleRef.get(PrismaService);
await prisma.onModuleInit(); await prisma.onModuleInit();
@@ -168,6 +176,98 @@ describe('SyncService', () => {
}); });
}); });
describe('sync guard thresholds', () => {
describe('shouldSkipStaleDeletion', () => {
it('skips stale deletion when the fetched count is below the hard floor', () => {
expect(shouldSkipStaleDeletion(2, 226)).toBe(true);
expect(shouldSkipStaleDeletion(9, 226)).toBe(true);
});
it('skips stale deletion when fetched is far smaller than existing (ratio guard)', () => {
expect(shouldSkipStaleDeletion(100, 250)).toBe(true);
});
it('does NOT skip when fetched count is healthy', () => {
expect(shouldSkipStaleDeletion(226, 226)).toBe(false);
expect(shouldSkipStaleDeletion(200, 226)).toBe(false);
});
it('does NOT skip when there are no existing SDS categories', () => {
expect(shouldSkipStaleDeletion(0, 0)).toBe(false);
expect(shouldSkipStaleDeletion(2, 0)).toBe(false);
});
});
describe('shouldRunDelistDetection', () => {
it('skips delist detection when leaf categories are too few', () => {
expect(shouldRunDelistDetection(2, 500)).toBe(false);
expect(shouldRunDelistDetection(9, 500)).toBe(false);
});
it('skips delist detection when the seen product count is too small', () => {
expect(shouldRunDelistDetection(148, 2)).toBe(false);
expect(shouldRunDelistDetection(148, 49)).toBe(false);
});
it('runs delist detection only when both metrics are healthy', () => {
expect(shouldRunDelistDetection(148, 500)).toBe(true);
expect(shouldRunDelistDetection(10, 50)).toBe(true);
});
});
it('category sync keeps existing SDS categories when upstream returns a degenerate tree', async () => {
const stamp = Date.now();
const keep = await prisma.category.create({
data: { sdsCategoryId: `keep-${stamp}`, categoryName: `Keep ${stamp}` },
});
createdSdsCategoryIds.push(`keep-${stamp}`);
sds.fetchCategoryTree.mockResolvedValueOnce([
{ id: `g-${stamp}-1`, name: 'Tiny 1' },
{ id: `g-${stamp}-2`, name: 'Tiny 2' },
]);
createdSdsCategoryIds.push(`g-${stamp}-1`, `g-${stamp}-2`);
const result = await service.syncCategories();
expect(result.deletedStale).toBe(0);
const still = await prisma.category.findUnique({ where: { id: keep.id } });
expect(still).not.toBeNull();
});
it('product sync does NOT delist origin goods when it sees too few products', async () => {
const stamp = Date.now();
const leaf = await prisma.category.create({
data: { sdsCategoryId: `leafguard-${stamp}`, categoryName: `LeafGuard ${stamp}` },
});
createdSdsCategoryIds.push(`leafguard-${stamp}`);
const active = await prisma.originGood.create({
data: { sdsGoodId: `active-${stamp}`, delisted: false, goodName: 'Active' },
});
createdSdsGoodIds.push(`active-${stamp}`);
sds.fetchProductsPage.mockImplementation(async (categoryId) => {
if (categoryId === `leafguard-${stamp}`) {
return {
content: [
{ id: `guardp-${stamp}-1`, name: 'P1' },
{ id: `guardp-${stamp}-2`, name: 'P2' },
],
};
}
return { content: [] };
});
const result = await service.syncProducts();
expect(result.delisted).toBe(0);
const still = await prisma.originGood.findUnique({ where: { id: active.id } });
expect(still?.delisted).toBe(false);
createdSdsGoodIds.push(`guardp-${stamp}-1`, `guardp-${stamp}-2`);
});
});
describe('getStatus', () => { describe('getStatus', () => {
it('returns recent logs ordered by startedAt desc', async () => { it('returns recent logs ordered by startedAt desc', async () => {
const logs = await service.getStatus(5); const logs = await service.getStatus(5);
@@ -176,3 +276,67 @@ describe('SyncService', () => {
}); });
}); });
}); });
describe('SyncService product detail scopes', () => {
const originGoods = [
{ id: 1n, sdsGoodId: 'all-1' },
{ id: 2n, sdsGoodId: 'all-2' },
];
function createService() {
const prisma = {
originGood: { findMany: jest.fn().mockResolvedValue(originGoods) },
} as unknown as PrismaService;
const sds = {
fetchProductDetail: jest.fn(async (goodId: string) => ({ id: goodId })),
} as unknown as SdsClientService;
const scopedService = new SyncService(prisma, sds);
jest
.spyOn(scopedService as any, 'persistProductDetail')
.mockResolvedValue(undefined);
return { scopedService, prisma, sds };
}
it('manual detail sync selects every active origin product', async () => {
const { scopedService, prisma, sds } = createService();
const result = await scopedService.syncAllProductDetails();
expect(prisma.originGood.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { delisted: false, source: 'SDS' } }),
);
expect(sds.fetchProductDetail).toHaveBeenCalledTimes(2);
expect(result).toEqual({ total: 2, synced: 2, failed: 0 });
});
it('hourly detail refresh remains limited to configured products', async () => {
const { scopedService, prisma } = createService();
await scopedService.syncConfiguredProductDetails();
expect(prisma.originGood.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { delisted: false, source: 'SDS', goods: { some: {} } },
}),
);
});
it('keeps hourly category/product sync separate from the daily detail sync', async () => {
const { scopedService } = createService();
const categories = jest.spyOn(scopedService, 'syncCategories').mockResolvedValue({
inserted: 0, updated: 0, total: 0, deletedStale: 0,
});
const products = jest.spyOn(scopedService, 'syncProducts').mockResolvedValue({
inserted: 0, updated: 0, total: 0, leafCategories: 0, delisted: 0,
});
const details = jest.spyOn(scopedService, 'syncProductDetails').mockResolvedValue({
total: 0, synced: 0, failed: 0,
});
await scopedService.hourlyCron();
expect(categories).toHaveBeenCalledTimes(1);
expect(products).toHaveBeenCalledTimes(1);
expect(details).not.toHaveBeenCalled();
await scopedService.dailyProductDetailCron();
expect(details).toHaveBeenCalledTimes(1);
});
});
+500 -46
View File
@@ -1,13 +1,25 @@
import { Injectable, Logger } from '@nestjs/common'; import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule'; import { Cron, CronExpression } from '@nestjs/schedule';
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { SdsClientService, SdsCategoryTreeNode, SdsProduct } from './sds-client.service'; import {
SdsClientService,
SdsCategoryTreeNode,
SdsProduct,
SdsProductDetail,
} from './sds-client.service';
import { normalizeProductDetail } from './sds-product-detail.mapper';
export interface CategorySyncResult { export interface CategorySyncResult {
inserted: number; inserted: number;
updated: number; updated: number;
total: number; total: number;
deletedStale: number;
} }
export interface ProductSyncResult { export interface ProductSyncResult {
@@ -15,12 +27,50 @@ export interface ProductSyncResult {
updated: number; updated: number;
total: number; total: number;
leafCategories: number; leafCategories: number;
delisted: number;
}
/**
* Safety guards so a degenerate/partial SDS response never triggers a
* destructive operation (stale category deletion / mass delist marking).
* Upstream normally returns ~226 categories and ~150 leaf categories with
* hundreds of products — the floors below only trigger on abnormal responses.
*/
export const SYNC_GUARDS = {
MIN_CATEGORY_COUNT: 10,
MIN_CATEGORY_RATIO: 0.5,
MIN_LEAF_CATEGORIES: 10,
MIN_SEEN_GOODS: 50,
} as const;
/**
* True when the fetched category count is suspiciously small compared to the
* categories already synced from SDS, i.e. the upstream response is likely
* partial/degenerate. In that case stale deletion must be skipped.
*/
export function shouldSkipStaleDeletion(fetched: number, existingSds: number): boolean {
if (existingSds <= 0) return false;
return (
fetched < SYNC_GUARDS.MIN_CATEGORY_COUNT ||
fetched < SYNC_GUARDS.MIN_CATEGORY_RATIO * existingSds
);
}
/**
* True only when both the leaf-category count and the number of seen products
* are healthy enough to trust the "not seen upstream => delisted" conclusion.
*/
export function shouldRunDelistDetection(leafCategories: number, seenGoods: number): boolean {
return (
leafCategories >= SYNC_GUARDS.MIN_LEAF_CATEGORIES &&
seenGoods >= SYNC_GUARDS.MIN_SEEN_GOODS
);
} }
@Injectable() @Injectable()
export class SyncService { export class SyncService {
private readonly logger = new Logger(SyncService.name); private readonly logger = new Logger(SyncService.name);
private running = { categories: false, products: false }; private running = { categories: false, products: false, details: false };
constructor( constructor(
private readonly prisma: PrismaService, private readonly prisma: PrismaService,
@@ -42,6 +92,52 @@ export class SyncService {
} }
} }
/** Fire-and-forget wrappers for manual triggers via HTTP. */
async startCategorySync(): Promise<{ message: string }> {
if (this.running.categories) {
return { message: 'Category sync already in progress' };
}
void this.syncCategories().catch((err) =>
this.logger.error('Category sync failed', err as Error),
);
return { message: 'Category sync started' };
}
async startProductSync(): Promise<{ message: string }> {
if (this.running.products) {
return { message: 'Product sync already in progress' };
}
void this.syncProducts().catch((err) =>
this.logger.error('Product sync failed', err as Error),
);
return { message: 'Product sync started' };
}
/** Refresh all active SDS product details once per day at 03:30. */
@Cron('0 30 3 * * *', { timeZone: 'Asia/Shanghai' })
async dailyProductDetailCron(): Promise<void> {
try {
await this.syncProductDetails();
} catch (err) {
this.logger.error('Daily product detail sync failed', err as Error);
}
}
async startProductDetailSync(): Promise<{ message: string }> {
if (this.running.details) {
return { message: 'Product detail sync already in progress' };
}
void this.syncProductDetails().catch((err) =>
this.logger.error('Product detail sync failed', err as Error),
);
return { message: 'Product detail sync started' };
}
/** Check if a sync type is currently running. */
isRunning(type: 'categories' | 'products' | 'details'): boolean {
return this.running[type];
}
async syncCategories(): Promise<CategorySyncResult> { async syncCategories(): Promise<CategorySyncResult> {
if (this.running.categories) { if (this.running.categories) {
throw new Error('Category sync already in progress'); throw new Error('Category sync already in progress');
@@ -54,60 +150,134 @@ export class SyncService {
const tree = await this.sds.fetchCategoryTree(); const tree = await this.sds.fetchCategoryTree();
const flat = this.flattenCategoryTree(tree); const flat = this.flattenCategoryTree(tree);
this.logger.log(`Fetched ${flat.length} SDS categories`); this.logger.log(`Fetched ${flat.length} SDS categories`);
const seenSdsIds = new Set(flat.map((n) => n.sdsId));
let inserted = 0; // Guard: if the upstream tree is suspiciously small vs what we already
let updated = 0; // have from SDS, skip stale deletion entirely — a partial response must
for (const node of flat) { // never wipe the category library.
const existing = await this.prisma.category.findUnique({ const existingSdsCount = await this.prisma.category.count({
where: { sdsCategoryId: node.sdsId }, where: { sdsCategoryId: { not: null } },
}); });
if (!existing) { const skipStaleDeletion = shouldSkipStaleDeletion(flat.length, existingSdsCount);
await this.prisma.category.create({ if (skipStaleDeletion) {
data: { this.logger.warn(
sdsCategoryId: node.sdsId, `Skipping stale category deletion: fetched=${flat.length} existingSds=${existingSdsCount} ` +
categoryName: node.name, `(below guard thresholds)`,
categoryIcon: node.icon ?? null, );
},
});
inserted++;
} else {
await this.prisma.category.update({
where: { id: existing.id },
data: {
categoryName: node.name,
categoryIcon: node.icon ?? null,
},
});
updated++;
}
} }
// Second pass: wire up parents by sdsCategoryId. // Single transaction: upsert + wire parents + delete stale.
for (const node of flat) { // SDS tree is the source of truth — anything not in the response gets deleted
if (!node.parentSdsId) continue; // (unless the response looks degenerate, see guard above).
const child = await this.prisma.category.findUnique({ const { inserted, updated, deletedStale } = await this.prisma.$transaction(async (tx) => {
where: { sdsCategoryId: node.sdsId }, let ins = 0;
}); let upd = 0;
const parent = await this.prisma.category.findUnique({
where: { sdsCategoryId: node.parentSdsId }, // 1. Upsert all SDS categories
}); for (const node of flat) {
if (child && parent && child.parentCategoryId !== parent.id) { const existing = await tx.category.findUnique({
await this.prisma.category.update({ where: { sdsCategoryId: node.sdsId },
where: { id: child.id },
data: { parentCategoryId: parent.id },
}); });
if (!existing) {
await tx.category.create({
data: {
sdsCategoryId: node.sdsId,
categoryName: node.name,
categoryIcon: node.icon ?? null,
},
});
ins++;
} else {
await tx.category.update({
where: { id: existing.id },
data: {
categoryName: node.name,
categoryIcon: node.icon ?? null,
},
});
upd++;
}
} }
}
// 2. Wire parent-child relationships
for (const node of flat) {
if (!node.parentSdsId) continue;
const child = await tx.category.findUnique({
where: { sdsCategoryId: node.sdsId },
});
const parent = await tx.category.findUnique({
where: { sdsCategoryId: node.parentSdsId },
});
if (child && parent && child.parentCategoryId !== parent.id) {
await tx.category.update({
where: { id: child.id },
data: { parentCategoryId: parent.id },
});
}
}
// 3. Delete stale categories (in DB but not in SDS response)
// Detach parent links first, then delete leaf-first to respect FK constraints.
// Skipped entirely when the response looks degenerate (see guard above).
let deletedStale = 0;
if (!skipStaleDeletion) {
const staleCats = await tx.category.findMany({
where: { sdsCategoryId: { notIn: [...seenSdsIds] } },
select: { id: true },
});
const staleIds = staleCats.map((c) => c.id);
// Protect categories that have configured goods — onDelete: Restrict
const goodsInStale = await tx.good.groupBy({
by: ['categoryId'],
where: { categoryId: { in: staleIds } },
});
const protectedIds = new Set(goodsInStale.map((g) => g.categoryId));
const deletableIds = staleIds.filter((id) => !protectedIds.has(id));
deletedStale = deletableIds.length;
// Detach all deletable categories from their parents
if (deletableIds.length > 0) {
await tx.category.updateMany({
where: { id: { in: deletableIds } },
data: { parentCategoryId: null },
});
// Also detach any non-deletable children pointing to deletable parents
await tx.category.updateMany({
where: { parentCategoryId: { in: deletableIds } },
data: { parentCategoryId: null },
});
// Delete leaf-first (repeatedly remove nodes with no children)
let remaining = [...deletableIds];
while (remaining.length > 0) {
const withChildren = await tx.category.findMany({
where: { parentCategoryId: { in: remaining } },
select: { parentCategoryId: true },
distinct: ['parentCategoryId'],
});
const hasChildSet = new Set(
withChildren.filter((c) => c.parentCategoryId).map((c) => c.parentCategoryId!.toString()),
);
const leaves = remaining.filter((id) => !hasChildSet.has(id.toString()));
if (leaves.length === 0) break; // safety: circular dependency
await tx.category.deleteMany({ where: { id: { in: leaves } } });
remaining = remaining.filter((id) => !leaves.some((l) => l === id));
}
}
}
return { inserted: ins, updated: upd, deletedStale };
});
await this.prisma.syncLog.update({ await this.prisma.syncLog.update({
where: { id: log.id }, where: { id: log.id },
data: { data: {
status: 'SUCCESS', status: 'SUCCESS',
finishedAt: new Date(), finishedAt: new Date(),
message: `inserted=${inserted} updated=${updated} total=${flat.length}`, message: `inserted=${inserted} updated=${updated} total=${flat.length} staleDeleted=${deletedStale}`,
}, },
}); });
return { inserted, updated, total: flat.length }; return { inserted, updated, total: flat.length, deletedStale };
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : String(err); const message = err instanceof Error ? err.message : String(err);
await this.prisma.syncLog.update({ await this.prisma.syncLog.update({
@@ -147,6 +317,7 @@ export class SyncService {
let inserted = 0; let inserted = 0;
let updated = 0; let updated = 0;
let total = 0; let total = 0;
const seenSdsGoodIds = new Set<string>();
for (const leaf of leafRows) { for (const leaf of leafRows) {
const sdsCategoryId = leaf.sdsCategoryId!; const sdsCategoryId = leaf.sdsCategoryId!;
@@ -157,6 +328,7 @@ export class SyncService {
const products = resp.items ?? resp.content ?? []; const products = resp.items ?? resp.content ?? [];
if (products.length === 0) break; if (products.length === 0) break;
for (const product of products) { for (const product of products) {
seenSdsGoodIds.add(String(product.id));
const upserted = await this.upsertOriginGood(product, sdsCategoryId); const upserted = await this.upsertOriginGood(product, sdsCategoryId);
if (upserted === 'inserted') inserted++; if (upserted === 'inserted') inserted++;
else updated++; else updated++;
@@ -172,15 +344,55 @@ export class SyncService {
} }
} }
// Detect delisted products: mark origin goods not seen in upstream as delisted,
// and re-activate any previously delisted goods that reappeared.
// Guard: only trust this conclusion when the sync covered a healthy number of
// leaf categories and saw a healthy number of products — otherwise a partial
// sync must never mass-delist the product library.
let delistedCount = 0;
let reactivatedCount = 0;
const runDelist = shouldRunDelistDetection(leafRows.length, seenSdsGoodIds.size);
if (runDelist) {
const delistedResult = await this.prisma.originGood.updateMany({
where: {
source: 'SDS',
sdsGoodId: { notIn: [...seenSdsGoodIds] },
delisted: false,
},
data: { delisted: true },
});
const reactivatedResult = await this.prisma.originGood.updateMany({
where: {
source: 'SDS',
sdsGoodId: { in: [...seenSdsGoodIds] },
delisted: true,
},
data: { delisted: false },
});
delistedCount = delistedResult.count;
reactivatedCount = reactivatedResult.count;
} else {
this.logger.warn(
`Skipping delist detection: leafCategories=${leafRows.length} seenGoods=${seenSdsGoodIds.size} ` +
`(below guard thresholds)`,
);
}
await this.prisma.syncLog.update({ await this.prisma.syncLog.update({
where: { id: log.id }, where: { id: log.id },
data: { data: {
status: 'SUCCESS', status: 'SUCCESS',
finishedAt: new Date(), finishedAt: new Date(),
message: `inserted=${inserted} updated=${updated} total=${total} leafCategories=${leafRows.length}`, message: `inserted=${inserted} updated=${updated} total=${total} delisted=${delistedCount} reactivated=${reactivatedCount} leafCategories=${leafRows.length}`,
}, },
}); });
return { inserted, updated, total, leafCategories: leafRows.length }; return {
inserted,
updated,
total,
leafCategories: leafRows.length,
delisted: delistedCount,
};
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : String(err); const message = err instanceof Error ? err.message : String(err);
await this.prisma.syncLog.update({ await this.prisma.syncLog.update({
@@ -204,6 +416,248 @@ export class SyncService {
}); });
} }
async syncProductDetails(): Promise<{
total: number;
synced: number;
failed: number;
}> {
if (this.running.details) {
throw new Error('Product detail sync already in progress');
}
this.running.details = true;
const log = await this.prisma.syncLog.create({
data: { type: 'PRODUCT_DETAILS', status: 'RUNNING' },
});
try {
const result = await this.syncAllProductDetails(async (progress) => {
await this.prisma.syncLog.update({
where: { id: log.id },
data: {
message: `processed=${progress.processed}/${progress.total} synced=${progress.synced} failed=${progress.failed}`,
},
});
});
await this.prisma.syncLog.update({
where: { id: log.id },
data: {
status: 'SUCCESS',
finishedAt: new Date(),
message: `total=${result.total} synced=${result.synced} failed=${result.failed}`,
},
});
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
await this.prisma.syncLog.update({
where: { id: log.id },
data: { status: 'FAILED', finishedAt: new Date(), message },
});
throw error;
} finally {
this.running.details = false;
}
}
async syncOneProductDetail(goodId: string): Promise<{
goodId: string;
variants: number;
detailSyncedAt: string;
}> {
const originGood = await this.prisma.originGood.findUnique({
where: { sdsGoodId: goodId },
select: { id: true, source: true },
});
if (!originGood) {
throw new NotFoundException(`SDS product ${goodId} not found locally`);
}
if (originGood.source !== 'SDS') {
throw new BadRequestException('自定义商品不支持从 SDS 同步详情');
}
const upstream = await this.sds.fetchProductDetail(goodId);
const normalized = normalizeProductDetail(upstream);
await this.persistProductDetail(originGood.id, upstream);
return {
goodId,
variants: normalized.variants.length,
detailSyncedAt: new Date().toISOString(),
};
}
queueProductDetailSync(goodId: string): void {
void this.syncOneProductDetail(goodId).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn(`Queued detail sync failed for ${goodId}: ${message}`);
});
}
async syncConfiguredProductDetails(): Promise<{ synced: number; failed: number }> {
const result = await this.syncMatchingProductDetails({
delisted: false,
source: 'SDS',
goods: { some: {} },
});
return { synced: result.synced, failed: result.failed };
}
async syncAllProductDetails(
onProgress?: (progress: {
processed: number;
total: number;
synced: number;
failed: number;
}) => Promise<void>,
): Promise<{ total: number; synced: number; failed: number }> {
return this.syncMatchingProductDetails(
{ delisted: false, source: 'SDS' },
onProgress,
2,
);
}
private async syncMatchingProductDetails(
where: Prisma.OriginGoodWhereInput,
onProgress?: (progress: {
processed: number;
total: number;
synced: number;
failed: number;
}) => Promise<void>,
attempts = 1,
): Promise<{ total: number; synced: number; failed: number }> {
const originGoods = await this.prisma.originGood.findMany({
where,
select: { id: true, sdsGoodId: true },
orderBy: { id: 'asc' },
});
let synced = 0;
let failed = 0;
let processed = 0;
for (const originGood of originGoods) {
let lastError: unknown;
let succeeded = false;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const upstream = await this.sds.fetchProductDetail(originGood.sdsGoodId);
await this.persistProductDetail(originGood.id, upstream);
synced++;
succeeded = true;
break;
} catch (error) {
lastError = error;
}
}
if (!succeeded) {
failed++;
const message = lastError instanceof Error ? lastError.message : String(lastError);
this.logger.warn(`Failed to sync SDS detail ${originGood.sdsGoodId}: ${message}`);
}
processed++;
if (onProgress && (processed % 10 === 0 || processed === originGoods.length)) {
await onProgress({ processed, total: originGoods.length, synced, failed });
}
}
return { total: originGoods.length, synced, failed };
}
async importProductDetail(upstream: SdsProductDetail): Promise<{
goodId: string;
variants: number;
sizeRows: number;
packageRows: number;
configuredGoods: number;
}> {
const goodId = String(upstream.id);
const normalized = normalizeProductDetail(upstream);
const originGood = await this.prisma.originGood.upsert({
where: { sdsGoodId: goodId },
create: {
sdsGoodId: goodId,
goodName: String(upstream.name ?? goodId),
goodImage: String(upstream.psd_img_url ?? upstream.img_url ?? upstream.blankDesignUrl ?? '') || null,
goodPrice:
upstream.min_price === undefined || upstream.min_price === null
? null
: new Prisma.Decimal(Number(upstream.min_price)),
},
update: {
goodName: upstream.name ? String(upstream.name) : undefined,
goodImage: String(upstream.psd_img_url ?? upstream.img_url ?? upstream.blankDesignUrl ?? '') || undefined,
goodPrice:
upstream.min_price === undefined || upstream.min_price === null
? undefined
: new Prisma.Decimal(Number(upstream.min_price)),
},
});
await this.persistProductDetail(originGood.id, upstream);
const configuredGoods = await this.prisma.good.count({
where: { originGoodId: originGood.id },
});
const sizeChart = normalized.sizeChart as { rows?: unknown[] } | null;
const packageSpecs = normalized.packageSpecs as { rows?: unknown[] } | null;
return {
goodId,
variants: normalized.variants.length,
sizeRows: sizeChart?.rows?.length ?? 0,
packageRows: packageSpecs?.rows?.length ?? 0,
configuredGoods,
};
}
private async persistProductDetail(originGoodId: bigint, upstream: SdsProductDetail): Promise<void> {
const normalized = normalizeProductDetail(upstream);
const { variants, ...detail } = normalized;
await this.prisma.$transaction(async (tx) => {
const json = (value: Prisma.InputJsonValue | null) => value ?? Prisma.DbNull;
// Backfill the origin good's price from upstream min_price when present
if (upstream.min_price !== undefined && upstream.min_price !== null) {
await tx.originGood.update({
where: { id: originGoodId },
data: { goodPrice: new Prisma.Decimal(Number(upstream.min_price)) },
});
}
await tx.originGoodDetail.upsert({
where: { originGoodId },
create: {
originGoodId,
...detail,
sizeChart: json(detail.sizeChart),
packageSpecs: json(detail.packageSpecs),
options: json(detail.options),
media: json(detail.media),
},
update: {
...detail,
sizeChart: json(detail.sizeChart),
packageSpecs: json(detail.packageSpecs),
options: json(detail.options),
media: json(detail.media),
syncedAt: new Date(),
},
});
const seenVariantIds: string[] = [];
for (const variant of variants) {
seenVariantIds.push(variant.sdsVariantId);
const { designData, ...data } = variant;
await tx.originGoodVariant.upsert({
where: {
originGoodId_sdsVariantId: {
originGoodId,
sdsVariantId: variant.sdsVariantId,
},
},
create: { originGoodId, ...data, designData: json(designData) },
update: { ...data, designData: json(designData) },
});
}
await tx.originGoodVariant.deleteMany({
where: {
originGoodId,
...(seenVariantIds.length ? { sdsVariantId: { notIn: seenVariantIds } } : {}),
},
});
});
}
/** /**
* Flattens the SDS nested tree into a list of `{ sdsId, parentSdsId?, name, icon? }`. * Flattens the SDS nested tree into a list of `{ sdsId, parentSdsId?, name, icon? }`.
*/ */

Some files were not shown because too many files have changed in this diff Show More