Compare commits

..

864 Commits

Author SHA1 Message Date
58758d3c82 chore(xiaoyi): bump client version to 1.2612.128 2026-12-05 01:35:41 +08:00
165ccfb515 fix(detail-agent-pi): remove undefined config ref and keep HTTP 429 retries same-route within budget 2026-12-05 01:35:40 +08:00
39067169c7 fix(detail-agent-pi): preserve verifiedRebase during save-wait retry and add onUserCanvasChanges to fake-canvas 2026-12-05 01:26:39 +08:00
70f1febd60 fix(detail-agent-pi): remove stray closing paren in toolsFor make() in agent.mjs 2026-12-05 01:19:40 +08:00
4cacb97c77 fix(photocraft): R2 fast canvas switch, steer runId, native tool relaxation, and slot-adopt-prep diagnostics 2026-12-05 01:08:49 +08:00
ad8f88b8d8 fix(photocraft): native explicit-layer & param parsing, canvas_read protection, AwaitingSave deadlock, 15s knowledge cache, stitch_state whitelabel 2026-12-05 01:02:48 +08:00
3cf1180133 fix(photocraft): S3 Rust host and canvas engine core fixes (S3-1..S3-5) 2026-12-05 00:32:37 +08:00
25234da02f feat(xiaoyi): polish S4 observability, reviewHints UI jump, and dual-end whitelabel gate 2026-12-05 00:28:36 +08:00
81f8da18ba feat(detail-agent-pi): liberate agent JS schemas, gates, and concurrent blob download 2026-12-05 00:24:53 +08:00
a9fe532694 fix(detail-agent-pi): S2 thin-harness stability and boundary fixes 2026-12-05 00:24:53 +08:00
2c1707e022 修复 Web 导入、账号与完结安全并支持外发检索 2026-12-05 00:24:53 +08:00
f2eb71b668 chore(xiaoyi): bump client version to 1.2612.127 2026-12-04 23:27:53 +08:00
398c4e6e7e fix(xiaoyi): isolate duplicate-barcode SKU files in subdirs and slim P2 tool schema 2026-12-04 23:27:09 +08:00
9b842d24e1 Refresh knowledge authorization and bound upstream failover 2026-12-04 23:12:33 +08:00
a9bbf5494d fix(xiaoyi): land Item 90 opaque/reviewHints/projection and thin-harness canvas sync 2026-12-04 23:11:37 +08:00
45b3cfdca9 fix(xiaoyi): resolve P0/P1 delivery revision, retry timezone, S3 download fallback, multi-res SKU bundle and CRLF copy 2026-12-04 22:17:17 +08:00
9359d836d9 fix(xiaoyi): align 20-template intake, package docs, and font manifest consumption 2026-12-04 22:17:17 +08:00
0c9cbdcf2f fix(xiaoyi): split SKU targets by spec and wire embedded_target smart object editing 2026-12-04 20:31:28 +08:00
dbfff0f160 fix: expose Xiaoyi listing assets by barcode and spec 2026-12-04 20:03:18 +08:00
035b373264 fix(xiaoyi): remove creation draft revision gate and show non-blocking template compatibility warnings 2026-12-04 19:25:40 +08:00
bcc71d4304 feat(detail-agent-pi): downgrade template metadata/version mismatches to soft compatibility warnings 2026-12-04 19:25:40 +08:00
3e79045665 refactor(xiaoyi): thin harness wave 2b rust write-lease subtraction 2026-12-04 19:25:39 +08:00
ed4d614f53 refactor(xiaoyi): thin harness Wave 2A JS context slimming and read caching 2026-12-04 19:25:39 +08:00
2c7d194cf5 release(xiaoyi): bump client version to 1.2612.126 2026-12-04 17:54:54 +08:00
5ac03ad245 refactor(xiaoyi): thin harness P0 subtraction and context slimming 2026-12-04 17:54:54 +08:00
c2112aa9de feat(xiaoyi): add super-admin product presets to the project wizard 2026-12-04 17:51:38 +08:00
414a3e87bc 新增自动上架回调配置与测试连接 2026-12-04 16:45:02 +08:00
623b4ec73e 修复小壹四图验收模板并新增超管测试商品预设 2026-12-04 16:17:45 +08:00
794be1c34f refactor: retire legacy department permission writes 2026-12-04 16:17:45 +08:00
5a72a92974 release(xiaoyi): bump client version to 1.2612.125 2026-12-04 15:26:48 +08:00
4a9f29589c 按目标校验小壹手动画布操作并保留生成原图 2026-12-04 15:26:48 +08:00
2198ede39d 修复小壹手动采纳、SKU 条码命名和生成图留存 2026-12-04 15:26:48 +08:00
3975b4a9f4 release(xiaoyi): bump client version to 1.2612.124 2026-12-04 14:23:06 +08:00
15e98d5247 修复小壹更新、候选回填、知识库读取与成品导出 2026-12-04 14:23:06 +08:00
95bb9db4ce 接入成品上架工作台单点登录 2026-12-04 14:23:06 +08:00
cb0296a44e release(xiaoyi): bump client version to 1.2612.123 2026-12-04 11:38:55 +08:00
c665fbd2ab fix: 自动保存候选采纳并拦截缺图导出 2026-12-04 11:38:55 +08:00
47d6c4ce6e Dispatch Xiaoyi feedback to GitHub, DingTalk and Agent webhook 2026-12-04 11:35:53 +08:00
581ee41cef refactor: simplify material download authorization 2026-12-04 11:30:34 +08:00
1662d1b634 docs: refresh README for current web, desktop client, and GitHub workflow 2026-12-04 11:15:06 +08:00
1387610f4a release(xiaoyi): bump client version to 1.2612.122 2026-12-04 10:06:03 +08:00
cca796ec37 fix(xiaoyi): resume incomplete project briefs 2026-12-04 10:06:03 +08:00
江林铖
60405e7b26 Restrict creative salary delivery rates to art workflows 2026-12-04 09:31:21 +08:00
ffe343ecd2 release(xiaoyi): bump client version to 1.2612.121 2026-12-04 00:21:24 +08:00
9757545ece feat(xiaoyi): polish 3-stage creation wizard UX, compact barcode accordion, and single-row footer 2026-12-04 00:13:04 +08:00
fe533072b4 统一智能体商品档案读取 2026-12-04 00:13:04 +08:00
cef79a9a39 refactor(xiaoyi): split production modules and trim tool guidance 2026-12-04 00:09:48 +08:00
9adba649e0 Separate script read pages from continuation notices 2026-12-04 00:09:48 +08:00
2ce30c1731 release(xiaoyi): bump client version to 1.2612.120 2026-12-03 20:42:54 +08:00
a9d4acffb8 fix(xiaoyi): keep image key excluded from flat feedback allowlist 2026-12-03 20:22:31 +08:00
3a4cb44833 fix(xiaoyi): align feedback v3 modelConfig keys between desktop and web 2026-12-03 20:11:08 +08:00
a3f7961814 feat: support desktop feedback v3 diagnostics 2026-12-03 20:09:05 +08:00
a0571c009a feat(xiaoyi): 扩充问题反馈诊断并优化弹窗 2026-12-03 20:09:05 +08:00
f66f4f131e fix(xiaoyi): persist structured barcode entries in creation briefs 2026-12-03 20:09:05 +08:00
2e75cea60d feat(xiaoyi): wire the three-stage creation wizard 2026-12-03 20:09:05 +08:00
2539e56e19 feat(xiaoyi): add three-stage creation wizard components 2026-12-03 20:09:05 +08:00
b2b63417c3 release(xiaoyi): bump client version to 1.2612.119 2026-12-03 19:11:18 +08:00
011109f188 fix(xiaoyi): allow slot-skeleton scope switches on bound template canvases 2026-12-03 19:05:29 +08:00
26503bd6cc fix(xiaoyi): preserve Feishu intake placeholder aliases in enterprise template metadata 2026-12-03 18:57:25 +08:00
5aa64164e0 fix(xiaoyi): keep projects page open on startup 2026-12-03 18:55:55 +08:00
da1ca87c67 fix(xiaoyi): restrict stable production to one project and settle save waits 2026-12-03 18:55:55 +08:00
7e20c4defa fix(xiaoyi): 修复建项拖放和模板资料交互 2026-12-03 18:55:55 +08:00
4fd6544c4c 恢复历史候选并随交付保存未采纳图片 2026-12-03 18:55:54 +08:00
8ab22a7a1d 验证桌面模板灰字提示完整透传 2026-12-03 18:55:54 +08:00
17af258226 release(xiaoyi): bump client version to 1.2612.118 2026-12-03 17:29:48 +08:00
96829dde30 修复小壹输出切换保存和对话模型兼容 2026-12-03 17:29:48 +08:00
41632b42fe release(xiaoyi): bump client version to 1.2612.117 2026-12-03 16:25:27 +08:00
bfd19f7a57 修复普通对话误读旧模板知识库凭据 2026-12-03 16:25:27 +08:00
343eb2e5ba release(xiaoyi): bump client version to 1.2612.116 2026-12-03 15:27:03 +08:00
500072d840 修复小壹知识库工具选择和固定模板恢复 2026-12-03 15:27:02 +08:00
f45b537d70 test(xiaoyi): close model settings by accessibility action 2026-12-03 15:07:55 +08:00
402b2fbbf7 docs(xiaoyi): specify release timestamp before publishing 2026-12-03 15:04:30 +08:00
78a7bb15b7 docs(xiaoyi): record the verified Gitea release route 2026-12-03 14:58:14 +08:00
949435c883 docs(xiaoyi): document Windows online update release 2026-12-03 14:54:52 +08:00
077ea1f8fe release(xiaoyi): bump client version to 1.2612.115 2026-12-03 14:46:05 +08:00
c77009902e 修复跨产物候选恢复与图位查看 2026-12-03 14:45:41 +08:00
eaf1476b4e 修复小壹手动检查更新弹窗和授权续接 2026-12-03 14:45:41 +08:00
2eb466deba Fix model settings popup on product brief 2026-12-03 14:45:41 +08:00
09766a4377 fix(xiaoyi): 修复项目列表页检查更新无响应与缩短自动检查间隔 (1.2612.114) 2026-12-03 13:03:25 +08:00
江林铖
4a9ed3031c Rename creative planning payroll labels 2026-12-03 11:45:13 +08:00
037a6c4461 fix(xiaoyi): open auth browser via Win32 ShellExecuteW with copy-link fallback for 1.2612.113 2026-12-03 11:12:32 +08:00
dbe453b40b fix(docker): use local node headers and npmmirror in detail-renderer-deps 2026-12-03 10:46:52 +08:00
031281aca6 chore(xiaoyi): bump client version to 1.2612.112 2026-12-03 10:37:38 +08:00
d407a42d61 修复多输出项目重开时的画布与图位错位 2026-12-03 10:33:10 +08:00
fb89b80a94 fix(xiaoyi): unblock mismatched tab switch and toolbar scope fallback 2026-12-03 10:29:42 +08:00
03aa6328d4 feat(client): capture rich diagnostics and ring-buffer logs in desktop feedback 2026-12-03 10:08:20 +08:00
22b21dc238 feat(feedback): enrich v2 diagnostics contract, DingTalk alert and web triage view 2026-12-03 09:52:28 +08:00
45f36bbe16 fix(xiaoyi): enforce lockfile+daemon boot checks and capture redacted stderr for 1.2612.111 2026-12-03 09:33:24 +08:00
ecb869bceb fix(xiaoyi): unify project card heights, prioritize GPU view redraw, and scope cross-tab canvas actions for 1.2612.110 2026-12-03 00:56:34 +08:00
7e0c4ed249 release(xiaoyi): bump client version to 1.2612.109 2026-12-02 22:16:58 +08:00
a52287d650 feat(xiaoyi): wire 1.2612.109 cross-track storage, multi-project UI and concurrency seams 2026-12-02 22:05:56 +08:00
b6a08be74a Merge Track 5 (W-UI-Design): 4-tier multi-project hierarchy and T8 storage UI 2026-12-02 21:33:02 +08:00
1511874065 Merge Track 4 (W-Storage-T8): storage pointer, crash-safe auto migration, disk GC 2026-12-02 21:33:02 +08:00
9cc72abd49 Merge Track 3 (W-RustUI-Engine): per-project slot engine, authoritative completion, UI snapshot 2026-12-02 21:33:01 +08:00
795704d544 Merge Track 2 (W-RustCore): image cancel/no-replay guard, multi-run routing, Scheme A pool 2026-12-02 21:33:01 +08:00
5c04e672f6 Merge Track 1 (W-NodePi): native Pi session, unknown-outcome safety, schema gate 2026-12-02 21:33:01 +08:00
9fadfaf6f1 feat(ui): T7B multi-project four-layer visual hierarchy and T8 storage management UI 2026-12-02 21:29:53 +08:00
0ed79ee40a 隔离小壹项目运行状态并校验部分交付 2026-12-02 21:09:27 +08:00
07374de859 fix(client): harden model dispatch and reuse project sessions 2026-12-02 21:09:15 +08:00
168361885e feat: 支持小壹存储迁移与磁盘清理 2026-12-02 21:08:19 +08:00
08668a2c93 fix(client): fence paid requests and isolate project runs 2026-12-02 21:07:06 +08:00
f7ad5d1efc release(xiaoyi): bump client version to 1.2612.108 2026-12-02 19:51:00 +08:00
ea139063d5 fix(ui-egui): guard intake preservation when platform refetch clears or changes template 2026-12-02 19:47:25 +08:00
1e6db9d5b8 Merge origin/main (b3f5c6a7) into release-1.2612.108 integration 2026-12-02 19:42:55 +08:00
53fb32e0e9 Merge T5B: redesign creation workspace, grouped SKU matrix, sticky footer and brief copilot 2026-12-02 19:42:52 +08:00
430e8ae977 feat(ui-egui): redesign creation workspace, grouped SKU matrix, sticky footer and brief copilot (T5B) 2026-12-02 19:35:46 +08:00
990869e85e Preserve paused production run when restoring empty stages checkpoint 2026-12-02 19:16:03 +08:00
6b19b4d7d4 Allow configured feedback DingTalk recipients to read feedback detail 2026-12-02 19:00:58 +08:00
0974156cf6 Merge T6: sofa output switching fix and feedback DingTalk notification upgrade 2026-12-02 18:59:36 +08:00
c37780889e Wire T5A normalizedProduct through jiansun_pi_runtime and plan_production 2026-12-02 18:56:15 +08:00
bf80fe7a7e fix(xiaoyi): 修复三件套切页与问题反馈通知 2026-12-02 18:56:03 +08:00
750dee7911 Merge T4: post-upgrade compat and seamless resume recovery 2026-12-02 18:53:01 +08:00
16be0ddf8a Merge T3: Rust host and UI mid-turn steer and chat abort 2026-12-02 18:52:45 +08:00
db485ab5f1 Merge T1: high-visibility update UX, dynamic changelog, smooth restart 2026-12-02 18:52:24 +08:00
6778a3722e Merge T5A: product platform data normalization 2026-12-02 18:52:24 +08:00
d64dc3187f Merge T2: native Pi schemas, model switch, steer, recovery 2026-12-02 18:52:23 +08:00
5f12ca834a 修复小壹旧工程兼容与中断续作 2026-12-02 18:45:11 +08:00
c1016a0b94 修复小壹更新提醒、日志布局与重启交接 2026-12-02 18:44:45 +08:00
04d974c9fd 支持小壹对话中途插话和停止 2026-12-02 18:35:52 +08:00
45fe8707c8 对齐小壹 Pi 工具协议、插话与会话恢复 2026-12-02 18:27:36 +08:00
417f0c31a7 Normalize product platform briefs and reference assets 2026-12-02 18:23:28 +08:00
江林铖
b3f5c6a740 fix(performance-survey): link item assessments to employees 2026-12-02 17:48:20 +08:00
b989cd0038 release(xiaoyi): bump client version to 1.2612.107 2026-12-02 15:56:11 +08:00
be47689273 test(desktop): align route mocks with sliding desktop session renewal 2026-12-02 15:36:58 +08:00
62dd764533 Merge commit '2ec00c82a17b96616fe3731c916775c22ae5f10d'; commit '40bf3ce012089117ac26af070b116d7b91d5780a'; commit '66c23c676d396dc89469ade9fc5adeb63b49fd5f' into release/1.2612.107 2026-12-02 15:32:52 +08:00
66c23c676d 修复小壹暂停显示、素材库重连和本地实拍恢复 2026-12-02 15:32:00 +08:00
40bf3ce012 修复小壹授权误暂停和桌面会话续期 2026-12-02 15:27:44 +08:00
2ec00c82a1 feat(api): support spu query in external image-assets 2026-12-02 15:17:47 +08:00
5258ad9ca7 fix(xiaoyi): guard null variants and unlock post-goal canvas follow-up 2026-12-02 15:13:30 +08:00
f256bb70b3 Merge commit 'b946b2865a5b4631e2982c0f600ec0b22c8945da' into release/1.2612.107 2026-12-02 14:28:50 +08:00
fc9d4e715c Merge commit 'bb4ba63ff4abf8f1208e7ae51ba566345b9e53fb' into release/1.2612.107 2026-12-02 14:28:50 +08:00
bfc57d411e Merge commit 'f5ab4140a6aa3386d68d66da0eb04b83eefcb291' into release/1.2612.107 2026-12-02 14:28:49 +08:00
c2ff32e139 Merge commit 'debd01cc9629acb2a86dd3ec4f5435c93e90f9e5' into release/1.2612.107 2026-12-02 14:28:49 +08:00
debd01cc96 按图层校验小壹写入并修复画布编辑和预览回执 2026-12-02 14:19:41 +08:00
b946b2865a 修复企业模板多原稿页面拼接顺序 2026-12-02 14:17:38 +08:00
bb4ba63ff4 适配 98k New API 模型目录与文字线路切换 2026-12-02 14:04:40 +08:00
f5ab4140a6 fix(desktop): 核验画布交付版本与人工填图状态 2026-12-02 14:00:50 +08:00
6aa6d2f0b4 统一画布续聊制作工具和模型线路故障切换 2026-12-02 13:58:36 +08:00
江林铖
cde2804105 feat(performance-survey): support video and document case attachments 2026-12-02 13:12:56 +08:00
d188f5f78a fix(desktop): preserve recognized knowledge proxy 404 codes 2026-12-02 10:47:58 +08:00
1b146a44ad fix(desktop): distinguish missing SPU from upstream 404 2026-12-02 10:25:43 +08:00
21ed900958 fix(xiaoyi): handle delayed and parallel OAuth callbacks 2026-12-02 09:43:29 +08:00
2fd30d7135 fix(xiaoyi): load optional Windows print APIs on demand 2026-12-02 09:30:01 +08:00
28d8eed17e feat(xiaoyi): simplify model choices for v1.2612.105 2026-12-02 00:51:40 +08:00
2ed3d2201d merge: integrate Xiaoyi v105 client and server 2026-12-02 00:36:28 +08:00
97cf32afde feat(xiaoyi): 优化项目工作台并接入问题反馈 2026-12-01 20:07:08 +08:00
ca0291fd82 fix(desktop): 解除创作任务登记对云端文档的依赖 2026-12-01 19:31:51 +08:00
77176e1dce feat(desktop): 新增小壹问题反馈提交与只读详情 2026-12-01 19:11:49 +08:00
7f312ce409 feat(xiaoyi): 接入产品平台 SPU 资料与模板图片框 2026-12-01 19:06:47 +08:00
c8cba8ff5e fix(desktop): 为小壹知识库签发超管标记 2026-12-01 18:51:46 +08:00
834dc587f1 Merge commit 'bd724813223084ce23a37ce659d5bc844eff1f6a' into feat/xiaoyi-client-v105-20261201 2026-12-01 18:47:50 +08:00
a6f567850d feat(desktop): 支持小壹按 SPU 查询产品平台资料 2026-12-01 18:41:23 +08:00
bd72481322 feat(xiaoyi): 精简产品资料表单与首次设置 2026-12-01 18:39:21 +08:00
ec83fa9f79 加固小壹跨网络连接并透传模板表单字段 2026-12-01 18:38:52 +08:00
316ff8c5cd Add authenticated desktop knowledge streaming proxy 2026-12-01 18:34:58 +08:00
da93de994c 集成小壹模板条码表单与自由条码入库 2026-12-01 16:47:15 +08:00
cc2f38db1a 收口小壹自由条码入库与查询契约 2026-12-01 16:16:42 +08:00
5a8ebae464 重整小壹模板条码表单与参考图预览 2026-12-01 15:55:10 +08:00
c5f289d7cf Merge commit '017f02d96f885fe3f79a24df6d58564051afec23' into feat/xiaoyi-free-barcode-backend-20261201 2026-12-01 15:52:40 +08:00
8f56e16f84 收口小壹条码制作契约和知识库自动授权 2026-12-01 15:39:26 +08:00
017f02d96f fix(desktop): align Xiaoyi delivery identity and knowledge authorization 2026-12-01 15:35:20 +08:00
4c5a76bb72 发布小壹 1.2612.103,支持多条码表单与知识库自动授权 2026-12-01 14:24:56 +08:00
ed2bfbc81c 接通小壹自动上架状态回传并准备发布 1.2612.102 2026-12-01 12:31:09 +08:00
江林铖
d5b23f4667 feat(salary): export monthly payroll details 2026-12-01 11:46:25 +08:00
36056a9c8e 修复旧工程完结并按条码交付 SKU 图 2026-12-01 10:56:12 +08:00
7835ccd77a 发布小壹 1.2611.3006 2026-11-30 22:49:03 +08:00
82af43b3d7 复制可定位的小壹问题详情 2026-11-30 22:49:03 +08:00
d654e55032 按最终成品校验完结并限定云同步范围 2026-11-30 22:49:02 +08:00
09e0108b83 按交付前的资料版本记录回执 2026-11-30 21:32:43 +08:00
679d712d32 保存已交付版本的完结状态 2026-11-30 21:31:41 +08:00
7635801265 使用成品回执中的分屏尺寸 2026-11-30 21:27:48 +08:00
e5ffe1d4e8 保留详情成品分屏尺寸 2026-11-30 21:25:36 +08:00
247595a3a7 整理交付验收脚本格式 2026-11-30 21:25:04 +08:00
5c317839a5 完善交付素材列表预览和文件入口 2026-11-30 21:25:01 +08:00
92eaa692d0 验证小壹完结素材交付链路 2026-11-30 21:25:01 +08:00
319ce683a1 根据成品尺寸建立交付项目身份 2026-11-30 21:24:15 +08:00
41123830e7 支持并发重试复用交付文件 2026-11-30 21:21:23 +08:00
d6d8e2c781 云同步保留已交付状态 2026-11-30 21:15:53 +08:00
cb33c03306 发布小壹 1.2611.3005 2026-11-30 21:14:24 +08:00
978836cf52 仅交付正式成品并独立备份工程 2026-11-30 21:13:00 +08:00
dad14e57cd 排除普通上传中的交付素材类型 2026-11-30 21:11:42 +08:00
1837234d92 阻止交付源文件上传 2026-11-30 21:11:21 +08:00
364a4b5f8f 支持小壹交付素材迁移审计 2026-11-30 21:10:51 +08:00
835ad8a89f 交付仅接收上架成品 2026-11-30 21:10:41 +08:00
71eecd09d6 提交详情成品到素材库 2026-11-30 21:10:29 +08:00
53712220f0 外部取件仅返回自动上架成品 2026-11-30 21:10:29 +08:00
9aaceb6148 对接自动上架成品文件 2026-11-30 21:10:14 +08:00
4b1a2f27a2 复用已合并的交付文件 2026-11-30 21:10:07 +08:00
9cabd38e77 区分上传认证失效与服务异常 2026-11-30 21:08:05 +08:00
ca88f25d47 对齐桌面交付账号清理策略 2026-11-30 21:06:03 +08:00
5850f25bd1 保留素材清理后的交付回执 2026-11-30 21:02:10 +08:00
9c3565b135 区分小壹完结入库和手工素材操作 2026-11-30 21:01:40 +08:00
e5ef71abab 说明自动上架素材的撤回语义 2026-11-30 21:00:02 +08:00
b883398aa8 验证原有网页分片上传认证 2026-11-30 20:59:13 +08:00
474c8508f3 支持小壹交付素材和自动上架通知 2026-11-30 20:58:31 +08:00
e50f49bb74 支持查看和下载小壹自动上架交付素材 2026-11-30 20:58:28 +08:00
5453dd606d 补充小壹自动上架对接契约 2026-11-30 20:56:23 +08:00
0f4a2eba6f 发布小壹 1.2611.3004 2026-11-30 20:36:45 +08:00
37e9761c07 使用制作 Key 读取已发布模板目录 2026-11-30 20:36:33 +08:00
fcfccb5c4f 开放有效素材库账号授权小壹客户端 2026-11-30 19:43:36 +08:00
5560b0f46c 小壹采用按日期和当天序号编排的版本号 2026-11-30 19:04:39 +08:00
ed03285779 发布小壹 1.1.1 并限定制作凭据传输范围 2026-11-30 18:46:18 +08:00
619f3fe4b8 归并小壹 1.1.0 发布基线与知识库设置修复 2026-11-30 18:46:12 +08:00
d2aad73bce 明确小壹知识库凭据用途与校验状态 2026-11-30 18:25:22 +08:00
01526dcbc0 发布包改用带图标的启动程序小壹.exe,并用 Inno Setup 生成按用户安装的 Windows 安装程序,去掉 .cmd 启动方式 2026-11-30 17:23:06 +08:00
4305b938ea 小壹客户端版本号改为 1.1.0 2026-11-30 17:07:30 +08:00
e84284de5c 资料页只保留一个精修开关:新工程开工前开关记下选择、随一键生成交给宿主,去掉合入时多出的精修选择 2026-11-30 16:48:11 +08:00
aa6a46a841 合入用户改动清单:目标模式中用户改了画布,宿主在回合开头或下一次回执里告诉小壹改了哪屏哪格(R5-Z73)
# Conflicts:
#	apps/detail-agent-pi/src/desktop-host.mjs
#	apps/detail-agent-pi/src/production-goal.mjs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs
2026-11-30 16:08:35 +08:00
江林铖
2884db42b7 fix(salary): exclude content workflows from two personal delivery rates 2026-11-30 16:06:22 +08:00
ef2023e7cf 小壹安装包下载签名改在版本模块内完成,不改动素材预览依赖的 s3 模块 2026-11-30 16:04:53 +08:00
9c6baff777 制作回合向小壹交付用户画布改动清单 2026-11-30 15:57:43 +08:00
9fe46c5a01 合入制作控制界面:资料页精修开关、停止三选一菜单与确认、继续制作、时间预算显示(R5-Z72)
# Conflicts:
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs
2026-11-30 15:52:51 +08:00
15c5415b57 合入报错回执与工具用法补全:屏号误填、候选号无效、图层样式、智能对象局部修饰、锚点数、交付修订号(R5-Z71) 2026-11-30 15:50:28 +08:00
51c644d7b5 合入精修开关、时间预算、每图位候选总数上限与整屏复核轮次(R5-Z70)
# Conflicts:
#	apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs
2026-11-30 15:50:28 +08:00
27b93c04ab 小壹资料页加精修开关,制作进度头部加停止菜单与时间预算(R5-Z72)
- 资料页"输出内容"下方新增"精修"开关与说明;开工后只读,暂停时可改,切换时登记 production-settings 操作
- 进度头部换成一个"停止"按钮,点开菜单三选一:只暂停直接执行,停止目标、停止并交付先确认;已暂停时显示"继续制作",菜单只剩两项
- 停止中、交付中置灰并显示进度,已结束、已交付显示结果,失败用提醒色原样显示错误
- 标题行下方显示"已用 N 分钟 / 预算 M 分钟",超出后提醒色显示"已超出预算,将自动交付"
- 按钮只登记 jiansun.action 同名操作,帧末经控制通道同一入口执行;停止与预算状态待停止任务合入后接上
2026-11-30 15:49:19 +08:00
a8603e2174 合入停止三选一:只暂停、停止目标、停止并交付,超出预算 10 分钟自动交付,修复停止后卡在忙碌(R5-Z69) 2026-11-30 15:48:42 +08:00
37ea0df677 正式发布包写入有效的最低可用版本,可用 --minimum 指定 2026-11-30 15:48:23 +08:00
e3556c2719 补齐小壹精修预算、候选上限和整屏复核历史 2026-11-30 15:37:29 +08:00
a52f31dc5b 支持小壹暂停、结束目标与按时交付 2026-11-30 15:36:16 +08:00
a897860377 新增小壹客户端版本查询、安装包下载与发布脚本 2026-11-30 15:32:56 +08:00
74e39090e9 补全小壹图片与原生命令报错回执(R5-Z71) 2026-11-30 15:07:56 +08:00
江林铖
acb861501e feat(salary): share the planning performance scheme for P2 and P3 2026-11-30 14:32:12 +08:00
9f3e6cec31 fix(materials): confirm task detail image replacements together 2026-11-30 13:06:14 +08:00
a7922a423f 合入切换制作画布时主动保存新画布并按回执绑定,修复切换卡死(R5-Z68) 2026-11-30 12:26:05 +08:00
204b4a8a10 修复小壹切换制作画布时遗漏保存交接 2026-11-30 12:24:57 +08:00
da374462da 更新胶囊圆点从小壹语义色取进行中亮色 2026-11-30 12:02:00 +08:00
5ce2b1c15b 更新胶囊圆点改用进行中亮色;重启更新被拒时按制作中、保存导出中、未保存修改分别说明原因 2026-11-30 11:56:15 +08:00
9a16e9b166 合入在线更新的界面:新版本胶囊、更新浮层与设置版本栏(R5-Z67) 2026-11-30 11:55:14 +08:00
66261b2a31 加上小壹在线更新的界面(R5-Z67)
- 顶栏"账户"左边加更新胶囊,与导航分段同高同圆角:有新版本、需更新、下载进度(底部 2pt 细线)、重启以更新;其余状态不显示
- 点胶囊弹出约 320 宽的浮层:版本与当前版本、更新说明(超过 6 行滚动)、安装包大小;主按钮随状态换成下载更新、进度条、重启并更新,动作返回的错误原样显示在按钮下方
- 小壹设置末尾加版本一栏:当前版本与提交号、检查更新(检查中置灰)、检查结果
- 重启沿用"文件 › 退出"的退出前保存流程,不另加确认框
2026-11-30 11:54:12 +08:00
7bb0b0e2d3 合入客户端版本管理、正式发布包与在线更新(R5-Z66) 2026-11-30 11:02:07 +08:00
7f6686c594 实现小壹正式发布包与客户端在线更新 2026-11-30 10:54:55 +08:00
b2c94bb6a9 合入图位用图来源与画面相似度回执(R5-Z63),相似度只比同一成品内的图位,不再载入其他成品画布 2026-11-30 10:18:40 +08:00
7c89221b85 补齐小壹图位用图来源与画面相似度回执 2026-11-30 10:13:02 +08:00
98c8b7742c 合入本机回合不再因安静期被判断连(R5-Z64) 2026-11-30 10:08:49 +08:00
037be99294 合入尺寸线与端点可辨性客观回执(R5-Z62) 2026-11-30 10:06:54 +08:00
644731c500 修复小壹上下文压缩期间提前清除本机回合 2026-11-30 10:00:37 +08:00
31096522a1 为小壹读屏补充尺寸标线和端点的可见性数据 2026-11-30 09:59:38 +08:00
dba8eb7aa6 合入交付回执精简,完整保真报告移出主对话(R5-Z60) 2026-11-30 09:52:27 +08:00
a17915b399 合入主小壹提前压缩上下文(R5-Z61) 2026-11-30 09:52:26 +08:00
3bad264969 精简小壹交付回执并保留原稿保真报告 2026-11-30 09:48:46 +08:00
cb0dccf771 fix(materials): combine task detail image groups in one approval 2026-11-30 09:46:32 +08:00
8bc34cf419 提前压缩主小壹上下文并保留制作关键事实 2026-11-30 09:44:03 +08:00
ae788c7f26 企业知识库内网地址改为 192.168.101.188(知识库服务已迁移) 2026-11-30 09:38:04 +08:00
b78fdad6e5 整屏复核助手输入附带文字样式差异与可读性事实(textLayers) 2026-11-30 06:34:04 +08:00
a66a28423a 更新引擎换字测试:跨样式段替换按分段保留样式(配合 R5-Z50) 2026-11-30 06:03:14 +08:00
1fb5fcfa2b 合入变换来源可指定为图位当前采用的图(R5-Z57) 2026-11-30 05:59:59 +08:00
17cdd43930 合入最小化/托盘时制作继续推进、画布写入等待有限(R5-Z54) 2026-11-30 05:59:57 +08:00
6261909627 支持以图位当前采用的图片作为变换来源 2026-11-30 05:53:42 +08:00
0b9f433ccb 修复小壹隐藏窗口制作推进与画布回执等待 2026-11-30 05:47:03 +08:00
026cedaeae 移除误入源码目录的 Z56 报告文件(已移到 output) 2026-11-30 05:45:50 +08:00
417da24520 合入复核尾段提速:助手首条附锁定知识入口全文、同屏复核结论复用(R5-Z56) 2026-11-30 05:45:42 +08:00
603b88270b 合入文字样式差异与可读性客观回执、修正跨分辨率字号和换字丢样式(R5-Z50) 2026-11-30 05:43:10 +08:00
0a86c73b3a 预载小壹锁定知识并复用同屏复核结论(R5-Z56) 2026-11-30 05:42:45 +08:00
bfcb7656d9 合入报错回执补改正信息、交付清单补页号(R5-Z52) 2026-11-30 05:34:25 +08:00
a6ecd570af 合入瘦身第 2 批:撤掉纯登记工具与文案样式账本(R5-Z51) 2026-11-30 05:33:45 +08:00
41f8d52275 为小壹读屏补充文字样式差异和可读性指标 2026-11-30 05:24:54 +08:00
e09e575f0d 补齐小壹工具纠错回执与交付页号 2026-11-30 05:24:42 +08:00
62d65be1fa 撤掉小壹纯登记工具与文案样式账本 2026-11-30 05:21:16 +08:00
12d6e5b405 合入尺寸线与标注对位能力、文字截断回执(R5-Z46) 2026-11-30 04:24:26 +08:00
48cf2e9b84 补齐小壹尺寸标注对位工具与文字裁切回执 2026-11-30 04:13:50 +08:00
dffd0b569b 合入重开后待核查清单按真实记录收口、续作按钮恢复(R5-Z45) 2026-11-30 03:25:18 +08:00
ebc683fb26 修复小壹重开工程后的原请求核查与继续制作 2026-11-30 03:24:38 +08:00
e219e20896 裁切来源候选支持本项目内唯一的编号前缀 2026-11-30 03:12:22 +08:00
8e7410cd5a 合入派发遇 524 无请求号的任务进入原号核查(R5-Z44) 2026-11-30 02:45:37 +08:00
9512ed2ce4 修复小壹生图网关超时后漏查原请求 2026-11-30 02:45:14 +08:00
cf86063860 合入网关查无此单时按未发起收口(R5-Z43) 2026-11-30 02:20:50 +08:00
39fe1a08a0 小壹原请求查无记录超过恢复预算后按未发起收口 2026-11-30 02:12:54 +08:00
194943e01d 合入制作助手少绕弯:首条输入给全、回执直给事实、读图复用(R5-Z42)
# Conflicts:
#	apps/detail-agent-pi/src/image-wait-summary.mjs
#	apps/detail-agent-pi/src/production-operations.mjs
2026-11-30 02:04:21 +08:00
a4546d627a 合入瘦身第一批:切断派发与查单自动验图(R5-Z41) 2026-11-30 02:00:19 +08:00
f237e7fa49 裁切来源候选编号无效时回报收到的值和正确来源 2026-11-30 01:51:06 +08:00
4cf00c5073 给制作助手预载图位输入并补全批量等待回执 2026-11-30 01:49:26 +08:00
616a729f18 小壹钥匙校验改用中性探测模板,不在客户端写死业务模板编号 2026-11-30 01:48:09 +08:00
b628be71c5 小壹生图派发与原单核查改为显式验图 2026-11-30 01:47:11 +08:00
b144597604 合入小壹专用知识库钥匙的正式接入(R5-Z39) 2026-11-30 01:46:43 +08:00
6cb7f37180 合入宿主整屏读取缓存提速(R5-Z38) 2026-11-30 01:43:37 +08:00
cd4c4079c7 合入今晚直改的回归测试与通道缺口修复(R5-Z36) 2026-11-30 01:43:37 +08:00
ae8cd25eb6 内置工具说明补充修订衔接、切换输出后的图层编号和知识路径用法 2026-11-30 01:41:27 +08:00
05f19b313a 补齐小壹制作回归测试并修复专用模板组件识别 2026-11-30 01:41:10 +08:00
86c3f3dfb4 合入实跑报错归因与通用修复(R5-Z37) 2026-11-30 01:40:37 +08:00
f4c76a697c 接入小壹专用知识库钥匙 2026-11-30 01:37:20 +08:00
29f58d2b43 加快小壹交替读取同一画布的整屏预览 2026-11-30 01:24:55 +08:00
fd688c9a25 补全小壹脚本、复核和原片编号的失败回执 2026-11-30 01:20:04 +08:00
eff36efe1b 查看图位图片:未出完的候选如实回报状态,同花色候选可跨图位查看,助手查看不限于委托组 2026-11-30 00:42:54 +08:00
fcfda09aad 小壹专用通道模板以发布版本作为知识来源标识 2026-11-30 00:25:07 +08:00
d4b2b6ada3 素材库暂时不可用时沿用本机登录,模型目录照常加载 2026-11-30 00:10:13 +08:00
fef5ab3466 生图线路可用环境变量指定,便于低价线路上游欠费时测试 2026-11-29 23:40:41 +08:00
7454237c04 合入去掉记账门禁、交付按真实文件核验(R5-Z33)
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
2026-11-29 23:34:10 +08:00
246b61651c 小壹按真实文件核验制作交付 2026-11-29 23:30:47 +08:00
9bdf943e56 合入主小壹统筹三件套出图(R5-Z35)
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
2026-11-29 23:28:50 +08:00
7624751998 让小壹统筹跨成品图位与候选复用 2026-11-29 23:26:20 +08:00
9581aa7c19 合入宿主侧去掉拦小壹的流程门禁(R5-Z34) 2026-11-29 23:21:59 +08:00
72ec85a1a0 移除小壹宿主的画布制作流程门禁 2026-11-29 23:16:04 +08:00
354d52b466 补回无人值守运行说明和画布命令对应说明 2026-11-29 23:15:24 +08:00
3386dffda2 合入小壹内置说明只留工具用法(R5-Z32) 2026-11-29 23:13:40 +08:00
855ba3535c 小壹内置说明仅保留工具用法和回执 2026-11-29 23:06:35 +08:00
b2191f9550 小壹启动时不再把环境变量里的知识库测试钥匙写入系统凭据库 2026-11-29 16:50:04 +08:00
ae9c80e88b 合入小壹制作改走企业知识库小壹专用通道(R5-Z31) 2026-11-29 16:41:21 +08:00
03f0ee9ed3 小壹首次开工按专用清单装配组件并复用资产 2026-11-29 16:38:19 +08:00
21da6a28da 小壹制作锁定企业知识库专用发布版本 2026-11-29 16:24:59 +08:00
28ec512ee1 小壹配图 Skill 写明本款缺某项尺寸时数字连同尺寸线和端点一起去掉 2026-11-29 16:13:06 +08:00
a0002a8fb4 在小壹配图 Skill 中说明 canvasFacts 的含义
说明画布外、无内容、不可见图层不会出现在成品里,修改前先确认属于本屏可见内容;尺寸数字留空时同组线条和端点一并处理。
2026-11-29 15:48:31 +08:00
b12352cc2e 合入小壹工具回执报告图层画布状态(R5-Z30) 2026-11-29 15:48:00 +08:00
4a1e7a52cc 合入小壹后台制作时视口不再移出画布(R5-Z29) 2026-11-29 15:47:59 +08:00
727affa3bd 修复小壹后台制作时详情页视口移出画布 2026-11-29 15:39:34 +08:00
ff118d5c78 在小壹工具回执中报告图层画布状态 2026-11-29 15:36:12 +08:00
6f0d56060d 生图准备请求放行模板底图选择
界面桥的字段白名单仍是旧的模板参考字段,小壹传 useTemplateBase 会被拒为不适用字段。改为放行 useTemplateBase,去掉已不支持的两个旧字段,并补桥接测试。
2026-11-29 15:25:07 +08:00
43007a2c50 合入小壹按公开目录价格自选对话和生图线路(R5-Z28) 2026-11-29 14:58:10 +08:00
96018c87b3 合入以模板原图为底图换商品与底图拍平(R5-Z27b/Z27c) 2026-11-29 14:58:09 +08:00
51ff1e0ee0 按原稿叠放顺序合成小壹模板底图 2026-11-29 14:56:33 +08:00
b726f01a98 对话线路在设置、对话、文案和资料分析中按同一规则选取
模型声明支持读图时,各处都优先选合同允许读图和工具的线路,再比价格,避免运行时落到与设置不同的线路。
2026-11-29 14:52:00 +08:00
a1b1bc046d 支持小壹以固定模板原图为底图换商品 2026-11-29 14:44:36 +08:00
8dd6e2e3c6 小壹按公开目录价格选择兼容线路 2026-11-29 14:44:01 +08:00
8fa26a111b 候选验图结论只评价候选本身,小标识归入画布修补
第 28 轮前 1 小时候选验图 90 次中 88 次返工:88 条理由都含整屏问题(同屏其他图位未回填、
模板旧文案未更新、叠层对比),50 条含供样铭牌,候选本身常被判为基本符合实拍。

- 说明 verdict 只评价候选图本身,整屏问题写入 imageIssues/overlayFixes/copyFixes 与 screenVerdict
- 面积小、周围纹理简单的标识或污点可在采用后用原生修补去除:其余合格时 pass + canvas_adjust + canvasFixes
- Skill 局部修补段说明 canvas_adjust 的标识可先采用再修补,不必为此重新生图
2026-11-29 12:11:24 +08:00
0631c4cfc7 合入制作会话不向小壹声明目标完成工具(R5-Z25) 2026-11-29 12:04:34 +08:00
3c9fbac269 从小壹制作会话隐藏目标完成工具 2026-11-29 12:02:23 +08:00
b75c7e3b53 合入已采用图位的原生局部修补(R5-Z24)
# Conflicts:
#	apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md
2026-11-29 11:57:04 +08:00
4b27d73048 支持小壹在已采用图位上执行原生修补 2026-11-29 11:53:59 +08:00
1d7524261c 合入局部放大读屏刻度与标注版面客观数据(R5-Z23) 2026-11-29 11:45:52 +08:00
d5edfc17f9 补全小壹局部读屏刻度和标注版面数据 2026-11-29 11:44:06 +08:00
1974f63823 候选复核说明不再用带点的字段路径
第 28 轮前 30 分钟,候选复核 11 次参数校验失败中有 8 次是同一原因:
说明写"候选模板风格填 checks.templateStyle",审图子代理把它当作字面字段名,
在顶层多写了 "checks.templateStyle"(或 checksTemplateStyle),整单被退回。

- 改为"填在 checks 对象内的 templateStyle 字段",说明与工具描述中不再出现带点写法
- 删除未被引用的 COPY_IMAGE_REVIEW_GUIDANCE(同样含 checks.copyAlignment 写法)
2026-11-29 11:43:01 +08:00
a9d62b8176 整套收尾未定稿时逐屏列出缺少声明的屏
第 26 轮小壹 6 次提交 scope=all 都把多屏合并成一条已知问题(field 写 S02/S04/...,page 只填一屏),
其余屏没有对应声明,交付一直未定稿。回执此前只返回完整的 pendingScreenReviews,没有说明匹配规则。

- 未定稿回执新增 undeclaredScreens(outputId、variantId、page、state)与 deliveryNote,说明每条 issues 只对应一屏
- 目标未完成提醒改为简明屏清单,不再整段转储复核详情
- finish_production 说明写明 field 不能代替 page
2026-11-29 10:48:52 +08:00
379f90bbcc 合入复核中无效可选引用仅丢弃并记录、保留可定位问题(R5-Z22) 2026-11-29 07:51:15 +08:00
f88e2d8fe4 保留小壹复核中可定位的问题并记录无效引用 2026-11-29 07:50:06 +08:00
15c1c1baf2 合入历史候选与大回执默认摘要、分页及按编号展开(R5-Z21) 2026-11-29 07:20:52 +08:00
63257d785f 精简小壹批量候选与历史工具回执 2026-11-29 07:20:17 +08:00
9d6a2c696e 尚无实时文案时候选复核省略文案对照,不再反复退回
第 24 轮复核子代理在文案未写入时引用整屏字段编号(如 M01-T01),候选文案清单为空,连续多次被判不在清单中。现在清单为空时提示省略 shownFields,提交时忽略该项;有实时文案时仍严格校验。补测试。
2026-11-29 07:17:33 +08:00
51364cb865 合入候选与整屏复核参数扁平化、统一编号(R5-Z18) 2026-11-29 06:45:46 +08:00
b9f1f0d4cb 简化小壹候选与整屏复核参数 2026-11-29 05:58:11 +08:00
914d8af738 原图变换报错同样引导选择 P01 编号 2026-11-29 05:21:36 +08:00
f0776e662b 原生后台任务被引擎拒绝时不再吊销整轮写入
引擎任务失败(如目标图层已锁定)时文档不变,也没有应用回执。原逻辑把它与无法核实的应用一并视为需吊销写入,导致整轮制作停止。第二十二轮两次停工都由锁定图层上的 edit.transform 触发。现在按普通命令错误回报原因,写入许可保留;无法核实的应用仍吊销。补回归测试。
2026-11-29 05:21:27 +08:00
efdab6cad3 同款原图报错改为引导从清单选择 P01 编号 2026-11-29 04:37:27 +08:00
27a646d2b9 修复多个光标标签挤在角落时界面线程卡死
egui 的 Rect::intersects 把相贴也算相交。标签往下排时只挪到另一标签外扩 2 点的边上,会一直判为相交且不再移动,界面线程卡死在循环里(第二十二轮实测 04:08 起界面无响应)。改为越过外扩边距再放,并补测试。
2026-11-29 04:26:30 +08:00
6749900c89 合入画布标注与商品轮廓的原生几何读取和标注 Skill(R5-Z15) 2026-11-29 03:33:47 +08:00
56cf62eb6c 合入小壹画布协作光标按真实事件分状态的动效重做 2026-11-29 03:27:46 +08:00
48f9e9b2c7 合入工具失败回执、图层级冲突判断、引用简化与回执瘦身(R5-Z14) 2026-11-29 03:27:04 +08:00
5696f57a9d 让小壹协作光标像真人一样在画布上操作
光标的每个动作都挂在真实事件上,只改呈现,不碰制作逻辑;按工具名分出改文字、生图、调整、阅读复核四种画法。

- 待机:回合进行中、画布上没有工具在执行时原地 2–3px 漂浮,指尖细环脉动,名字略淡,按 50ms 低帧率重绘
- 移动:二次贝塞尔缓弧,控制点偏移与路程成比例,时长随距离 250–700ms,先加速后减速,越过落点几像素再回稳,身后一条短淡轨迹
- 到位与画框:指尖缩小再弹回并扩散涟漪;从左上角拖到右下角,蚂蚁线流动、尺寸数字实时变化,松手后转实线、四角控制点淡入
- 改文字:I 形光标,高亮扫过旧字;文档里这段字真的变了才落字,用去掉这段字的真实背景盖住新字,按真实字形边界逐字揭开,插入符跟随,打完闪烁
- 改图:魔棒;生图时斜向光泽来回扫;图位采纳记录真的换了才以光标为中心圆形揭开新图;目标尺寸变化时选框和控制点带回弹跟到新尺寸
- 复核与阅读:放大镜,扫描线自上而下,放大镜跟着读;验图回执通过弹小对勾、退回弹小警示,没有结论只淡出
- 完成:小对勾轻弹、停留后淡出,选框退去,转入待机
- 多光标:同时在场的光标各用一个色系,标签写明「动作 · 目标」,自动换位不互相遮挡
- 减少动效:只保留淡入淡出与直接定位;静止、最小化、看不见或没有光标时不申请重绘

新增离屏逐帧预览测试 presence_motion_frames(默认忽略),按 12 组状态输出帧序列。
2026-11-29 03:19:49 +08:00
a267ff80f9 放宽字体菜单测试的稳定步数上限,避免机器高负载时误报 2026-11-29 03:14:03 +08:00
b6631c9a5d 精简等待图位回执并支持按屏读取完整复核 2026-11-29 03:09:42 +08:00
cfa51c7aa7 完善原始调用回放所需的回执与宿主复用 2026-11-29 03:09:42 +08:00
cda37369c0 按图层核对原生写入并简化小壹工具引用 2026-11-29 03:09:41 +08:00
45fe35fb16 补全小壹工具失败回执并修复制作画布交接与批量验图读取 2026-11-29 03:09:34 +08:00
94f05fbbc1 提供小壹画布标注与商品轮廓的原生几何读取 2026-11-29 03:05:29 +08:00
bf74aaf70b 模板原屏快照保存失败写入日志 2026-11-29 03:05:01 +08:00
8d361c3c86 合入读屏与复核的模板原稿对照和保真说明(R5-Z16) 2026-11-29 03:04:39 +08:00
54c0625165 合入交付名称保留完整型号与同名目录编号(R5-Z17 补充) 2026-11-29 03:02:48 +08:00
b1c7db1f1b 保留小壹交付名称中的完整商品型号 2026-11-29 03:02:23 +08:00
48bed2e445 合入交付包去重、短路径与按引用精简候选(R5-Z17) 2026-11-29 02:54:19 +08:00
be2f108698 修复四个界面测试丢弃未处理纹理增量导致的失败
测试结束前清空 run_ui 输出的 textures_delta,与代码库其余测试的做法一致。
2026-11-29 02:53:04 +08:00
e5b18fef5d 合入制作消息追加时按条目失效的布局缓存(R5-Z12 第三部分) 2026-11-29 02:35:52 +08:00
07a3bad265 精简小壹交付工程资源并核验可移植性 2026-11-29 02:28:19 +08:00
efc0c27d37 追加制作消息时保留未变条目的布局缓存 2026-11-29 02:21:46 +08:00
6572d75089 合入读屏复核和项目缩略图走流式显卡合成(R5-Z11) 2026-11-29 02:14:27 +08:00
1589b3216a 合入制作回合内按视口裁剪离屏条目与输入区高度复用(R5-Z12 第二部分) 2026-11-29 02:13:44 +08:00
9cc251e6ef 补全小壹读屏与复核的模板原稿对照 2026-11-29 02:06:26 +08:00
4a477df23f 按视口裁剪活跃制作回合的离屏条目 2026-11-29 02:06:00 +08:00
2be3fbbd09 复用展开输入区的草稿高度测量 2026-11-29 02:01:25 +08:00
e6d12ddae0 用单个活跃制作回合复现长对话界面负载 2026-11-29 01:49:53 +08:00
952104c655 合入界面分区慢帧计时与对话历史回合复用布局(R5-Z12 第一部分) 2026-11-29 01:48:16 +08:00
eeea6e5a5b 流式显卡合成加速小壹读屏和项目缩略图 2026-11-29 01:35:24 +08:00
e6dd66371e 复用对话行布局并跳过离屏历史回合 2026-11-29 01:19:50 +08:00
25684b601c 为离线制作基准提供匹配的模板画布 2026-11-29 01:14:07 +08:00
c77b64e264 为基准夹具绑定离线制作回合并维持心跳 2026-11-29 01:11:19 +08:00
498393326d 合入大型文档打开和切换时按可见区分帧刷新显卡画布(R5-Z13)
- 大文档首次整图显卡刷新改为每帧一块、看得见的先画,界面线程不再整段冻住
- 小壹写画布前:文档未变时跳过图层扫描,解析编辑参数时不再复制 JSON
- 无窗口实测(1440×34838、304 层):打开最长单帧 715→117 ms,切换 339→128 ms;全部画完 0.72→0.90 s、0.35→0.83 s
- 拆块结果与整图刷新逐像素一致;界面全量 5540 项通过,另有 4 项属合入前已有的测试收尾问题,与本次无关
2026-11-29 00:58:44 +08:00
a49446cc72 合入小壹续做保存回执修复(R5-Z10)
- 当前画布版本已保存时,续做、继续制作和成品导出直接往下走,不再空等保存回执
- 回执版本或画布身份对不上时结束等待并提示重新提交,不再永久卡在"正在保存产品资料"
- 审核补充:更早版本的回执(仍在途的资料保存)不算失败,继续等本次操作自己的回执
2026-11-29 00:47:44 +08:00
01a6f1daf4 增加小壹画布操作及保存提交的计时基准 2026-11-29 00:45:14 +08:00
796762834a 增加大型文档首开与切换的无窗口基准 2026-11-29 00:43:57 +08:00
1958f5537b 减少小壹画布写入前的文档扫描与参数复制 2026-11-29 00:43:23 +08:00
dae00ec02f 支持长对话基准在三个滚动位置离屏截图 2026-11-29 00:43:08 +08:00
e6e2616f0f 按可见区域分帧刷新大型文档的 GPU 画布 2026-11-29 00:43:07 +08:00
0b7aacf285 增加小壹长对话的无窗口帧耗时基准 2026-11-29 00:42:50 +08:00
f9924a8531 记录小壹、停靠面板及画布叠层的慢帧耗时 2026-11-29 00:42:30 +08:00
7ff78a1fd5 修复小壹续做时的画布保存等待 2026-11-28 23:59:53 +08:00
42c87278fb 合入小壹采用图按生图、实拍原片、变换三种来源交付(R5-Z8c) 2026-11-28 23:36:39 +08:00
199cb9d528 统一采用图产物读取并验证三类交付来源 2026-11-28 23:31:08 +08:00
0b31d7ac53 合入小壹主机卡顿慢操作日志与整图合成移出界面线程(R5-Z2) 2026-11-28 23:30:02 +08:00
478d9412bd 合入小壹生图附件不带模板图、参考方式与主图画幅按配置声明(R5-Z6)
# Conflicts:
#	apps/detail-agent-pi/src/candidate-review.mjs
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs
2026-11-28 23:24:10 +08:00
3645613860 按已选主图画幅统计进度并导出交付 2026-11-28 23:20:35 +08:00
495bcd8b87 合入小壹交付清单接入逐字段待核实事实(R5-Z8b)
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
2026-11-28 23:20:16 +08:00
c04eccb68f 合入小壹每图位双候选挑优、默认四张封顶与候选验收补项(R5-Z9)
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
2026-11-28 23:16:39 +08:00
50103ea861 将逐字段待核实记录写入交付清单 2026-11-28 23:10:01 +08:00
e224e4fb3e 实现小壹图位双候选派发与验收 2026-11-28 23:09:13 +08:00
8a9359862f 合入小壹交付前保真对照、重开逐层回读与交付包补齐(R5-Z8)
# Conflicts:
#	apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs
2026-11-28 23:08:54 +08:00
27ab409a29 合入小壹切走成品取原片与裁切、等出图三分钟回报、回执补数据(R5-Z4)
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
2026-11-28 23:05:04 +08:00
443871ab28 合入小壹模板制作配置的字段层清样例、共用端点与按页层号(R5-Z5) 2026-11-28 22:59:37 +08:00
9fc9fb9e95 给小壹候选回执和在途等待设置时限 2026-11-28 22:59:37 +08:00
5fba04bc1c 记录小壹宿主慢操作并后台合成成品画布 2026-11-28 22:49:36 +08:00
2cdac1a99c 补齐小壹模板保真、重开核验及采用图交付证据 2026-11-28 22:48:59 +08:00
28cee583d8 合入小壹读屏叠层组关系与图位下方透出层(R5-Z1)
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-agent-pi/src/screen-review.mjs
2026-11-28 22:40:04 +08:00
2079e1e6dd 按制作配置规划主图画幅并隔离模板生图参考 2026-11-28 22:26:17 +08:00
6f1c126300 合入小壹逐字段填写要求与旧值冲突清单(R5-Z7) 2026-11-28 22:20:25 +08:00
1974159caa 记录小壹逐字段填写依据和模板旧值冲突 2026-11-28 22:18:52 +08:00
dac0658448 让小壹后台成品先制作和复核候选 2026-11-28 22:12:04 +08:00
43968c5945 修复小壹待填尺寸字段、共用端点和原稿层号作用域 2026-11-28 22:05:40 +08:00
2aed7dc1cf 小壹续做时锁定版本在知识库已下线或换号,提示后继续用本地锁定资料;认证失败仍停止 2026-11-28 22:02:50 +08:00
7f4d666aa8 补全小壹整屏读屏的图层组和遮挡数据 2026-11-28 22:02:49 +08:00
a8d52c5ec0 合入小壹主代理去掉过期截图、子代理指引进缓存前缀、知识库连接池(R5-Z3) 2026-11-28 21:55:21 +08:00
2fc959e741 修正小壹候选复核字段和资料刷新回执 2026-11-28 21:48:24 +08:00
79ff0d87bf 精简小壹制作上下文并并行处理知识库请求 2026-11-28 21:47:34 +08:00
17cae200a4 合入小壹热文件清理:去掉整轮封锁、自动核查、无画布模式与第二协议,未知请求只挡本图位(R5-X) 2026-11-28 21:24:42 +08:00
2b42f2c05a 清理小壹热文件里的整轮封锁、自动核查与无画布模式(R5-X)
- 普通对话里写入失败不再封锁整轮:未派发、用户接手、修订冲突的宿主原因原样作为工具回执交回,下一步由小壹决定
- 结果未知的原请求按图位留存,只挡同一图位;同图位先按原号核查或等过期,其他图位与画布编辑照常
- 删去"本轮相同操作已有原记录"拦截,花费由每图位生图上限控制
- 删去普通对话的 pi-recover 自动核查整套(后端早已不处理该动作)
- 开工不再因任意无关的未结束记录被拒
- 删去无画布模式和画布方法存在性判断,测试与 QA 脚本改用完整假画布
- 删去第二套 structured-json 工具协议
2026-11-28 21:21:57 +08:00
1d456a0bad 合入小壹企业知识库读取修通与规则附件锁定(R5-Y) 2026-11-28 21:18:16 +08:00
15f9af8453 修通小壹企业知识库读取与项目规则锁定 2026-11-28 20:38:07 +08:00
31ec1585a4 合入小壹 Node 侧防御过度代码清理(R5-V) 2026-11-28 20:32:43 +08:00
6fd9203ec2 合入小壹 Node 侧防御过度清理(R5-V) 2026-11-28 20:11:24 +08:00
7746f71f02 清理小壹 Node 侧防御过度代码
- 删除生产无调用方的 receipt.mjs 和 NativeCanvas 兼容转出口
- 删除只为测试假对象写的画布方法存在性判断及生产走不到的兜底分支
- 未派发回执只认 phase 与 operationId,不再逐字段复核宿主数据
- 企业知识库去掉与 Pi 原生校验重复的本地校验,保留服务端真实校验原因
- 测试同步:删死代码用例,无画布主机工具清单补齐原生工具
2026-11-28 20:08:18 +08:00
787427a01b 合入小壹复核状态分清通过与未改、交稿按导出版本核验、读屏给出产品实际范围(R5-U) 2026-11-28 20:04:35 +08:00
1751b490bd 区分小壹整屏复核状态并核验成品交付 2026-11-28 19:58:19 +08:00
e0642e5061 合入小壹按屏先派子代理、切走的成品后台照常生图(R5-R),与 R5-S 整屏验图并存 2026-11-28 19:40:13 +08:00
9b5ac97eb1 合入小壹原生命令回执去掉工作台状态与重复结果(R5-W) 2026-11-28 19:36:14 +08:00
e333079754 精简小壹原生命令回执 2026-11-28 19:33:42 +08:00
ea7a6d0a4a 让小壹按屏分派并跨成品后台生图 2026-11-28 19:28:41 +08:00
dd29589bad 合入小壹产品图收纳坞改成左下角悬浮按钮组与浮层(不再压缩画布) 2026-11-28 19:27:34 +08:00
f52c29c332 产品图收纳坞改为画布左下角的悬浮按钮和浮层,不再占用画布
- 去掉画布底部通栏,画布视口不再被压缩。收起时只剩画布内容区左下角一组带底板的计数按钮
  (产品图、图片资源),离左边和横向滚动条各 10,高 34;不常驻文字,悬停或键盘焦点时提示
  「产品图 · N 张」「图片资源 · N 张」,数量为 0 的按钮不显示。
- 点按钮在按钮组正上方 8 弹出浮层(t.card、t.field_border、圆角 10、弹层阴影),宽度贴合内容、
  最宽为画布 60%,图片资源最高为画布 40%;产品图缩略图 64px,横向滚动。
- 再点同一个按钮、点浮层外面或按 Esc 收起,点另一个按钮切换内容。开合只在本次运行内有效,
  默认收起;对话框、变换、重生成或其他弹层出现时收起。
- 开合淡入淡出并带 6 的位移,时长 motion::NATIVE;减少动态效果时直接切换,空闲不重绘。
- 保留拖到画布、双击退回收纳坞(退回后打开产品图浮层)。收纳坞盖住的地方不再选中、拖动或
  缩放下面的图片;浮层打开时 Esc 不再同时取消选区、后台任务或全屏。
- 新增收纳坞交互单测,更新双击退回与离屏截图验收。
2026-11-28 19:24:25 +08:00
c8993ae09b 合入小壹验图按候选原图+整屏合成一起判(R5-S) 2026-11-28 19:14:30 +08:00
f57ef0e77a 按整屏合成复核小壹候选图 2026-11-28 19:08:56 +08:00
ec374e3c11 合入小壹模型请求结果未知时按原生重试续上(R5-T) 2026-11-28 18:47:26 +08:00
5e5c460670 修复小壹模型流结果未知时未触发原生重试 2026-11-28 18:46:59 +08:00
05878e4992 合入小壹出图子代理企业指引短路径与读取回执(R5-Q) 2026-11-28 18:28:47 +08:00
fbd1fcfae0 修复小壹子代理企业指引路径与读取回执 2026-11-28 18:28:04 +08:00
b0bab65aba 合入小壹企业知识库 Key 由宿主注入(R5-P,哈基米底线 1) 2026-11-28 09:50:38 +08:00
fe000ac4f9 无人值守明确由小壹代为决定前置选择;主代理重试窗口加长到约 2.5 分钟以扛住网关 502 2026-11-28 09:46:55 +08:00
742a85fc1f 将小壹企业知识库凭据收口到原生宿主 2026-11-28 09:28:28 +08:00
ed50a65aa7 子代理与主代理工具失败原因取最后一段文字(脚本报错在输出之后) 2026-11-28 09:12:50 +08:00
d2b391e558 合入小壹主代理上下文瘦身:折叠被取代的旧回执、收紧回执样板(R5-O) 2026-11-28 09:06:44 +08:00
b3efeb0a91 减少小壹制作主代理的重复工具回执 2026-11-28 09:05:02 +08:00
3b5e452025 合入小壹整屏复核按本屏内容指纹失效(R5-M) 2026-11-28 08:57:15 +08:00
0755146f62 制作目标完成以宿主核验的交付回执为准,模型提前声明完成时返回待交付事实 2026-11-28 08:57:14 +08:00
b844eceb88 子代理工具失败时在事件日志记录原因(截断 300 字) 2026-11-28 08:42:26 +08:00
12157621b5 合入小壹企业规则开工锁定下载与模板固定版本复用(R5-N) 2026-11-28 08:39:48 +08:00
b811e593c4 修复小壹整屏复核的失效范围 2026-11-28 08:39:10 +08:00
0c5876a967 修复小壹制作规则与模板的本地版本锁定 2026-11-28 08:38:57 +08:00
00db1a859c 合入小壹读图池排队不拒(R5) 2026-11-28 06:32:36 +08:00
953a88f672 修复小壹详情读图队列满时拒绝请求 2026-11-28 06:20:14 +08:00
f3cef63742 合入小壹交付 PNG 尺寸与文案复核回执(R5) 2026-11-28 05:54:10 +08:00
ba94b6c92d 修复小壹 PNG 交付并在回执中记录未复核文案 2026-11-28 05:39:31 +08:00
47fdb50a2e 子代理轮数预算按两轮实测调到 24,只截失控循环 2026-11-28 05:13:19 +08:00
019243f245 合入小壹子代理退回事实与轮数预算(R5) 2026-11-28 05:11:18 +08:00
67ff51b37d 为小壹原生子代理补全复核退回回执和轮数预算 2026-11-28 05:10:54 +08:00
6504b620ab 合入小壹整屏读取排队修复(R5) 2026-11-28 03:13:11 +08:00
f8162064db 修复小壹整屏复核队列满时漏屏 2026-11-28 02:59:57 +08:00
960176b901 小壹无人值守说明只保留在制作系统提示一处 2026-11-28 02:07:39 +08:00
32fbc9fd06 合入 R4 修复到 R5(含生图链接结果、有界恢复与恢复队列收口) 2026-11-28 02:07:10 +08:00
344add2816 合入 R4 生图恢复并统一宿主原请求队列 2026-11-28 02:05:39 +08:00
816950c992 合入小壹 R5-K 知识库适配(harness 侧) 2026-11-28 01:51:47 +08:00
f7051b4f57 适配小壹企业知识库的项目规则锁定与模板配置 2026-11-28 01:51:22 +08:00
38b1729f2f 合入小壹 P2-A 单主代理通管 A 级 2026-11-28 01:47:47 +08:00
d02913a609 同步小壹 R5 并保留跨成品制作 2026-11-28 01:47:30 +08:00
c49c48b475 合入小壹 P2-F 界面空闲零重绘与工作中光球动效 2026-11-28 01:43:25 +08:00
a570630e37 恢复小壹工作时的低频光球动效 2026-11-28 01:43:09 +08:00
74db96dc6b 合入小壹 R4-H 生图结果改取链接 2026-11-28 01:41:29 +08:00
69c6fdd300 小壹生图在线路声明时改用 URL 结果并下载网关链接
- 线路契约在 response_format 的 enum 或 const 中明确列出 url 时,生图请求取 URL 结果;只声明 b64_json、开放字符串或未声明的线路保持原样
- 结果链接只接受 https://api.vip98k.com/api/external/assets/ 下的网关限时链接;网关源码中该链接本身即凭证,下载不再附带个人 Key,下载后照常解码并保存为 generated.png
- 原请求恢复取回的留存响应带 URL 时按同样方式下载;链接下载返回 404 或 410 时原请求记为 expired,图位可以另备新请求
- 同步 reconcile_image_slots 工具说明与 JIANSUN.md
2026-11-28 01:40:32 +08:00
7eaca128b7 Merge branch 'feat/xiaoyi-hajimi-v2-r5-20261127' into feat/xiaoyi-p2-idle-power-20261127 2026-11-28 01:35:10 +08:00
1a80c8956b 让小壹按成品保留制作任务与复用候选 2026-11-28 01:34:29 +08:00
72ee5898df 减少小壹空闲与后台制作时的界面重绘 2026-11-28 01:34:12 +08:00
332e876e5a 合入小壹 P2-D 通用化收尾 2026-11-28 01:28:45 +08:00
72399173db 保持资料页模板尺寸与工作流状态一致 2026-11-28 01:28:07 +08:00
70efd65061 说明小壹无人值守制作没有人工后期环节 2026-11-28 01:25:04 +08:00
5aa212f51a 合入小壹 R4-E2 收纳坞对齐界面约定 2026-11-28 01:24:35 +08:00
a707175d97 合入小壹 R4-G 生图原请求有界恢复与参考图压缩 2026-11-28 01:19:18 +08:00
32ebdab2ad 合入小壹 P2-G 首开画布与整屏读取提速 2026-11-28 01:14:55 +08:00
04889a4f1e 稳定小壹生图原请求恢复并压缩传输体积
- 线路契约声明压缩出图格式且背景为不透明时,出图改用 JPEG/WebP,契约声明 output_compression 时取 95;R3 所用线路只声明 png/gif 并禁用 output_compression,保持 PNG
- 线路接受 JPEG 参考图时,不透明参考图以 JPEG q95 上传;带透明像素的参考图和实拍合成的模板底图保持 PNG。编码由保存的文件扩展名决定,旧请求的规格哈希不变
- 恢复重查改用结构化等待原因(processing、unresolved、running、network),不再按错误文案判断
- 原幂等键查询为 unresolved 时,从首次观测起计 180 秒恢复预算,用完仍为 unresolved 即记为 expired,图位可以另备新请求;410 与 failed 的处理不变,结果有留存时仍按原请求号取回
- 同步 reconcile_image_slots 工具说明与 JIANSUN.md
2026-11-28 01:14:26 +08:00
f91d700300 合入小壹 P2-C 付费生图请求状态收口到宿主 2026-11-28 01:13:14 +08:00
9e92d66957 合入小壹 P2-H 草稿增量存盘 2026-11-28 01:08:45 +08:00
fc67959ec3 合入小壹 R5 最新集成基线 2026-11-28 01:03:49 +08:00
ebb9460a98 同步小壹 R5 薄 Harness 与生图额度 2026-11-28 01:02:47 +08:00
948bd7dee8 按内容增量保存小壹工程草稿 2026-11-28 00:59:54 +08:00
a0586028b4 合入小壹 P2-I 生图次数默认上限 2026-11-28 00:58:27 +08:00
cf193a3edb 为小壹图位生图设置内置额度 2026-11-28 00:50:11 +08:00
82c7f37856 同步小壹 R5 上下文与薄宿主基线 2026-11-28 00:47:15 +08:00
61f0c10543 合入小壹 P2-2 上下文按需加载与 P2-B 薄 harness 收尾 2026-11-28 00:41:27 +08:00
11104d63a0 核验旧模型记录不阻断素材操作 2026-11-28 00:34:26 +08:00
a4483a0d64 按宿主已派发记录计算图位预算 2026-11-28 00:28:59 +08:00
855734419d 收口历史账本投影与模型请求观测 2026-11-28 00:28:11 +08:00
7595399c93 保留规则变更和接手后的原生停机回执 2026-11-28 00:25:23 +08:00
95ef25ef9c 合入小壹 R5 运行记录收口 2026-11-28 00:21:17 +08:00
2a6b05fd94 派发前的候选预留不占生图预算 2026-11-28 00:21:15 +08:00
186385b8f9 同步小壹 R5 集成基线 2026-11-28 00:21:14 +08:00
86aac48a79 收薄小壹模型传输、知识读取和制作目标 2026-11-28 00:09:09 +08:00
0c878d616e 同步小壹 R5 并更新生图回执测试夹具 2026-11-28 00:09:09 +08:00
4679f5d214 合入小壹 P2-4 运行垃圾数据与过程记录收口 2026-11-28 00:04:19 +08:00
bdf220a2a0 收口小壹生图原请求状态到宿主档案 2026-11-27 23:54:33 +08:00
83ca07e1f1 加快小壹详情草稿打开和重复整屏读取 2026-11-27 23:54:21 +08:00
44cea7323f 修复小壹收纳坞控件与图片资源验收契约 2026-11-27 23:53:58 +08:00
727b7c0221 移除小壹客户端的固定产品版式与字段编号推断 2026-11-27 23:48:43 +08:00
ee9f312e19 合入小壹 P2-4 运行时数据精简 2026-11-27 23:36:35 +08:00
c0e7525346 合入小壹 P2-4 运行时数据精简 2026-11-27 23:36:02 +08:00
fa55f70941 合入小壹制作上下文与文案修订校验 2026-11-27 23:35:28 +08:00
a6e9aeb2a2 合入小壹 P2-1 子代理改用 Pi 原生会话 2026-11-27 23:27:45 +08:00
4d7938d41f 合入小壹 P2-7 操作过程协作光标 2026-11-27 23:25:45 +08:00
de9eaf8a81 合入小壹 P2-5 交付结果文件优化 2026-11-27 23:25:24 +08:00
5c3da9269e 合入小壹 P2-3 画布流程提速 2026-11-27 23:25:13 +08:00
b2f62abeee 在小壹画布显示协作光标 2026-11-27 23:06:33 +08:00
8075429395 用画布修订号和原文确认文案写入 2026-11-27 22:59:46 +08:00
eacd0e3922 优化小壹交付包命名、去重与缺项清单 2026-11-27 22:59:31 +08:00
b77f674e4d 同步小壹 R4 集成分支 2026-11-27 22:58:28 +08:00
009926e425 将小壹子代理迁移到 Pi 原生会话并收口对话重试 2026-11-27 22:54:18 +08:00
871d7c0f2b 合入小壹 R4 最新集成基线 2026-11-27 22:48:58 +08:00
98bc6e2e0d 合入小壹 R4-B1 与 R4-F
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-agent-pi/src/photocraft-extension.mjs
#	apps/detail-agent-pi/test/production-operations.test.mjs
2026-11-27 22:48:54 +08:00
0708945132 同步小壹 R4-A 与 R4-B1 集成基线 2026-11-27 22:48:31 +08:00
6b37fae127 合入小壹 R4-F 生产代理技能来源隔离 2026-11-27 22:48:22 +08:00
18f5647a2a 合入小壹 R4 跨成品画布和切换修复 2026-11-27 22:48:16 +08:00
4440e33d41 合入小壹 R4-B1 切换成品不阻塞与空转续跑暂停 2026-11-27 22:47:06 +08:00
d65f2495be 合入小壹 R4-A 跨成品画布回填与手改保护 2026-11-27 22:46:42 +08:00
2440f085d4 合入小壹 R4-A 跨成品画布回填与手改保护 2026-11-27 22:45:47 +08:00
0632847c39 精简小壹制作上下文和企业知识加载 2026-11-27 22:43:54 +08:00
4c8ed7fe7e 隔离小壹生产代理的技能来源 2026-11-27 22:42:09 +08:00
3742aa21f1 精简小壹运行时数据和过程记录 2026-11-27 22:42:07 +08:00
14578d3890 移除小壹输入框的定时画布轮询 2026-11-27 22:36:21 +08:00
a0434daf0e 合入小壹 R4 成品切换与续跑修复 2026-11-27 22:29:06 +08:00
a4e272e6b5 合入小壹 R4-E 图片资源并入产品图收纳坞 2026-11-27 22:21:40 +08:00
6424dd730b 合入小壹 R4-B2 文案就绪回执与开局规则读取 2026-11-27 22:17:40 +08:00
605ec26c05 整合小壹画布收纳坞与图片资源入口 2026-11-27 22:13:09 +08:00
7ea52d85d8 为小壹补充整屏叠层和交付进度事实 2026-11-27 22:07:37 +08:00
81b1d9873f 修复小壹成品切换阻塞和空转续跑 2026-11-27 22:03:21 +08:00
bf6df62b92 修复小壹跨成品画布回填与手改保护 2026-11-27 21:43:19 +08:00
bf59451cfb 修复小壹开局规则读取与派图文案回执 2026-11-27 21:38:24 +08:00
15a87efc92 合入小壹跨阶段生图尾巴恢复 2026-11-27 19:25:14 +08:00
d56cd1415a 合入小壹活跃制作生图尾巴监控 2026-11-27 19:25:14 +08:00
591eb6c2fc 并行恢复小壹跨阶段生图任务 2026-11-27 19:16:51 +08:00
6a0c3a6bbf 让小壹并行核查活跃制作的生图原请求 2026-11-27 18:52:58 +08:00
ba1ff1683d 补齐按屏复核活动和客户端离线检查 2026-11-27 18:34:10 +08:00
d22146a73b Merge commit '7eb150ba13ff02c333980cbe4153806e236166fb' into feat/xiaoyi-hajimi-v2-r3-20261127 2026-11-27 18:33:34 +08:00
27ccb52198 加快小壹整屏预览并提供可见叠层清单 2026-11-27 18:29:19 +08:00
7eb150ba13 小壹按屏并行复核与原生画布命令速查 2026-11-27 18:22:58 +08:00
9c2caf3110 小壹整屏叠层复核与制作请求瘦身 2026-11-27 18:11:32 +08:00
b08d5f1252 移除小壹制作时限并保留画布引用身份 2026-11-27 18:01:23 +08:00
120ee36597 修复小壹文案写入、图位生图上限和引用 2026-11-27 17:50:16 +08:00
55f12e971c 完善小壹时间流文案回执与子代理状态 2026-11-27 17:44:36 +08:00
0585524796 小壹按批派发图位并按整屏复核确认文案 2026-11-27 17:38:32 +08:00
e6c501996c 合并哈基米 V2 画布绑定热修复与小壹 UI 精修 2026-11-27 16:34:57 +08:00
5e5bef4a2e 修复小壹流式正文显露和思考状态显示 2026-11-27 16:29:40 +08:00
936a6d1c7f 修复哈基米 V2 画布绑定派发与制作阻塞登记 2026-11-27 16:12:32 +08:00
705d1e28b1 fix(materials): open approval notifications in desktop browsers 2026-11-27 15:50:39 +08:00
c477ec7611 验证跨成品实时文案并补齐原生离屏回归 2026-11-27 15:02:09 +08:00
ac0a6d3142 Merge commit '39991ad7c26fbbfaead4a7f8dea7c187251de4d4' into feat/xiaoyi-hajimi-v2-20261127 2026-11-27 14:44:10 +08:00
ca1e8dbad1 Merge commit 'cf630e2c150ce85f10d85bbf8684670dafc924e1' into feat/xiaoyi-hajimi-v2-20261127 2026-11-27 14:43:33 +08:00
753ab4a9fb Merge commit '49313f45eb047b385f5e19eff52516c0cee5c894' into feat/xiaoyi-hajimi-v2-20261127 2026-11-27 14:43:11 +08:00
4bcf94d7d5 Merge commit 'c9c1d326876c65c0666db02a5d34eb41aa9e0590' into feat/xiaoyi-hajimi-v2-20261127 2026-11-27 14:42:43 +08:00
c9c1d32687 移除小壹旧版整套制作链路 2026-11-27 14:35:52 +08:00
39991ad7c2 让小壹按实时卖点文案核对画面主角 2026-11-27 14:33:36 +08:00
fc273c69f5 fix(materials): require a bound DingTalk ID for sub-admin bypass 2026-11-27 14:33:29 +08:00
49313f45eb 让单一制作会话切换成品并返回交付回执 2026-11-27 14:28:47 +08:00
b63be5efa9 fix(materials): authorize direct task detail edits by sub-admin role 2026-11-27 14:18:41 +08:00
cf630e2c15 接入小壹视频原子工具与种草视频预检 2026-11-27 14:15:15 +08:00
8a6ec37526 在草稿回归用例中显式释放离屏纹理增量 2026-11-27 13:52:34 +08:00
52ee55dffb fix(materials): route task detail approvals to department sub-admins 2026-11-27 13:46:35 +08:00
635b129a6a Merge commit '19d2c8bf3b2a7992671d580700b992e9c388bfc6' into feat/xiaoyi-integrated-all-20261127 2026-11-27 13:45:35 +08:00
19d2c8bf3b 按组蒙版范围导出多页画布的纯色填充像素 2026-11-27 13:44:09 +08:00
cacfad0ba6 使用小壹品牌呈现便携包运行组件 2026-11-27 13:36:42 +08:00
江林铖
6011a53c6c build(salary): package performance version migration tooling 2026-11-27 13:35:52 +08:00
3c4a8394af Merge commit '52ac1f74' into feat/xiaoyi-integrated-all-20261127 2026-11-27 13:33:43 +08:00
ae008bde5a Merge commit 'fca2710b' into feat/xiaoyi-integrated-all-20261127 2026-11-27 13:33:42 +08:00
aa0bc8927a Merge commit '8691a842' into feat/xiaoyi-integrated-all-20261127 2026-11-27 13:33:41 +08:00
ec31df66fd Merge commit '0ec1532b' into feat/xiaoyi-integrated-all-20261127 2026-11-27 13:33:40 +08:00
江林铖
18b3d20ae6 feat(salary): version performance schemes by effective month 2026-11-27 13:33:27 +08:00
d8334581b7 优化小壹截图上下文与原生命令目录查询 2026-11-27 13:10:28 +08:00
5d9d866ed7 fix(materials): use short storage names for SKU previews 2026-11-27 13:10:16 +08:00
d52a1d0f4c 允许制作任务返工替换自己已采纳的图位 2026-11-27 13:03:31 +08:00
52ac1f74ee 修复小壹连续采纳和画布图片引用 2026-11-27 12:12:53 +08:00
e77f53929b 在制作画布应用后台原生命令结果 2026-11-27 12:11:50 +08:00
fca2710be5 细化小壹时间流与工具活动呈现 2026-11-27 11:50:34 +08:00
8691a8421c 修正小壹自动保存与暂缓输出原图恢复 2026-11-27 11:41:20 +08:00
93de08babf 修复小壹进度格、正文动效和工具回执 2026-11-27 11:33:23 +08:00
2a119f4434 抛光小壹制作时间流和窄窗工作台 2026-11-27 11:00:36 +08:00
2e0a455c44 更新企业模板保真测试的页面和花色绑定 2026-11-27 10:49:52 +08:00
ec22ffe6c8 允许未发布固定层策略的模板编辑原生图层 2026-11-27 10:43:10 +08:00
0ec1532be1 docs(xiaoyi): 明确旧制作入口下线条件与单主代理瘦身路径 2026-11-27 10:30:44 +08:00
cb09741133 说明已绑定画布的输出交接方式 2026-11-27 01:02:41 +08:00
79fc1c3514 稳定校验子代理成图与资源列表展开 2026-11-27 00:46:18 +08:00
112aa23bf2 引导小壹自主复核图文一致性 2026-11-27 00:37:39 +08:00
6b785c8d2e merge: 接通小壹子代理进度与生图回执 2026-11-27 00:35:05 +08:00
14639b1a4e merge: 接入小壹新版目标驾驶舱与制作时间流 2026-11-27 00:35:04 +08:00
7c64d09606 Integrate Xiaoyi goal cockpit and production timeline 2026-11-27 00:19:47 +08:00
5d90e40234 fix(xiaoyi): connect production worker progress and image receipts 2026-11-27 00:13:48 +08:00
f2bc022743 merge: 整页视觉审核提示词与无人值守默认提示词 2026-11-26 23:53:57 +08:00
f7b1113f80 Merge Xiaoyi Stitch components and conversation motion 2026-11-26 23:52:39 +08:00
b1bf4a5610 feat(xiaoyi): guide whole-page review and unattended canvas production 2026-11-26 23:44:10 +08:00
0986287a26 fix(xiaoyi): move whole-set production to composer shortcuts 2026-11-26 23:33:32 +08:00
bd977e3ec2 fix(xiaoyi): align canvas outputs and keep project actions visible 2026-11-26 23:23:12 +08:00
a2b288798e Strip account epoch from Pi action arguments after authorization 2026-11-26 22:56:21 +08:00
ef2c97a76f feat(xiaoyi): consolidate Stitch components and conversation motion 2026-11-26 22:40:28 +08:00
a213178c46 Merge commit 'ede0436c' into feat/xiaoyi-integration-core 2026-11-26 22:05:31 +08:00
01276bdfb2 Merge commit '314b4fca' into feat/xiaoyi-integration-core 2026-11-26 22:05:30 +08:00
d6deaa2214 Merge commit '6ab902d2' into feat/xiaoyi-integration-core
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-agent-pi/src/photocraft-extension.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs
2026-11-26 22:05:30 +08:00
b0e406cd32 Exercise canvas transforms with the production request signature 2026-11-26 21:46:30 +08:00
fab2136df3 Bind production request scope to the selected working output 2026-11-26 21:42:48 +08:00
314b4fca3a feat(xiaoyi): show upcoming video outputs 2026-11-26 21:33:51 +08:00
6ab902d2e3 fix(xiaoyi): unify client and assistant product copy 2026-11-26 21:17:20 +08:00
18374d9c79 Preserve cancelled response receipts and production continuity tests 2026-11-26 21:16:11 +08:00
ede0436ca3 Add chair acceptance launcher and delivery bundle verifier 2026-11-26 21:15:33 +08:00
44792c2379 Merge commit 'ec5ba7fc' into feat/xiaoyi-integration-core
# Conflicts:
#	apps/detail-photocraft/crates/ui-egui/src/dialogs/discard_ui.rs
#	apps/detail-photocraft/crates/ui-egui/src/menus/invoke.rs
2026-11-26 21:14:01 +08:00
629b278fe7 Merge commit '1ee72c20' into feat/xiaoyi-integration-core
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
2026-11-26 21:13:52 +08:00
f06d3792c5 Merge commit '807d7df4' into feat/xiaoyi-integration-core
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-agent-pi/src/request-purpose.mjs
2026-11-26 21:13:43 +08:00
9a17a543ba Merge commit 'd468305d' into feat/xiaoyi-integration-core
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-agent-pi/test/production-operations.test.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs
2026-11-26 21:13:28 +08:00
4104355bc5 Merge commit '60a5351ec2373ee56584b9bf91d90174dda34566' into feat/xiaoyi-integration-core
# Conflicts:
#	apps/detail-agent-pi/src/production-operations.mjs
#	apps/detail-agent-pi/test/production-operations.test.mjs
2026-11-26 21:13:15 +08:00
1ee72c20f1 Make Xiaoyi canvas adjustments advisory 2026-11-26 21:03:00 +08:00
60a5351ec2 feat(xiaoyi): publish verified production bundles to a chosen folder 2026-11-26 20:24:38 +08:00
254e5291bd Keep Xiaoyi composition repairs in the native canvas 2026-11-26 20:06:00 +08:00
807d7df4b8 refactor(xiaoyi): use Pi resource loading and simplify original recovery 2026-11-26 19:45:29 +08:00
ec5ba7fcd6 fix(web): omit desktop exit guards from wasm 2026-11-26 19:40:58 +08:00
dd953287d6 feat(xiaoyi): bundle HarmonyOS Sans SC for desktop UI 2026-11-26 19:34:53 +08:00
dcd0f13f26 Record R28 artifact checks and model quota stop 2026-11-26 19:27:58 +08:00
7b731cd0ff Record R28 recovery and native production verification 2026-11-26 19:20:12 +08:00
90408a4f02 Merge commit '93df00c892890bbf08a72ac8de8d79742f91deb3' into feat/xiaoyi-slice4-auto-delivery-bundle
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-agent-pi/src/desktop-host.mjs
#	apps/detail-agent-pi/src/store.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs
2026-11-26 19:09:05 +08:00
125a304660 Merge commit '65e7c47bbd8c551611768b16e62d435c08c951b4' into feat/xiaoyi-slice4-auto-delivery-bundle
# Conflicts:
#	apps/detail-agent-pi/src/desktop-daemon.mjs
#	apps/detail-agent-pi/src/desktop-host.mjs
#	apps/detail-agent-pi/src/native-bridge.mjs
#	apps/detail-agent-pi/test/desktop-daemon.test.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_prompt_library.rs
2026-11-26 19:08:48 +08:00
d468305d4b fix(xiaoyi): keep unfinished production queued and recover original images 2026-11-26 19:07:54 +08:00
269372923e Bind candidate reviews to the template field requirement 2026-11-26 19:05:34 +08:00
fd8c6473bc Identify the candidate and references in image reviews 2026-11-26 18:55:35 +08:00
93df00c892 fix(xiaoyi): isolate production writes and publish verified generations
Fence stopped runs and bind background canvas activity to the production document and variant. Publish immutable export manifests atomically and correlate native and Pi execution events in the project journal.
2026-11-26 18:39:06 +08:00
82d3e4ef23 feat(xiaoyi): keep active work in the tray and flush on exit 2026-11-26 18:38:36 +08:00
3dbf28f471 Wait for native copy writes to become available 2026-11-26 18:31:07 +08:00
65e7c47bbd feat(xiaoyi): fence account workloads and declare project backup contents 2026-11-26 18:25:50 +08:00
704937bf4d Keep production active through image work and dispatch by prepared ID 2026-11-26 18:08:41 +08:00
e15a1692e4 Open project ledgers on long Windows paths 2026-11-26 17:54:57 +08:00
aa4c9868de Settle expired image results by their original request 2026-11-26 17:45:29 +08:00
f4648cbfc3 Merge commit '217cfdc3' into codex/xiaoyi-whole-detail-fidelity 2026-11-26 17:36:49 +08:00
d9420d9005 Merge commit 'e26df068' into codex/xiaoyi-whole-detail-fidelity 2026-11-26 17:36:38 +08:00
ee288059e1 Merge candidate request ownership and automatic adoption 2026-11-26 17:36:38 +08:00
05d9b23cde Merge SQLite project production repository 2026-11-26 17:36:31 +08:00
8947444009 Merge commit 'dce921b3' into codex/xiaoyi-whole-detail-fidelity 2026-11-26 17:36:24 +08:00
28b07ebfee Merge first saved canvas binding and native cancellation 2026-11-26 17:36:22 +08:00
f4648a0df3 docs(xiaoyi): record R28 production and verified SKU delivery 2026-11-26 17:25:19 +08:00
33486533d6 feat(xiaoyi): freeze formal image prompts and auto-adopt reviewed candidates 2026-11-26 17:22:21 +08:00
dce921b363 perf(xiaoyi): unblock canvas reads and match copy fields 2026-11-26 17:21:06 +08:00
f172172db4 fix(xiaoyi): omit blank retry identities from image preparation 2026-11-26 17:05:25 +08:00
5c5bf1eed0 fix(xiaoyi): include saved product facts in the production plan 2026-11-26 17:02:29 +08:00
f88776dd7c fix(xiaoyi): bind the first saved production canvas 2026-11-26 16:56:47 +08:00
217cfdc34a feat(xiaoyi): execute pinned Skill scripts in the project sandbox 2026-11-26 16:55:57 +08:00
e26df068ef feat(xiaoyi): preflight selected output capabilities 2026-11-26 16:55:34 +08:00
f8426faec4 feat(xiaoyi): store project production records in SQLite 2026-11-26 16:54:42 +08:00
7c8cb213d9 fix(upload): separate display names from storage paths 2026-11-26 16:46:55 +08:00
13bec4f390 fix(xiaoyi): bind the first mapped production canvas 2026-11-26 16:45:03 +08:00
bd5e425c77 fix(xiaoyi): streamline native tools and frozen image dispatch 2026-11-26 16:14:04 +08:00
026739ef3a fix(xiaoyi): verify image request scope before freezing 2026-11-26 15:49:41 +08:00
be5485a44c docs(xiaoyi): record frozen request validation and production handoff 2026-11-26 15:46:33 +08:00
f79aed2e28 refactor(xiaoyi): use published review skills and protect fixed template layers 2026-11-26 15:39:26 +08:00
f3fee2dc98 feat(xiaoyi): persist and dispatch reviewed image requests by frozen id 2026-11-26 15:27:13 +08:00
b13ddba701 docs(xiaoyi): record scoped bridge verification 2026-11-26 15:12:13 +08:00
d32916151a refactor(xiaoyi): scope canvas operations and type bridge failures 2026-11-26 15:09:43 +08:00
8fe19a443d docs(xiaoyi): record production session and tool regression evidence 2026-11-26 14:54:26 +08:00
0adb3874c9 refactor(xiaoyi): isolate legacy production and trim active tools 2026-11-26 14:52:52 +08:00
6282c0c390 refactor(xiaoyi): bind the first output inside the production session 2026-11-26 14:46:10 +08:00
ff6713f762 docs(xiaoyi): record first canvas selection verification 2026-11-26 14:28:20 +08:00
f74b4641c6 feat(xiaoyi): let Pi select the first production canvas 2026-11-26 14:28:02 +08:00
江林铖
61e9386469 fix(salary): align planner points with art dashboard 2026-11-26 13:59:48 +08:00
f6265c6db0 docs(xiaoyi): record Pi canvas handoff verification 2026-11-26 13:56:34 +08:00
74edb1e905 feat(xiaoyi): let Pi choose the next production canvas 2026-11-26 13:53:48 +08:00
bdc4e41648 docs(xiaoyi): record rework evidence and on-demand context verification 2026-11-26 13:46:02 +08:00
c01865ca7f fix(xiaoyi): propagate production stop to Pi sessions and workers 2026-11-26 13:43:44 +08:00
f8e9206f00 perf(xiaoyi): load production detail and reference pixels on demand 2026-11-26 13:42:08 +08:00
566c872ba4 fix(xiaoyi): preserve image rework evidence and asynchronous receipts 2026-11-26 13:00:59 +08:00
f33e963007 docs(xiaoyi): record image review and canvas acceptance 2026-11-26 12:41:37 +08:00
51f502c2fc fix(xiaoyi): recheck a changed image role before adoption 2026-11-26 12:25:09 +08:00
16395a90fc fix(xiaoyi): keep usable images for native canvas refinement 2026-11-26 12:01:03 +08:00
cbe66a920b fix(xiaoyi): refresh unchanged copy fields and review same-product archives 2026-11-26 11:39:53 +08:00
af46f80f10 feat(xiaoyi): show and persist the project production budget 2026-11-26 11:33:17 +08:00
江林铖
36cd111f52 Load salary details by role with independent data sources 2026-11-26 11:23:11 +08:00
45f9f42070 perf(xiaoyi): return compact production indexes and reuse image references 2026-11-26 11:21:41 +08:00
54df18b021 feat(xiaoyi): return production image submissions without waiting 2026-11-26 11:10:08 +08:00
43acd1ee57 fix(xiaoyi): give image rework the rejected candidate and dispatched prompt 2026-11-26 11:03:41 +08:00
0641e8e79f fix(xiaoyi): use Pi session affinity for production worker caching 2026-11-26 10:42:49 +08:00
522edbe84e docs(xiaoyi): use native canvas edits before regenerating usable images 2026-11-26 10:42:49 +08:00
2681fa0e87 fix(xiaoyi): distinguish product and style rework from canvas adjustments 2026-11-26 10:42:49 +08:00
17e2de76cd feat(xiaoyi): retire failed candidates with their original receipts 2026-11-26 10:24:05 +08:00
cf02d40a22 docs(xiaoyi): record published skill reference verification 2026-11-26 10:10:08 +08:00
8fa11fe734 fix(xiaoyi): resolve linked enterprise skill documents on Pi reads 2026-11-26 10:02:05 +08:00
dca9dfa74c docs(xiaoyi): record image source trace acceptance 2026-11-26 09:44:19 +08:00
33652b5747 feat(xiaoyi): trace delivered image fields to their source archives 2026-11-26 09:41:48 +08:00
1842111361 docs(xiaoyi): record variant isolation verification 2026-11-26 09:26:46 +08:00
4c336dac65 fix(xiaoyi): scope production changes to the edited variant 2026-11-26 09:25:31 +08:00
d656df7bc6 docs(xiaoyi): record original image recovery verification 2026-11-26 08:54:32 +08:00
2174b193ab fix(xiaoyi): recover image generation by durable operation identity 2026-11-26 08:46:47 +08:00
8d9fec390a docs(xiaoyi): record shared material and independent placements 2026-11-26 08:31:40 +08:00
9dcbd78635 feat(xiaoyi): reuse one material across independent image slots 2026-11-26 08:29:23 +08:00
41a5cc8984 docs(xiaoyi): verify archived candidate provenance on the desk project 2026-11-26 08:15:10 +08:00
f460fe62bd feat(xiaoyi): let Pi inspect and stage archived image candidates 2026-11-26 08:13:48 +08:00
e32535492d docs(xiaoyi): record desk settlement and native result replay 2026-11-26 08:01:46 +08:00
6614df5689 fix(xiaoyi): page retained native results on demand 2026-11-26 07:57:49 +08:00
769b2442a0 fix(xiaoyi): expose the owning document tab index in the native catalog 2026-11-26 07:31:46 +08:00
d3fb2558e8 fix(xiaoyi): distinguish viewing from production in tool receipts 2026-11-26 07:23:17 +08:00
414dfa4c47 docs(xiaoyi): record real batch editing and draft recovery 2026-11-26 07:06:21 +08:00
04629e07c5 fix(xiaoyi): wait for the original native write to become ready 2026-11-26 06:45:05 +08:00
63483a3d26 docs(xiaoyi): record production retry and handoff evidence 2026-11-26 06:08:28 +08:00
b934cc90e2 fix(xiaoyi): return definitive native rejections as completed receipts 2026-11-26 05:46:10 +08:00
ce126fe949 fix(photocraft): use explicit layer targets in batch edit preconditions 2026-11-26 05:40:36 +08:00
88352c55e8 docs(xiaoyi): verify Pi 503 recovery in a real production goal 2026-11-26 05:25:30 +08:00
79120c209e docs(xiaoyi): record desk dispatch, original lookup and draft settlement 2026-11-26 05:21:23 +08:00
5216332cbf fix(xiaoyi): reuse the verified route at output handoff 2026-11-26 04:58:49 +08:00
a891310b54 fix(xiaoyi): preserve transient inference errors for Pi retry 2026-11-26 04:52:16 +08:00
1844e635c6 fix(xiaoyi): read the requested canvas summary depth 2026-11-26 04:49:57 +08:00
0c8c012fef docs(xiaoyi): record verified model routes and desk settlement 2026-11-26 04:34:45 +08:00
0ca2435239 docs(xiaoyi): record the frozen prompt and actual 2K candidate evidence 2026-11-26 04:27:03 +08:00
2397692946 fix(xiaoyi): keep the agent's specific reason on saved drafts 2026-11-26 04:24:29 +08:00
66ce00b0f8 fix(xiaoyi): keep valid image delegations in a mixed batch 2026-11-26 04:17:37 +08:00
c8d62c7787 docs(xiaoyi): record verified desk SKU delivery 2026-11-26 04:12:39 +08:00
f7a91dce32 test(xiaoyi): audit composited images against original request files 2026-11-26 03:55:22 +08:00
74aba6a782 fix(xiaoyi): reuse verified model selection across production workers 2026-11-26 03:50:47 +08:00
62a6f21618 fix(xiaoyi): assemble slot prompts before dispatch 2026-11-26 03:48:17 +08:00
b8ceb54a17 docs(xiaoyi): compare frozen image prompts with dispatched task bodies 2026-11-26 03:42:56 +08:00
b6a10b8ad5 docs(xiaoyi): record desk recovery settlement and new acceptance run 2026-11-26 03:41:56 +08:00
4ee5a5b442 fix(xiaoyi): report temporary waits separately from stale revisions 2026-11-26 03:39:10 +08:00
f101fda31a fix(xiaoyi): retain useful canvas searches when a screen id is missing 2026-11-26 03:38:07 +08:00
fd24d8c016 docs(xiaoyi): include visible fixed product claims in Pi review 2026-11-26 03:33:25 +08:00
141ea99980 feat(xiaoyi): let Pi inspect several canvas screens in one call 2026-11-26 03:22:19 +08:00
8a5003f323 test(xiaoyi): verify published layout edits survive reopening 2026-11-26 03:21:13 +08:00
ec0872155a docs(xiaoyi): record unavailable result on the original 2K request 2026-11-26 03:13:33 +08:00
887aafa6c8 fix(xiaoyi): return original image recovery reason 2026-11-26 03:08:32 +08:00
2d9f5cea57 docs(xiaoyi): record field rules and active desk rerun 2026-11-26 03:02:08 +08:00
1f7657eb7c fix(xiaoyi): expose published copy rules on scoped reads 2026-11-26 03:01:55 +08:00
8237712b5a docs(xiaoyi): record verified SKU delivery and remaining template defects 2026-11-26 02:55:17 +08:00
327e2b3074 docs(xiaoyi): record native edits and image resolution evidence 2026-11-26 02:52:47 +08:00
ccfb64b4f3 feat(xiaoyi): expose supported 2K image frame preference 2026-11-26 02:52:31 +08:00
25e15c203c docs(xiaoyi): clarify image retry tool input 2026-11-26 02:46:28 +08:00
970fae4c10 fix(xiaoyi): use native edit receipts in production 2026-11-26 02:46:08 +08:00
68977c2f34 docs(xiaoyi): record persisted detail and scoped lookup evidence 2026-11-26 02:41:35 +08:00
a11429ead1 fix(xiaoyi): preserve scoped canvas searches 2026-11-26 02:41:21 +08:00
a01fc9b762 docs(xiaoyi): verify long instructions and live Pi compaction 2026-11-26 02:30:54 +08:00
2a55a90084 docs(xiaoyi): record restart recovery evidence 2026-11-26 02:28:55 +08:00
2c1e3c19a7 fix(xiaoyi): recover original image candidates after restart 2026-11-26 02:27:46 +08:00
356b7237b5 docs(xiaoyi): trace live image reference bytes 2026-11-26 02:27:17 +08:00
8bc63b160e fix(xiaoyi): keep Pi default tool scheduling 2026-11-26 02:24:23 +08:00
0e169bb3e3 docs(xiaoyi): record real project shell and resume build 2026-11-26 02:21:50 +08:00
079cd8169a test(xiaoyi): verify pending tool events are accepted 2026-11-26 02:17:03 +08:00
4dd63cbee3 docs(xiaoyi): record editable blank field evidence 2026-11-26 02:16:12 +08:00
adb1749563 docs(xiaoyi): record desk settlement and published SKU rule 2026-11-26 02:14:12 +08:00
d203a07aa1 feat(xiaoyi): record intentional empty template text 2026-11-26 02:13:38 +08:00
43bea986cf fix(xiaoyi): keep originals available when a layout reference fails 2026-11-26 02:04:47 +08:00
9ef7c3050c docs(xiaoyi): explain native equivalents for canvas edits 2026-11-26 02:02:03 +08:00
609285dc05 docs(xiaoyi): record concurrent review and slot recovery evidence 2026-11-26 01:37:56 +08:00
0bd4dfcce6 fix(xiaoyi): isolate slot receipts from project recovery 2026-11-26 01:37:46 +08:00
58ecb3cc93 docs(xiaoyi): capture desk settlement and live scene dispatch 2026-11-26 01:32:29 +08:00
9e329689a6 fix(xiaoyi): report original candidate pixels to reviewers 2026-11-26 01:32:02 +08:00
67f0b97807 docs(xiaoyi): track desk review timing and saved copy evidence 2026-11-26 01:20:57 +08:00
34e6d8db62 fix(xiaoyi): report a deferred canvas copy write 2026-11-26 01:20:27 +08:00
0689de5b6d feat(xiaoyi): let Pi continue during independent image review 2026-11-26 01:17:49 +08:00
6db926a79f docs(xiaoyi): record partial candidate-review receipts 2026-11-26 01:13:12 +08:00
bbdc44721e fix(xiaoyi): isolate candidate review errors within a batch 2026-11-26 01:12:42 +08:00
2008331b99 docs(xiaoyi): record desk scene-source decision and output handoff 2026-11-26 01:08:17 +08:00
6d63f1f0a0 fix(xiaoyi): expose scene generation and original crop semantics 2026-11-26 01:07:59 +08:00
6642b9f5b9 docs(xiaoyi): track native request and tool passage in desk run 2026-11-26 01:01:38 +08:00
15d0d8ad3c docs(xiaoyi): record native tool-declaration rejection and recovery 2026-11-26 00:56:02 +08:00
eb10aa7420 fix(xiaoyi): let Pi own provider tool declarations 2026-11-26 00:55:16 +08:00
d17adf534c docs(xiaoyi): record real desk copy roundtrip evidence 2026-11-26 00:51:24 +08:00
04d213403a fix(xiaoyi): separate text placement bounds from authored safety frames 2026-11-26 00:47:43 +08:00
f1fe7a3678 test(xiaoyi): track unattended milestones and inspect delivered files 2026-11-26 00:45:06 +08:00
8b454f5723 fix(xiaoyi): follow skill references and read live workflow on demand 2026-11-26 00:43:25 +08:00
3473c08dfe fix(xiaoyi): continue each output in the original Pi goal 2026-11-26 00:38:46 +08:00
342d669b11 perf(xiaoyi): scope native command discovery once per page 2026-11-26 00:38:41 +08:00
e94f7f066f perf(xiaoyi): compress and time published model catalog loading 2026-11-26 00:38:40 +08:00
ceb1b507a9 fix(xiaoyi): report layout clipping after writing copy 2026-11-26 00:38:34 +08:00
3d8fc1c7e4 fix(xiaoyi): preserve paid original when adopting another image 2026-11-26 00:29:11 +08:00
2176a3589f fix(xiaoyi): keep adoption receipt until canvas checkpoint 2026-11-26 00:28:50 +08:00
737fd7cfc2 fix(xiaoyi): keep production running after known edit rejection 2026-11-26 00:28:02 +08:00
ad21604fe4 refactor(xiaoyi): let Pi direct production operations 2026-11-26 00:26:33 +08:00
a5cf7adff8 refactor(xiaoyi): read project facts on demand 2026-11-26 00:21:28 +08:00
545ebbaec7 refactor(xiaoyi): preserve image reviewer decisions 2026-11-26 00:15:35 +08:00
4341a37860 refactor(xiaoyi): open canvas commands and separate production reads 2026-11-26 00:05:13 +08:00
2a337a42cb refactor(xiaoyi): restore native Pi session and production tools 2026-11-25 23:47:09 +08:00
6de9700d93 fix(xiaoyi): resume Pi production compaction from original receipts 2026-11-25 23:09:43 +08:00
795f1ea3ab feat(xiaoyi): load pinned enterprise skills in Pi production 2026-11-25 22:57:54 +08:00
9c5ceb09d9 fix(xiaoyi): pause production and checkpoint before exit 2026-11-25 22:46:44 +08:00
726b8ba500 fix(xiaoyi): bind published component originals and isolate unavailable outputs 2026-11-25 22:28:53 +08:00
7c478d652b docs(xiaoyi): record native audit and unattended desk acceptance 2026-11-25 22:21:12 +08:00
bdc372f9e4 refactor(xiaoyi): source production profiles from versioned template packages 2026-11-25 22:12:43 +08:00
5d125eb833 fix(xiaoyi): enforce production deadlines during pending agent work 2026-11-25 22:12:36 +08:00
6542719117 fix(xiaoyi): preserve mixed template text with default style mapping 2026-11-25 22:12:28 +08:00
d1347f6344 fix(xiaoyi): settle expired adoption checks before reporting a stage 2026-11-25 22:08:14 +08:00
419182862e fix(xiaoyi): export templates that have no fixed-copy policy 2026-11-25 22:01:35 +08:00
f980f593ef fix(xiaoyi): reconcile interrupted canvas adoption
Record the existing local Harness implementation as the starting point for scoped audit corrections.
2026-11-25 21:57:13 +08:00
7048ce993b feat(api): expose read-only task details by material ID 2026-11-25 18:56:51 +08:00
江林铖
f0ac4d3db4 fix(salary): unify technical detail tables and hide zero-share KPIs 2026-11-24 09:46:31 +08:00
江林铖
14f168c471 fix(deploy): retain reviewed alias transport failures in preview gate 2026-11-21 16:22:01 +08:00
江林铖
a1987a043d fix(deploy): classify unfinished preview shells as unverified 2026-11-21 16:04:33 +08:00
江林铖
d413a68000 feat(salary): compare monthly salary with the previous month 2026-11-21 14:43:27 +08:00
3d84c01da5 fix(client): use the template frame to place approved images 2026-11-17 19:11:43 +08:00
5eeb81c6c2 fix(client): preserve edits and report settled Pi slot outcomes 2026-11-17 18:54:44 +08:00
edcfc08b27 feat(client): run Pi slot agents alongside canvas editing 2026-11-17 18:16:00 +08:00
b9f294158d fix(client): report actual one-click image and placement counts 2026-11-17 16:38:02 +08:00
0ad013a372 fix(client): fill the first approved image without another model turn 2026-11-17 16:11:18 +08:00
965d91161c fix(client): run one-click detail creation with one agent 2026-11-17 16:02:13 +08:00
a256305a70 fix(client): authorize the scoped Pi detail tools 2026-11-17 15:45:10 +08:00
d503bfc3f3 Merge main into one-click detail-page generation 2026-11-17 15:39:09 +08:00
9c56afc579 feat(client): let Pi workers produce and review detail-page slots in parallel 2026-11-17 15:36:14 +08:00
a068bc7edd fix(client): streamline chat and load authorized model catalog 2026-11-17 14:47:20 +08:00
3da7688bdf fix(client): settle original failures with gateway error metadata 2026-11-17 13:30:49 +08:00
48f95a2220 fix(client): require actual source pixels for structural detail evidence 2026-11-17 12:59:48 +08:00
c409268dec feat(client): make detail-page image production resumable and reviewable 2026-11-17 12:54:55 +08:00
fbb88e99fa fix(client): compare pinned originals and close generation on dispatch 2026-11-16 18:41:22 +08:00
9796529020 fix(client): align candidate cards and refresh image models and prompts 2026-11-16 17:59:12 +08:00
21860d7ea3 feat(client): animate image slot tabs and keep generation entry 2026-11-16 17:06:25 +08:00
0e6c77f444 feat(client): prefill editable template prompts in image dialog 2026-11-16 15:25:22 +08:00
ac91d3ff6c fix(client): preserve mapped layers during native deletion 2026-11-16 14:34:22 +08:00
f01372e351 fix(client): recover template layers and synchronize canvas images 2026-11-16 14:25:15 +08:00
0381375bab fix(client): wait quietly for reference thumbnails 2026-11-16 13:20:41 +08:00
1e938555ab fix(client): stabilize Agent conversation scrolling 2026-11-16 12:35:13 +08:00
b4e71305ab fix(client): remove frames from chat reference previews 2026-11-16 11:51:15 +08:00
e81d74d930 fix(client): send and display canvas references in Xiaoyi chat 2026-11-16 11:16:48 +08:00
108945d4a8 fix(client): reference canvas objects directly from the context menu 2026-11-16 10:19:47 +08:00
e1ee87cf96 fix(client): improve candidate preview and serialize canvas image transforms 2026-11-16 09:53:45 +08:00
96306f9582 fix(client): bind workflow image loading cards to the reserved candidate 2026-11-13 19:06:55 +08:00
daeca64172 test(client): verify the canvas waiting animation with native rendering 2026-11-13 18:25:50 +08:00
8787ec7dd4 fix(client): restore image cards and direct canvas interactions 2026-11-13 18:21:10 +08:00
2df29d15f5 fix(client): report generated candidates from native receipts 2026-11-13 10:30:46 +08:00
fd1710b6ee fix(client): keep the local agent alive during cold startup 2026-11-13 10:21:56 +08:00
dcd68ff494 fix(client): recover delayed image results without resubmitting 2026-11-13 09:32:46 +08:00
64358a7870 test(client): align agent regressions with current behavior 2026-11-12 17:48:38 +08:00
2156598a2d fix(client): reject empty imported brand rules 2026-11-12 17:44:13 +08:00
b21f34ad98 refactor(client): use resource maps for enterprise templates 2026-11-12 17:26:23 +08:00
748e7f0a9d fix(deploy): verify task detail ZIP cleanup migration audit 2026-11-12 17:06:39 +08:00
d89c40076c fix(client): refresh cached template selections when resource maps change 2026-11-12 16:58:23 +08:00
a95f3f5b93 fix(deploy): include task detail ZIP cleanup migration in runner 2026-11-12 16:35:00 +08:00
be0d4fe7be fix(materials): retry cleanup of replaced task detail ZIPs 2026-11-12 16:31:14 +08:00
29980e697a fix(client): avoid rewriting restored projects on startup 2026-11-12 16:16:27 +08:00
b7be214b9a fix(client): open coat-rack templates across mapping formats and bit depths 2026-11-12 15:18:28 +08:00
318c8da1f4 fix(materials): clean up unreferenced replaced ZIPs 2026-11-12 14:43:48 +08:00
fc8e53a0fa feat(materials): submit image groups together with review previews 2026-11-12 13:09:37 +08:00
2d8e3df626 feat(materials): edit entire task detail image groups 2026-11-12 11:13:20 +08:00
cfc1452f8b fix(client): streamline template selection and show required product fields 2026-11-11 17:07:22 +08:00
3cb65c4b58 fix(client): recover original requests and restore library authorization dialog 2026-11-11 14:27:17 +08:00
5088bcf63d fix(materials): preserve video release policy for internal accounts 2026-11-10 10:52:06 +08:00
03e54dd541 fix(materials): grant super admins full restricted asset access 2026-11-10 10:41:26 +08:00
268ca4886f fix(materials): enforce public scope across external APIs 2026-11-10 10:26:27 +08:00
016c7504d6 feat(materials): add Operations G card badge and scope filter 2026-11-10 09:51:29 +08:00
9cc0075ff1 fix(materials): use SKU image filenames as upload codes 2026-11-09 16:26:23 +08:00
ade0807d8a fix(client): normalize enterprise template layer mappings 2026-11-09 15:03:03 +08:00
525ec62a78 fix(client): reuse verified resource map templates 2026-11-09 14:25:44 +08:00
e849449a0d fix(client): read SKU mappings with nested layer paths 2026-11-09 14:19:15 +08:00
江林铖
b3954b64e3 feat(salary): calculate supervisor metrics from direct department members 2026-11-09 13:12:54 +08:00
e52e0d7785 feat(client): select templates from the knowledge resource map 2026-11-09 12:41:20 +08:00
30973d81aa feat(client): choose output colors from SKU variants 2026-11-09 10:24:28 +08:00
江林铖
fe3cb6600c fix(salary): align survey scores with official employee assessments 2026-11-07 17:51:39 +08:00
1c05dbb9ef fix(materials): let super admins view restricted assets 2026-11-07 16:36:29 +08:00
江林铖
1299ba5cf0 fix(salary): align headers and sync planner departments 2026-11-07 16:03:50 +08:00
29d2fa38b1 fix(materials): show scope controls only for operations G 2026-11-07 15:24:27 +08:00
江林铖
2df4dfd66f fix(salary): show and freeze nickname as first column 2026-11-07 14:17:00 +08:00
江林铖
053f6a4f3b fix(salary): trust configured origins behind reverse proxies 2026-11-07 13:18:13 +08:00
0ab40c942a fix(client): retain project presence during Windows context saves 2026-11-07 10:49:46 +08:00
江林铖
df7450148b fix(salary): show configured management tables without personnel 2026-11-07 10:40:03 +08:00
cdd481a35f fix(client): exclude tagged analysis from conversation projections 2026-11-07 10:35:13 +08:00
fbf9ff20c8 fix(client): wait for project saves and classify undispatched operations 2026-11-07 10:09:45 +08:00
f893869f69 feat(client): align v0.19 source with project loading and candidate recovery 2026-11-07 09:32:29 +08:00
149d31f680 fix(docker): preserve preview source access for the service user 2026-11-06 20:23:46 +08:00
ce2ce5bf9d fix(docker): make runtime assets readable by the service user 2026-11-06 20:12:16 +08:00
2f647798b9 fix(deploy): retain candidate diagnostics for standard releases 2026-11-06 20:07:16 +08:00
b058a3bca1 fix(deploy): stream verified Git sources and reuse loaded images 2026-11-06 19:59:21 +08:00
0724f9625f fix(deploy): bundle preview checks with the verified runtime image 2026-11-06 19:55:43 +08:00
73c03332b9 fix(deploy): scope preview checks to affected delivery paths 2026-11-06 19:47:31 +08:00
631f26f0ad fix(deploy): align material scope audit with approved migrations 2026-11-06 19:27:44 +08:00
638569afe6 Merge material organization access and native cloud sync for main release 2026-11-06 18:53:46 +08:00
3df75b13fd Merge production salary features while preserving main client development 2026-11-06 18:52:01 +08:00
江林铖
4b92729191 fix(deploy): require personnel grade migration in release audit 2026-11-06 16:38:46 +08:00
江林铖
424e19471a feat(salary): match personnel job grades to performance schemes 2026-11-06 16:33:25 +08:00
江林铖
9d585ca240 feat(salary): show all market intent evidence records 2026-11-04 18:51:39 +08:00
江林铖
d83eb67c56 fix(salary): assess market intent from previous completed month 2026-11-03 18:06:01 +08:00
江林铖
68ddf00572 fix(desktop): preserve live native template catalog patch in source 2026-11-03 18:06:01 +08:00
江林铖
4cbb618ea6 feat(salary): collapse configuration navigation groups independently 2026-11-02 16:13:23 +08:00
江林铖
a762f8e528 feat(salary): calculate rounded performance coefficient and monthly pay 2026-10-30 18:03:51 +08:00
江林铖
48fb30596a feat(salary): score market validation from top-three intent growth 2026-10-30 15:17:49 +08:00
江林铖
a362203fab fix(salary): restore raw KPI values beside assessment scores 2026-10-30 11:08:22 +08:00
江林铖
080e4f82a1 merge: reconcile verified live salary runtime and material image fixes
Reconstruct the deployed 72674fd runtime from its verified 7e230ef full source and four material overrides. Retain the deployed desktop and preview release gates. Production source hashes and schema were checked before reconstruction.
2026-10-30 11:08:22 +08:00
江林铖
7e230efd99 fix(salary): count exempt workflows on time and show final KPI contributions 2026-10-29 13:06:48 +08:00
江林铖
ed1695197d feat(organization): configure salary positions and performance weights 2026-10-29 09:46:05 +08:00
江林铖
8929a70f75 fix(organization): read authoritative workflow overtime exemptions 2026-10-28 13:39:33 +08:00
江林铖
91975ef258 feat(organization): publish real salary details with authoritative planner points 2026-10-28 09:47:18 +08:00
3050 changed files with 859749 additions and 372738 deletions

View File

@ -153,6 +153,7 @@ scripts/**
!scripts/create-verified-production-backup.mjs
!scripts/verify-prisma-client-schema.mjs
!scripts/seed-team-function-config.ts
!scripts/maintain-salary-performance-versions.ts
__tests__
*.test.ts
*.test.js
@ -223,8 +224,6 @@ temp_*.sql
!prisma/migrations/**
!data/team-function-initial-content.json
!lib/desktop-client/agent-rule-catalog.json
!lib/desktop-client/template-packs/gj-desk-dnz0385-native-v1.json
!lib/desktop-client/template-packs/yjd-desk-dnz0385-native-v1.json
# Private generated data never belongs to a build context.
/detail-generator-private

View File

@ -532,6 +532,7 @@
"自动化工作流在 Department Shell 内使用 232px 二级业务栏与同源真实操作面,移动端改为顶部两列菜单。",
"数据口径在 Department Shell 内使用 232px 二级栏直接显示“公司组织架构”,右侧复用真实组织树和人员明细,不增加折叠层。",
"人员架构在 Department Shell 内直接复用真实组织工作面,并将组织树根节点限定为“品牌中心”。",
"绩效薪资沿用 232px 二级栏,在“薪资明细”下固定展开 AI全案策划岗、摄影中心岗、空间视觉岗、管理岗、AI技术设计师岗五个入口;选中态与 URL、右侧标题同步,月份随岗位切换保留。“后台配置”以分隔线独立分组,下设平级的“人员薪资配置”和“岗位绩效配置”;人员配置再展开岗位及“未分配”子层级;岗位绩效配置也展开共用岗位子列表,仅显示岗位名称,不含全部、未分配或人数。绩效岗位子导航、选择器与方案通过 `config=performance&position=稳定ID` 同步并保留月份;缺省或无效岗位进入首岗,新增后选中、改名后同步,删除当前岗位后回到首岗或空状态。手机子导航为两列,长岗位名换行。人员与绩效方案按稳定岗位 ID 关联,明细按岗位分表并由配置生成绩效列,表旁明确提示最新配置适用于所有月份。人员配置最顶部为独立公共工具栏,先选择“全部人员 / 现有岗位 / 未分配”,再提供“导出当前岗位人员”“导出全部人员”和主按钮“新增岗位”;选择与路由、左侧岗位高亮受控同步,并保留月份。下方独立岗位人员区展示岗位标题、人数、“新增人员”、条件显示的“删除岗位”及人员列表;“全部人员”和“未分配”不显示删除岗位。手机工具栏纵向排列、自然换行;此处新增共用岗位只填写名称、薪资展示入口和说明,考核维度仍在岗位绩效配置维护。有人员的岗位禁止确认删除,删除保留审计。仅超级管理员维护,获准查看的指定账号也可导出当前岗位或全部人员的已保存长期基础档案,Excel 每岗一表,包含岗位和七项基础字段。明细只读展示已接入数据,缺失值用“——”表示;“导出薪资模板”仍只输出空白模板,岗位配置导出只包含已保存方案。分区表头左对齐、字段表头换行,明细固定表头和首个身份列。手机岗位入口为顶部两列、后台配置独立一行,表单纵向排列,人员基础信息转为纵向列表;宽表只在表格区域滚动,不撑宽页面。维护使用原生模态弹窗,保留键盘焦点,关闭后返回触发按钮;保存、加载和导出显示状态,错误可重试,版本冲突保留草稿,未保存关闭须确认。",
"素材资产库按权威组织归属选择外壳:品牌中心成员保留 Department Shell,外部普通用户只显示 64px 中性顶栏、素材工作面与退出入口。"
],
"rules": [

View File

@ -40,3 +40,9 @@
- `README.md`
- `.private\gongxiangp2-完整敏感接管清单-2026-08-13.md`
## 7. Git 协作与发布
- 开发和验证可使用独立功能分支,所有部署必须从权威仓库的 `main` 分支发布。
- 同事提供的分支用于补齐和整合源码;相关改动验证后必须合并并推送到 `main`,再按 `main` 上的明确提交执行构建和部署。
- 发布前确认目标提交已包含在远端 `main` 历史中,不直接部署功能分支或同事分支。

View File

@ -154,7 +154,7 @@ components:
- 自动化工作流在 Department Shell 内使用 232px 二级业务栏与同源真实操作面,移动端改为顶部两列菜单。
- 组织架构复用真实组织树与人员明细,提供“品牌中心 / 全公司”范围切换,沿用原管理员权限。
- 权限管理提供“权限组 / 人员权限”两个视图,侧栏只有一个入口。
- 绩效薪资使用 232px 二级栏,在“薪资明细”分组下固定展开 AI全案策划岗、摄影中心岗、空间视觉岗、管理岗,后台配置以分隔线区分为独立入口。岗位选中态与 URL、右侧标题同步;手机岗位入口为两列,后台配置独立一行,各项最小高度 44px。四岗按确认的 Excel 结构展示只读空模板,月份选择后查询,当前月份与岗位保存在 URL;四岗整套模板可一次导出。分区表头左对齐,字段表头换行、首列固定,桌面和手机均在表格内部横向滚动;不带入真实工资或预设计算公式。
- 绩效薪资沿用 232px 二级栏,在“薪资明细”下固定展开 AI全案策划岗、摄影中心岗、空间视觉岗、管理岗、AI技术设计师岗五个入口;选中态与 URL、右侧标题同步,月份随岗位切换保留。“后台配置”以分隔线独立分组,下设平级的“人员薪资配置”和“岗位绩效配置”两个独立折叠组;组标题为带展开箭头的原生按钮,支持 Enter / Space 和明确焦点,aria-expanded、aria-controls 与子列表显隐同步。默认展开当前配置组;手动收起不切换页面或重置右侧表单,访问其它配置或岗位时展开目标组。人员组包含“全部人员”、共用岗位及“未分配”子层级;岗位绩效配置也展开共用岗位子列表,仅显示岗位名称,不含全部、未分配或人数。绩效岗位子导航、选择器与方案通过 `config=performance&position=稳定ID` 同步并保留月份;缺省或无效岗位进入首岗,新增后选中、改名后同步,删除当前岗位后回到首岗或空状态。手机子导航为两列,长岗位名换行。人员与绩效方案按稳定岗位 ID 关联,明细按岗位分表并由配置生成绩效列,表旁明确提示最新配置适用于所有月份。人员配置最顶部为独立公共工具栏,先选择“全部人员 / 现有岗位 / 未分配”,再提供“导出当前岗位人员”“导出全部人员”和主按钮“新增岗位”;选择与路由、左侧岗位高亮受控同步,并保留月份。下方独立岗位人员区展示岗位标题、人数、“新增人员”、条件显示的“删除岗位”及人员列表;“全部人员”和“未分配”不显示删除岗位。手机工具栏纵向排列、自然换行;此处新增共用岗位只填写名称、薪资展示入口和说明,考核维度仍在岗位绩效配置维护。有人员的岗位禁止确认删除,删除保留审计。仅超级管理员维护,获准查看的指定账号也可导出当前岗位或全部人员的已保存长期基础档案,Excel 每岗一表,包含岗位和七项基础字段。明细只读展示已接入数据,缺失值用“——”表示;市场验证专用指标按薪资月上月完结流程取数,表头标注“上月”,来源提示与可展开计算明细展示实际考核月份和跨月观察窗口,其他指标保留所选薪资月;“导出薪资明细”按所选月份汇总全部岗位的真实人员与计算值,按当月方案分表,岗位配置导出只包含已保存方案。分区表头左对齐、字段表头换行,明细固定表头和首个身份列。手机岗位入口为顶部两列、后台配置独立一行,表单纵向排列,人员基础信息转为纵向列表;宽表只在表格区域滚动,不撑宽页面。维护使用原生模态弹窗,保留键盘焦点,关闭后返回触发按钮;保存、加载和导出显示状态,错误可重试,版本冲突保留草稿,未保存关闭须确认。
- 素材资产库按权威组织归属选择外壳:品牌中心成员保留 Department Shell,外部普通用户只显示 64px 中性顶栏、素材工作面与退出入口。
- 进行中项目明细采用可键盘聚焦的横向滚动数据表:桌面固定“审批单标题”首列并保留 14 项业务字段,移动端转换为同字段的语义化定义列表;节点时间在数值下方标注对应流程节点名称。
- 按时交付明细使用紧凑的三项流程筛选条;当前项用浅蓝底和蓝字表达,未选项悬停为灰底,切换时同步更新公式、数量和横向明细表。

View File

@ -22,9 +22,10 @@ RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk
apk add --no-cache python3 make g++ cairo-dev jpeg-dev pango-dev giflib-dev
WORKDIR /opt/detail-renderer
COPY workers/detail-renderer/package.json workers/detail-renderer/package-lock.json ./
RUN --mount=type=cache,target=/root/.npm CXXFLAGS="-include cstdint" npm_config_build_from_source=canvas npm ci --no-audit --no-fund
RUN --mount=type=cache,target=/root/.npm npm config set registry https://registry.npmmirror.com && CXXFLAGS="-include cstdint" npm_config_build_from_source=canvas npm_config_nodedir=/usr/local npm ci --prefer-offline --no-audit --no-fund
COPY workers/detail-renderer/ ./
RUN node -e "require('canvas').createCanvas(1,1); console.log('isolated Canvas smoke passed')"
RUN chmod -R a+rX /opt/detail-renderer && \
node -e "require('canvas').createCanvas(1,1); console.log('isolated Canvas smoke passed')"
# 安装依赖阶段
FROM base AS deps
@ -48,11 +49,19 @@ RUN --mount=type=cache,target=/root/.npm \
node -e "const sharp=require('sharp'); sharp(Buffer.alloc(4),{raw:{width:1,height:1,channels:4}}).png().toBuffer().then(()=>console.log('sharp dependency smoke passed')).catch((error)=>{console.error(error);process.exit(1)})" && \
echo "Dependencies installed ($(du -sh /app/node_modules | cut -f1))"
# File parsers use an unprivileged Landlock/seccomp sandbox inside the default container profile.
FROM base AS performance-preview-sandbox
ARG ALPINE_MIRROR
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && apk add --no-cache build-base linux-headers
COPY workers/performance-preview/sandbox.c /tmp/sandbox.c
RUN cc -O2 -Wall -Wextra -Werror -static /tmp/sandbox.c -o /performance-preview-sandbox
# 本地开发阶段:复用依赖层,并补齐项目运行时会调用的媒体处理工具。
# 源码由 Compose 绑定挂载,避免每次修改代码都重新构建镜像。
FROM deps AS dev
COPY --from=performance-preview-sandbox /performance-preview-sandbox /usr/local/bin/performance-preview-sandbox
ARG ALPINE_MIRROR
RUN apk add --no-cache ffmpeg openssl poppler-utils
RUN apk add --no-cache ffmpeg openssl poppler-utils libreoffice font-noto-cjk
ENV NODE_ENV=development
ENV NEXT_TELEMETRY_DISABLED=1
@ -127,6 +136,14 @@ RUN test -f "/app/prisma/migrations/20261008_permission_group_department_identit
test -f "/app/prisma/migrations/20261013_ai_model_capabilities/migration.sql" && \
test -f "/app/prisma/migrations/20261013_ai_model_verifications/migration.sql"
RUN test -f "/app/prisma/migrations/20261106160000_salary_personnel_grade/migration.sql" && \
test -f "/app/prisma/migrations/20261028090000_salary_position_configuration/migration.sql" && \
test -f "/app/prisma/migrations/20261126120000_salary_performance_versions/migration.sql" && \
test -f "/app/prisma/migrations/20261130120000_desktop_material_deliveries/migration.sql" && \
test -f "/app/prisma/migrations/20261201140000_xiaoyi_listing_status/migration.sql" && \
test -f "/app/prisma/migrations/20261201190000_desktop_client_feedbacks/migration.sql" && \
test -f "/app/prisma/migrations/20261202090000_performance_survey_attachments/migration.sql"
# 这两个动态路由负责兜底访问本地上传文件;如果它们在构建上下文里丢失,
# 线上音频/视频就会直接 404。这里提前失败,避免再把缺路由的镜像发出去。
RUN test -f "/app/app/api/uploads/[...path]/route.ts" && \
@ -151,7 +168,8 @@ RUN --mount=type=cache,target=/app/.next/cache \
CIRCLE_NODE_TOTAL=2 NODE_ENV=production npm run build
# 清理 standalone 目录中不需要的文件(减少 1GB+ 体积)
RUN echo "清理 standalone 目录..." && \
RUN chmod -R a+rX .next/standalone .next/static app public lib prisma scripts && \
echo "清理 standalone 目录..." && \
rm -rf .next/standalone/uploads && \
rm -rf .next/standalone/.build-cache && \
rm -rf .next/standalone/.docker-cache && \
@ -203,7 +221,9 @@ COPY --from=builder --chown=root:root /app/scripts/safe-production-migrate.mjs .
COPY --from=builder --chown=root:root /app/scripts/create-verified-production-backup.mjs ./scripts/create-verified-production-backup.mjs
COPY --from=builder --chown=root:root /app/scripts/seed-team-function-config.ts ./scripts/seed-team-function-config.ts
COPY --from=builder --chown=root:root /app/scripts/initialize-personnel-salary-production.ts ./scripts/initialize-personnel-salary-production.ts
COPY --from=builder --chown=root:root /app/lib/personnel-salary.ts /app/lib/personnel-salary-contract.ts /app/lib/performance-salary-access.ts ./lib/
COPY --from=builder --chown=root:root /app/scripts/maintain-salary-performance-versions.ts ./scripts/maintain-salary-performance-versions.ts
COPY --from=builder --chown=root:root /app/lib/personnel-salary.ts /app/lib/personnel-salary-contract.ts /app/lib/performance-salary-access.ts /app/lib/salary-organization-department.ts ./lib/
COPY --from=builder --chown=root:root /app/lib/salary-position-seeds.ts /app/lib/salary-position-contract.ts /app/lib/salary-market-intent-contract.ts ./lib/
# Source closure for the team-function seed; no application routes or services.
COPY --from=builder --chown=root:root /app/lib/auto-personnel-rules.ts /app/lib/organization-material-permissions.ts /app/lib/prisma.ts /app/lib/team-function-contract.ts /app/lib/department-permission.ts /app/lib/employee-directory.ts /app/lib/env-validation.ts /app/lib/material-type-mapper.ts /app/lib/material-type-options.ts /app/lib/permission-groups.ts /app/lib/team-functions.ts /app/lib/user-permission-inherit.ts /app/lib/video-material-types.ts ./lib/
COPY --from=builder --chown=root:root /app/tsconfig.json ./tsconfig.json
@ -219,6 +239,7 @@ ENTRYPOINT ["node", "scripts/safe-production-migrate.mjs"]
# 生产运行阶段
FROM base AS runner
COPY --from=performance-preview-sandbox /performance-preview-sandbox /usr/local/bin/performance-preview-sandbox
WORKDIR /app
ENV NODE_ENV=production
@ -226,7 +247,7 @@ ENV NEXT_TELEMETRY_DISABLED=1
ARG ALPINE_MIRROR
RUN sed -i "s|https://dl-cdn.alpinelinux.org/alpine|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache ffmpeg python3 cairo jpeg pango giflib openssl poppler-utils flock && \
apk add --no-cache ffmpeg python3 cairo jpeg pango giflib openssl poppler-utils flock libreoffice font-noto-cjk && \
command -v flock >/dev/null && \
flock --exclusive --timeout 1 --conflict-exit-code 75 --no-fork \
/tmp/material-upload-flock-probe.lock sh -c 'true' && \
@ -300,10 +321,21 @@ COPY --from=builder --chown=root:root /app/prisma/migrations/20261020090000_desk
COPY --from=builder --chown=root:root /app/prisma/migrations/20261020120000_desktop_creation_tasks ./prisma/migrations/20261020120000_desktop_creation_tasks
COPY --from=builder --chown=root:root /app/prisma/migrations/20261020150000_desktop_project_deletion ./prisma/migrations/20261020150000_desktop_project_deletion
COPY --from=builder --chown=root:root /app/prisma/migrations/20261023130000_personnel_salary_base ./prisma/migrations/20261023130000_personnel_salary_base
COPY --from=builder --chown=root:root /app/prisma/migrations/20261028090000_salary_position_configuration ./prisma/migrations/20261028090000_salary_position_configuration
COPY --from=builder --chown=root:root /app/prisma/migrations/20261106160000_salary_personnel_grade ./prisma/migrations/20261106160000_salary_personnel_grade
COPY --from=builder --chown=root:root /app/prisma/migrations/20261106110000_material_access_scope ./prisma/migrations/20261106110000_material_access_scope
COPY --from=builder --chown=root:root /app/prisma/migrations/20261112154000_task_detail_zip_cleanup ./prisma/migrations/20261112154000_task_detail_zip_cleanup
COPY --from=builder --chown=root:root /app/prisma/migrations/20261126120000_salary_performance_versions ./prisma/migrations/20261126120000_salary_performance_versions
COPY --from=builder --chown=root:root /app/prisma/migrations/20261130120000_desktop_material_deliveries ./prisma/migrations/20261130120000_desktop_material_deliveries
COPY --from=builder --chown=root:root /app/prisma/migrations/20261201140000_xiaoyi_listing_status ./prisma/migrations/20261201140000_xiaoyi_listing_status
COPY --from=builder --chown=root:root /app/prisma/migrations/20261201190000_desktop_client_feedbacks ./prisma/migrations/20261201190000_desktop_client_feedbacks
COPY --from=builder --chown=root:root /app/prisma/migrations/20261202090000_performance_survey_attachments ./prisma/migrations/20261202090000_performance_survey_attachments
COPY --from=builder --chown=root:root /app/lib ./lib
COPY --from=builder --chown=root:root /app/scripts/public-traffic-rollup-from-nginx.py ./scripts/public-traffic-rollup-from-nginx.py
COPY --from=builder --chown=root:root /app/scripts/collapse-performance-survey-template-versions.mjs ./scripts/collapse-performance-survey-template-versions.mjs
COPY --from=builder --chown=root:root /app/scripts/backfill-art-workflow-planner-owner.mjs ./scripts/backfill-art-workflow-planner-owner.mjs
COPY --from=builder --chown=root:root /app/scripts/backfill-salary-departments.ts ./scripts/backfill-salary-departments.ts
COPY --from=builder --chown=root:root /app/scripts/safe-production-migrate.mjs /app/scripts/create-verified-production-backup.mjs /app/scripts/salary-grade-configuration.cjs /app/scripts/maintain-salary-grade-configuration.cjs ./scripts/
# 代码在 COPY 时直接归 root,避免再次改动整棵目录产生重复镜像层。
# 仅运行时缓存和存储目录允许 nextjs 写入,代码权限保持只读。
@ -314,11 +346,12 @@ RUN install -d -o nextjs -g nodejs -m 0755 /app/.next/cache && \
test "$(stat -c '%a' /app/DEPLOYMENT_COMMIT)" = 444 && \
test -s /app/public/brand/header-logo.png && \
test -s /app/public/brand/login-logo.png && \
test -s /app/public/brand/favicon.png && \
node -e "const sharp=require('sharp'); Promise.all(['header-logo.png','login-logo.png','favicon.png'].map((name)=>sharp('/app/public/brand/'+name,{failOn:'error',limitInputPixels:25000000,animated:false}).rotate().toBuffer())).then(()=>console.log('runner brand image decode smoke passed')).catch((error)=>{console.error(error);process.exit(1)})"
test -s /app/public/brand/favicon.png
USER nextjs
RUN node -e "const fs=require('fs'); fs.readdirSync('/app/public/brand'); fs.readdirSync('/app/public/detail-generator/fonts'); for(const file of ['lib/desktop-client/contract.mjs','prisma/schema.prisma','lib/url-rewrite.ts','lib/proxy-media-security.ts','app/api/proxy-media/route.ts','lib/s3.ts','lib/network-detection.ts'])fs.readFileSync('/app/'+file); fs.accessSync('/opt/detail-renderer/cli.mjs',fs.constants.R_OK); const sharp=require('sharp'); Promise.all(['header-logo.png','login-logo.png','favicon.png'].map((name)=>sharp('/app/public/brand/'+name,{failOn:'error',limitInputPixels:25000000,animated:false}).rotate().toBuffer())).then(()=>console.log('runner brand image decode smoke passed')).catch((error)=>{console.error(error);process.exit(1)})"
EXPOSE 3000
ENV PORT=3000

431
README.md
View File

@ -1,390 +1,111 @@
# 由壹点 3D 素材平台
# 共享素材库与小壹桌面端(gongxiangp2)
当前仓库对应的是一个已经在线上运行的业务项目,不是演示性质的素材站。项目围绕素材上传、管理、下载、分享、权限控制和运维诊断构建,当前代码已经明显超出早期 README 里那种“注册登录 + 预览图 + 压缩包”的简单形态。
> 更新日期:2026-12-04(已按当前线上架构与仓库结构重写)
> 本 README 已于 2026-03-06 按当前代码结构重写,优先反映现状。
本仓库包含两条核心产品线:
1. **共享素材库主站(Web)**:面向企业内部创意、视觉、电商与运营团队的素材资产管理、分发下载、组织权限治理、品牌中心与绩效协同平台。
2. **小壹桌面客户端(Windows)**:面向商品详情页、主图与 SKU 视觉生产的桌面工作台,集成原生画布编辑、智能体制作引擎、企业模板库与在线热更新体系。
## 项目概览
---
- 基于 Next.js 14 App Router 的素材协作与分发系统
- 默认以新素材流程为主,不再把“新老素材兼容”作为日常主路径
- 同时使用 PostgreSQL、Prisma、S3/MinIO、本地 `uploads` 目录,以及可选 Redis 上传会话
- 已覆盖首页浏览、素材上传、分享下载、后台管理、外部接口、内外网状态识别、健康检查等完整链路
- 当前项目已经在线上运行,涉及权限、下载、上传、转码、批量删除等改动时需要先验证再发布
## 核心能力
## 当前核心能力
### 1. 创意资产库与分发(Web)
- **素材类型全覆盖**:3D 原图、AI 原图、实拍图、任务-详情、商品套包、视频与直播切片、证书/检测报告、标准模特白底图等。
- **上传与转码链路**:分片上传与断点续传、SKU 维度资产管理、视频异步转码与封面/10 秒预览片段生成(PostgreSQL 租约恢复)。
- **下载与分享**:权限前置校验、源文件(PSD / 3D 原文件)分级控制、视频保护等待期策略、分享链接与外部授权下载、内外网访问自适应。
- **回收站与审计**:基于数据库 Outbox 任务与独立清理机制的安全永久删除、引用检查与完整操作/下载审计日志。
### 1. 用户与登录
### 2. 组织架构与权限体系
- **认证体系**:账号密码登录 + 钉钉登录与花名册组织绑定(NextAuth)。
- **权限治理**:
- 组织架构与素材权限包(按组织生效 + 个人权限继承 + 超级管理员兜底);
- 内容级保护规则:私人素材权限、专属/限定可见范围素材权限、视频等待期、PSD/3D 源文件下载权限。
- **协同与管理**:品牌中心、团队职能与绩效协同、AI 模型接入注册表、系统设置与诊断监控。
- 账号密码登录
- 钉钉登录与账号补全流程
- NextAuth 会话管理
- 个人资料页、个人素材、收藏与点赞
### 3. 小壹桌面客户端(`apps/`)
- **原生画布与图层引擎(`apps/detail-photocraft`)**:Rust 桌面应用,支持 GPU 渲染画布、分层工程文件(`.pcraft`)、模板图层映射、候选图预览/采纳、整图与分屏导出、三步建项向导与草稿续接。
- **智能体制作运行时(`apps/detail-agent-pi`)**:Node.js 后台服务,负责商品资料汇总、企业模板解析、文案与出图编排、画布原子工具调度与完整性校验。
- **在线更新发布**:仅发布 Windows `stable` 在线更新包(`.zip` + `release.json`),支持启动器自动检测更新、版本切换与 `--previous` 一键回滚。
### 2. 素材浏览与分发
- 首页搜索、筛选、分页加载
- 收藏、点赞、排行榜、分享页
- 下载前校验与前端客户端下载兜底
- 素材分享链接与外部下载接口
### 3. 素材上传与处理
- 分片上传、断点续传、上传会话管理
- 支持多种素材类型上传,当前代码中已覆盖:
- 3D 原图
- AI 原图
- 实拍图
- 视频截图
- 任务页素材
- 商品套包
- 标准模特白底图
- SKU 维度文件管理、排序、批量下载
- 详情图 / 素材资产管理
- 直播切片(仅视频):直播日期 / 主播 / 平台元数据,批量多选上传,关键词搜主播与平台,按平台与日期区间筛选,豁免 15 天视频下载保护期
- 证书-检测报告元数据:报告标题、报告类型(成品 / 原材料)、检测与到期日期(到期默认检测日期 + 1 年)
- 商品套包未完成上传的中止与回滚
- 视频转码、封面 / 预览片段生成、PostgreSQL 租约任务恢复与重试
- 默认生成 720P H.265 主预览和 10 秒片段;素材建档后异步经历 `pending → processing → done/failed`
### 4. 后台与权限
- 素材管理、用户管理、分类管理
- 部门管理与部门素材权限控制
- 数据统计、统计导出、素材操作日志
- 回收站永久删除:数据库 outbox 任务 + 应用内 worker(租约、重试、断点续跑、审计),引用检查走 GIN 表达式索引
- 权限组绑定花名册组织身份;品牌中心"团队职能"数据库化配置
- API Key、API 日志、系统设置、回收站、超级管理员相关能力
### 5. 运行与诊断
- 内外网状态识别、健康检查与受控运维监控
- 健康检查接口与内存检查接口
- 快速性能检查接口
- 内外网 URL 重写与下载链路适配
### 6. AI 能力(灰度中,默认关闭)
- AI 模型接入管理(仅超管):上游服务商与模型注册表,按用途做"真实协议测试"(真读图、真出图)后才允许开放;能力变更即要求重新验证
- AI 商品详情页生成器(正式验收前仅超管):资料分析 → 卖点大纲 → 逐屏生成 → 导出 PNG / 长图 / 分层 PSD;渲染走独立子进程 `workers/detail-renderer`(自带依赖锁,与主应用隔离)
---
## 技术栈
- 前端:Next.js 14、React 18、TypeScript、Tailwind CSS
- 认证:NextAuth.js
- 数据库:PostgreSQL + Prisma ORM
- 对象存储:S3 / MinIO
- 本地文件:`uploads` 目录
- 缓存 / 会话:Redis(可选,上传会话优先使用)
- 文件与媒体处理:`sharp`、`jszip`、`adm-zip`、`archiver`
- 测试:Jest + Testing Library
| 模块 | 技术栈 |
| :--- | :--- |
| **Web 主站** | Next.js 14 (App Router)、React 18、TypeScript、Tailwind CSS、NextAuth |
| **数据与存储** | PostgreSQL + Prisma ORM、S3 兼容对象存储、Redis(可选) |
| **小壹桌面端** | Rust(Cargo Workspace、egui、wgpu)、Node.js 24 |
| **独立 Worker** | `detail-renderer`、`database-migrator`、`performance-preview` |
| **测试与校验** | Jest + Testing Library、Node `node:test`、Rust `cargo test` |
---
## 目录结构
```text
gongxiangp2/
├── app/ # 页面、App Router、API 路由
│ ├── admin/ # 管理后台页面(素材库管理,旧壳待统一)
│ ├── api/ # 业务 API
│ ├── login/ # 登录页
│ ├── materials/ # 创意资产库(原素材库首页)
│ ├── organization/ # 组织管理(人员架构顶层页)
│ ├── register/ # 注册页
│ ├── share/ # 分享页
│ └── page.tsx # 登录与权限跳转至实际工作面
├── components/ # 通用组件、后台组件、上传组件、看板壳(board/)
├── lib/ # 业务工具、上传/下载/转码/权限逻辑
├── prisma/ # Prisma schema
├── scripts/ # 运维/修复/清理脚本
├── workers/ # 独立子进程:detail-renderer(详情页渲染)、database-migrator(精简迁移镜像)
├── docs/ # 网络、接口与部署等项目文档
├── uploads/ # 本地上传与处理中间文件
├── app/ # Next.js App Router 页面与全站 API 路由
│ ├── admin/ # 管理后台(用户、素材、权限包、模型配置等)
│ ├── api/ # 业务接口、素材下载、客户端更新与反馈接口
│ ├── materials/ # 创意资产库工作面
│ └── organization/ # 组织架构与人员管理
├── apps/
│ ├── detail-photocraft/ # 小壹桌面客户端(Rust Workspace,含核心引擎与界面层)
│ └── detail-agent-pi/ # 小壹智能体后台运行时(Node.js)
├── components/ # Web 通用组件、上传器、后台与看板组件
├── hooks/ # React Hooks
├── lib/ # 核心业务逻辑(权限校验、上传下载、S3、模型接入等)
├── prisma/ # Prisma Schema 与数据库迁移脚本
├── workers/ # 独立运行子进程(迁移器、详情渲染、绩效预览)
├── scripts/ # 发布、验收、运维与数据校验脚本
├── docs/ # 架构、接口与部署文档
├── public/ # 静态资源与公共字体
└── README.md
```
## 数据模型概览
---
当前 Prisma 模型已经不止早期的 `User` / `Material` 两张表,核心模型包括但不限于:
- `User`
- `Material`
- `MaterialSku`
- `MaterialAsset`
- `MaterialLog`
- `MaterialDownloadLog`
- `Department`
- `DepartmentMaterialPermission`
- `ApiKey`
- `ApiCallLog`
- `VideoTranscodeProgress`
- `SystemSettings`
- AI 模型注册表:`AiModelProvider` / `AiModelCatalog` / `AiModelVerification` / `AiModelConfiguration` / `AiModelAudit`
- 详情页生成器:`DetailGeneratorProject` / `DetailGeneratorBrandProfile` / `DetailGeneratorAsset` / `DetailGeneratorJob`
- 回收站永久删除:`MaterialPurgeJob` / `MaterialPurgeAudit`
- 组织与团队职能:`TeamFunctionConfig` / `TeamFunctionConfigAudit`
角色枚举当前包含:
- `USER`
- `ADMIN`
- `DEPT_ADMIN`
- `SYSTEM_ADMIN`
## 快速开始
### 1. 安装依赖
## 本地开发与常用校验
### Web 主站
```bash
npm install
```
### 2. 配置环境变量
仓库当前没有维护独立的 `.env.example`,请自行准备本地环境变量文件,并且不要把真实密钥再次提交到仓库。
最小必需:
```bash
DATABASE_URL=postgresql://...
NEXTAUTH_SECRET=replace-this-with-a-strong-secret
```
启用素材平台 API Key 创建和后续查看时,还必须配置独立且稳定的加密密钥:
```bash
# 至少 32 个字符;生产环境必须独立生成并稳定保存
API_KEY_ENCRYPTION_KEY=replace-this-with-a-separate-strong-secret
```
常用配置:
```bash
# 站点地址
NEXTAUTH_URL=http://localhost:3000
APP_PUBLIC_URL=http://localhost:3000
# 仅限直接运行 `npm run dev` 的非容器本地开发目录
UPLOAD_DIR=./uploads
# S3 / MinIO
S3_ENDPOINT=http://127.0.0.1:9000
S3_BUCKET=your-bucket
S3_ACCESS_KEY_ID=your-access-key
S3_SECRET_ACCESS_KEY=your-secret-key
S3_REGION=us-east-1
S3_PUBLIC_DOMAIN=https://your-s3-domain
S3_FILE_PATH=your-prefix/
# Redis(上传会话)
USE_REDIS=true
REDIS_URL=redis://127.0.0.1:6379
# 钉钉登录
DINGTALK_CLIENT_ID=your-dingtalk-app-key
DINGTALK_CLIENT_SECRET=your-dingtalk-app-secret
NEXT_PUBLIC_DINGTALK_CLIENT_ID=your-dingtalk-app-key
# 考核调研通知:work_notice(工作通知)或 robot_oto(机器人单聊)
DINGTALK_PERFORMANCE_SURVEY_NOTIFICATION_CHANNEL=robot_oto
DINGTALK_ROBOT_CODE=your-dingtalk-robot-code
# 灰度阶段填写允许走机器人单聊的钉钉 userId,多个用逗号分隔;留空表示全量启用
DINGTALK_ROBOT_OTO_TEST_USER_IDS=user-id-1,user-id-2
# 通知中心管理后台代理(仅服务端使用,绝不能下发到浏览器)
YYD_NOTIFICATION_CENTER_ADMIN_URL=https://notify-admin.example.com/notification-center/admin
YYD_NOTIFICATION_CENTER_ADMIN_API_SECRET=replace-with-server-side-admin-secret
# 可选,请求超时毫秒;默认 8000
YYD_NOTIFICATION_CENTER_ADMIN_TIMEOUT_MS=8000
# 下载与外部接口
DOWNLOAD_TOKEN_SECRET=replace-this
ADMIN_API_KEY=replace-this-if-needed
# 标题栏商品搜索(淘宝详情代理)
TAOBAO_DETAIL_PLUS_API_BASE_URL=http://156.225.27.52:60024
TAOBAO_DETAIL_PLUS_API_KEY=your-api-key
TAOBAO_DETAIL_PLUS_TIMEOUT_MS=12000
# 内外网链路改写
SERVER_IP=127.0.0.1
MINIO_API_PORT=9000
# 视频转码(按需)
VIDEO_TRANSCODE_MAX_CONCURRENT=1
VIDEO_TRANSCODE_THREADS=1
VIDEO_TRANSCODE_TIMEOUT=3600000
VIDEO_PREVIEW_RESOLUTION=720
VIDEO_CLIP_DURATION=10
VIDEO_PREVIEW_CRF=20
VIDEO_CLIP_CRF=24
VIDEO_MAX_TEMP_FILE_SIZE=10737418240
# AI 聊天(按需)
GEMINI_API_KEY=your-api-key
GEMINI_API_BASE_URL=https://generativelanguage.googleapis.com/v1beta
GEMINI_MODEL=gemini-2.0-flash-exp
```
### 3. 初始化数据库
```bash
npm run prisma:generate
npm run prisma:push
```
### 4. 初始化管理员账号
首次启动后,可以先注册一个普通账号,再在数据库里把角色改成 `ADMIN`。
```sql
UPDATE users
SET role = 'ADMIN'
WHERE email = 'your@email.com';
```
### 5. 启动开发环境
```bash
npx prisma generate
npm run dev
```
直接运行 `npm run dev` 时,`UPLOAD_DIR=./uploads` 只保存本机开发数据。容器化的本地集成测试请使用 `docker-compose.local-test.yml` 中的独立命名卷,不要把相对目录配置复制到默认 Compose 或生产环境。
### 6. 默认 Compose 的 uploads 挂载门禁
根目录 `docker-compose.yml` 是生产形态的单机参考配置(正式发布仍以 `scripts/git-incremental-deploy.ps1` 为准)。它不会再自动创建或挂载仓库内的 `./uploads`,启动前必须显式提供已经核验的宿主机 uploads 挂载:
### 小壹智能体运行时单测
```bash
export GONGXIANGP2_UPLOADS_MOUNT=/mnt/PoolOne/youyidian-uploads
docker compose config
docker compose up -d
cd apps/detail-agent-pi
node --test test/*.test.mjs
```
- 当前生产宿主机的真实独立 ZFS 数据集路径是 `/mnt/PoolOne/youyidian-uploads`;先在宿主机用 `findmnt` 核验它确实是预期挂载,不能只确认目录存在。
- 容器内统一使用 `UPLOAD_DIR=/app/uploads`,不要把宿主机路径写进容器环境变量。
- `create_host_path: false` 会在路径缺失时直接失败,避免 Docker 静默新建空目录后让素材写入错误磁盘。
- 相对 `./uploads` 只允许用于明确的非容器开发;影子环境使用其独立的 `uploads-shadow`,本地集成测试使用命名卷,二者都不能当作生产数据目录。
### 小壹客户端发布与线上校验脚本
- 发布在线更新:`scripts/publish-xiaoyi-client.ts`(默认预演,确认后追加 `--apply`)
- 线上版本验通:`scripts/verify-xiaoyi-client.ts <版本号> [提交SHA]`
- 回滚稳定版本:`scripts/publish-xiaoyi-client.ts --set-latest <上一稳定版> --channel stable --apply`
默认访问地址:
---
```text
http://localhost:3000
```
## 仓库协作与问题反馈闭环
登录后的一级入口为“品牌中心部门看板”,当前页面路由如下:
本仓库托管于 GitHub 私有仓库,统一承载代码、PR 与用户问题反馈流转:
```text
品牌中心部门看板:http://localhost:3000/
小项二级框架示例:http://localhost:3000/workspaces/dashboard/core-metrics
由壹点3D素材:http://localhost:3000/assets/material-library
```
- **分支与提交**:功能开发与缺陷修复均在独立分支完成,通过对应定向测试与检查后再合入 `main`。
- **问题反馈 Issue 标签约定**:
- `feedback`:小壹用户提交的问题反馈
- `status:triage`:新反馈待排查
- `status:investigating`:正在定位或修复中
- `status:needs-owner`:需要负责人拍板或确认方向
- `status:ready-to-release`:已完成修复并测通,待确认发布
- `status:fixed`:已修复并上线验证
- `severity:p0`:严重阻断问题
### 无本机 Node 环境时使用 Docker 开发
---
仓库提供一套隔离的 Docker 开发环境,包含 Node.js 22、PostgreSQL、Redis、MinIO 和支持源码热更新的 Next.js。它使用独立数据卷,不连接生产数据库或生产对象存储。
```bash
docker compose \
--env-file .env.docker-test.local \
-f docker-compose.local-test.yml \
-f docker-compose.dev.yml \
up -d --build
```
首次启动会自动执行 `prisma generate` 和 `prisma db push`。启动完成后访问:
```text
应用:http://localhost:4321
MinIO 控制台:http://localhost:59001
```
查看应用日志或停止环境:
```bash
docker compose \
--env-file .env.docker-test.local \
-f docker-compose.local-test.yml \
-f docker-compose.dev.yml \
logs -f app
docker compose \
--env-file .env.docker-test.local \
-f docker-compose.local-test.yml \
-f docker-compose.dev.yml \
down
```
`down` 会保留本地数据库和上传文件;只有显式增加 `--volumes` 才会清除本地开发数据。
## 常用脚本
```bash
npm run dev
npm run build
npm run start
npm run lint
npm run test
npm run test:watch
npm run test:coverage
npm run prisma:generate
npm run prisma:push
npm run prisma:studio
```
## 部署说明
### 当前标准部署
当前线上默认使用 Git 增量部署:
```powershell
.\scripts\git-incremental-deploy.ps1 -DryRun
.\scripts\git-incremental-deploy.ps1 -Commit '<40位小写提交SHA>'
```
部署链路是:源码推送到 Git -> 构建机增量拉取并构建镜像 -> 生产机拉取镜像并替换应用容器。旧的 `deploy-remote-build.ps1` 属于本地历史脚本名,只作为识别应急资料使用,不是仓库交付入口,也不再作为默认推荐方式。
详细说明见:
- `docs/Git增量部署方案.md`
- `docs/部署规范.md`
- `docs/部署脚本安全说明.md`
### 本地或单机生产启动
```bash
npm run build
npm run start
```
### Docker / Compose
仓库内已经包含以下部署文件:
- `Dockerfile`
- `Dockerfile.base`
- `docker-compose.yml`
- `docker-compose.shadow.yml`
但当前线上环境并不只依赖容器本身,还依赖网络入口、FRP、域名与反向代理链路。因此如果要碰部署问题,建议连同项目文档一起看,而不是只看 Compose 文件。
### 发布前重点核对
- 登录是否正常
- 首页筛选、上传、下载、分享是否正常
- 管理后台核心页签是否可用
- 视频转码数据库任务 / 租约是否异常堆积(Redis 仅检查上传会话,不作为视频队列)
- `/api/health` 是否正常
- 如果改了网络或下载链路,再验证一次内外网访问
## 相关文档
- `docs/NETWORK_TOPOLOGY.md`:当前网络拓扑与故障排查
- `docs/部署规范.md`:当前部署规范
- `docs/Git增量部署方案.md`:Git 增量部署方案
- `docs/生产存储桶接入信息.md`:当前 MinIO / uploads 存储事实
- `docs/外部接口文档.md`:当前对外接口说明
## 说明
- 当前仓库 `package.json` 为 `private: true`
- 本仓库目前没有单独声明开源许可证,不应继续沿用旧 README 中的 `MIT` 说法
- 项目已在线上运行,任何会影响上传、下载、权限、批量删除、资源链路的改动,都应先验证再发布
## 安全与红线提醒
- 严禁将 `.env`、凭据文件、密钥或内网敏感配置提交到 Git 历史;
- 涉及数据库 Schema(`prisma/`)或迁移脚本变更前,必须先评估影响范围并做备份与灰度验证;
- 客户端发版前必须完成版本元信息、PE 导入表、启动参数、运行时依赖与后台心跳校验后再切换 `stable` 通道。

View File

@ -383,7 +383,7 @@ export default function AdminPage() {
: 'text-[#6b7075] hover:text-[#1a1c1d]'
}`}
>
部门权限配置
旧部门权限
</button>
<button

View File

@ -31,6 +31,7 @@ jest.mock('@/lib/department-permission', () => ({
jest.mock('@/lib/external-api', () => ({
ApiKeyEncryptionConfigError: class ApiKeyEncryptionConfigError extends Error {},
ApiKeyNotRecoverableError: class ApiKeyNotRecoverableError extends Error {},
XIAOYI_LISTING_KEY_SCOPE: 'xiaoyi_auto_listing',
getApiKeys: jest.fn(),
createApiKey: jest.fn(),
getApiKeyPreview: jest.fn((key: string) => `${String(key).slice(0, 8)}...`),
@ -61,6 +62,17 @@ describe('admin api-keys routes', () => {
;(isSuperAdmin as jest.Mock).mockResolvedValue(true)
})
test('仅接受已知的密钥用途并将小壹上架用途传给创建函数', async () => {
;(createApiKey as jest.Mock).mockResolvedValue({ id: 'listing-key', key: 'isolated-test-key' })
const request = (scope: string) => new Request('http://localhost/api/admin/api-keys', {
method: 'POST', body: JSON.stringify({ name: '自动上架', scope }),
})
expect((await createApiKeyRoute(request('wrong') as any)).status).toBe(400)
expect(createApiKey).not.toHaveBeenCalled()
expect((await createApiKeyRoute(request('xiaoyi_auto_listing') as any)).status).toBe(200)
expect(createApiKey).toHaveBeenCalledWith('自动上架', 'admin-1', 'xiaoyi_auto_listing')
})
test('GET 会继续返回 masked key 预览', async () => {
;(getApiKeys as jest.Mock).mockResolvedValue([
{ id: 'key-1', key: 'abcdefgh12345678', name: '任务系统', isActive: true, canReveal: true },

View File

@ -13,6 +13,7 @@ import {
createApiKey,
getApiKeyPreview,
getApiKeys,
XIAOYI_LISTING_KEY_SCOPE,
} from '@/lib/external-api';
/**
@ -81,7 +82,7 @@ export async function POST(request: NextRequest) {
}
const body = await request.json();
const { name } = body;
const { name, scope } = body;
if (!name || typeof name !== 'string' || name.trim().length === 0) {
return NextResponse.json(
@ -90,7 +91,13 @@ export async function POST(request: NextRequest) {
);
}
const apiKey = await createApiKey(name.trim(), userId);
if (scope !== undefined && scope !== 'general' && scope !== XIAOYI_LISTING_KEY_SCOPE) {
return NextResponse.json({ success: false, error: '密钥用途无效' }, { status: 400 });
}
const apiKey = scope === XIAOYI_LISTING_KEY_SCOPE
? await createApiKey(name.trim(), userId, scope)
: await createApiKey(name.trim(), userId);
return NextResponse.json(
{

View File

@ -0,0 +1,31 @@
import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { z } from 'zod'
import { authOptions } from '@/lib/auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
export const targetIdSchema = z.string().trim().min(1).max(128)
export function autoListingResponse(body: object, status = 200) {
return NextResponse.json(body, { status, headers: { 'Cache-Control': 'no-store' } })
}
export function autoListingFailure(error: string, status: number) {
return autoListingResponse({ success: false, error }, status)
}
export async function withAutoListingSuperAdmin(handle: () => Promise<NextResponse>) {
try {
const session = await getServerSession(authOptions)
const userId = session?.user?.id
if (!userId || !(await isSuperAdmin(userId))) {
return autoListingFailure('仅超级管理员可操作', 403)
}
return await handle()
} catch (error) {
if (error instanceof AutoListingCallbackError) return autoListingFailure(error.message, error.status)
console.error('[admin/auto-listing-targets] request failed', error instanceof Error ? error.name : 'UnknownError')
return autoListingFailure('操作失败,请稍后重试', 500)
}
}

View File

@ -0,0 +1,161 @@
/** @jest-environment node */
import { getServerSession } from 'next-auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
import {
createExternalNotificationTarget,
listExternalNotificationDeliveries,
listExternalNotificationTargets,
setExternalNotificationTargetActive,
testExternalNotificationTarget,
updateExternalNotificationTarget,
XIAOYI_AUTO_LISTING_EVENT_TYPE,
} from '@/lib/external-auto-listing'
import { GET, PATCH, POST } from './route'
import { POST as TEST } from './test/route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: {} }))
jest.mock('@/lib/department-permission', () => ({ isSuperAdmin: jest.fn() }))
jest.mock('@/lib/external-auto-listing', () => ({
...jest.requireActual('@/lib/external-auto-listing'),
createExternalNotificationTarget: jest.fn(),
listExternalNotificationDeliveries: jest.fn(),
listExternalNotificationTargets: jest.fn(),
setExternalNotificationTargetActive: jest.fn(),
testExternalNotificationTarget: jest.fn(),
updateExternalNotificationTarget: jest.fn(),
}))
const operator = { id: 'operator', name: '操作员', email: 'operator@example.com' }
const route = 'https://material.example.com/api/admin/auto-listing-targets'
const target = {
id: 'target-1',
name: '上架系统',
callbackUrl: 'https://listing.example.com/callback',
isActive: false,
authType: 'header',
authConfig: { headerName: 'X-Signature', headerValue: 'private-callback-secret' },
eventTypes: [XIAOYI_AUTO_LISTING_EVENT_TYPE],
createdAt: '2026-12-04T08:00:00.000Z',
updatedAt: '2026-12-04T08:00:00.000Z',
}
function request(method: string, body?: unknown, path = '') {
return new Request(route + path, { method, body: body === undefined ? undefined : JSON.stringify(body) })
}
beforeEach(() => {
jest.resetAllMocks()
jest.mocked(getServerSession).mockResolvedValue({ user: { ...operator, role: 'USER' }, expires: '2026-12-05' })
jest.mocked(isSuperAdmin).mockResolvedValue(true)
})
test.each(['USER', 'DEPT_ADMIN', 'SYSTEM_ADMIN'] as const)('拒绝没有超管权限的 %s', async (role) => {
jest.mocked(getServerSession).mockResolvedValue({ user: { ...operator, role, isSuperAdmin: true }, expires: '2026-12-05' })
jest.mocked(isSuperAdmin).mockResolvedValue(false)
const responses = await Promise.all([
GET(request('GET')),
POST(request('POST', {})),
PATCH(request('PATCH', {})),
TEST(request('POST', {}, '/test')),
])
expect(responses.map((response) => response.status)).toEqual([403, 403, 403, 403])
expect(isSuperAdmin).toHaveBeenCalledWith('operator')
for (const operation of [listExternalNotificationTargets, listExternalNotificationDeliveries,
createExternalNotificationTarget, updateExternalNotificationTarget, setExternalNotificationTargetActive,
testExternalNotificationTarget]) {
expect(operation).not.toHaveBeenCalled()
}
})
test('超管列表只返回鉴权状态和安全的投递摘要', async () => {
jest.mocked(listExternalNotificationTargets).mockResolvedValue([{
...target,
callbackUrl: 'https://user:private-url-secret@listing.example.com/callback?token=private-query-secret',
}])
jest.mocked(listExternalNotificationDeliveries).mockResolvedValue([{
id: 'delivery-1', targetId: target.id, targetName: target.name,
eventType: XIAOYI_AUTO_LISTING_EVENT_TYPE, materialId: 'material-1', materialType: '详情',
taskNo: null, status: 'retrying', attemptCount: 1, maxAttempts: 5, nextRetryAt: null,
lastStatusCode: 401, lastResponseBody: 'Authorization: private-response-secret',
lastError: 'Authorization: private-error-secret', payload: { token: 'private-payload-secret', projectId: 'project-1', eventId: 'event-1' },
createdAt: target.createdAt, updatedAt: target.updatedAt, completedAt: null,
}])
const response = await GET(request('GET', undefined, '?status=retrying&q=%20project-1%20'))
const data = (await response.json()).data
expect(response.status).toBe(200)
expect(response.headers.get('Cache-Control')).toBe('no-store')
expect(data.targets[0]).toMatchObject({
callbackUrl: target.callbackUrl, authConfigured: true,
authConfig: { headerName: 'X-Signature' },
})
expect(data.recentDeliveries[0]).toMatchObject({
lastError: '接收方返回 HTTP 401', projectId: 'project-1', eventId: 'event-1',
})
expect(data.recentDeliveries[0]).not.toHaveProperty('lastResponseBody')
expect(data.recentDeliveries[0]).not.toHaveProperty('payload')
expect(JSON.stringify(data)).not.toContain('private-')
expect(listExternalNotificationDeliveries).toHaveBeenCalledWith({
canAccessOperationsG: true, status: 'retrying', query: 'project-1', limit: 50,
})
})
test('超管可新增、编辑及启停目标,响应都不含明文凭据', async () => {
jest.mocked(createExternalNotificationTarget).mockResolvedValue(target)
jest.mocked(updateExternalNotificationTarget).mockResolvedValue(target)
jest.mocked(setExternalNotificationTargetActive)
.mockResolvedValueOnce({ ...target, isActive: true })
.mockResolvedValueOnce(target)
const { name, callbackUrl, authType, authConfig } = target
const input = { name, callbackUrl, authType, authConfig }
const responses = [
await POST(request('POST', input)),
await POST(request('POST', { id: target.id, name, callbackUrl, authType })),
await PATCH(request('PATCH', { id: target.id, isActive: true })),
await PATCH(request('PATCH', { id: target.id, isActive: false })),
]
expect(responses.map((response) => response.status)).toEqual([200, 200, 200, 200])
for (const response of responses) expect(await response.text()).not.toContain('private-callback-secret')
expect(createExternalNotificationTarget).toHaveBeenCalledWith({
...input, isActive: false, eventTypes: [XIAOYI_AUTO_LISTING_EVENT_TYPE],
})
expect(updateExternalNotificationTarget).toHaveBeenCalledWith(target.id, { name, callbackUrl, authType })
expect(setExternalNotificationTargetActive).toHaveBeenNthCalledWith(1, target.id, true)
expect(setExternalNotificationTargetActive).toHaveBeenNthCalledWith(2, target.id, false)
})
test('拒绝无效请求和回调地址,未知目标返回 404', async () => {
jest.mocked(createExternalNotificationTarget).mockRejectedValue(new AutoListingCallbackError('回调地址指向受保护的网络'))
jest.mocked(updateExternalNotificationTarget).mockResolvedValue(null)
jest.mocked(setExternalNotificationTargetActive).mockResolvedValue(null)
const { name, callbackUrl } = target
expect((await POST(request('POST', { name, callbackUrl, eventTypes: ['unknown'] }))).status).toBe(400)
expect((await POST(request('POST', { name, callbackUrl: 'https://127.0.0.1/callback' }))).status).toBe(400)
expect((await POST(request('POST', { id: target.id, name, callbackUrl }))).status).toBe(404)
expect((await PATCH(request('PATCH', { id: target.id, isActive: false }))).status).toBe(404)
})
test('测试接口只接收已保存目标的编号并报告接收方状态', async () => {
jest.mocked(testExternalNotificationTarget)
.mockResolvedValueOnce({ statusCode: 204, error: null })
.mockResolvedValueOnce({ statusCode: 401, error: '接收方返回 HTTP 401' })
.mockResolvedValueOnce(null)
expect((await TEST(request('POST', { id: target.id, callbackUrl: target.callbackUrl }, '/test'))).status).toBe(400)
expect(testExternalNotificationTarget).not.toHaveBeenCalled()
const send = () => TEST(request('POST', { id: target.id }, '/test'))
const success = await send()
expect(success.status).toBe(200)
expect(await success.json()).toEqual({ success: true, statusCode: 204 })
const failure = await send()
expect(failure.status).toBe(502)
expect(await failure.json()).toEqual({ success: false, statusCode: 401, error: '接收方返回 HTTP 401' })
expect((await send()).status).toBe(404)
expect(testExternalNotificationTarget).toHaveBeenCalledWith(target.id)
})

View File

@ -0,0 +1,81 @@
import { z } from 'zod'
import {
AUTO_LISTING_AUTH_TYPE,
AUTO_LISTING_DELIVERY_STATUS,
SUPPORTED_AUTO_LISTING_EVENT_TYPES,
XIAOYI_AUTO_LISTING_EVENT_TYPE,
buildExternalNotificationTargetAdminView,
createExternalNotificationTarget,
listExternalNotificationDeliveries,
listExternalNotificationTargets,
setExternalNotificationTargetActive,
summarizeExternalNotificationDelivery,
updateExternalNotificationTarget,
} from '@/lib/external-auto-listing'
import { autoListingFailure, autoListingResponse, targetIdSchema, withAutoListingSuperAdmin } from './_shared'
const saveTarget = z.object({
id: targetIdSchema.optional(),
name: z.string().trim().min(1).max(120),
callbackUrl: z.string().trim().min(1).max(2048),
authType: z.nativeEnum(AUTO_LISTING_AUTH_TYPE).optional(),
authConfig: z.object({
token: z.string().max(4096).optional(),
headerName: z.string().max(128).optional(),
headerValue: z.string().max(4096).optional(),
}).strict().optional(),
eventTypes: z.array(z.enum(SUPPORTED_AUTO_LISTING_EVENT_TYPES)).min(1).optional(),
isActive: z.boolean().optional(),
}).strict()
const toggleTarget = z.object({ id: targetIdSchema, isActive: z.boolean() }).strict()
export async function GET(request: Request) {
return withAutoListingSuperAdmin(async () => {
const { searchParams } = new URL(request.url)
const status = z.nativeEnum(AUTO_LISTING_DELIVERY_STATUS).safeParse(searchParams.get('status'))
const query = searchParams.get('q')?.trim()
if (query && query.length > 160) return autoListingFailure('检索内容过长', 400)
const targets = await listExternalNotificationTargets()
const deliveries = await listExternalNotificationDeliveries({
canAccessOperationsG: true,
status: status.success ? status.data : undefined,
...(query && { query }),
limit: 50,
})
return autoListingResponse({
success: true,
data: {
targets: targets.map(buildExternalNotificationTargetAdminView),
recentDeliveries: deliveries.map(summarizeExternalNotificationDelivery),
},
})
})
}
export async function POST(request: Request) {
return withAutoListingSuperAdmin(async () => {
const result = saveTarget.safeParse(await request.json().catch(() => null))
if (!result.success) return autoListingFailure('请检查目标名称、回调地址、鉴权和订阅事件', 400)
const { id, ...input } = result.data
const target = id
? await updateExternalNotificationTarget(id, input)
: await createExternalNotificationTarget({
...input,
eventTypes: input.eventTypes ?? [XIAOYI_AUTO_LISTING_EVENT_TYPE],
isActive: input.isActive ?? false,
})
if (!target) return autoListingFailure('回调目标不存在', 404)
return autoListingResponse({ success: true, data: buildExternalNotificationTargetAdminView(target) })
})
}
export async function PATCH(request: Request) {
return withAutoListingSuperAdmin(async () => {
const result = toggleTarget.safeParse(await request.json().catch(() => null))
if (!result.success) return autoListingFailure('请提供回调目标和启停状态', 400)
const target = await setExternalNotificationTargetActive(result.data.id, result.data.isActive)
if (!target) return autoListingFailure('回调目标不存在', 404)
return autoListingResponse({ success: true, data: buildExternalNotificationTargetAdminView(target) })
})
}

View File

@ -0,0 +1,20 @@
import { z } from 'zod'
import { testExternalNotificationTarget } from '@/lib/external-auto-listing'
import { autoListingFailure, autoListingResponse, targetIdSchema, withAutoListingSuperAdmin } from '../_shared'
const testTarget = z.object({ id: targetIdSchema }).strict()
export async function POST(request: Request) {
return withAutoListingSuperAdmin(async () => {
const result = testTarget.safeParse(await request.json().catch(() => null))
if (!result.success) return autoListingFailure('请指定已保存的回调目标', 400)
const probe = await testExternalNotificationTarget(result.data.id)
if (!probe) return autoListingFailure('回调目标不存在', 404)
return autoListingResponse({
success: !probe.error,
statusCode: probe.statusCode,
...(probe.error ? { error: probe.error } : {}),
}, probe.error ? 502 : 200)
})
}

View File

@ -1,92 +1 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSuperAdmin } from '@/lib/department-permission';
/**
* POST - 批量更新权限配置
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const body = await request.json();
const { department } = body || {};
const permissions: Array<{
materialType: string;
canView?: boolean;
canDownload?: boolean;
canDownloadSource?: boolean;
canShare?: boolean;
}> = body?.permissions || [];
if (!department || !Array.isArray(permissions) || permissions.length === 0) {
return NextResponse.json(
{ error: '部门名称和素材类型列表不能为空' },
{ status: 400 }
);
}
const materialTypes = permissions.map((p) => p.materialType).filter(Boolean);
// 检查是否有关联部门
const existing = await prisma.departmentMaterialPermission.findFirst({
where: {
department,
materialType: { in: materialTypes },
linkedToDepartment: { not: null },
},
});
if (existing) {
return NextResponse.json(
{ error: '该部门已关联到其他部门,请先取消关联' },
{ status: 400 }
);
}
// 批量更新权限配置
const updates = permissions.map((perm) =>
prisma.departmentMaterialPermission.upsert({
where: {
department_materialType: {
department,
materialType: perm.materialType,
},
},
update: {
canView: perm.canView ?? false,
canDownload: perm.canDownload ?? false,
canDownloadSource: perm.canDownloadSource ?? false,
canShare: perm.canShare ?? true,
linkedToDepartment: null,
},
create: {
department,
materialType: perm.materialType,
canView: perm.canView ?? false,
canDownload: perm.canDownload ?? false,
canDownloadSource: perm.canDownloadSource ?? false,
canShare: perm.canShare ?? true,
linkedToDepartment: null,
},
})
);
await Promise.all(updates);
return NextResponse.json({
message: '批量更新成功',
updatedCount: permissions.length,
});
} catch (error) {
console.error('[Department Permissions Batch] Error:', error);
return NextResponse.json({ error: '批量更新失败' }, { status: 500 });
}
}
export { retiredDepartmentPermissionWrite as POST } from '@/lib/retired-department-permission-write'

View File

@ -1,76 +1 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSuperAdmin } from '@/lib/department-permission';
/**
* POST - 复制权限配置
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const { sourceDepartment, targetDepartments } = await request.json();
if (!sourceDepartment || !targetDepartments || !Array.isArray(targetDepartments)) {
return NextResponse.json(
{ error: '源部门和目标部门不能为空' },
{ status: 400 }
);
}
// 获取源部门的所有权限配置
const sourcePermissions = await prisma.departmentMaterialPermission.findMany({
where: { department: sourceDepartment },
});
if (sourcePermissions.length === 0) {
return NextResponse.json(
{ error: '源部门没有权限配置' },
{ status: 400 }
);
}
// 为每个目标部门复制权限
for (const targetDept of targetDepartments) {
if (targetDept === sourceDepartment) {
continue; // 跳过自己
}
// 先删除目标部门的所有权限配置
await prisma.departmentMaterialPermission.deleteMany({
where: { department: targetDept },
});
// 复制源部门的权限配置
const newPermissions = sourcePermissions.map((perm) => ({
department: targetDept,
materialType: perm.materialType,
canView: perm.canView,
canDownload: perm.canDownload,
canDownloadSource: perm.canDownloadSource,
canShare: perm.canShare,
linkedToDepartment: null, // 复制后不关联
}));
await prisma.departmentMaterialPermission.createMany({
data: newPermissions,
});
}
return NextResponse.json({
message: '权限复制成功',
copiedCount: targetDepartments.length,
});
} catch (error) {
console.error('[Department Permissions Copy] Error:', error);
return NextResponse.json({ error: '复制权限失败' }, { status: 500 });
}
}
export { retiredDepartmentPermissionWrite as POST } from '@/lib/retired-department-permission-write'

View File

@ -1,136 +1 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSuperAdmin } from '@/lib/department-permission';
import { filterSelectableMaterialTypes } from '@/lib/material-type-options';
/**
* DELETE - 删除部门的所有自定义权限配置,使其恢复为继承父部门权限
*/
export async function DELETE(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const { searchParams } = new URL(request.url);
const department = searchParams.get('department');
if (!department) {
return NextResponse.json({ error: '部门名称不能为空' }, { status: 400 });
}
// 删除该部门的所有权限配置(不包括关联的,因为关联的需要先取消关联)
await prisma.departmentMaterialPermission.deleteMany({
where: {
department,
linkedToDepartment: null, // 只删除非关联的权限配置
},
});
return NextResponse.json({
message: '已还原为继承父部门权限',
department,
});
} catch (error) {
console.error('[Department Permissions Inherit] DELETE Error:', error);
return NextResponse.json({ error: '还原失败' }, { status: 500 });
}
}
/**
* POST - 基于父部门权限创建独立配置
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const body = await request.json();
const { department } = body;
if (!department) {
return NextResponse.json({ error: '部门名称不能为空' }, { status: 400 });
}
// 获取部门信息(包括父部门)
const dept = await prisma.department.findFirst({
where: { name: department },
include: { parent: true },
});
if (!dept) {
return NextResponse.json({ error: '部门不存在' }, { status: 404 });
}
if (!dept.parentId) {
return NextResponse.json({ error: '该部门没有父部门,无法继承' }, { status: 400 });
}
// 获取父部门的权限配置
const { getDepartmentPermissions, getAllMaterialTypes } = await import('@/lib/department-permission');
const allMaterialTypes = filterSelectableMaterialTypes(await getAllMaterialTypes());
// 获取所有部门用于权限继承检查
const allDepartments = await prisma.department.findMany({
select: { id: true, name: true, parentId: true },
});
const parentPermissions = await getDepartmentPermissions(
dept.parent!.name,
allDepartments,
allMaterialTypes
);
// 检查是否已经有自定义权限配置
const existingCount = await prisma.departmentMaterialPermission.count({
where: {
department,
linkedToDepartment: null,
},
});
if (existingCount > 0) {
return NextResponse.json(
{ error: '该部门已有自定义权限配置,请先还原为继承后再操作' },
{ status: 400 }
);
}
// 基于父部门权限创建独立配置
const newPermissions = allMaterialTypes.map((materialType) => {
const parentPerm = parentPermissions[materialType];
return {
department,
materialType,
canView: parentPerm?.canView ?? false,
canDownload: parentPerm?.canDownload ?? false,
canDownloadSource: parentPerm?.canDownloadSource ?? false,
canShare: parentPerm?.canShare ?? true,
linkedToDepartment: null,
};
});
await prisma.departmentMaterialPermission.createMany({
data: newPermissions,
});
return NextResponse.json({
message: '已创建独立配置',
department,
createdCount: newPermissions.length,
});
} catch (error) {
console.error('[Department Permissions Inherit] POST Error:', error);
return NextResponse.json({ error: '创建独立配置失败' }, { status: 500 });
}
}
export { retiredDepartmentPermissionWrite as POST, retiredDepartmentPermissionWrite as DELETE } from '@/lib/retired-department-permission-write'

View File

@ -1,118 +1 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { getAllMaterialTypes, createDefaultPermissionsForDepartment, isSuperAdmin } from '@/lib/department-permission';
import { filterSelectableMaterialTypes } from '@/lib/material-type-options';
/**
* POST - 关联权限配置
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const { targetDepartment, sourceDepartment } = await request.json();
if (!targetDepartment || !sourceDepartment) {
return NextResponse.json(
{ error: '目标部门和源部门不能为空' },
{ status: 400 }
);
}
if (targetDepartment === sourceDepartment) {
return NextResponse.json(
{ error: '不能关联到自己' },
{ status: 400 }
);
}
// 确保源部门有权限配置
await createDefaultPermissionsForDepartment(sourceDepartment);
// 确保目标部门有权限配置
await createDefaultPermissionsForDepartment(targetDepartment);
// 获取所有素材类型(从数据库动态获取)
const allMaterialTypes = filterSelectableMaterialTypes(await getAllMaterialTypes());
// 更新目标部门所有素材类型的关联
for (const materialType of allMaterialTypes) {
await prisma.departmentMaterialPermission.upsert({
where: {
department_materialType: {
department: targetDepartment,
materialType,
},
},
update: {
linkedToDepartment: sourceDepartment,
},
create: {
department: targetDepartment,
materialType,
canView: false,
canDownload: false,
canShare: true,
linkedToDepartment: sourceDepartment,
},
});
}
return NextResponse.json({
message: '权限关联成功',
targetDepartment,
sourceDepartment,
});
} catch (error) {
console.error('[Department Permissions Link] Error:', error);
return NextResponse.json({ error: '关联权限失败' }, { status: 500 });
}
}
/**
* DELETE - 取消关联权限配置
*/
export async function DELETE(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const { searchParams } = new URL(request.url);
const department = searchParams.get('department');
if (!department) {
return NextResponse.json({ error: '部门名称不能为空' }, { status: 400 });
}
// 清除该部门所有权限配置的关联
await prisma.departmentMaterialPermission.updateMany({
where: {
department,
linkedToDepartment: { not: null },
},
data: {
linkedToDepartment: null,
},
});
return NextResponse.json({
message: '已取消关联',
department,
});
} catch (error) {
console.error('[Department Permissions Unlink] Error:', error);
return NextResponse.json({ error: '取消关联失败' }, { status: 500 });
}
}
export { retiredDepartmentPermissionWrite as POST, retiredDepartmentPermissionWrite as DELETE } from '@/lib/retired-department-permission-write'

View File

@ -0,0 +1,79 @@
/** @jest-environment node */
import { getServerSession } from 'next-auth'
import { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
import { POST as createDepartment } from '@/app/api/departments/route'
import { PUT as saveOrganizationLegacy } from '@/app/api/organization/material-permissions/route'
import { POST as saveLegacy } from './route'
import { POST as saveLegacyBatch } from './batch/route'
import { POST as copyLegacy } from './copy/route'
import { POST as linkLegacy, DELETE as unlinkLegacy } from './link/route'
import { POST as createLegacyOverride, DELETE as removeLegacyOverride } from './inherit/route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({
prisma: {
user: { findUnique: jest.fn() },
department: { findUnique: jest.fn(), create: jest.fn() },
departmentMaterialPermission: {
findMany: jest.fn().mockResolvedValue([]),
createMany: jest.fn(),
upsert: jest.fn(),
updateMany: jest.fn(),
deleteMany: jest.fn(),
},
},
}))
const writes = [
['部门权限', saveLegacy],
['部门权限批量保存', saveLegacyBatch],
['部门权限复制', copyLegacy],
['部门权限关联', linkLegacy],
['部门权限解除关联', unlinkLegacy],
['部门权限独立配置', createLegacyOverride],
['部门权限恢复继承', removeLegacyOverride],
['组织路径旧权限保存和恢复继承', saveOrganizationLegacy],
] as const
beforeEach(() => {
jest.clearAllMocks()
jest.mocked(getServerSession).mockResolvedValue({ user: { id: 'manager', role: 'SYSTEM_ADMIN' } })
jest.mocked(prisma.user.findUnique).mockResolvedValue({ isSuperAdmin: true } as never)
})
test.each(writes)('%s 返回 410 并指向权限管理', async (_name, handler) => {
const response = await handler()
expect(response.status).toBe(410)
expect(await response.json()).toEqual({
error: expect.stringContaining('权限管理'),
managementUrl: '/workspaces/governance/permissions',
})
for (const operation of Object.values(prisma.departmentMaterialPermission)) {
expect(operation).not.toHaveBeenCalled()
}
})
test('退役接口仍拒绝未登录账号和非超级管理员', async () => {
jest.mocked(getServerSession).mockResolvedValueOnce(null)
expect((await saveLegacy()).status).toBe(401)
jest.mocked(prisma.user.findUnique).mockResolvedValueOnce({ isSuperAdmin: false } as never)
expect((await saveOrganizationLegacy()).status).toBe(403)
})
test('新建部门只创建部门资料,不初始化旧权限表', async () => {
jest.mocked(prisma.department.findUnique).mockResolvedValueOnce(null)
jest.mocked(prisma.department.create).mockResolvedValueOnce({ id: 'new-dept', name: '新部门' } as never)
const response = await createDepartment(new NextRequest('http://localhost/api/departments', {
method: 'POST',
body: JSON.stringify({ name: '新部门' }),
}))
expect(response.status).toBe(201)
expect(prisma.department.create).toHaveBeenCalledTimes(1)
expect(prisma.departmentMaterialPermission.findMany).not.toHaveBeenCalled()
expect(prisma.departmentMaterialPermission.createMany).not.toHaveBeenCalled()
})

View File

@ -5,7 +5,6 @@ import { prisma } from '@/lib/prisma';
import {
getAllMaterialTypes,
getDepartmentPermissions,
createDefaultPermissionsForDepartment,
isSuperAdmin,
} from '@/lib/department-permission';
import { filterSelectableMaterialTypes } from '@/lib/material-type-options';
@ -90,72 +89,4 @@ export async function GET(request: NextRequest) {
}
}
/**
* POST - 更新权限配置
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const body = await request.json();
const { department, materialType, canView, canDownload, canShare, canDownloadSource } = body;
if (!department || !materialType) {
return NextResponse.json({ error: '部门名称和素材类型不能为空' }, { status: 400 });
}
// 检查是否有关联部门(如果有关联,不允许直接修改)
const existing = await prisma.departmentMaterialPermission.findUnique({
where: {
department_materialType: {
department,
materialType,
},
},
});
if (existing?.linkedToDepartment) {
return NextResponse.json(
{ error: '该部门已关联到其他部门,请先取消关联' },
{ status: 400 }
);
}
// 更新或创建权限配置
const permission = await prisma.departmentMaterialPermission.upsert({
where: {
department_materialType: {
department,
materialType,
},
},
update: {
canView: canView ?? false,
canDownload: canDownload ?? false,
canShare: canShare ?? true,
canDownloadSource: canDownloadSource ?? false,
linkedToDepartment: null, // 更新时清除关联
},
create: {
department,
materialType,
canView: canView ?? false,
canDownload: canDownload ?? false,
canShare: canShare ?? true,
canDownloadSource: canDownloadSource ?? false,
linkedToDepartment: null,
},
});
return NextResponse.json({ permission });
} catch (error) {
console.error('[Department Permissions] POST Error:', error);
return NextResponse.json({ error: '更新权限配置失败' }, { status: 500 });
}
}
export { retiredDepartmentPermissionWrite as POST } from '@/lib/retired-department-permission-write'

View File

@ -1,9 +1,8 @@
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { listExternalNotificationDeliveries } from '@/lib/external-auto-listing'
import { listExternalNotificationDeliveries, summarizeExternalNotificationDelivery } from '@/lib/external-auto-listing'
async function assertAdminPermission() {
const session = await getServerSession(authOptions)
@ -27,21 +26,26 @@ export async function GET(request: NextRequest) {
}
const { searchParams } = new URL(request.url)
const query = searchParams.get('q')?.trim()
if (query && query.length > 160) {
return NextResponse.json({ success: false, error: '检索内容过长' }, { status: 400 })
}
const rawLimit = searchParams.get('limit')
const parsedLimit = rawLimit ? Number(rawLimit) : undefined
const limit = Number.isFinite(parsedLimit) && parsedLimit! > 0 ? parsedLimit : undefined
const deliveries = await listExternalNotificationDeliveries({
canAccessOperationsG: await canAccessOperationsGMaterials(operatorUserId),
canAccessOperationsG: true,
status: searchParams.get('status') || undefined,
targetId: searchParams.get('targetId') || undefined,
materialId: searchParams.get('materialId') || undefined,
query,
limit,
})
return NextResponse.json({
success: true,
data: deliveries,
data: deliveries.map(summarizeExternalNotificationDelivery),
})
} catch (error) {
console.error('[admin/external-notification-deliveries] GET error:', error)

View File

@ -2,11 +2,10 @@ import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
import {
buildExternalNotificationTargetAdminView,
getExternalNotificationTargetById,
updateExternalNotificationTarget,
type ExternalNotificationTarget,
} from '@/lib/external-auto-listing'
async function assertAdminPermission() {
@ -23,50 +22,6 @@ async function assertAdminPermission() {
return null
}
function normalizeAuthConfigInput(
value: unknown,
existing: ExternalNotificationTarget,
nextAuthType: string,
): Record<string, string> | undefined {
const record =
value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null
if (!record) return undefined
if (nextAuthType === 'bearer') {
const token = String(record.token || '').trim()
return { token: token || String(existing.authConfig.token || '').trim() }
}
if (nextAuthType === 'header') {
const headerName = String(record.headerName || existing.authConfig.headerName || '').trim()
const headerValue = String(record.headerValue || '').trim()
|| String(existing.authConfig.headerValue || '').trim()
const nextConfig: Record<string, string> = {}
if (headerName) nextConfig.headerName = headerName
if (headerValue) nextConfig.headerValue = headerValue
return nextConfig
}
return {}
}
function toErrorResponse(error: unknown) {
const message = error instanceof Error ? error.message : '服务器错误'
const status =
message === '通知目标不存在'
? 404
: message.includes('不能为空') ||
message.includes('格式不正确') ||
message.includes('仅支持') ||
message.includes('必须提供')
? 400
: 500
return NextResponse.json({ success: false, error: message }, { status })
}
export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } },
@ -83,28 +38,30 @@ export async function PUT(
}
const body = await request.json()
const existing = await getExternalNotificationTargetById(targetId)
if (!existing) {
return NextResponse.json({ success: false, error: '通知目标不存在' }, { status: 404 })
}
const nextAuthType =
typeof body?.authType === 'string' ? body.authType : existing.authType
const target = await updateExternalNotificationTarget(targetId, {
name: typeof body?.name === 'string' ? body.name : undefined,
callbackUrl: typeof body?.callbackUrl === 'string' ? body.callbackUrl : undefined,
isActive: typeof body?.isActive === 'boolean' ? body.isActive : undefined,
authType: typeof body?.authType === 'string' ? body.authType : undefined,
authConfig: normalizeAuthConfigInput(body?.authConfig, existing, nextAuthType),
authConfig:
body?.authConfig && typeof body.authConfig === 'object' && !Array.isArray(body.authConfig)
? body.authConfig
: undefined,
eventTypes: Array.isArray(body?.eventTypes) ? body.eventTypes : undefined,
})
if (!target) return NextResponse.json({ success: false, error: '通知目标不存在' }, { status: 404 })
return NextResponse.json({
success: true,
data: buildExternalNotificationTargetAdminView(target),
message: '通知目标更新成功',
})
} catch (error) {
console.error('[admin/external-notification-targets/[id]] PUT error:', error)
return toErrorResponse(error)
console.error('[admin/external-notification-targets/[id]] PUT error:', error instanceof Error ? error.name : 'UnknownError')
if (error instanceof AutoListingCallbackError) {
return NextResponse.json({ success: false, error: error.message }, { status: error.status })
}
return NextResponse.json({ success: false, error: '服务器错误' }, { status: 500 })
}
}

View File

@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
import {
buildExternalNotificationTargetAdminView,
createExternalNotificationTarget,
@ -23,16 +24,9 @@ async function assertAdminPermission() {
}
function toErrorResponse(error: unknown) {
const message = error instanceof Error ? error.message : '服务器错误'
const status =
message.includes('不能为空') ||
message.includes('格式不正确') ||
message.includes('仅支持') ||
message.includes('必须提供')
? 400
: 500
return NextResponse.json({ success: false, error: message }, { status })
return error instanceof AutoListingCallbackError
? NextResponse.json({ success: false, error: error.message }, { status: error.status })
: NextResponse.json({ success: false, error: '服务器错误' }, { status: 500 })
}
export async function GET(request: NextRequest) {
@ -48,7 +42,7 @@ export async function GET(request: NextRequest) {
data: targets.map(buildExternalNotificationTargetAdminView),
})
} catch (error) {
console.error('[admin/external-notification-targets] GET error:', error)
console.error('[admin/external-notification-targets] GET error:', error instanceof Error ? error.name : 'UnknownError')
return toErrorResponse(error)
}
}
@ -79,7 +73,7 @@ export async function POST(request: NextRequest) {
message: '通知目标创建成功',
})
} catch (error) {
console.error('[admin/external-notification-targets] POST error:', error)
console.error('[admin/external-notification-targets] POST error:', error instanceof Error ? error.name : 'UnknownError')
return toErrorResponse(error)
}
}

View File

@ -1,4 +1,4 @@
import { canAccessOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access'
import { canUseOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access'
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
@ -53,7 +53,7 @@ export async function GET(request: NextRequest) {
const endDate = searchParams.get('endDate')
const keyword = normalizeKeyword(searchParams.get('keyword'))
const excludedIds = await canAccessOperationsGMaterials((session.user as any).id) ? [] : await getOperationsGMaterialIds()
const excludedIds = await canUseOperationsGMaterials((session.user as any).id) ? [] : await getOperationsGMaterialIds()
const materialLogWhere: any = { ...(excludedIds.length ? { materialId: { notIn: excludedIds } } : {}) }
const downloadLogWhere: any = { ...(excludedIds.length ? { materialId: { notIn: excludedIds } } : {}) }

View File

@ -1,10 +1,11 @@
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { buildMaterialPrivacyWhere, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { isSystemAdmin } from '@/lib/department-permission'
import { isSuperAdmin, isSystemAdmin } from '@/lib/department-permission'
import { createMaterialLog } from '@/lib/material-log'
import { enqueueMaterialPurge, ensureMaterialPurgeWorkerStarted, MaterialPurgeError } from '@/lib/material-purge'
@ -25,19 +26,18 @@ export async function POST(request: NextRequest) {
const session = await getServerSession(authOptions)
// 使用统一的权限检查函数(与单条删除保持一致)
if (!session || !isSystemAdmin((session.user as any)?.role)) {
const operatorId = (session?.user as any)?.id
if (!session || (!isSystemAdmin(session.user?.role) && !(await isSuperAdmin(operatorId)))) {
return NextResponse.json({ error: '无权限,需要系统管理员权限' }, { status: 403 })
}
if (!operatorId) {
return NextResponse.json({ error: '缺少操作人信息' }, { status: 401 })
}
const { ids, permanent } = await request.json()
if (permanent !== undefined && typeof permanent !== 'boolean') {
return NextResponse.json({ error: '删除方式无效' }, { status: 400 })
}
const operatorId = (session.user as any).id
if (!operatorId) {
return NextResponse.json({ error: '缺少操作人信息' }, { status: 401 })
}
// 校验 ids 是数组且非空
if (!Array.isArray(ids) || ids.length === 0 || ids.length > 100) {
@ -63,15 +63,19 @@ export async function POST(request: NextRequest) {
// 查询素材(需要处理任务号)
const materials = await prisma.material.findMany({
where: { id: { in: ids } },
select: { id: true, taskNo: true, productModel: true, materialType: true, accessScope: true }
select: { id: true, taskNo: true, productModel: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT }
})
if (materials.length === 0) {
return NextResponse.json({ error: '未找到要删除的素材' }, { status: 404 })
}
if (materials.some((material) => material.accessScope === 'operations_g') && !(await canAccessOperationsGMaterials(operatorId))) {
return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 })
if (materials.some(isRestrictedMaterial)) {
const privacyWhere = await buildMaterialPrivacyWhere(operatorId)
const materialIds = materials.map((material) => material.id)
if (privacyWhere.OR && await prisma.material.count({ where: { id: { in: materialIds }, ...privacyWhere } }) !== materialIds.length) {
return NextResponse.json({ error: '无权限操作部分素材' }, { status: 403 })
}
}
const deletedAt = new Date()

View File

@ -1,17 +1,18 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isSystemAdmin } from '@/lib/department-permission'
import { isSuperAdmin, isSystemAdmin } from '@/lib/department-permission'
import { prisma } from '@/lib/prisma'
import { canAccessOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access'
import { canUseOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access'
import { ensureMaterialPurgeWorkerStarted, MaterialPurgeError, retryMaterialPurge, toPurgeJobView } from '@/lib/material-purge'
export const dynamic = 'force-dynamic'
async function operator() {
const session = await getServerSession(authOptions)
if (!session?.user || !(session.user as any).id) return null
return isSystemAdmin((session.user as any).role) ? (session.user as any).id as string : null
const user = session?.user
if (!user?.id) return null
return isSystemAdmin(user.role) || await isSuperAdmin(user.id) ? user.id : null
}
export async function GET(request: NextRequest) {
@ -22,7 +23,7 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: '清理任务无效' }, { status: 400 })
}
try {
const excludedIds = await canAccessOperationsGMaterials(operatorId) ? [] : await getOperationsGMaterialIds()
const excludedIds = await canUseOperationsGMaterials(operatorId) ? [] : await getOperationsGMaterialIds()
const scopeWhere = excludedIds.length ? { materialId: { notIn: excludedIds } } : {}
const [pending, tracked] = await Promise.all([
prisma.materialPurgeJob.findMany({ where: { ...scopeWhere, status: { not: 'completed' } }, orderBy: { createdAt: 'asc' }, take: 100 }),

View File

@ -1,4 +1,4 @@
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { createHash, timingSafeEqual } from 'crypto'
import { lstat, realpath } from 'fs/promises'
@ -292,7 +292,7 @@ export async function POST(request: NextRequest) {
throw new RegeneratePdfPreviewInputError('素材不存在', 404)
}
const session = isRestrictedMaterial(material) ? await getServerSession(authOptions) : null
if (isRestrictedMaterial(material) && !(await canAccessOperationsGMaterials((session?.user as any)?.id))) {
if (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) {
throw new RegeneratePdfPreviewInputError('无权限操作此素材', 403)
}
if (material.materialType !== '品牌VI灵感') {

View File

@ -1,4 +1,4 @@
import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access'
import { buildMaterialPrivacyWhere } from '@/lib/task-detail-privacy'
/**
* 回收站 API - 获取已删除的素材
*
@ -9,13 +9,15 @@ import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { isSuperAdmin, isSystemAdmin } from '@/lib/department-permission'
import { rewriteMaterialStorageUrlsForClient } from '@/lib/url-rewrite'
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || (session.user as any).role !== 'ADMIN') {
const user = session?.user
if (!user?.id || (!isSystemAdmin(user.role) && !(await isSuperAdmin(user.id)))) {
return NextResponse.json(
{ error: '无权限' },
{ status: 403 }
@ -27,7 +29,7 @@ export async function GET(req: NextRequest) {
const pageSize = parseInt(searchParams.get('pageSize') || '20')
const skip = (page - 1) * pageSize
const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id)
const scopeWhere = await buildMaterialPrivacyWhere(user.id)
// 获取已删除的素材
const [deletedMaterials, total] = await Promise.all([

View File

@ -21,7 +21,6 @@ export async function GET() {
role: true,
isActive: true, // 保留,向后兼容
status: true, // 新增:用户状态(阶段一)
canDownload: true,
department: true, // 保留,向后兼容
departmentId: true, // 新增:部门ID(阶段二)
managedDepartment: true, // 管理员负责的部门

View File

@ -0,0 +1,35 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { POST } from './route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/department-permission', () => ({ isSystemAdmin: (role: string) => role === 'SYSTEM_ADMIN' }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { update: jest.fn() } } }))
test.each([
[{ isActive: false }, 'suspended'],
[{ status: 'pending' }, 'suspended'],
[{ status: 'archived' }, 'archived'],
[{ isActive: true }, 'active'],
])('管理员设置用户状态 %j → %s', async (input, state) => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: 'operator', role: 'SYSTEM_ADMIN' } })
const response = await POST(new NextRequest('http://example.test/api/admin/users/toggle-active', {
method: 'POST',
body: JSON.stringify({ userId: 'target', ...input }),
}))
expect(response.status).toBe(200)
expect(prisma.user.update).toHaveBeenLastCalledWith({
where: { id: 'target' },
data: {
status: state,
isActive: state === 'active',
archivedAt: state === 'archived' ? expect.any(Date) : null,
statusChangedAt: expect.any(Date),
statusChangedBy: 'operator',
},
})
})

View File

@ -38,7 +38,7 @@ export async function POST(request: NextRequest) {
{ status: 400 }
);
}
targetStatus = status;
targetStatus = status === 'pending' ? 'suspended' : status;
targetIsActive = status === 'active';
} else if (isActive !== undefined) {
// 旧格式:使用 isActive 参数(向后兼容)
@ -49,7 +49,7 @@ export async function POST(request: NextRequest) {
);
}
targetIsActive = isActive;
targetStatus = isActive ? 'active' : 'pending';
targetStatus = isActive ? 'active' : 'suspended';
} else {
return NextResponse.json(
{ error: '缺少参数:需要 isActive 或 status' },
@ -73,27 +73,19 @@ export async function POST(request: NextRequest) {
);
}
// 双写:同时更新 status 和 isActive
const updateData: any = {
isActive: targetIsActive, // 旧字段(向后兼容)
status: targetStatus, // 新字段(阶段一新增)
};
// 如果状态为 archived,设置 archivedAt
if (targetStatus === 'archived') {
updateData.archivedAt = new Date();
} else if (targetStatus !== 'archived') {
// 如果从 archived 状态恢复,清除 archivedAt
updateData.archivedAt = null;
}
const now = new Date()
await prisma.user.update({
where: { id: userId },
data: updateData,
data: {
isActive: targetIsActive,
status: targetStatus,
archivedAt: targetStatus === 'archived' ? now : null,
statusChangedAt: now,
statusChangedBy: sessionUserId,
},
});
const statusMessages: Record<string, string> = {
'pending': '用户已设置为待激活',
'active': '用户已激活',
'suspended': '用户已暂停',
'archived': '用户已归档',

View File

@ -1,82 +1,13 @@
// 切换用户下载权限API
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSystemAdmin } from '@/lib/department-permission';
import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isSystemAdmin } from '@/lib/department-permission'
// POST - 切换用户下载权限(仅管理员)
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user || !(session.user as any).id) {
return NextResponse.json(
{ error: '未登录' },
{ status: 401 }
);
}
// 给还在使用旧页面的管理员返回配置位置,旧字段保留供回滚兼容。
export async function POST() {
const session = await getServerSession(authOptions)
if (!session?.user?.id) return NextResponse.json({ error: '请先登录' }, { status: 401 })
if (!isSystemAdmin(session.user.role)) return NextResponse.json({ error: '只有系统管理员可以管理下载权限' }, { status: 403 })
const userRole = (session.user as any).role;
if (!isSystemAdmin(userRole)) {
return NextResponse.json(
{ error: '无权限' },
{ status: 403 }
);
}
const { userId } = await request.json();
if (!userId) {
return NextResponse.json(
{ error: '缺少用户ID' },
{ status: 400 }
);
}
const sessionUserId = (session.user as any).id;
// 不能修改自己的下载权限
if (userId === sessionUserId) {
return NextResponse.json(
{ error: '不能修改自己的下载权限' },
{ status: 400 }
);
}
// 检查用户是否存在
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
return NextResponse.json(
{ error: '用户不存在' },
{ status: 404 }
);
}
// 不能修改管理员的下载权限
if (user.role === 'ADMIN') {
return NextResponse.json(
{ error: '不能修改管理员的下载权限' },
{ status: 400 }
);
}
// 切换下载权限
const updatedUser = await prisma.user.update({
where: { id: userId },
data: { canDownload: !user.canDownload },
});
return NextResponse.json({
message: updatedUser.canDownload ? '已开启下载权限' : '已关闭下载权限',
canDownload: updatedUser.canDownload,
});
} catch (error) {
console.error('Error toggling download permission:', error);
return NextResponse.json(
{ error: '操作失败' },
{ status: 500 }
);
}
return NextResponse.json({ error: '请在「权限管理」中按素材类型配置下载权限' }, { status: 410 })
}

View File

@ -2,6 +2,7 @@ import { getServerSession } from 'next-auth'
import { createReadStream } from 'fs'
import { stat } from 'fs/promises'
import { Readable } from 'stream'
import path from 'path'
import { prisma } from '@/lib/prisma'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
@ -80,7 +81,7 @@ describe('brand knowledge file route', () => {
const response = await GET(new Request('http://localhost/file'), { params: { id: 'knowledge-1' } })
expect(response.status).toBe(200)
expect(createReadStream).toHaveBeenCalledWith('/uploads/brand-knowledge/guide.pdf')
expect(createReadStream).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/guide.pdf'))
expect(prisma.brandKnowledge.updateMany).not.toHaveBeenCalled()
expect(await response.text()).toBe('test')
expect(prisma.brandKnowledge.updateMany).toHaveBeenCalledWith({

View File

@ -1,5 +1,6 @@
import { getServerSession } from 'next-auth'
import { readFile, stat } from 'fs/promises'
import path from 'path'
import { prisma } from '@/lib/prisma'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
@ -64,7 +65,7 @@ describe('brand knowledge preview route', () => {
)
expect(response.status).toBe(200)
expect(readFile).toHaveBeenCalledWith('/uploads/brand-knowledge/part-002.webp')
expect(readFile).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/part-002.webp'))
expect(response.headers.get('content-type')).toBe('image/webp')
await expect(response.text()).resolves.toBe('slice-02')
})
@ -103,7 +104,7 @@ describe('brand knowledge preview route', () => {
const response = await GET(new Request('http://localhost/preview'), { params: { id: 'knowledge-1' } })
expect(response.status).toBe(200)
expect(readFile).toHaveBeenCalledWith('/uploads/brand-knowledge/legacy.png')
expect(readFile).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/legacy.png'))
expect(response.headers.get('content-type')).toBe('image/png')
})
})

View File

@ -1,3 +1,5 @@
/** @jest-environment node */
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { assertBrandCenterDashboardAccess } from '@/lib/brand-center-dashboard-access'
@ -14,7 +16,7 @@ jest.mock('@/lib/brand-center-dashboard-access', () => ({
jest.mock('@/lib/department-permission', () => ({ isSuperAdmin: jest.fn(async () => false) }))
jest.mock('@/lib/prisma', () => ({
prisma: {
brandKnowledge: { findMany: jest.fn(), findFirst: jest.fn(), updateMany: jest.fn() },
brandKnowledge: { count: jest.fn().mockResolvedValue(1), findMany: jest.fn(), findFirst: jest.fn(), updateMany: jest.fn() },
brandKnowledgeLike: { upsert: jest.fn(), deleteMany: jest.fn(), count: jest.fn() },
brandKnowledgeFavorite: { upsert: jest.fn(), deleteMany: jest.fn() },
},

View File

@ -1,5 +1,6 @@
import { getServerSession } from 'next-auth'
import { link, rename, unlink, writeFile } from 'fs/promises'
import path from 'path'
import { prisma } from '@/lib/prisma'
import { prepareBrandKnowledgePreview } from '@/lib/brand-knowledge-preview'
import { validateBrandKnowledgeUploadedPreviewSlices } from '@/lib/brand-knowledge-preview'
@ -78,7 +79,7 @@ const previewFile = {
arrayBuffer: async () => Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]).buffer,
}
function uploadRequest() {
function uploadRequest(originalFileName = 'knowledge.pdf') {
const values = new Map<string, unknown>([
['title', '长图规范'],
['knowledgeType', '主图模板'],
@ -86,7 +87,7 @@ function uploadRequest() {
['productCategoryName', '衣柜'],
['uploadId', 'upload-1'],
['existingFilePath', '/uploads/temp/upload-1/merged-knowledge.pdf'],
['originalFileName', 'knowledge.pdf'],
['originalFileName', originalFileName],
['fileSize', '4'],
['previewImage', previewFile],
])
@ -234,6 +235,24 @@ describe('brand knowledge upload route', () => {
}))
})
test('stores the full display name for a source with a short storage path', async () => {
const fileName = `${'组合款知识'.repeat(22)}...pdf`
jest.mocked(resolveOwnedMergedUpload).mockResolvedValueOnce({
uploadId: 'upload-1',
filePath: '/uploads/temp/upload-1/merged-file.pdf',
session: {
fileName, fileSize: 4, totalChunks: 1, chunks: new Map(),
createdAt: Date.now(), userId: 'user-1', uploadPurpose: 'brand-knowledge',
},
})
const response = await POST(uploadRequest(fileName))
expect(response.status).toBe(201)
expect(prisma.brandKnowledge.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ fileName, filePath: 'uploads/brand-knowledge/source-upload-1.pdf' }),
}))
})
test('stores ordered WebP slices and keeps the first slice as the card preview', async () => {
const response = await POST(uploadRequest())
const call = (prisma.brandKnowledge.create as jest.Mock).mock.calls[0][0]
@ -266,8 +285,8 @@ describe('brand knowledge upload route', () => {
expect(response.status).toBe(500)
expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/source-upload-1.pdf')
expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/upload-1-preview-part-001.webp')
expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/upload-1-preview-part-002.webp')
expect(unlink).toHaveBeenCalledWith(path.join('/uploads', 'brand-knowledge', 'upload-1-preview-part-001.webp'))
expect(unlink).toHaveBeenCalledWith(path.join('/uploads', 'brand-knowledge', 'upload-1-preview-part-002.webp'))
expect(cleanupConsumedUploadSession).not.toHaveBeenCalled()
expect(errorSpy).toHaveBeenCalled()
expect(releaseRequestSlot).toHaveBeenCalledTimes(1)

View File

@ -10,6 +10,7 @@ import { prisma } from '@/lib/prisma'
import { isSuperAdmin } from '@/lib/department-permission'
import { getUploadRootDir } from '@/lib/upload-paths'
import { ensureSafeDirectoryWithinRoot, isPathFreeOfSymbolicLinks, normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security'
import { normalizeUploadFileName } from '@/lib/upload-file-name'
import { assertBoundedMultipartHeaders, assertMultipartFiles } from '@/lib/multipart-request-guard'
import { boundedMultipartRequestLimiter, getBoundedMultipartFailure } from '@/lib/multipart-route-limits'
import { prepareBrandKnowledgePreview, validateBrandKnowledgeUploadedPreviewSlices } from '@/lib/brand-knowledge-preview'
@ -286,7 +287,7 @@ export async function POST(request: Request) {
const productCategoryName = normalizeText(formData.get('productCategoryName'), 80)
uploadId = normalizeText(formData.get('uploadId'), 128)
const existingFilePath = normalizeText(formData.get('existingFilePath'), 4096)
const safeOriginalName = normalizeSafeFileName(normalizeText(formData.get('originalFileName'), 255))
const safeOriginalName = normalizeUploadFileName(formData.get('originalFileName'))
const declaredFileSize = Number(normalizeText(formData.get('fileSize'), 20))
if (!title) return NextResponse.json({ success: false, error: '请填写知识标题' }, { status: 400, headers: PRIVATE_HEADERS })
if (!KNOWLEDGE_TYPES.has(knowledgeType)) return NextResponse.json({ success: false, error: '知识类型不合法' }, { status: 400, headers: PRIVATE_HEADERS })
@ -355,7 +356,7 @@ export async function POST(request: Request) {
)
}
if (
normalizeSafeFileName(ownedMergedUpload.session.fileName) !== safeOriginalName
normalizeUploadFileName(ownedMergedUpload.session.fileName) !== safeOriginalName
|| ownedMergedUpload.session.fileSize !== declaredFileSize
|| ownedMergedUpload.session.uploadPurpose !== 'brand-knowledge'
) {

View File

@ -50,4 +50,14 @@ describe('GET /api/department-dashboard/core-metrics/on-time-delivery', () => {
expect(response.status).toBe(400)
await expect(response.json()).resolves.toEqual({ success: false, error: 'month格式应为YYYY-MM' })
})
it('免扣来源失败保留503及私有不缓存头,恢复后可重新读取', async () => {
;(getOnTimeDeliverySummary as jest.Mock).mockRejectedValueOnce(new DingWorkflowMetricApiError('交付免扣配置暂时无法读取,请稍后重试。', 503))
const unavailable = await GET(new Request('https://sc.jiansun.vip/api/department-dashboard/core-metrics/on-time-delivery'))
expect(unavailable.status).toBe(503)
expect(unavailable.headers.get('cache-control')).toContain('private, no-store')
const restored = await GET(new Request('https://sc.jiansun.vip/api/department-dashboard/core-metrics/on-time-delivery'))
expect(restored.status).toBe(200)
expect(restored.headers.get('cache-control')).toContain('private, no-store')
})
})

View File

@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { createDefaultPermissionsForDepartment, isSystemAdmin } from '@/lib/department-permission';
import { isSystemAdmin } from '@/lib/department-permission';
// GET /api/departments - 获取部门列表
export async function GET(request: NextRequest) {
@ -163,14 +163,6 @@ export async function POST(request: NextRequest) {
data: createData,
});
// 自动创建默认权限配置
try {
await createDefaultPermissionsForDepartment(name);
} catch (error) {
console.error('Error creating default permissions for department:', error);
// 不阻止部门创建,只记录错误
}
return NextResponse.json(department, { status: 201 });
} catch (error: any) {
console.error('Error creating department:', error);

View File

@ -0,0 +1,89 @@
/** @jest-environment node */
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
import { getDesktopDelivery } from '@/lib/desktop-client/deliveries'
import { requireDesktop } from '@/lib/desktop-client/service'
import { FinishedWebSsoError, issueFinishedWebLink } from '@/lib/finished-web-sso'
import { GET, POST } from './route'
jest.mock('next-auth', () => ({}))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
jest.mock('@/lib/desktop-client/deliveries', () => ({ getDesktopDelivery: jest.fn() }))
jest.mock('@/lib/employee-directory', () => ({}))
jest.mock('@/lib/finished-web-sso', () => ({
...jest.requireActual('@/lib/finished-web-sso'),
issueFinishedWebLink: jest.fn(),
}))
const path = ['deliveries', 'owned-project', 'detail', 'owned-material', 'finished-web']
const receipt = {
requestId: 'owned-request', materialId: 'owned-material', materialType: '自动上架-详情',
state: 'completed' as const, listingStatus: null,
}
const link = {
url: 'https://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link',
expiresAt: '2027-01-02T07:04:20.518Z',
user: { id: 123, username: 'operator', name: '测试账号', role: 'operator' },
}
function request(method: 'POST' | 'GET' = 'POST', segments = path) {
const input = new Request('http://localhost:3000/api/desktop/' + segments.join('/'), {
method, headers: { Authorization: 'Bearer desktop-session-placeholder' },
})
return (method === 'POST' ? POST : GET)(input, { params: { path: segments } })
}
beforeEach(() => {
jest.resetAllMocks()
jest.mocked(requireDesktop).mockResolvedValue({
id: 'session', account: { id: 'owner', name: '实名' }, expiresAt: new Date(), isSuperAdmin: false,
})
jest.mocked(getDesktopDelivery).mockResolvedValue(receipt)
jest.mocked(issueFinishedWebLink).mockResolvedValue(link)
})
test('桌面会话只能为当前账户的指定详情交付换链', async () => {
const response = await request()
expect(jest.mocked(requireDesktop).mock.calls[0][0].headers.get('authorization')).toBe('Bearer desktop-session-placeholder')
expect(getDesktopDelivery).toHaveBeenCalledWith('owner', 'owned-project', 'detail')
expect(issueFinishedWebLink).toHaveBeenCalledWith('owner')
expect(response.status).toBe(200)
expect(response.headers.get('cache-control')).toBe('private, no-store')
expect(await response.json()).toEqual(link)
})
test('无效或已撤销的 Bearer 会话无法进入交付查询', async () => {
jest.mocked(requireDesktop).mockRejectedValue(new DesktopClientError('请重新登录', 401, 'session_expired'))
expect((await request()).status).toBe(401)
expect(getDesktopDelivery).not.toHaveBeenCalled()
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test('无权访问项目时不签发', async () => {
jest.mocked(getDesktopDelivery).mockRejectedValue(new DesktopClientError('项目不存在或无权访问', 404, 'not_found'))
expect((await request()).status).toBe(404)
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test.each([
['无交付', null],
['已删除', { ...receipt, state: 'removed' as const }],
['成品编号不一致', { ...receipt, materialId: 'other-material' }],
])('%s时不签发', async (_label, value) => {
jest.mocked(getDesktopDelivery).mockResolvedValue(value)
expect((await request()).status).toBe(404)
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test('GET 和非详情类型均不能触发签发', async () => {
expect((await request('GET')).status).toBe(404)
expect((await request('POST', [path[0], path[1], 'video', path[3], path[4]])).status).toBe(404)
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test('上游 401 与客户端会话失效有不同错误码', async () => {
jest.mocked(issueFinishedWebLink).mockRejectedValue(new FinishedWebSsoError('工作台拒绝了服务授权', 401, 'finished_web_upstream'))
const response = await request()
expect(response.status).toBe(401)
expect(await response.json()).toEqual({ error: '工作台拒绝了服务授权', code: 'finished_web_upstream' })
})

View File

@ -3,6 +3,7 @@ import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { desktopAssert, desktopPortal, DesktopClientError, DESKTOP_CLIENT_ID } from '@/lib/desktop-client/contract.mjs'
import {isAllowedCorsOrigin} from '@/lib/cors-origin'
import {isSuperAdmin} from '@/lib/department-permission'
import { approveDesktop, desktopUser, exchangeDesktop, getDesktopAsset, getDesktopProject, listDesktopDevices, listDesktopProjects, putDesktopAsset, putDesktopProject, requireDesktop, revokeDesktop, deleteDesktopProject } from '@/lib/desktop-client/service'
export const runtime='nodejs'
export const dynamic='force-dynamic'
@ -33,8 +34,25 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
else throw new DesktopClientError('接口不存在',404)
}else{
const auth=await requireDesktop(request),ownerId=auth.account.id
if(parts[0]==='session'&&parts.length===1){if(method==='GET')value={account:auth.account,expiresAt:auth.expiresAt};else if(method==='DELETE'){await revokeDesktop(auth.id,ownerId);value={revoked:true}}else throw new DesktopClientError('接口不存在',404)}
if(parts[0]==='session'&&parts.length===1){if(method==='GET')value={account:{...auth.account,isSuperAdmin:auth.isSuperAdmin},expiresAt:auth.expiresAt};else if(method==='DELETE'){await revokeDesktop(auth.id,ownerId);value={revoked:true}}else throw new DesktopClientError('接口不存在',404)}
else if(parts[0]==='knowledge'&&parts[1]==='session'&&parts.length===2&&method==='GET'){
const {issueKnowledgeSession}=await import('@/lib/desktop-client/knowledge-session')
value=issueKnowledgeSession(ownerId,auth.expiresAt,auth.isSuperAdmin)
}
else if(parts[0]==='product-platform'&&parts[1]==='spu'&&parts.length===2&&method==='GET'){
const {desktopProductPlatformSpu}=await import('@/lib/desktop-client/product-platform')
value=await desktopProductPlatformSpu(url.searchParams)
}
else if(parts[0]==='test-product-presets'&&parts.length===1&&method==='GET'){
desktopAssert(await isSuperAdmin(ownerId),'无权读取测试商品资料',403,'forbidden')
const {desktopTestProductPresets}=await import('@/lib/desktop-client/test-presets')
value=desktopTestProductPresets()
}
else if(parts[0]==='capabilities'&&parts.length===1&&method==='GET')value={documentVersions:[1,2,3],projectDeletion:true,nativeFiles:{streaming:true,maxFileBytes:536870912,maxProjectBytes:1073741824,source:'sha256',range:true},catalog:{brands:true,materials:true,products:true},modelExecution:'client',creationTasks:{version:1,leases:true,recovery:'read-only'}}
else if(parts[0]==='feedback'&&parts.length===1&&method==='POST'){
const {submitDesktopFeedback}=await import('@/lib/desktop-client/feedback')
value=await submitDesktopFeedback(ownerId,(await body(request,262144)).toString('utf8'))
}
else if(parts[0]==='tasks'){
const tasks=await import('@/lib/desktop-client/tasks')
if(parts.length===2&&method==='GET')value=await tasks.listCreationTasks(auth,parts[1])
@ -44,6 +62,10 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
else if(parts.length===3&&method==='PUT')value=await tasks.checkpointCreationTask(auth,parts[1],parts[2],JSON.parse((await body(request,900000)).toString()))
else throw new DesktopClientError('接口不存在',404)
}
else if(parts.length===1&&parts[0]==='template-packs'&&method==='GET'){
const {desktopTemplateCatalog}=await import('@/lib/desktop-client/template-packs')
value=desktopTemplateCatalog(url.searchParams)
}
else if(parts[0]==='catalog'&&method==='GET'){
const catalog=await import('@/lib/desktop-client/catalog')
if(parts.length===2&&parts[1]==='brands')value=await catalog.desktopBrands(url.searchParams)
@ -65,11 +87,34 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
for(const option of config.modelOptions.copy){const resolved=await resolveAiModel('copy',option.value);const base=new URL(resolved.binding.baseUrl);if(base.hostname==='api.vip98k.com'&&base.protocol==='https:'&&['openai-chat','anthropic-messages'].includes(resolved.protocol.id))models.push({key:option.value,id:resolved.binding.modelId,label:option.label,protocol:resolved.protocol.id,path:resolved.protocol.path})}
value={models}
}
else if(parts[0]==='deliveries'){
const delivery = await import('@/lib/desktop-client/deliveries')
if(method==='POST'&&parts.length===1){
const reauthorize=async()=>{
const current=await requireDesktop(request)
desktopAssert(current.account.id===ownerId&&current.id===auth.id,'客户端授权已变更,请重新登录',401,'session_expired')
return current.account
}
value=await delivery.createDesktopDelivery(ownerId,JSON.parse((await body(request)).toString()),reauthorize)
}
else if(method==='GET'&&parts.length===3)value=await delivery.getDesktopDelivery(ownerId,parts[1],parts[2]) || {delivery:null}
else if(method==='POST'&&parts.length===5&&parts[2]==='detail'&&parts[4]==='finished-web'){
const receipt = await delivery.getDesktopDelivery(ownerId, parts[1], 'detail')
desktopAssert(receipt?.state === 'completed' && receipt.materialId === parts[3], '该详情成品不存在或无权访问', 404, 'not_found')
const { issueFinishedWebLink } = await import('@/lib/finished-web-sso')
value = await issueFinishedWebLink(ownerId)
}
else throw new DesktopClientError('接口不存在',404)
}
else if(parts[0]==='projects'){
if(method==='GET'&&parts.length===1)value=await listDesktopProjects(ownerId,url.searchParams.get('cursor'))
else if(parts.length===3&&method==='GET')value=await getDesktopProject(ownerId,parts[1],parts[2])
else if(parts.length===3&&method==='GET'){
const result=await getDesktopProject(ownerId,parts[1],parts[2])
const author={authorId:ownerId,authorName:auth.account.name}
value={...result,project:{...result.project,...author,document:{...result.project.document,...author}}}
}
else if(parts.length===3&&method==='DELETE')value=await deleteDesktopProject(ownerId,parts[1],parts[2],JSON.parse((await body(request,1000)).toString()))
else if(parts.length===3&&parts[1]==='desktop'&&method==='PUT')value=await putDesktopProject(ownerId,parts[2],JSON.parse((await body(request)).toString()))
else if(parts.length===3&&parts[1]==='desktop'&&method==='PUT')value=await putDesktopProject(auth.account,parts[2],JSON.parse((await body(request)).toString()))
else if(parts.length===5&&parts[1]==='desktop'&&parts[3]==='native'){
const native=await import('@/lib/desktop-client/native-storage')
const reauthorize=async()=>{const current=await requireDesktop(request);desktopAssert(current.account.id===ownerId,'账户已变更',401);return current}
@ -88,6 +133,7 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
}catch(error){
const known=error instanceof DesktopClientError||Boolean(error&&typeof error==='object'&&'status'in error)
const item=error as {status?:number;code?:string;message?:string}
if(!known)console.error('[desktop-proxy] unexpected error',{status:503,route:'/api/desktop/[...path]'})
return NextResponse.json({error:known?item.message:'客户端服务暂不可用,请稍后重试',code:known?item.code||'invalid_request':'service_unavailable'},{status:known?item.status||400:503,headers})
}
}

View File

@ -0,0 +1,22 @@
import { NextResponse } from 'next/server'
import { requireDesktop } from '@/lib/desktop-client/service'
import { DesktopClientError, desktopAssert } from '@/lib/desktop-client/contract.mjs'
import { readRelease, signReleaseDownload, validVersion } from '@/lib/desktop-client/client-release'
import { headers, releaseError, releaseQuery } from '../shared'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export async function GET(request: Request) {
try {
await requireDesktop(request)
const { query, channel } = releaseQuery(request)
const version = query.get('version')
desktopAssert(query.getAll('version').length === 1 && validVersion(version), '下载安装包的版本无效', 400, 'invalid_request')
const release = await readRelease(channel, version!)
if (!release) throw new DesktopClientError('客户端版本不存在', 404, 'not_found')
return NextResponse.redirect(await signReleaseDownload(channel, release), { status: 302, headers })
} catch (error) {
return releaseError(error)
}
}

View File

@ -0,0 +1,38 @@
import { createHash } from 'node:crypto'
import { NextResponse } from 'next/server'
import { requireDesktop } from '@/lib/desktop-client/service'
import { desktopAssert } from '@/lib/desktop-client/contract.mjs'
import { readRelease, readReleaseJson, releasePrefix, semver, validVersion } from '@/lib/desktop-client/client-release'
import { headers, releaseError, releaseQuery } from './shared'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export async function GET(request: Request) {
try {
await requireDesktop(request)
const { query, channel } = releaseQuery(request)
const current = query.get('current')
desktopAssert(query.getAll('current').length === 1 && validVersion(current), '客户端版本无效', 400, 'invalid_request')
const pointer = await readReleaseJson<{ version: string }>(`${releasePrefix(channel)}/latest.json`)
let value: object = { latest: null, updateAvailable: false }
if (pointer) {
if (!validVersion(pointer.version)) throw new Error('发布指针无效')
const release = await readRelease(channel, pointer.version)
if (!release) throw new Error('发布指针对应的清单不存在')
const { version, builtAt, publishedAt, notes, minimumVersion, file } = release
value = {
latest: { version, channel, builtAt, publishedAt, notes, minimumVersion, file: { name: file.name, size: file.size, sha256: file.sha256 } },
updateAvailable: semver.gt(version, current!),
mandatory: semver.gt(minimumVersion, current!),
}
}
const etag = `"${createHash('sha256').update(JSON.stringify(value)).digest('hex')}"`
const responseHeaders = { ...headers, ETag: etag }
if (request.headers.get('if-none-match') === etag) return new NextResponse(null, { status: 304, headers: responseHeaders })
return NextResponse.json(value, { headers: responseHeaders })
} catch (error) {
return releaseError(error)
}
}

View File

@ -0,0 +1,20 @@
import { NextResponse } from 'next/server'
import { DesktopClientError, desktopAssert } from '@/lib/desktop-client/contract.mjs'
import { validChannel } from '@/lib/desktop-client/client-release'
export const headers = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' }
export function releaseQuery(request: Request) {
const query = new URL(request.url).searchParams
const channel = query.get('channel') ?? 'stable'
desktopAssert(query.getAll('channel').length <= 1 && validChannel(channel), '发布通道无效', 400, 'invalid_request')
return { query, channel }
}
export function releaseError(error: unknown) {
const known = error instanceof DesktopClientError
return NextResponse.json({
error: known ? error.message : '客户端版本暂时无法读取',
code: known ? error.code : 'internal_error',
}, { status: known ? error.status : 500, headers })
}

View File

@ -0,0 +1,26 @@
import { NextResponse } from 'next/server'
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
import { proxyKnowledge, knowledgeResponseHeaders } from '@/lib/desktop-client/knowledge-proxy'
import { requireDesktop } from '@/lib/desktop-client/service'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
async function route(request: Request) {
try {
const { account, expiresAt, isSuperAdmin } = await requireDesktop(request)
return await proxyKnowledge(request, account.id, expiresAt, isSuperAdmin)
} catch (error) {
const known = error instanceof DesktopClientError
const status = known ? error.status : 503
const headers = new Headers(knowledgeResponseHeaders)
if (status === 405) headers.set('Allow', 'GET, HEAD')
if (request.method === 'HEAD') return new NextResponse(null, { status, headers })
return NextResponse.json({
error: known ? error.message : '客户端服务暂不可用,请稍后重试',
code: known ? error.code : 'service_unavailable',
}, { status, headers })
}
}
export { route as GET, route as HEAD, route as POST, route as PUT, route as PATCH, route as DELETE, route as OPTIONS }

View File

@ -1,26 +0,0 @@
import { createHash } from 'node:crypto'
import { NextResponse } from 'next/server'
import { requireDesktop } from '@/lib/desktop-client/service'
import { DesktopClientError, desktopAssert } from '@/lib/desktop-client/contract.mjs'
import { desktopTemplatePacks } from '@/lib/desktop-client/template-packs'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
const headers = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' }
export async function GET(request: Request) {
try {
// Every request, including a conditional hit, checks current session and
// feature authority. Native account-scoped caching cannot replace this.
await requireDesktop(request)
const query = new URL(request.url).searchParams
desktopAssert(query.getAll('brandId').length === 1 && query.getAll('categoryId').length === 1, '请提供唯一的品牌和品类编号', 400, 'invalid_request')
const value = desktopTemplatePacks(query.get('brandId'), query.get('categoryId'))
const etag = `"${createHash('sha256').update(JSON.stringify(value)).digest('hex')}"`
if (request.headers.get('if-none-match') === etag) return new NextResponse(null, { status: 304, headers: { ...headers, ETag: etag } })
return NextResponse.json(value, { headers: { ...headers, ETag: etag } })
} catch (error) {
const known = error instanceof DesktopClientError
return NextResponse.json({ error: known ? error.message : '模板暂时无法读取', code: known ? error.code : 'internal_error' }, { status: known ? error.status : 500, headers })
}
}

View File

@ -1,3 +1,4 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
import {
@ -181,7 +182,7 @@ export async function GET(request: NextRequest) {
try {
const matchedMaterial = await prisma.material.findFirst({
where: {
taskDetailPrivate: false, accessScope: 'general',
...EXTERNAL_MATERIAL_SCOPE_WHERE,
deletedAt: null,
productModel: trace.normalizedSpu,
...(materialType ? { materialType } : {}),

View File

@ -1,4 +1,7 @@
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { EXTERNAL_MATERIAL_SCOPE_WHERE, isRestrictedMaterial } from '@/lib/material-access-scope'
import { resolveStoredUploadPath } from '@/lib/upload-paths'
import { isXiaoyiDeliveryMaterial, xiaoyiSkuDimensions } from '@/lib/xiaoyi-delivery-material'
import { getS3ObjectStream } from '@/lib/s3'
/**
* 外部接口:文件下载
* GET - 通过 Token 下载文件
@ -19,6 +22,7 @@ import { lookup, extension } from 'mime-types';
import { isProductPackageType } from '@/lib/material-type-mapper';
import { resolveExternalImageDownloadSource } from '@/lib/external-image-assets';
import { resolveTaskDetailDownload } from '@/lib/external-task-details';
import { resolveCertificateReportSource } from '@/lib/external-certificate-reports';
import { nodeReadableToWebStream } from '@/lib/node-readable-stream';
import { createArchiveDownloadStream } from '@/lib/archive-download-stream';
@ -66,9 +70,32 @@ async function handleDownload(request: NextRequest) {
const { materialId, downloadType, assetId, skuId } = payload;
try {
if (downloadType === 'task-detail-file') {
const file = await resolveTaskDetailDownload(materialId, payload.taskDetailFile);
if (!file) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND);
if (file.kind === 'original') {
return new NextResponse(nodeReadableToWebStream(file.stream), {
headers: {
'Content-Type': lookup(file.fileName) || 'application/octet-stream',
'Content-Length': String(file.size),
'Content-Disposition': `attachment; filename="${encodeURIComponent(file.fileName)}"`,
'X-Content-Type-Options': 'nosniff',
},
});
}
const response = await downloadSingleFile(file, rangeHeader);
const contentType = lookup(file.fileName);
if (response.ok && file.preview && contentType && contentType.startsWith('image/') && contentType !== 'image/svg+xml') {
response.headers.set('Content-Type', contentType);
response.headers.set('Content-Disposition', `inline; filename="${encodeURIComponent(file.fileName)}"`);
}
response.headers.set('X-Content-Type-Options', 'nosniff');
return response;
}
// 查询素材
const material: any = await prisma.material.findUnique({
where: { accessScope: 'general', id: materialId, deletedAt: null },
where: { ...EXTERNAL_MATERIAL_SCOPE_WHERE, id: materialId, deletedAt: null },
include: {
assets: true,
},
@ -134,9 +161,37 @@ async function handleDownload(request: NextRequest) {
);
}
// TODO: 权限检查(暂时保留接口,后续扩展)
// 后续需要实现:根据 API Key 或用户权限检查下载权限
// 参考:/api/materials/download 中的权限检查逻辑
if (isXiaoyiDeliveryMaterial(material.materialType)) {
if (downloadType === 'all') {
const assets = material.assets.filter((item: any) => ['main','sku','detail','video','buyer_show'].includes(item.assetType))
if (!assets.length) {
return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
}
const prefetchedStreams = new Map<string, { body: Readable; contentLength?: number }>()
for (const item of assets) {
const normalizedUrl = normalizeAssetFileUrl(item.fileUrl)
const local = resolveAssetLocalPath(normalizedUrl)
if (local && fs.existsSync(local)) continue
if (isHttpUrl(normalizedUrl)) continue
const remote = await openRemoteFallbackStream(normalizedUrl)
if (remote) {
prefetchedStreams.set(item.id, remote)
continue
}
for (const stream of Array.from(prefetchedStreams.values())) {
stream.body.destroy()
}
return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
}
return await downloadAsZip(assets, material.id, 'all', prefetchedStreams)
}
if (downloadType !== 'single' || !assetId) {
return NextResponse.json({success:false,error:{code:'INVALID_DOWNLOAD_TYPE',message:'请指定交付文件'}},{status:400})
}
const asset = material.assets.find((item: any) => item.id === assetId)
if (!asset) return NextResponse.json({success:false,error:{code:'ASSET_NOT_FOUND',message:'资产不存在'}},{status:404})
return await downloadSingleFile(asset, rangeHeader)
}
// 任务类型素材:使用assets逻辑
const isTaskMaterial = ['任务-详情', '任务-页面', '任务-其他', '任务-3D原图', '任务-AI原图', '任务-实拍原图', '任务-视频截图'].includes(material.materialType);
@ -319,7 +374,7 @@ async function downloadStandardModelWhiteBackground(
}
const sku = await prisma.materialSku.findFirst({
where: { material: { accessScope: 'general' },
where: { material: EXTERNAL_MATERIAL_SCOPE_WHERE,
id: skuId,
materialId: material.id,
deletedAt: null,
@ -405,9 +460,22 @@ async function downloadSingleFile(asset: any, rangeHeader: string | null = null)
const fileName = resolveAssetFileName(asset, normalizedFileUrl);
const localPath = resolveAssetLocalPath(asset?.fileUrl);
// 本地文件
// 本地文件(缺失时自动兜底远程对象存储)
if (localPath) {
if (!fs.existsSync(localPath)) {
const remote = await openRemoteFallbackStream(normalizedFileUrl);
if (remote) {
const contentType = getContentType(fileName);
const stream = nodeReadableToWebStream(remote.body);
return new NextResponse(stream as any, {
status: 200,
headers: {
'Content-Type': contentType,
'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`,
...(remote.contentLength != null ? { 'Content-Length': String(remote.contentLength) } : {}),
},
});
}
return NextResponse.json(
{ success: false, error: { code: 'FILE_NOT_FOUND', message: '文件不存在' } },
{ status: 404 }
@ -632,10 +700,43 @@ async function appendExternalAssetToArchive(
archive.file(localPath, { name: entryName });
}
async function openRemoteFallbackStream(
fileUrl?: string | null,
): Promise<{ body: Readable; contentLength?: number } | null> {
if (!process.env.S3_BUCKET?.trim()) {
return null;
}
const normalized = normalizeAssetFileUrl(fileUrl).replace(/^\/+/, '');
if (!normalized || isHttpUrl(normalized) || path.isAbsolute(String(fileUrl || '')) || normalized.split('/').some((seg) => seg === '..')) {
return null;
}
const s3Prefix = String(process.env.S3_FILE_PATH || '')
.trim()
.replace(/\\/g, '/')
.replace(/^\/+|\/+$/g, '');
const candidateKeys = s3Prefix ? [`${s3Prefix}/${normalized}`, normalized] : [normalized];
for (const key of candidateKeys) {
try {
const result = await getS3ObjectStream(key);
if (result?.body) {
return result;
}
} catch {
// Try next candidate key.
}
}
return null;
}
/**
* 打包下载为 ZIP
*/
async function downloadAsZip(assets: any[], taskNo: string, downloadType: string) {
async function downloadAsZip(
assets: any[],
taskNo: string,
downloadType: string,
prefetchedStreams?: Map<string, { body: Readable; contentLength?: number }>,
) {
console.log(`[downloadAsZip] ========== 开始打包下载 ==========`);
console.log(`[downloadAsZip] taskNo: ${taskNo}, downloadType: ${downloadType}`);
console.log(`[downloadAsZip] 待打包资产数量: ${assets.length}`);
@ -648,10 +749,40 @@ async function downloadAsZip(assets: any[], taskNo: string, downloadType: string
let successCount = 0;
let failCount = 0;
for (const asset of assets) {
const skuNames = new Map<string, number>();
const skuResolutions = new Set<string>();
const files = assets.map(asset => {
const fileUrl = normalizeAssetFileUrl(asset.fileUrl);
const fileName = asset.fileName || path.basename(fileUrl);
const entryName = `${asset.assetType}/${fileName}`;
const { resolution } = xiaoyiSkuDimensions(asset.assetType, fileUrl);
if (resolution) skuResolutions.add(resolution);
if (asset.assetType === 'sku') {
const name = fileName.toLowerCase();
skuNames.set(name, (skuNames.get(name) ?? 0) + 1);
}
return { asset, fileUrl, fileName, resolution };
});
const groupedFiles = files.map(({ asset, fileUrl, fileName, resolution }) => {
const repeatedSkuName = asset.assetType === 'sku' && (skuNames.get(fileName.toLowerCase()) ?? 0) > 1;
const group = repeatedSkuName || (resolution && skuResolutions.size > 1)
? `sku/${resolution ?? asset.sortOrder}` : asset.assetType;
return { asset, fileUrl, fileName, group };
});
const skuGroupNameCounts = new Map<string, number>();
for (const item of groupedFiles) {
if (item.asset.assetType !== 'sku') continue;
const key = `${item.group}\u0000${item.fileName.toLowerCase()}`;
skuGroupNameCounts.set(key, (skuGroupNameCounts.get(key) ?? 0) + 1);
}
const skuGroupNameOffsets = new Map<string, number>();
for (const { asset, fileUrl, fileName, group } of groupedFiles) {
const key = `${group}\u0000${fileName.toLowerCase()}`;
let entryName = `${group}/${fileName}`;
if (asset.assetType === 'sku' && (skuGroupNameCounts.get(key) ?? 0) > 1) {
const offset = (skuGroupNameOffsets.get(key) ?? 0) + 1;
skuGroupNameOffsets.set(key, offset);
entryName = `${group}/${String(offset).padStart(2, '0')}/${fileName}`;
}
try {
const localPath = resolveAssetLocalPath(fileUrl);
@ -660,8 +791,20 @@ async function downloadAsZip(assets: any[], taskNo: string, downloadType: string
successCount++;
continue;
}
const prefetched = asset?.id ? prefetchedStreams?.get(asset.id) : undefined;
if (prefetched) {
archive.append(archiveDownload.trackSource(prefetched.body), { name: entryName });
successCount++;
continue;
}
if (localPath) {
console.error(`[downloadAsZip] ❌ 本地文件不存在: ${localPath}`);
const remote = await openRemoteFallbackStream(fileUrl);
if (remote) {
archive.append(archiveDownload.trackSource(remote.body), { name: entryName });
successCount++;
continue;
}
console.error(`[downloadAsZip] ❌ 本地与远程文件均不存在: ${localPath}`);
failCount++;
continue;
}
@ -762,8 +905,8 @@ function resolveAssetLocalPath(fileUrl?: string | null): string | null {
return null;
}
if (normalizedUrl.startsWith('/uploads/')) {
return path.join(process.cwd(), normalizedUrl.slice(1));
if (/^(?:\.\/|\/)?uploads\//i.test(normalizedUrl)) {
return resolveStoredUploadPath(normalizedUrl.replace(/^\/+/, ''));
}
if (path.isAbsolute(fileUrl)) {

View File

@ -1,3 +1,4 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
import { generateDownloadUrl } from '@/lib/download-token'
@ -276,7 +277,8 @@ export async function GET(request: NextRequest) {
try {
const searchOrConditions = await buildMaterialSearchOrConditions(trace.normalizedSpu)
const materials = await prisma.material.findMany({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
deletedAt: null,
...(searchOrConditions ? { OR: searchOrConditions } : {}),
materialType: {

View File

@ -37,7 +37,9 @@ export async function POST(request: NextRequest) {
let taskNo: string | undefined
try {
const body = await request.json()
const body = await request.json().catch(() => {
throw new ExternalMaterialImportError(400, 'INVALID_REQUEST', '请求体必须为 JSON')
})
taskNo = body?.formData?.taskNo
const result = await createExternalMaterialImportJob({
@ -70,7 +72,7 @@ export async function POST(request: NextRequest) {
} catch (error) {
const status = error instanceof ExternalMaterialImportError ? error.status : 500
const code = error instanceof ExternalMaterialImportError ? error.code : 'SERVER_ERROR'
const message = error instanceof Error ? error.message : '服务器内部错误'
const message = error instanceof ExternalMaterialImportError ? error.message : '服务器内部错误'
await logApiCall({
apiKeyId: keyRecord.id,

View File

@ -1,4 +1,11 @@
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { prisma } from '@/lib/prisma'
import {
isXiaoyiDeliveryMaterial, readXiaoyiDeliveryMetadata, XIAOYI_DELIVERY_LOG_ACTION,
XIAOYI_DELIVERY_MATERIAL_TYPES, XIAOYI_DETAIL_ASSET_GROUPS, xiaoyiSkuDimensions, type XiaoyiDeliveryKind,
} from '@/lib/xiaoyi-delivery-material'
import { parseListingUpdate, pendingListingStatus, recordListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status'
import { XIAOYI_LISTING_KEY_SCOPE } from '@/lib/external-api'
/**
* 外部接口:产品全案素材查询和删除
@ -21,7 +28,7 @@ import {
getMaterialById,
getMaterialByTaskNo,
updateTaskStatus,
softDeleteByTaskNo,
softDeleteExternalMaterial,
TASK_STATUS,
ASSET_TYPE,
} from '@/lib/product-package';
@ -55,11 +62,14 @@ export async function GET(request: NextRequest) {
const materialId = request.nextUrl.searchParams.get('materialId')
// 验证 API Key
const keyRecord = await validateApiKey(apiKey);
const keyRecord = await validateApiKey(apiKey, true);
if (!keyRecord) {
return errorResponse(API_ERROR.INVALID_API_KEY);
}
const listingOnly = keyRecord.scope === XIAOYI_LISTING_KEY_SCOPE
if (listingOnly && !isValidMaterialId(materialId)) return errorResponse(API_ERROR.INVALID_MATERIAL_ID)
if (!taskNo && !materialId) {
await logApiCall({
apiKeyId: keyRecord.id,
@ -104,7 +114,14 @@ export async function GET(request: NextRequest) {
// 查询素材
console.log('[external/product-assets] Querying material:', { taskNo, materialId });
const found: any = materialId ? await getMaterialById(materialId) : await getMaterialByTaskNo(taskNo as string);
const material = found && !isRestrictedMaterial(found) ? found : null;
let material = found && !isRestrictedMaterial(found)
&& (!listingOnly || isXiaoyiDeliveryMaterial(found.materialType)) ? found : null;
if (material && !material.deletedAt && material.taskStatus !== TASK_STATUS.FETCHED) {
const updated = await updateTaskStatus(material.id, TASK_STATUS.FETCHED, {
taskFetchedAt: new Date(),
});
if (!updated.count) material = null;
}
console.log('[external/product-assets] Material found:', material ? {
id: material.id,
taskNo: material.taskNo,
@ -142,13 +159,6 @@ export async function GET(request: NextRequest) {
return errorResponse(API_ERROR.MATERIAL_DELETED);
}
// 更新任务状态为 fetched
if (material.taskStatus !== TASK_STATUS.FETCHED) {
await updateTaskStatus(material.id, TASK_STATUS.FETCHED, {
taskFetchedAt: new Date(),
});
}
const baseUrl = getBaseUrl();
const resolvedIsFullSet = deriveTaskDetailIsFullSet(
material.materialType,
@ -158,6 +168,103 @@ export async function GET(request: NextRequest) {
console.log('[external/product-assets] Base URL:', baseUrl);
console.log('[external/product-assets] Material type:', material.materialType);
if (isXiaoyiDeliveryMaterial(material.materialType)) {
const [delivery] = await prisma.$queryRaw<Array<{
brandName: string; productName: string; eventId: string | null; listingStatus: ListingStatus | null
deliveryGroupId: string; authorId: string; detailBarcode: string | null; barcodes: string[] | null
relatedMaterials: Partial<Record<XiaoyiDeliveryKind, string>> | null
metadataChanges: string | null
}>>`
SELECT d.brand_name AS "brandName", d.product_name AS "productName",
e.id AS "eventId", d.listing_status AS "listingStatus", d.project_id AS "deliveryGroupId", d.owner_id AS "authorId",
siblings."relatedMaterials", codes."detailBarcode", codes.barcodes,
(SELECT log.changes FROM material_logs log
WHERE log."materialId" = d.material_id AND log.action = ${XIAOYI_DELIVERY_LOG_ACTION}
ORDER BY log.timestamp DESC LIMIT 1) AS "metadataChanges"
FROM desktop_material_deliveries d
JOIN materials delivered ON delivered.id = d.material_id
LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id
LEFT JOIN LATERAL (
SELECT jsonb_object_agg(related.kind, related.material_id) AS "relatedMaterials"
FROM desktop_material_deliveries related
JOIN materials rm ON rm.id = related.material_id AND rm."userId" = related.owner_id
WHERE related.project_id = d.project_id AND related.owner_id = d.owner_id
AND UPPER(rm."productModel") = UPPER(delivered."productModel")
AND rm."deletedAt" IS NULL AND NOT rm.is_incomplete_shell
AND rm.access_scope = 'general' AND NOT rm.task_detail_private
) siblings ON TRUE
LEFT JOIN LATERAL (
SELECT min(b.barcode) FILTER (WHERE a.asset_type = 'detail') AS "detailBarcode",
array_agg(DISTINCT b.barcode COLLATE "C" ORDER BY b.barcode COLLATE "C") FILTER (WHERE a.asset_type = 'sku') AS barcodes
FROM material_assets a
JOIN material_asset_barcodes b ON b.asset_id = a.id
WHERE a.material_id = (siblings."relatedMaterials"->>'detail')
) codes ON TRUE
WHERE d.material_id = ${material.id}
`
if (listingOnly && !delivery?.eventId) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND)
const metadata = readXiaoyiDeliveryMetadata(delivery?.metadataChanges)
const groups: Record<string, any[]> = {main: [], sku: [], detail: [], video: [], buyer_show: []}
for (const asset of material.assets || []) {
if (!groups[asset.assetType]) continue
const spec = metadata?.assetSpecs?.[asset.id]
groups[asset.assetType].push({
id: asset.id,
fileName: asset.fileName || '',
fileSize: Number(asset.fileSize || 0),
sortOrder: asset.sortOrder || 0,
...xiaoyiSkuDimensions(asset.assetType, asset.fileUrl),
specId: spec?.specId ?? null,
variantId: spec?.variantId ?? null,
variantName: spec?.variantName ?? null,
...(asset.assetType === 'sku' ? {
skuCode: asset.skuCode || null,
barcodes: (asset.barcodes || []).map((entry: { barcode: string }) => entry.barcode),
} : {}),
downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'single', assetId: asset.id}),
})
}
await logApiCall({
apiKeyId: keyRecord.id, endpoint: '/api/external/product-assets', method: 'GET',
statusCode: 200, duration: Date.now() - startTime, ipAddress: getClientIp(request),
userAgent: request.headers.get('user-agent') || undefined,
})
const relatedMaterial = (id?: string) => id ? {
materialId: id,
downloadUrl: generateDownloadUrl(baseUrl, {materialId: id, downloadType: 'all'}),
} : null
const response = successResponse({
materialId: material.id, materialType: material.materialType, productModel: material.productModel,
identifier: material.productModel,
spu: delivery || groups.sku.some(asset => asset.barcodes.length) ? material.productModel : null,
categoryName: material.categoryName, productCategoryName: material.productCategoryName,
storeCategoryName: metadata?.storeCategoryName ?? (material.categoryName || null),
authorId: delivery?.authorId ?? material.userId,
authorName: material.authorName,
detailBarcode: delivery?.detailBarcode ?? null,
barcodes: delivery?.barcodes ?? Array.from(new Set<string>(groups.sku.flatMap(asset => asset.barcodes))),
...(delivery?.deliveryGroupId && {
deliveryGroupId: delivery.deliveryGroupId,
relatedMaterials: {
detail: relatedMaterial(delivery.relatedMaterials?.detail),
video: relatedMaterial(delivery.relatedMaterials?.video),
buyer_show: relatedMaterial(delivery.relatedMaterials?.buyer_show),
},
}),
brandName: delivery?.brandName || '', productName: delivery?.productName || '', identifierType: delivery ? 'spu' : '',
isFullSet: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.detail && XIAOYI_DETAIL_ASSET_GROUPS.every(group => groups[group].length),
...(delivery?.eventId && { eventId: delivery.eventId, listingStatus: delivery.listingStatus ?? pendingListingStatus }),
assets: groups,
files: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.video ? groups.video
: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.buyer_show ? groups.buyer_show : [],
downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all'}),
downloadUrls: {all: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all'})},
createdAt: material.createdAt.toISOString(), updatedAt: material.updatedAt.toISOString(),
})
response.headers.set('Cache-Control', 'private, no-store')
return response
}
// 根据素材类型返回不同结构
if (isProductPackageType(material.materialType)) {
// 任务-详情
@ -369,6 +476,36 @@ export async function GET(request: NextRequest) {
}
}
/** PATCH - Report a listing outcome for a Xiaoyi delivery. */
export async function PATCH(request: NextRequest) {
const startTime = Date.now()
const key = await validateApiKey(getApiKeyFromRequest(request), true)
if (!key) return errorResponse(API_ERROR.INVALID_API_KEY)
if (key.scope !== XIAOYI_LISTING_KEY_SCOPE) {
return errorResponse({ code: 'INVALID_KEY_SCOPE', message: '需要小壹自动上架专用 API Key', status: 403 })
}
const materialId = request.nextUrl.searchParams.get('materialId')
if (!isValidMaterialId(materialId)) return errorResponse(API_ERROR.INVALID_MATERIAL_ID)
const input = await request.json().catch(() => null)
const update = parseListingUpdate(input)
if (!update) return errorResponse({ code: 'INVALID_LISTING_STATUS', message: '上架状态回传字段无效', status: 400 })
try {
const result = await recordListingStatus(materialId, update)
await logApiCall({
apiKeyId: key.id, endpoint: '/api/external/product-assets', method: 'PATCH',
queryType: 'materialId', queryValue: materialId, statusCode: result.status, duration: Date.now() - startTime, ipAddress: getClientIp(request),
userAgent: request.headers.get('user-agent') || undefined,
})
if (result.status !== 200) return errorResponse(result)
const response = successResponse({ materialId, applied: result.applied, listingStatus: result.listingStatus })
response.headers.set('Cache-Control', 'private, no-store')
return response
} catch (error) {
console.error('[external/product-assets] Failed to persist listing status:', error)
return errorResponse(API_ERROR.SERVER_ERROR)
}
}
/**
* DELETE - 删除素材
*/
@ -432,7 +569,7 @@ export async function DELETE(request: NextRequest) {
}
// 软删除
await softDeleteByTaskNo(taskNo);
const deleted = await softDeleteExternalMaterial(material.id);
// 记录日志
await logApiCall({
@ -440,12 +577,14 @@ export async function DELETE(request: NextRequest) {
endpoint: '/api/external/product-assets',
method: 'DELETE',
taskNo,
statusCode: 200,
statusCode: deleted.count ? 200 : 404,
duration: Date.now() - startTime,
ipAddress: getClientIp(request),
userAgent: request.headers.get('user-agent') || undefined,
});
if (!deleted.count) return errorResponse(API_ERROR.TASK_NOT_FOUND);
return successResponse({
taskNo,
deletedAt: new Date().toISOString(),

View File

@ -1,6 +1,10 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
import { rewriteStorageUrlForClient } from '@/lib/url-rewrite'
import { generateDownloadUrl } from '@/lib/download-token'
import { getPublicAppOrigin } from '@/lib/public-app-url'
import { XIAOYI_DELIVERY_MATERIAL_TYPES, xiaoyiSkuDimensions } from '@/lib/xiaoyi-delivery-material'
import {
API_ERROR,
errorResponse,
@ -20,7 +24,14 @@ interface BarcodeImageItem {
shopName: string
sceneName: string
skuCode: string | null
barcode: string
barcodes: string[]
materialType: string
assetType: string
width: number | null
height: number | null
resolution: string | null
aspectRatio: string | null
previewUrl: string
fileName: string
sortOrder: number
@ -61,10 +72,12 @@ export async function GET(request: NextRequest) {
where: {
barcode,
asset: {
assetType: 'sku-preview',
OR: [
{ assetType: 'sku-preview', material: { materialType: '任务-详情' } },
{ assetType: 'sku', material: { materialType: XIAOYI_DELIVERY_MATERIAL_TYPES.detail } },
],
material: {
materialType: '任务-详情',
taskDetailPrivate: false, accessScope: 'general',
...EXTERNAL_MATERIAL_SCOPE_WHERE,
deletedAt: null,
},
},
@ -75,6 +88,7 @@ export async function GET(request: NextRequest) {
asset: {
select: {
id: true,
assetType: true,
fileUrl: true,
fileName: true,
sortOrder: true,
@ -89,6 +103,7 @@ export async function GET(request: NextRequest) {
material: {
select: {
id: true,
materialType: true,
taskNo: true,
productModel: true,
categoryName: true,
@ -124,10 +139,16 @@ export async function GET(request: NextRequest) {
shopName: String(material.categoryName || ''),
sceneName: String(material.sceneName || ''),
skuCode: asset.skuCode || null,
barcode: match.barcode,
barcodes: Array.from(
new Set((asset.barcodes || []).map((item: any) => String(item.barcode || '').trim()).filter(Boolean)),
new Set((asset.barcodes || []).map(item => item.barcode.trim()).filter(Boolean)),
),
previewUrl: rewriteStorageUrlForClient(asset.fileUrl, request) || String(asset.fileUrl || ''),
materialType: material.materialType,
assetType: asset.assetType,
...xiaoyiSkuDimensions(asset.assetType, asset.fileUrl),
previewUrl: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.detail
? generateDownloadUrl(getPublicAppOrigin(), { materialId: material.id, downloadType: 'single', assetId: asset.id })
: rewriteStorageUrlForClient(asset.fileUrl, request) || String(asset.fileUrl || ''),
fileName: String(asset.fileName || ''),
sortOrder: Number(asset.sortOrder || 0),
uploadedAt: asset.createdAt.toISOString(),
@ -186,7 +207,9 @@ export async function GET(request: NextRequest) {
userAgent: request.headers.get('user-agent') || undefined,
})
return successResponse(responseData)
const response = successResponse(responseData)
response.headers.set('Cache-Control', 'private, no-store')
return response
} catch (error) {
console.error('[external/product-barcode-images] GET error:', error)

View File

@ -1,3 +1,4 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import path from 'path'
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
@ -291,7 +292,8 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace
deletedAt: null,
skuName: normalizedSkuName,
material: {
is: { accessScope: 'general',
is: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
materialType: '标准模型',
deletedAt: null,
},
@ -354,6 +356,7 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace
prisma.materialAsset.findMany({
where: {
materialId: matchedSku.materialId,
material: EXTERNAL_MATERIAL_SCOPE_WHERE,
...getWhiteBackgroundAssetWhereForSku(matchedSku.id),
},
select: {
@ -415,7 +418,8 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace
async function handleSpuQuery(normalizedSpu: string, logBase: LogBase, trace: TraceContext) {
try {
const material = await prisma.material.findFirst({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
productModel: normalizedSpu,
materialType: '标准模型',
deletedAt: null,
@ -464,6 +468,7 @@ async function handleSpuQuery(normalizedSpu: string, logBase: LogBase, trace: Tr
? prisma.materialAsset.findMany({
where: {
materialId: material.id,
material: EXTERNAL_MATERIAL_SCOPE_WHERE,
OR: skuIds.flatMap((skuId) => getWhiteBackgroundAssetWhereForSku(skuId).OR),
},
select: {

View File

@ -7,6 +7,7 @@ import {
validateApiKey,
} from '@/lib/external-api'
import {
assertExternalWhiteBackgroundReplayVisible,
completeExternalApiIdempotencyRecord,
ExternalWhiteBackgroundBarcodeError,
failExternalApiIdempotencyRecord,
@ -17,6 +18,7 @@ import {
startExternalApiIdempotencyRecord,
} from '@/lib/external-standard-model-white-background-by-barcode'
import { cleanupStandardModelWhiteBackgroundForSku } from '@/lib/standard-model-white-background-service'
import { MaterialUploadRequestError } from '@/lib/material-upload-request-guard'
export const runtime = 'nodejs'
@ -156,6 +158,7 @@ export async function POST(request: NextRequest) {
})
if (idempotency.mode === 'replay') {
await assertExternalWhiteBackgroundReplayVisible(idempotency.record.responseBody)
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: idempotency.record.responseStatus || 200 })
return finalizeResponse(
NextResponse.json(idempotency.record.responseBody, {
@ -168,11 +171,16 @@ export async function POST(request: NextRequest) {
const activeIdempotencyRecordId = String(idempotency.record.id)
idempotencyRecordId = activeIdempotencyRecordId
const results = []
const targets = []
for (const barcode of barcodes) {
const resolved = await resolveStandardModelSkuByBarcode(barcode)
targets.push({ barcode, resolved: await resolveStandardModelSkuByBarcode(barcode) })
}
const results = []
for (const { barcode, resolved } of targets) {
const cleanup = await cleanupStandardModelWhiteBackgroundForSku({
materialId: resolved.materialId,
externalOnly: true,
skuId: resolved.skuId,
operatorUserId: keyRecord.createdBy,
reason,
@ -209,7 +217,7 @@ export async function POST(request: NextRequest) {
await failExternalApiIdempotencyRecord(idempotencyRecordId)
}
if (error instanceof ExternalWhiteBackgroundBarcodeError) {
if (error instanceof ExternalWhiteBackgroundBarcodeError || error instanceof MaterialUploadRequestError) {
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: error.status })
return finalizeResponse(buildErrorResponse(error.status, error.code, error.message), trace)
}

View File

@ -7,6 +7,7 @@ import {
validateApiKey,
} from '@/lib/external-api'
import {
assertExternalWhiteBackgroundReplayVisible,
completeExternalApiIdempotencyRecord,
ExternalWhiteBackgroundBarcodeError,
failExternalApiIdempotencyRecord,
@ -268,6 +269,7 @@ export async function POST(request: NextRequest) {
})
if (idempotency.mode === 'replay') {
await assertExternalWhiteBackgroundReplayVisible(idempotency.record.responseBody)
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: idempotency.record.responseStatus || 200 })
return finalizeResponse(
NextResponse.json(idempotency.record.responseBody, {
@ -283,6 +285,7 @@ export async function POST(request: NextRequest) {
const resolved = await resolveStandardModelSkuByBarcode(barcode)
const uploadResult = await uploadStandardModelWhiteBackground({
materialId: resolved.materialId,
externalOnly: true,
skuId: resolved.skuId,
skuName: resolved.skuName,
sourceType,

View File

@ -1,3 +1,4 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
import {
@ -7,6 +8,7 @@ import {
validateApiKey,
} from '@/lib/external-api'
import {
assertExternalWhiteBackgroundReplayVisible,
completeExternalApiIdempotencyRecord,
ExternalWhiteBackgroundBarcodeError,
failExternalApiIdempotencyRecord,
@ -16,6 +18,7 @@ import {
startExternalApiIdempotencyRecord,
} from '@/lib/external-standard-model-white-background-by-barcode'
import { prisma } from '@/lib/prisma'
import { acquireTaskMaterialCompletionLock } from '@/lib/material-upload-cross-process-lock'
import {
normalizeWhiteBackgroundSkuName,
STANDARD_MODEL_WHITE_BG_OTHER_FIELD_NAME,
@ -233,7 +236,8 @@ async function findDuplicateStandardModelSkuName(skuName: string, excludeMateria
},
...(excludeMaterialId ? { NOT: { materialId: excludeMaterialId } } : {}),
material: {
is: { accessScope: 'general',
is: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
materialType: '标准模型',
deletedAt: null,
},
@ -299,7 +303,7 @@ async function createStandardModelSku(input: {
skuName: string
}) {
const maxSortOrder = await prisma.materialSku.aggregate({
where: { material: { accessScope: 'general' }, materialId: input.materialId },
where: { material: EXTERNAL_MATERIAL_SCOPE_WHERE, materialId: input.materialId },
_max: { sortOrder: true },
})
@ -325,7 +329,7 @@ async function ensureProductBarcodeBinding(input: {
skuId: string
}) {
const existing = await prisma.materialSkuBarcode.findFirst({
where: { sku: { material: { accessScope: 'general' } },
where: { sku: { material: EXTERNAL_MATERIAL_SCOPE_WHERE },
barcode: input.barcode,
deletedAt: null,
},
@ -380,7 +384,7 @@ async function ensureProductBarcodeBinding(input: {
} catch (error: any) {
if (error?.code === 'P2002') {
const current = await prisma.materialSkuBarcode.findFirst({
where: { sku: { material: { accessScope: 'general' } },
where: { sku: { material: EXTERNAL_MATERIAL_SCOPE_WHERE },
barcode: input.barcode,
deletedAt: null,
},
@ -429,7 +433,8 @@ async function resolveStandardModelTargetBySpu(input: {
operatorUserId: string
}): Promise<ResolvedStandardModelTarget> {
const matches = await prisma.material.findMany({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
productModel: {
equals: input.spu,
mode: 'insensitive',
@ -439,17 +444,6 @@ async function resolveStandardModelTargetBySpu(input: {
},
select: {
id: true,
productModel: true,
categoryName: true,
productCategoryName: true,
skus: {
where: { deletedAt: null },
select: {
id: true,
skuName: true,
},
orderBy: { sortOrder: 'asc' },
},
},
orderBy: { createdAt: 'asc' },
take: 2,
@ -464,28 +458,16 @@ async function resolveStandardModelTargetBySpu(input: {
}
const existingMaterial = matches[0]
if (existingMaterial) {
const existingSku = existingMaterial.skus.find(
(sku) => normalizeWhiteBackgroundSkuName(sku.skuName) === input.skuName,
)
if (existingSku) {
return {
materialId: existingMaterial.id,
skuId: existingSku.id,
resolvedSpu: existingMaterial.productModel,
resolvedSkuName: existingSku.skuName,
createdMaterial: false,
createdSku: false,
barcode: input.barcode,
...(await ensureProductBarcodeBinding({
barcode: input.barcode,
skuId: existingSku.id,
})),
}
let materialId = existingMaterial?.id
if (!materialId) {
if (!input.productCategoryName) {
throw new ExternalWhiteBackgroundBySpuError(
400,
'PRODUCT_CATEGORY_REQUIRED',
'该 SPU 尚未在标准模型内存在,新建标准模型 SPU 时必须传 productCategoryName',
)
}
const duplicateSku = await findDuplicateStandardModelSkuName(input.skuName, existingMaterial.id)
const duplicateSku = await findDuplicateStandardModelSkuName(input.skuName)
if (duplicateSku) {
throw new ExternalWhiteBackgroundBySpuError(
409,
@ -493,67 +475,58 @@ async function resolveStandardModelTargetBySpu(input: {
`SKU 名称 ${input.skuName} 已被标准模型 SPU ${duplicateSku.material.productModel} 占用`,
)
}
const sku = await createStandardModelSku({
materialId: existingMaterial.id,
skuName: input.skuName,
const created = await createStandardModelMaterial({
spu: input.spu,
productCategoryName: input.productCategoryName,
platformName: input.platformName,
operatorUserId: input.operatorUserId,
})
materialId = created.id
}
return {
materialId: existingMaterial.id,
skuId: sku.id,
resolvedSpu: existingMaterial.productModel,
resolvedSkuName: sku.skuName,
createdMaterial: false,
createdSku: true,
barcode: input.barcode,
...(await ensureProductBarcodeBinding({
barcode: input.barcode,
skuId: sku.id,
})),
const release = await acquireTaskMaterialCompletionLock(materialId, { mode: 'shared' })
try {
release.assertHeld()
const material = await prisma.material.findFirst({
where: { id: materialId, deletedAt: null, ...EXTERNAL_MATERIAL_SCOPE_WHERE },
select: {
id: true,
productModel: true,
skus: {
where: { deletedAt: null },
select: { id: true, skuName: true },
orderBy: { sortOrder: 'asc' },
},
},
})
if (!material) {
throw new ExternalWhiteBackgroundBySpuError(404, 'MATERIAL_NOT_FOUND', '素材不存在或不可访问')
}
}
if (!input.productCategoryName) {
throw new ExternalWhiteBackgroundBySpuError(
400,
'PRODUCT_CATEGORY_REQUIRED',
'该 SPU 尚未在标准模型内存在,新建标准模型 SPU 时必须传 productCategoryName',
)
}
const duplicateSku = await findDuplicateStandardModelSkuName(input.skuName)
if (duplicateSku) {
throw new ExternalWhiteBackgroundBySpuError(
409,
'SKU_NAME_OCCUPIED',
`SKU 名称 ${input.skuName} 已被标准模型 SPU ${duplicateSku.material.productModel} 占用`,
)
}
const material = await createStandardModelMaterial({
spu: input.spu,
productCategoryName: input.productCategoryName,
platformName: input.platformName,
operatorUserId: input.operatorUserId,
})
const sku = await createStandardModelSku({
materialId: material.id,
skuName: input.skuName,
})
return {
materialId: material.id,
skuId: sku.id,
resolvedSpu: material.productModel,
resolvedSkuName: sku.skuName,
createdMaterial: true,
createdSku: true,
barcode: input.barcode,
...(await ensureProductBarcodeBinding({
barcode: input.barcode,
const existingSku = material.skus.find((sku) => normalizeWhiteBackgroundSkuName(sku.skuName) === input.skuName)
if (existingMaterial && !existingSku) {
const duplicateSku = await findDuplicateStandardModelSkuName(input.skuName, material.id)
if (duplicateSku) {
throw new ExternalWhiteBackgroundBySpuError(
409,
'SKU_NAME_OCCUPIED',
`SKU 名称 ${input.skuName} 已被标准模型 SPU ${duplicateSku.material.productModel} 占用`,
)
}
}
const sku = existingSku ?? await createStandardModelSku({ materialId: material.id, skuName: input.skuName })
const binding = await ensureProductBarcodeBinding({ barcode: input.barcode, skuId: sku.id })
return {
materialId: material.id,
skuId: sku.id,
})),
resolvedSpu: material.productModel,
resolvedSkuName: sku.skuName,
createdMaterial: !existingMaterial,
createdSku: !existingSku,
barcode: input.barcode,
...binding,
}
} finally {
await release()
}
}
@ -701,6 +674,7 @@ export async function POST(request: NextRequest) {
})
if (idempotency.mode === 'replay') {
await assertExternalWhiteBackgroundReplayVisible(idempotency.record.responseBody)
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: idempotency.record.responseStatus || 200 })
return finalizeResponse(
NextResponse.json(idempotency.record.responseBody, {
@ -723,6 +697,7 @@ export async function POST(request: NextRequest) {
})
const uploadResult = await uploadStandardModelWhiteBackground({
materialId: resolved.materialId,
externalOnly: true,
skuId: resolved.skuId,
skuName: resolved.resolvedSkuName,
sourceType,

View File

@ -1,3 +1,4 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import path from 'path'
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
@ -301,7 +302,8 @@ export async function GET(request: NextRequest) {
deletedAt: null,
skuName: normalizedSkuName,
material: {
is: { accessScope: 'general',
is: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
materialType: '标准模型',
deletedAt: null,
},
@ -358,6 +360,7 @@ export async function GET(request: NextRequest) {
const whiteBackgroundAssets = await prisma.materialAsset.findMany({
where: {
materialId: matchedSku.materialId,
material: EXTERNAL_MATERIAL_SCOPE_WHERE,
...getWhiteBackgroundAssetWhereForSku(matchedSku.id),
},
select: {
@ -500,7 +503,8 @@ async function handleSpuQuery(
try {
// 通过 productModel(SPU)查找标准模型素材
const material = await prisma.material.findFirst({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
productModel: normalizedSpu,
materialType: '标准模型',
deletedAt: null,
@ -548,6 +552,7 @@ async function handleSpuQuery(
const allWhiteBackgroundAssets = await prisma.materialAsset.findMany({
where: {
materialId: material.id,
material: EXTERNAL_MATERIAL_SCOPE_WHERE,
OR: allSkuIds.flatMap((skuId) => [
{ assetType: { startsWith: `standard-model-white-bg-view:${skuId}:` } },
{ assetType: { startsWith: `standard-model-white-bg-other:${skuId}:` } },
@ -642,7 +647,7 @@ async function getTaskDetailMaterialsBySpu(normalizedSpu: string) {
where: {
productModel: normalizedSpu,
materialType: '任务-详情',
taskDetailPrivate: false, accessScope: 'general',
...EXTERNAL_MATERIAL_SCOPE_WHERE,
deletedAt: null,
},
select: {
@ -743,7 +748,8 @@ async function handleTaskDetailSkuQuery(
deletedAt: null,
skuName: normalizedSkuName,
material: {
is: { accessScope: 'general',
is: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
materialType: '标准模型',
deletedAt: null,
},

39
app/api/external/task-details/route.ts vendored Normal file
View File

@ -0,0 +1,39 @@
import { timingSafeEqual } from 'node:crypto'
import { NextRequest } from 'next/server'
import { API_ERROR, errorResponse, getApiKeyFromRequest, successResponse } from '@/lib/external-api'
import { getExternalTaskDetail } from '@/lib/external-task-details'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
const materialIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
function hasTaskDetailKey(request: NextRequest): boolean {
const configuredKey = Buffer.from(process.env.EXTERNAL_TASK_DETAIL_API_KEY?.trim() || '')
const providedKey = Buffer.from(getApiKeyFromRequest(request) || '')
return configuredKey.length > 0 && configuredKey.length === providedKey.length &&
timingSafeEqual(configuredKey, providedKey)
}
export async function GET(request: NextRequest) {
const response = await query(request)
response.headers.set('Cache-Control', 'private, no-store')
return response
}
async function query(request: NextRequest) {
if (!hasTaskDetailKey(request)) return errorResponse(API_ERROR.INVALID_API_KEY)
const materialId = request.nextUrl.searchParams.get('materialId')?.trim()
if (!materialId || !materialIdPattern.test(materialId)) {
return errorResponse(API_ERROR.INVALID_MATERIAL_ID)
}
try {
const material = await getExternalTaskDetail(materialId)
return material ? successResponse(material) : errorResponse(API_ERROR.MATERIAL_NOT_FOUND)
} catch (error) {
console.error('[external/task-details] lookup failed', error)
return errorResponse(API_ERROR.SERVER_ERROR)
}
}

View File

@ -1,3 +1,4 @@
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
import { randomUUID } from 'crypto'
import { NextRequest, NextResponse } from 'next/server'
import { generateDownloadUrl } from '@/lib/download-token'
@ -239,7 +240,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
where: {
barcode: { equals: keyword, mode: 'insensitive' },
deletedAt: null,
sku: { material: { accessScope: 'general' }, deletedAt: null },
sku: { material: EXTERNAL_MATERIAL_SCOPE_WHERE, deletedAt: null },
},
select: { sku: { select: { materialId: true } } },
})
@ -250,7 +251,8 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
)
const materials = await prisma.material.findMany({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
id: { in: materialIds },
deletedAt: null,
materialType: { in: VIDEO_MATERIAL_TYPES },
@ -266,7 +268,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
// ── Layer 2: SKU-name contains match ──────────────────────────────────
const skuRecords = await prisma.materialSku.findMany({
where: { material: { accessScope: 'general' },
where: { material: EXTERNAL_MATERIAL_SCOPE_WHERE,
skuName: { contains: keyword, mode: 'insensitive' },
deletedAt: null,
},
@ -277,7 +279,8 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
const materialIds = Array.from(new Set(skuRecords.map((r) => r.materialId)))
const materials = await prisma.material.findMany({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
id: { in: materialIds },
deletedAt: null,
materialType: { in: VIDEO_MATERIAL_TYPES },
@ -293,7 +296,8 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
// ── Layer 3: SPU (productModel) contains match ────────────────────────
const materials = await prisma.material.findMany({
where: { accessScope: 'general',
where: {
...EXTERNAL_MATERIAL_SCOPE_WHERE,
productModel: { contains: keyword, mode: 'insensitive' },
deletedAt: null,
materialType: { in: VIDEO_MATERIAL_TYPES },

View File

@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { TaskDetailAssetEditError } from '@/lib/task-detail-asset-edit'
import {
listTaskDetailChanges,
submitTaskDetailChange,
@ -22,7 +23,7 @@ function actor(session: unknown) {
}
function errorResponse(error: unknown) {
if (error instanceof TaskDetailChangeApprovalError) {
if (error instanceof TaskDetailChangeApprovalError || error instanceof TaskDetailAssetEditError) {
return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode })
}
console.error('[task-detail-change] request error:', error)

View File

@ -0,0 +1,55 @@
/** @jest-environment node */
import { GET } from './route'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { canUserDownloadMaterial, canUserViewMaterial, isSuperAdmin } from '@/lib/department-permission'
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
import { stat } from 'fs/promises'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { material: { findFirst: jest.fn() }, materialAsset: { findFirst: jest.fn() }, user: { findUnique: jest.fn() } } }))
jest.mock('@/lib/department-permission', () => ({ canUserDownloadMaterial: jest.fn(), canUserViewMaterial: jest.fn(), isSuperAdmin: jest.fn() }))
jest.mock('@/lib/task-detail-privacy', () => ({ canAccessMaterialPrivacy: jest.fn(), TASK_DETAIL_PRIVACY_SELECT: {} }))
jest.mock('fs/promises', () => ({ stat: jest.fn() }))
jest.mock('fs', () => ({ createReadStream: jest.fn(() => ({})) }))
jest.mock('@/lib/node-readable-stream', () => ({ nodeReadableToWebStream: jest.fn(() => new ReadableStream()) }))
const params = { id: 'material', assetId: 'asset' }
function request(download = false, range?: string) {
return { nextUrl: new URL(`http://localhost/file${download ? '?download=1' : ''}`), headers: new Headers(range ? { range } : {}) } as any
}
beforeEach(() => {
jest.resetAllMocks()
;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'owner', role: 'USER' } })
;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ id: 'material', userId: 'owner', materialType: '自动上架-视频' })
;(prisma.materialAsset.findFirst as jest.Mock).mockResolvedValue({ fileUrl: 'uploads/xiaoyi-deliveries/file.mp4', fileName: 'file.mp4' })
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ canDownload: true })
;(canAccessMaterialPrivacy as jest.Mock).mockResolvedValue(true)
;(isSuperAdmin as jest.Mock).mockResolvedValue(false)
;(stat as jest.Mock).mockResolvedValue({ isFile: () => true, size: 1000 })
})
test('创建人可以播放视频片段', async () => {
const response = await GET(request(false, 'bytes=100-199'), { params })
expect(response.status).toBe(206)
expect(response.headers.get('content-range')).toBe('bytes 100-199/1000')
})
test('其他用户没有新类型查看权限时无法访问文件', async () => {
;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'other', role: 'USER' } })
;(canUserViewMaterial as jest.Mock).mockResolvedValue(false)
expect((await GET(request(), { params })).status).toBe(403)
expect(prisma.materialAsset.findFirst).not.toHaveBeenCalled()
})
test('其他用户即使可以查看,缺少下载权限时不能下载', async () => {
;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'other', role: 'USER' } })
;(canUserViewMaterial as jest.Mock).mockResolvedValue(true)
;(canUserDownloadMaterial as jest.Mock).mockResolvedValue(false)
expect((await GET(request(true), { params })).status).toBe(403)
})
test('创建人保留交付文件下载资格,旧账号开关关闭也不影响', async () => {
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ canDownload: false })
const response = await GET(request(true), { params })
expect(response.status).toBe(200)
expect(response.headers.get('content-disposition')).toContain('attachment')
expect(prisma.user.findUnique).not.toHaveBeenCalled()
})

View File

@ -0,0 +1,60 @@
import { createReadStream } from 'fs'
import { stat } from 'fs/promises'
import path from 'path'
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { lookup } from 'mime-types'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { canUserDownloadMaterial, canUserViewMaterial, isSuperAdmin } from '@/lib/department-permission'
import { createDownloadPermissionError, createDownloadPrivacyError } from '@/lib/download-errors'
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths'
import { isPathInAllowedDirs } from '@/lib/path-security'
import { nodeReadableToWebStream } from '@/lib/node-readable-stream'
export async function GET(request: NextRequest, { params }: { params: { id: string; assetId: string } }) {
const session = await getServerSession(authOptions)
const user = session?.user as any
if (!user?.id) return new NextResponse('请先登录', { status: 401 })
const material = await prisma.material.findFirst({
where: { id: params.id, deletedAt: null },
select: { id: true, userId: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT },
})
if (!material || !isXiaoyiDeliveryMaterial(material.materialType)) return new NextResponse('素材不存在', { status: 404 })
if (!(await canAccessMaterialPrivacy(material, user.id))) return new NextResponse(createDownloadPrivacyError(material).error, { status: 403 })
const admin = await isSuperAdmin(user.id)
const owner = material.userId === user.id
const canView = owner || admin || await canUserViewMaterial(user.department, user.role, user.managedDepartment, material.materialType, user.id)
if (!canView) return new NextResponse('你的权限包未开通这类素材的查看权限', { status: 403 })
const download = request.nextUrl.searchParams.get('download') === '1'
if (download && !admin) {
const permitted = owner || await canUserDownloadMaterial(user.department, user.role, user.managedDepartment, material.materialType, user.id)
if (!permitted) return new NextResponse(createDownloadPermissionError('materialType').error, { status: 403 })
}
const asset = await prisma.materialAsset.findFirst({ where: { id: params.assetId, materialId: material.id }, select: { fileUrl: true, fileName: true } })
if (!asset?.fileUrl) return new NextResponse('文件不存在', { status: 404 })
const filePath = resolveStoredUploadPath(asset.fileUrl)
if (!isPathInAllowedDirs(filePath, [getUploadRootDir()])) return new NextResponse('文件不存在', { status: 404 })
const name = asset.fileName || path.basename(filePath)
const mime = lookup(name) || 'application/octet-stream'
if (!download && !/^image\/(jpeg|png|gif|webp)$|^video\/(mp4|webm|ogg)$/.test(mime)) return new NextResponse('此文件不支持预览', { status: 415 })
const info = await stat(filePath).catch(() => null)
if (!info?.isFile()) return new NextResponse('文件不存在', { status: 404 })
const headers = new Headers({ 'Content-Type': mime, 'Accept-Ranges': 'bytes', 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' })
if (download) headers.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(name)}`)
const range = request.headers.get('range')?.match(/^bytes=(\d*)-(\d*)$/)
let start = 0
let end = info.size - 1
if (range) {
if (range[1]) start = Number(range[1])
if (range[2]) end = Number(range[2])
if (!range[1] && range[2]) { start = Math.max(0, info.size - Number(range[2])); end = info.size - 1 }
end = Math.min(end, info.size - 1)
if (start > end || start >= info.size) return new NextResponse(null, { status: 416, headers: { 'Content-Range': `bytes */${info.size}` } })
headers.set('Content-Range', `bytes ${start}-${end}/${info.size}`)
}
headers.set('Content-Length', String(end - start + 1))
return new NextResponse(nodeReadableToWebStream(createReadStream(filePath, { start, end })), { status: range ? 206 : 200, headers })
}

View File

@ -0,0 +1,101 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { canUserViewMaterial } from '@/lib/department-permission'
import { FinishedWebSsoError, issueFinishedWebLink } from '@/lib/finished-web-sso'
import { prisma } from '@/lib/prisma'
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
import { POST } from './route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { material: { findFirst: jest.fn() } } }))
jest.mock('@/lib/department-permission', () => ({ canUserViewMaterial: jest.fn() }))
jest.mock('@/lib/task-detail-privacy', () => ({ canAccessMaterialPrivacy: jest.fn(), TASK_DETAIL_PRIVACY_SELECT: {} }))
jest.mock('@/lib/employee-directory', () => ({}))
jest.mock('@/lib/finished-web-sso', () => ({
...jest.requireActual('@/lib/finished-web-sso'),
issueFinishedWebLink: jest.fn(),
}))
const params = { id: 'detail-material' }
const user = { id: 'viewer', role: 'USER', department: '运营部', managedDepartment: null }
const material = { userId: 'owner', materialType: '自动上架-详情', accessScope: 'general' }
const link = {
url: 'https://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link',
expiresAt: '2027-01-02T07:04:20.518Z',
user: { id: 123, username: 'operator', name: '测试账号', role: 'operator' },
}
function request(headers: Record<string, string> = { Origin: 'http://localhost:3000' }) {
return POST(new NextRequest('http://localhost:3000/api/materials/detail-material/finished-web', {
method: 'POST', headers, body: JSON.stringify({ nickname: '不应使用的花名', userId: 'other-user' }),
}), { params })
}
beforeEach(() => {
jest.resetAllMocks()
;(getServerSession as jest.Mock).mockResolvedValue({ user })
jest.mocked(prisma.material.findFirst).mockResolvedValue(material as never)
jest.mocked(canUserViewMaterial).mockResolvedValue(true)
jest.mocked(canAccessMaterialPrivacy).mockResolvedValue(true)
jest.mocked(issueFinishedWebLink).mockResolvedValue(link)
})
test('登录用户可按素材权限换链,签发身份只取自会话', async () => {
const response = await request()
expect(response.status).toBe(200)
expect(response.headers.get('cache-control')).toBe('private, no-store')
expect(await response.json()).toEqual(link)
expect(prisma.material.findFirst).toHaveBeenCalledWith(expect.objectContaining({
where: { id: params.id, deletedAt: null, materialType: '自动上架-详情' },
}))
expect(canAccessMaterialPrivacy).toHaveBeenCalledWith(material, user.id)
expect(canUserViewMaterial).toHaveBeenCalledWith(user.department, user.role, null, material.materialType, user.id)
expect(issueFinishedWebLink).toHaveBeenCalledWith(user.id)
})
test('成品所有者沿用分享页的查看权限', async () => {
jest.mocked(prisma.material.findFirst).mockResolvedValue({ ...material, userId: user.id } as never)
jest.mocked(canUserViewMaterial).mockResolvedValue(false)
expect((await request()).status).toBe(200)
expect(canAccessMaterialPrivacy).toHaveBeenCalled()
expect(canUserViewMaterial).not.toHaveBeenCalled()
})
test('未登录时拒绝换链', async () => {
;(getServerSession as jest.Mock).mockResolvedValue(null)
expect((await request()).status).toBe(401)
expect(prisma.material.findFirst).not.toHaveBeenCalled()
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test.each([
{},
{ Origin: 'https://untrusted.example', 'Sec-Fetch-Site': 'cross-site' },
])('拒绝非本站请求 %j', async headers => {
expect((await request(headers as Record<string, string>)).status).toBe(403)
expect(prisma.material.findFirst).not.toHaveBeenCalled()
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test('成品不存在、已删除或不是详情类型时不签发', async () => {
jest.mocked(prisma.material.findFirst).mockResolvedValue(null)
expect((await request()).status).toBe(404)
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test.each(['privacy', 'type'])('越权拒绝(%s)', async scope => {
jest.mocked(canAccessMaterialPrivacy).mockResolvedValue(scope !== 'privacy')
jest.mocked(canUserViewMaterial).mockResolvedValue(scope !== 'type')
expect((await request()).status).toBe(403)
expect(issueFinishedWebLink).not.toHaveBeenCalled()
})
test('传递签发模块提供的中文消息和 HTTP 状态', async () => {
jest.mocked(issueFinishedWebLink).mockRejectedValue(new FinishedWebSsoError('请稍后再试', 429, 'finished_web_upstream'))
const response = await request()
expect(response.status).toBe(429)
expect(await response.json()).toEqual({ error: '请稍后再试' })
expect(response.headers.get('cache-control')).toBe('private, no-store')
})

View File

@ -0,0 +1,41 @@
import { NextResponse, type NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isAllowedCorsOrigin } from '@/lib/cors-origin'
import { canUserViewMaterial } from '@/lib/department-permission'
import { FinishedWebSsoError, issueFinishedWebLink } from '@/lib/finished-web-sso'
import { prisma } from '@/lib/prisma'
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
import { XIAOYI_DELIVERY_MATERIAL_TYPES } from '@/lib/xiaoyi-delivery-material'
export const runtime = 'nodejs'
const headers = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' }
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
const fail = (error: string, status: number) => NextResponse.json({ error }, { status, headers })
try {
const session = await getServerSession(authOptions)
const user = session?.user as { id?: string; role: string; department?: string; managedDepartment?: string | null } | undefined
if (!user?.id) return fail('请先登录素材库', 401)
const origin = request.headers.get('origin')
if (!origin || request.headers.get('sec-fetch-site') === 'cross-site' || !isAllowedCorsOrigin(request, origin)) {
return fail('请从素材库详情页打开成品上架工作台', 403)
}
const material = await prisma.material.findFirst({
where: { id: params.id, deletedAt: null, materialType: XIAOYI_DELIVERY_MATERIAL_TYPES.detail },
select: { userId: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT },
})
if (!material) return fail('该详情成品不存在', 404)
if (!(await canAccessMaterialPrivacy(material, user.id)) || (
material.userId !== user.id &&
!(await canUserViewMaterial(user.department, user.role, user.managedDepartment, material.materialType, user.id))
)) {
return fail('无权限查看该详情成品', 403)
}
return NextResponse.json(await issueFinishedWebLink(user.id), { headers })
} catch (error) {
if (error instanceof FinishedWebSsoError) return fail(error.message, error.status)
return fail('成品上架工作台暂不可用,请稍后再试', 503)
}
}

View File

@ -1,4 +1,6 @@
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
import { isPreviewAssetType, isRestrictedMaterial } from '@/lib/material-access-scope'
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy';
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
@ -9,6 +11,7 @@ import {
canUserDownloadMaterial,
canUserDownloadSource,
canUserViewMaterial,
isSuperAdmin,
isSystemAdmin,
} from '@/lib/department-permission';
import { updateMaterialWithSharedRules, type MaterialUpdateInput } from '@/lib/material-update';
@ -130,15 +133,6 @@ function buildSourceFileUrl(materialId: string): string {
return `/api/materials/download?id=${encodeURIComponent(materialId)}`
}
function isPreviewAssetType(assetType: unknown): boolean {
const normalized = String(assetType || '').trim()
return (
['preview', 'main-preview', 'sku-preview', 'detail-preview', 'report-image'].includes(normalized) ||
normalized.startsWith('standard-model-white-bg-view:') ||
normalized.startsWith('standard-model-white-bg-other:')
)
}
// GET /api/materials/[id] - 获取单个素材详情
export async function GET(
request: NextRequest,
@ -146,7 +140,7 @@ export async function GET(
) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
if (!session?.user?.id) {
return NextResponse.json(
{ error: '请先登录' },
{ status: 401 }
@ -325,11 +319,15 @@ export async function GET(
if (!material) {
return NextResponse.json({ error: '素材不存在' }, { status: 404 });
}
if (!(await canAccessMaterialPrivacy(material as any, (session.user as any).id))) {
const { id: userId, role: userRole, department: userDepartment, managedDepartment } = session.user as any;
const [hasPrivacyAccess, userIsSuperAdmin] = await Promise.all([
canAccessMaterialPrivacy(material as any, userId),
isSuperAdmin(userId),
]);
if (!hasPrivacyAccess) {
return NextResponse.json({ error: '无权限查看此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
}
let canAccessSource = false;
const videoPreviewPolicy = getVideoPreviewPolicyFields(
(material as any).materialType,
(material as any).createdAt,
@ -349,18 +347,8 @@ export async function GET(
{ status: 403 },
);
const userRole = (session.user as any).role;
const userDepartment = (session.user as any).department;
const managedDepartment = (session.user as any).managedDepartment;
const userId = (session.user as any).id;
// 超级管理员不受限制
const { isSuperAdmin } = await import('@/lib/department-permission');
const userIsSuperAdmin = await isSuperAdmin(userId);
const canBypassVideoPreviewGate = isSystemAdmin(userRole) || userIsSuperAdmin;
const canEdit =
(material as any).userId === userId ||
canBypassVideoPreviewGate;
const canEdit = (material as any).userId === userId || canBypassVideoPreviewGate;
const materialWithUser = material as any;
const displayAuthorName =
materialWithUser.user?.realName ||
@ -415,11 +403,12 @@ export async function GET(
taskDetailDemandType: materialWithUser.taskDetailDemandType || null,
taskDetailPrivate: materialWithUser.taskDetailPrivate === true,
accessScope: materialWithUser.accessScope || 'general',
canSelectOperationsGScope: await canAccessOperationsGMaterials(userId),
canEdit: true,
});
}, { headers: { 'Cache-Control': 'private, no-store' } });
}
if (!userIsSuperAdmin && !isRestrictedMaterial(material as any)) {
if (!userIsSuperAdmin && !isRestrictedMaterial(material as any) && !(isXiaoyiDeliveryMaterial((material as any).materialType) && material.userId === userId)) {
const canView = await canUserViewMaterial(
userDepartment,
userRole,
@ -440,36 +429,18 @@ export async function GET(
return buildVideoPreviewBlockedResponse();
}
if (isSystemAdmin(userRole) || userIsSuperAdmin) {
canAccessSource = true;
} else {
const userDownloadSetting = await prisma.user.findUnique({
where: { id: userId },
select: { canDownload: true },
});
if (userDownloadSetting?.canDownload) {
const canDownloadMaterial = isRestrictedMaterial(material as any) || await canUserDownloadMaterial(
userDepartment,
userRole,
managedDepartment,
(material as any).materialType,
userId
);
const requiresSourcePermission =
isProductPackageType((material as any).materialType) ||
is3DOriginalType((material as any).materialType);
const hasSourcePermission = requiresSourcePermission
? await canUserDownloadSource(
userDepartment,
userRole,
managedDepartment,
(material as any).materialType,
userId
)
: true;
canAccessSource = canDownloadMaterial && hasSourcePermission;
}
}
const materialType = materialWithUser.materialType;
const requiresSourcePermission = isProductPackageType(materialType) || is3DOriginalType(materialType);
const canDownloadMaterial = !videoPreviewPolicy.videoPreviewBlocked && (
userIsSuperAdmin ||
(isXiaoyiDeliveryMaterial(materialType) && material.userId === userId) ||
isRestrictedMaterial(materialWithUser) ||
await canUserDownloadMaterial(userDepartment, userRole, managedDepartment, materialType, userId)
);
const canAccessSource = canDownloadMaterial && (
userIsSuperAdmin || !requiresSourcePermission ||
await canUserDownloadSource(userDepartment, userRole, managedDepartment, materialType, userId)
);
const formattedAssets = (materialWithUser.assets || []).map((asset: any) =>
formatTaskDetailAsset(asset, displayAuthorName),

View File

@ -19,7 +19,8 @@ import {
} from '@/lib/standard-model-white-background'
import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths'
import { isPathInAllowedDirs } from '@/lib/path-security'
import { canDownloadSkuMaterial } from '../../authorization'
import { TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
import { getSkuDownloadDenial } from '../../authorization'
import { nodeReadableToWebStream } from '@/lib/node-readable-stream'
import { createArchiveDownloadStream } from '@/lib/archive-download-stream'
@ -88,21 +89,12 @@ export async function GET(
}
const userId = (session.user as any).id
const user = await prisma.user.findUnique({
where: { id: userId },
select: { canDownload: true },
})
if (!user?.canDownload) {
return NextResponse.json({ error: '您没有下载权限,请联系管理员' }, { status: 403 })
}
const { skuId } = params
const materialId = params.id
const material = await prisma.material.findFirst({
where: { id: materialId, deletedAt: null },
select: { id: true, userId: true, materialType: true },
select: { id: true, userId: true, materialType: true, ...TASK_DETAIL_PRIVACY_SELECT },
})
if (!material) {
@ -113,8 +105,9 @@ export async function GET(
return NextResponse.json({ error: '只有标准模型类型才支持 SKU 下载' }, { status: 400 })
}
if (!(await canDownloadSkuMaterial(session.user as any, material))) {
return NextResponse.json({ error: '无权限下载此素材' }, { status: 403 })
const denial = await getSkuDownloadDenial(session.user as any, material)
if (denial) {
return NextResponse.json(denial, { status: 403, headers: { 'Cache-Control': 'private, no-store' } })
}
const sku = await prisma.materialSku.findFirst({

View File

@ -52,7 +52,8 @@ export async function GET(
return NextResponse.json({ error: '素材不存在' }, { status: 404 })
}
const session = await getServerSession(authOptions)
if (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) {
const userId = (session?.user as any)?.id
if (!(await canAccessMaterialPrivacy(material, userId))) {
return NextResponse.json({ error: '无权限访问此素材' }, {
status: session?.user ? 403 : 401,
headers: { 'Cache-Control': 'private, no-store' },

View File

@ -6,6 +6,7 @@ import {
import { prisma } from '@/lib/prisma'
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT, type TaskDetailPrivacyMaterial } from '@/lib/task-detail-privacy'
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { createDownloadPermissionError, createDownloadPrivacyError, type DownloadErrorResponse } from '@/lib/download-errors'
export interface SkuRouteSessionUser {
id: string
@ -27,25 +28,25 @@ export async function canManageSkuMaterial(
): Promise<boolean> {
const stored = await prisma.material.findUnique({ where: { id: material.id }, select: TASK_DETAIL_PRIVACY_SELECT })
if (!stored || !(await canAccessMaterialPrivacy(stored, user.id))) return false
if (material.userId === user.id || isSystemAdmin(user.role) || user.isSuperAdmin === true) {
if (material.userId === user.id || isSystemAdmin(user.role)) {
return true
}
return isSuperAdmin(user.id)
}
export async function canDownloadSkuMaterial(
export async function getSkuDownloadDenial(
user: SkuRouteSessionUser,
material: SkuRouteMaterial,
): Promise<boolean> {
const stored = await prisma.material.findUnique({ where: { id: material.id }, select: TASK_DETAIL_PRIVACY_SELECT })
if (!stored || !(await canAccessMaterialPrivacy(stored, user.id))) return false
if (isRestrictedMaterial(stored)) return true
return canUserDownloadMaterial(
): Promise<DownloadErrorResponse | null> {
if (!(await canAccessMaterialPrivacy(material, user.id))) return createDownloadPrivacyError(material)
if (isRestrictedMaterial(material)) return null
const allowed = await canUserDownloadMaterial(
user.department,
user.role || 'USER',
user.managedDepartment,
material.materialType,
user.id,
)
return allowed ? null : createDownloadPermissionError('materialType')
}

View File

@ -15,7 +15,8 @@ import {
} from '@/lib/standard-model-white-background'
import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths'
import { isPathInAllowedDirs } from '@/lib/path-security'
import { canDownloadSkuMaterial } from '../authorization'
import { TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
import { getSkuDownloadDenial } from '../authorization'
import { createArchiveDownloadStream } from '@/lib/archive-download-stream'
type DownloadType = 'model' | 'white-background'
@ -78,15 +79,6 @@ export async function POST(
}
const userId = (session.user as any).id
const user = await prisma.user.findUnique({
where: { id: userId },
select: { canDownload: true },
})
if (!user?.canDownload) {
return NextResponse.json({ error: '您没有下载权限,请联系管理员' }, { status: 403 })
}
const materialId = params.id
const body = await request.json()
const skuIds = Array.isArray(body?.skuIds) ? body.skuIds : []
@ -98,7 +90,7 @@ export async function POST(
const material = await prisma.material.findFirst({
where: { id: materialId, deletedAt: null },
select: { id: true, productModel: true, materialType: true, userId: true },
select: { id: true, productModel: true, materialType: true, userId: true, ...TASK_DETAIL_PRIVACY_SELECT },
})
if (!material) {
@ -109,8 +101,9 @@ export async function POST(
return NextResponse.json({ error: '只有标准模型类型才支持 SKU 批量下载' }, { status: 400 })
}
if (!(await canDownloadSkuMaterial(session.user as any, material))) {
return NextResponse.json({ error: '无权限下载此素材' }, { status: 403 })
const denial = await getSkuDownloadDenial(session.user as any, material)
if (denial) {
return NextResponse.json(denial, { status: 403, headers: { 'Cache-Control': 'private, no-store' } })
}
const skus = await prisma.materialSku.findMany({

View File

@ -65,7 +65,8 @@ export async function GET(
return NextResponse.json({ error: '素材不存在' }, { status: 404 })
}
const session = await getServerSession(authOptions)
if (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) {
const userId = (session?.user as any)?.id
if (!(await canAccessMaterialPrivacy(material, userId))) {
return NextResponse.json({ error: '无权限访问该私密素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } })
}
@ -165,7 +166,7 @@ export async function GET(
}
}),
total: skus.length,
})
}, { headers: { 'Cache-Control': 'private, no-store' } })
} catch (error) {
console.error('获取 SKU 列表失败:', error)
return NextResponse.json({ error: '获取 SKU 列表失败' }, { status: 500 })

View File

@ -14,14 +14,17 @@ import { lookup } from 'mime-types';
import {
canUserDownloadMaterial,
canUserDownloadSource,
isSuperAdmin,
} from '@/lib/department-permission';
import {
DownloadErrorCode,
createDownloadError,
createDownloadPermissionError,
createDownloadPrivacyError,
} from '@/lib/download-errors';
import { is3DOriginalType, isProductPackageType } from '@/lib/material-type-mapper';
import { ensureMaterialDownloadLogsTable } from '@/lib/material-download-log';
import { resolveStoredUploadPath } from '@/lib/upload-paths';
import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths';
import {
getVideoDownloadAvailability,
getVideoDownloadUnavailableMessage,
@ -38,30 +41,15 @@ function normalizeStoredLocalPath(filePath: string) {
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
if (!session?.user?.id) {
return NextResponse.json(
createDownloadError(DownloadErrorCode.UNAUTHORIZED),
{ status: 401 }
);
}
const userId = (session.user as any).id;
const userRole = (session.user as any).role;
// 检查用户级别的下载权限
if (userRole !== 'ADMIN') {
const user = await prisma.user.findUnique({
where: { id: userId },
select: { canDownload: true },
});
if (!user || !user.canDownload) {
return NextResponse.json(
createDownloadError(DownloadErrorCode.FORBIDDEN),
{ status: 403 }
);
}
}
const { id: userId, role: userRole, department: userDepartment, managedDepartment } = session.user;
const userIsSuperAdmin = await isSuperAdmin(userId);
const { searchParams } = new URL(request.url);
const materialId = searchParams.get('id');
@ -102,7 +90,7 @@ export async function GET(request: NextRequest) {
);
}
if (!(await canAccessMaterialPrivacy(material, userId))) {
return NextResponse.json(createDownloadError(DownloadErrorCode.NO_PERMISSION, '无权限下载此素材'), { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
return NextResponse.json(createDownloadPrivacyError(material), { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
}
const videoDownloadAvailability = getVideoDownloadAvailability(
@ -121,13 +109,9 @@ export async function GET(request: NextRequest) {
);
}
// 所有下载请求都必须检查部门和源文件权限,查询参数不能绕过。
const userDepartment = (session.user as any).department;
const managedDepartment = (session.user as any).managedDepartment;
// 超级管理员不受限制
const { isSuperAdmin } = await import('@/lib/department-permission');
if (!(await isSuperAdmin(userId))) {
// 通用素材查下载权限包,已通过准入的私密及专属素材沿用范围授权。
// 超级管理员可跳过权限包,视频保护期仍由上面的规则判定。
if (!userIsSuperAdmin) {
const canDownload = isRestrictedMaterial(material) || await canUserDownloadMaterial(
userDepartment,
userRole,
@ -138,7 +122,7 @@ export async function GET(request: NextRequest) {
if (!canDownload) {
return NextResponse.json(
createDownloadError(DownloadErrorCode.NO_PERMISSION),
createDownloadPermissionError('materialType'),
{ status: 403 }
);
}
@ -158,7 +142,7 @@ export async function GET(request: NextRequest) {
if (!canDownloadSourceFile) {
return NextResponse.json(
createDownloadError(DownloadErrorCode.NO_PERMISSION, '无权限下载该源文件'),
createDownloadPermissionError('sourceFile'),
{ status: 403 }
);
}
@ -261,7 +245,7 @@ async function serveFile(filePath: string, material: any, fileNameSuffix: string
);
}
const allowedDirs = getAllowedFileDirectories();
const allowedDirs = [getUploadRootDir(), ...getAllowedFileDirectories()];
if (!isPathInAllowedDirs(filePath, allowedDirs)) {
console.error('[Download] 路径越界:', filePath, '允许的目录:', allowedDirs);
return NextResponse.json(

View File

@ -217,6 +217,7 @@ export async function GET(request: NextRequest) {
const responseData = {
total,
canFilterOperationsGScope: context.canAccessOperationsGMaterials === true,
categories: categoryResult.items,
scenes: sceneResult.items,
platforms: platformResult.items,

View File

@ -1,5 +1,6 @@
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
import { isSuperAdmin, isSystemAdmin } from '@/lib/department-permission'
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
@ -15,7 +16,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: '未登录' }, { status: 401 });
}
const userRole = (session.user as any).role;
if (userRole !== 'ADMIN') {
const userId = (session.user as any).id;
if (!isSystemAdmin(userRole) && !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '无权限' }, { status: 403 });
}
@ -34,8 +36,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: '素材不存在' }, { status: 404 });
}
if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials((session.user as any).id))) {
return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 });
if (!(await canAccessMaterialPrivacy(material, userId))) {
return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 });
}
const restoredTaskNo = getOriginalTaskNo((material as any).taskNo);
@ -143,7 +145,6 @@ export async function POST(request: NextRequest) {
]);
// 记录操作日志
const userId = (session.user as any).id;
await createMaterialLog({
materialId: id,
userId,

View File

@ -1,12 +1,12 @@
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy';
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSystemAdmin } from '@/lib/department-permission';
import { canUserViewMaterial, isSuperAdmin, isSystemAdmin } from '@/lib/department-permission';
import { createMaterialLog } from '@/lib/material-log';
import { enqueueMaterialPurge, ensureMaterialPurgeWorkerStarted, MaterialPurgeError } from '@/lib/material-purge';
import { normalizeUrl, normalizeMaterial } from '@/lib/utils';
@ -14,6 +14,7 @@ import { rewriteMediaUrlForClient } from '@/lib/url-rewrite';
import { detectIsIntranet } from '@/lib/network-detection';
import {
buildMaterialWhereFromSearchParams,
createMaterialQueryContext,
MaterialQueryError,
} from '@/lib/material-query';
import { getMaterialCoverUrl } from '@/lib/product-package';
@ -174,7 +175,8 @@ export async function GET(request: NextRequest) {
if (!material) {
return NextResponse.json({ material: null });
}
if (!(await canAccessMaterialPrivacy(material, (session.user as any).id))) {
const userId = (session.user as any).id;
if (!(await canAccessMaterialPrivacy(material, userId))) {
return NextResponse.json({ error: '无权限查看此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
}
@ -182,10 +184,8 @@ export async function GET(request: NextRequest) {
const userRole = (session.user as any).role;
const userDepartment = (session.user as any).department;
const managedDepartment = (session.user as any).managedDepartment;
const userId = (session.user as any).id;
// 超级管理员不受限制
const { isSuperAdmin, canUserViewMaterial } = await import('@/lib/department-permission');
if (!isRestrictedMaterial(material) && !(await isSuperAdmin(userId))) {
const canView = await canUserViewMaterial(
userDepartment,
@ -263,13 +263,12 @@ export async function GET(request: NextRequest) {
// 优先使用用户的真实姓名或用户名,如果没有才使用 authorName
const displayAuthorName = material.user?.realName || material.user?.username || material.authorName;
const formattedAssets = (material.assets || []).map((asset: any) =>
formatTaskDetailAssetSummary(
const formattedAssets = (material.assets || [])
.map((asset: any) => formatTaskDetailAssetSummary(
asset,
displayAuthorName,
(fileUrl) => rewriteMediaUrlForClient(fileUrl, request, 'image'),
),
);
));
const normalizedMaterial = normalizeMaterial({
...material,
@ -303,10 +302,9 @@ export async function GET(request: NextRequest) {
console.warn(`[Materials API] pageSize 超过限制:${rawPageSize} > ${MAX_PAGE_SIZE},已自动限制为 ${MAX_PAGE_SIZE}`);
}
const { where, empty } = await buildMaterialWhereFromSearchParams(
searchParams,
session.user as any,
);
const user = session.user as any;
const context = await createMaterialQueryContext(searchParams, user);
const { where, empty } = await buildMaterialWhereFromSearchParams(searchParams, user, { context });
if (empty) {
return NextResponse.json({
@ -768,9 +766,29 @@ export async function GET(request: NextRequest) {
}
}
// 交付素材使用已有鉴权文件接口作为卡片封面,视频没有图片时保持占位。
const deliveryCoverMap = new Map<string, string>();
const deliveryCoverIds = materials.filter((m) =>
(m.materialType === '自动上架-详情' || m.materialType === '自动上架-买家秀') && !m.previewUrl
).map((m) => m.id);
if (deliveryCoverIds.length) {
const deliveryAssets = await prisma.materialAsset.findMany({
where: { materialId: { in: deliveryCoverIds }, assetType: { in: ['main', 'sku', 'detail', 'buyer_show'] } },
select: { id: true, materialId: true, assetType: true, fileName: true, sortOrder: true },
orderBy: [{ sortOrder: 'asc' }],
});
const rank: Record<string, number> = { main: 0, sku: 1, detail: 2, buyer_show: 0 };
deliveryAssets.sort((a, b) => (rank[a.assetType] ?? 9) - (rank[b.assetType] ?? 9) || a.sortOrder - b.sortOrder);
for (const asset of deliveryAssets) {
if (!deliveryCoverMap.has(asset.materialId) && /\.(jpe?g|png|webp|gif)$/i.test(asset.fileName || '')) {
deliveryCoverMap.set(asset.materialId, `/api/materials/${encodeURIComponent(asset.materialId)}/delivery-assets/${encodeURIComponent(asset.id)}`);
}
}
}
const formattedMaterials = materials.map(material => {
// 处理previewUrl的fallback逻辑
let previewUrl = material.previewUrl || material.videoCoverUrl || '';
let previewUrl = material.previewUrl || material.videoCoverUrl || deliveryCoverMap.get(material.id) || '';
if (!previewUrl && material.materialType === '任务-页面') {
const coverUrl = coverUrlMap.get(material.id);
@ -805,13 +823,12 @@ export async function GET(request: NextRequest) {
// 优先使用用户的真实姓名或用户名,如果没有才使用 authorName
const displayAuthorName = material.user?.realName || material.user?.username || material.authorName;
const formattedAssets = (material.assets || []).map((asset: any) =>
formatTaskDetailAssetSummary(
const formattedAssets = (material.assets || [])
.map((asset: any) => formatTaskDetailAssetSummary(
asset,
displayAuthorName,
(fileUrl) => rewriteMediaUrlForClient(fileUrl, request, 'image'),
),
);
));
const formatted = {
...material,
@ -854,7 +871,7 @@ export async function GET(request: NextRequest) {
const rewrittenMaterial = {
...formatted,
// 图片:使用统一规则(内网用户直接访问内网MinIO,外网用户根据文件大小决定是否走代理)
previewUrl: rewriteMediaUrlForClient(formatted.previewUrl, request, 'image'),
previewUrl: isXiaoyiDeliveryMaterial(formatted.materialType) ? formatted.previewUrl : rewriteMediaUrlForClient(formatted.previewUrl, request, 'image'),
videoCoverUrl: rewriteMediaUrlForClient(formatted.videoCoverUrl, request, 'image'),
displayImages: formatted.displayImages?.map((img: string) =>
rewriteMediaUrlForClient(img, request, 'image')
@ -912,7 +929,8 @@ export async function DELETE(request: NextRequest) {
);
}
const userRole = (session.user as any).role;
if (!isSystemAdmin(userRole)) {
const userId = (session.user as any).id;
if (!isSystemAdmin(userRole) && !(await isSuperAdmin(userId))) {
return NextResponse.json(
{ error: '无权限' },
{ status: 403 }
@ -948,10 +966,8 @@ export async function DELETE(request: NextRequest) {
);
}
const userId = (session.user as any).id;
if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) {
return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 });
if (!(await canAccessMaterialPrivacy(material, userId))) {
return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 });
}
// 软删除

View File

@ -1,4 +1,5 @@
import { isRestrictedMaterial } from '@/lib/material-access-scope'
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
import { isPreviewAssetType, isRestrictedMaterial } from '@/lib/material-access-scope'
import { canAccessMaterialPrivacy, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy';
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
@ -7,10 +8,10 @@ import { prisma } from '@/lib/prisma';
import path from 'path';
import { rewriteMediaUrlForClient } from '@/lib/url-rewrite';
import {
canUserViewMaterial,
canUserDownloadMaterial,
canUserDownloadSource,
hasSystemAdminPermission,
isSystemAdmin,
} from '@/lib/department-permission';
import { isProductPackageType, is3DOriginalType, needsAssetsList } from '@/lib/material-type-mapper';
import { deriveTaskDetailIsFullSet } from '@/lib/task-detail-full-set';
@ -96,15 +97,6 @@ function buildSourceFileUrl(materialId: string): string {
return `/api/materials/download?id=${encodeURIComponent(materialId)}`
}
function isPreviewAssetType(assetType: unknown): boolean {
const normalized = String(assetType || '').trim()
return (
['preview', 'main-preview', 'sku-preview', 'detail-preview', 'report-image'].includes(normalized) ||
normalized.startsWith('standard-model-white-bg-view:') ||
normalized.startsWith('standard-model-white-bg-other:')
)
}
// GET /api/materials/share - 获取分享素材信息(无需登录,但登录用户会返回点赞和收藏状态)
export async function GET(request: NextRequest) {
try {
@ -172,6 +164,14 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: '请登录有权限的账号查看此素材' }, { status: userId ? 403 : 401, headers: { 'Cache-Control': 'private, no-store' } });
}
if (isXiaoyiDeliveryMaterial((material as any).materialType)) {
if (!userId) return NextResponse.json({ error: '请登录后查看此素材' }, { status: 401 })
const user = session!.user as any
if (material.userId !== userId && !(await canUserViewMaterial(user.department, user.role, user.managedDepartment, (material as any).materialType, userId))) {
return NextResponse.json({ error: '无权限查看该素材' }, { status: 403 })
}
}
const videoPreviewPolicy = getVideoPreviewPolicyFields(
(material as any).materialType,
(material as any).createdAt,
@ -263,7 +263,6 @@ export async function GET(request: NextRequest) {
role: string;
department: string | null;
managedDepartment: string | null;
canDownload: boolean;
isSuperAdmin: boolean;
} | null = null;
@ -287,7 +286,6 @@ export async function GET(request: NextRequest) {
role: true,
department: true,
managedDepartment: true,
canDownload: true,
isSuperAdmin: true,
},
}),
@ -298,33 +296,19 @@ export async function GET(request: NextRequest) {
currentUser = user;
}
// 任务-详情 PSD 和任务原图 ZIP 按各自素材类型检查源文件权限。
let canAccessSource = false;
if (userId && currentUser) {
if (hasSystemAdminPermission(currentUser.role, Boolean(currentUser.isSuperAdmin))) {
canAccessSource = true;
} else if (currentUser.canDownload) {
const canDownloadMaterial = isRestrictedMaterial(material as any) || await canUserDownloadMaterial(
currentUser.department,
currentUser.role,
currentUser.managedDepartment,
material.materialType as unknown as string,
userId
);
const requiresSourcePermission =
isProductPackageType(material.materialType as unknown as string) ||
is3DOriginalType(material.materialType as unknown as string);
const hasSourcePermission = requiresSourcePermission
? await canUserDownloadSource(
currentUser.department,
currentUser.role,
currentUser.managedDepartment,
material.materialType as unknown as string,
userId
)
: true;
canAccessSource = canDownloadMaterial && hasSourcePermission;
}
const materialType = material.materialType as unknown as string;
const { department, role, managedDepartment, isSuperAdmin } = currentUser;
const requiresSourcePermission = isProductPackageType(materialType) || is3DOriginalType(materialType);
const canDownloadMaterial = isSuperAdmin ||
(isXiaoyiDeliveryMaterial(materialType) && material.userId === userId) ||
isRestrictedMaterial(material) ||
await canUserDownloadMaterial(department, role, managedDepartment, materialType, userId);
canAccessSource = canDownloadMaterial && (
isSuperAdmin || !requiresSourcePermission ||
await canUserDownloadSource(department, role, managedDepartment, materialType, userId)
);
}
const capabilities = {
@ -337,8 +321,7 @@ export async function GET(request: NextRequest) {
hasSystemAdminPermission(currentUser.role, Boolean(currentUser.isSuperAdmin))
)
),
// 与 DELETE /api/materials 当前契约保持一致:仅系统管理员角色可删除。
canDelete: Boolean(currentUser && isSystemAdmin(currentUser.role)),
canDelete: Boolean(currentUser && hasSystemAdminPermission(currentUser.role, currentUser.isSuperAdmin)),
};
// 任务-详情单图编辑(替换/改名/删除)与元数据编辑权限口径不同:

View File

@ -1,4 +1,4 @@
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { canUseOperationsGMaterials } from '@/lib/material-organization-access'
// 视频转码API - 完整版本(支持自动恢复)
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
@ -6,7 +6,7 @@ import { prisma } from '@/lib/prisma';
import { transcodeQueue, VIDEO_MATERIAL_TYPES } from '@/lib/video-transcode-queue';
import { executeTranscodeTask, USER_TRANSCODE_FAILURE_MESSAGE } from '@/lib/video-transcode-task';
import { authOptions } from '@/lib/auth';
import { canUserViewMaterial, hasSystemAdminPermission } from '@/lib/department-permission';
import { canUserViewMaterial, hasSystemAdminPermission, isSuperAdmin } from '@/lib/department-permission';
export const dynamic = 'force-dynamic';
export const maxDuration = 3600; // 1小时
@ -69,10 +69,7 @@ export async function GET(request: NextRequest) {
}
const sessionUser = session.user as any;
const isSystemAdministrator = hasSystemAdminPermission(
sessionUser.role,
Boolean(sessionUser.isSuperAdmin),
);
const isSystemAdministrator = hasSystemAdminPermission(sessionUser.role) || await isSuperAdmin(sessionUser.id);
const retryAfter = consumeRateLimit(`status:${String(sessionUser.id || 'unknown')}`, STATUS_RATE_LIMIT);
if (retryAfter) {
return rateLimitResponse(retryAfter);
@ -111,7 +108,7 @@ export async function GET(request: NextRequest) {
{ status: 404 }
);
}
const canAccessG = await canAccessOperationsGMaterials(sessionUser.id);
const canAccessG = await canUseOperationsGMaterials(sessionUser.id);
if (material.accessScope === 'operations_g' && !canAccessG) {
return NextResponse.json({ error: '无权限访问此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
}
@ -173,10 +170,7 @@ export async function POST(request: NextRequest) {
}
const sessionUser = session.user as any;
const isSystemAdministrator = hasSystemAdminPermission(
sessionUser.role,
Boolean(sessionUser.isSuperAdmin),
);
const isSystemAdministrator = hasSystemAdminPermission(sessionUser.role) || await isSuperAdmin(sessionUser.id);
const retryAfter = consumeRateLimit(`start:${String(sessionUser.id || 'unknown')}`, START_RATE_LIMIT);
if (retryAfter) {
@ -223,7 +217,7 @@ export async function POST(request: NextRequest) {
);
}
const canAccessG = await canAccessOperationsGMaterials(sessionUser.id);
const canAccessG = await canUseOperationsGMaterials(sessionUser.id);
if (material.accessScope === 'operations_g' && !canAccessG) {
return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 });
}

View File

@ -2,7 +2,7 @@ import { randomUUID } from 'crypto'
import { mkdir, open, rename, rm } from 'fs/promises'
import path from 'path'
import { NextRequest, NextResponse } from 'next/server'
import { getAuthenticatedUploadUserId } from '@/lib/upload-auth'
import { getAuthenticatedUploadUserId, getDesktopDeliveryUploadUserId } from '@/lib/upload-auth'
import { getUploadSession, updateChunkWithStats } from '@/lib/upload-sessions'
import {
getExpectedUploadChunkBytes,
@ -58,7 +58,7 @@ export async function POST(req: NextRequest) {
try {
const authStartedAt = Date.now()
const userId = await getAuthenticatedUploadUserId(req)
const userId = await getDesktopDeliveryUploadUserId(req, 'chunk') || await getAuthenticatedUploadUserId(req)
const authTime = Date.now() - authStartedAt
console.log(`[UploadChunk] 🔐 认证完成: ${authTime}ms`)

View File

@ -11,7 +11,7 @@ import {
mergeUploadChunksAtomically,
} from '@/lib/material-upload-merge'
import { MaterialUploadStorageReservationManager } from '@/lib/material-upload-storage-reservation'
import { cancelUploadSessionSeal } from '@/lib/material-upload-session-seal'
import { beginUploadCompletionSeal, cancelUploadSessionSeal, completeUploadCompletionSeal } from '@/lib/material-upload-session-seal'
import {
deleteUploadSession,
getOwnedUploadSession,
@ -87,6 +87,21 @@ describe('material upload complete safety', () => {
expect(await readFile(secondBody.existingFilePath)).toEqual(fileBytes)
})
test('发布前已经完成的会话继续返回原合并路径', async () => {
const tempDir = path.join(uploadRoot, 'temp', uploadId)
const legacyPath = path.join(tempDir, `merged-${fileName}`)
await writeFile(legacyPath, fileBytes)
const seal = await beginUploadCompletionSeal(uploadId)
if (seal.state !== 'sealing') throw new Error('预期会话可封存')
await completeUploadCompletionSeal(seal.handle)
await rm(path.join(tempDir, 'chunk-0'))
await rm(path.join(tempDir, 'chunk-1'))
const response = await POST(completeRequest())
expect(response.status).toBe(200)
await expect(response.json()).resolves.toMatchObject({ existingFilePath: legacyPath, fileName })
})
test('cancelled 终态让 complete 结构化 fail-closed', async () => {
await cancelUploadSessionSeal(uploadId)

View File

@ -1,11 +1,12 @@
import { PERFORMANCE_CASE_UPLOAD_PURPOSE } from '@/lib/performance-survey-attachment-contract'
// 分片上传完成合并接口
// 负责将分片文件按顺序合并为完整文件,校验大小,并返回服务器侧可复用的文件路径
// 供前端在第二步调用正式上传接口时复用,避免重复上传大文件
import { lstat, rm } from 'fs/promises'
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { getDesktopDeliveryUploadUserId } from '@/lib/upload-auth'
import {
acquireUploadMergeDiskReservation,
mergeUploadChunksAtomically,
@ -24,8 +25,9 @@ import {
getOwnedUploadSession,
isSafeUploadId,
} from '@/lib/upload-sessions'
import { getUploadRootDir } from '@/lib/upload-paths'
import { normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security'
import { getUploadRootDir, inspectUploadOutput } from '@/lib/upload-paths'
import { resolveStrictChildPath } from '@/lib/path-security'
import { normalizeUploadFileName } from '@/lib/upload-file-name'
import {
acquireMaterialUploadStorageLock,
type MaterialUploadStorageLockRelease,
@ -49,8 +51,9 @@ export async function POST(req: NextRequest) {
let completionSealFinalized = false
try {
const session = await getServerSession(authOptions)
const userId = String((session?.user as { id?: unknown } | undefined)?.id || '').trim()
const desktopUserId = await getDesktopDeliveryUploadUserId(req, 'complete')
const session = desktopUserId ? null : await getServerSession(authOptions)
const userId = desktopUserId || String((session?.user as { id?: unknown } | undefined)?.id || '').trim()
if (!userId) {
return NextResponse.json({ error: '请先登录' }, { status: 401 })
}
@ -68,13 +71,14 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: '上传会话不存在、已过期或无权访问' }, { status: 404 })
}
const mergedFileName = normalizeSafeFileName(uploadSession.fileName)
if (uploadSession.uploadPurpose === PERFORMANCE_CASE_UPLOAD_PURPOSE) {
return NextResponse.json({ error: '请从考核调研提交附件' }, { status: 403 })
}
const mergedFileName = normalizeUploadFileName(uploadSession.fileName)
const uploadRoot = getUploadRootDir()
const tempDir = resolveStrictChildPath(uploadRoot, 'temp', uploadId)
const mergedPath = mergedFileName
? resolveStrictChildPath(tempDir || '', `merged-${mergedFileName}`)
: null
if (!tempDir || !mergedFileName || !mergedPath) {
if (!tempDir || !mergedFileName) {
return NextResponse.json({ error: '上传会话路径无效' }, { status: 400 })
}
@ -117,11 +121,10 @@ export async function POST(req: NextRequest) {
// 第一次请求可能已经成功,只是响应在公网链路中丢失。完整且大小一致的
// merged 文件是同一会话的确定结果,重复调用直接返回同一路径。
const existingMerged = await inspectExistingMergedFile(
mergedPath,
uploadSession.fileSize,
const { outputPath: mergedPath, existing } = await inspectUploadOutput(
tempDir, 'merged-file', 'merged-', mergedFileName,
)
if (existingMerged === 'valid') {
if (existing?.stats.isFile() && existing.stats.size === uploadSession.fileSize) {
if (completionSealHandle) {
await completeUploadCompletionSeal(completionSealHandle)
completionSealFinalized = true
@ -129,7 +132,7 @@ export async function POST(req: NextRequest) {
await cleanupCompletedUpload(uploadId, chunks.map((chunk) => chunk.path))
return createCompletedResponse({
uploadId,
mergedPath,
mergedPath: existing.filePath,
mergedFileName,
fileSize: uploadSession.fileSize,
})
@ -141,8 +144,8 @@ export async function POST(req: NextRequest) {
'UPLOAD_COMPLETED_FILE_INVALID',
)
}
if (existingMerged === 'invalid') {
await rm(mergedPath, { force: true })
if (existing) {
await rm(existing.filePath, { force: true })
}
for (let index = 0; index < chunks.length; index += 1) {
@ -222,25 +225,6 @@ export async function POST(req: NextRequest) {
}
}
async function inspectExistingMergedFile(
mergedPath: string,
expectedBytes: number,
): Promise<'missing' | 'valid' | 'invalid'> {
try {
const stats = await lstat(mergedPath)
return !stats.isSymbolicLink()
&& stats.isFile()
&& stats.size === expectedBytes
? 'valid'
: 'invalid'
} catch (error: any) {
if (error?.code === 'ENOENT') {
return 'missing'
}
throw error
}
}
async function cleanupCompletedUpload(uploadId: string, chunkFiles: string[]): Promise<void> {
for (const chunkFile of chunkFiles) {
try {

View File

@ -0,0 +1,102 @@
/** @jest-environment node */
import { mkdtemp, readFile, rm } from 'fs/promises'
import os from 'os'
import path from 'path'
import { getServerSession } from 'next-auth'
import { NextRequest } from 'next/server'
import { POST as init } from './init/route'
import { POST as chunk } from './chunk/route'
import { POST as complete } from './complete/route'
import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup'
import { getOwnedUploadSession, getUploadedFile, resolveOwnedMergedUpload } from '@/lib/upload-sessions'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
function jsonRequest(endpoint: string, body: object) {
return new NextRequest(`http://localhost/api/materials/upload/${endpoint}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
}
describe('分片上传展示名与实际文件路径', () => {
const content = Buffer.from('source-content')
const owner = 'user-1'
let uploadRoot: string
const previousUploadDir = process.env.UPLOAD_DIR
beforeEach(async () => {
uploadRoot = await mkdtemp(path.join(os.tmpdir(), 'upload-file-name-'))
process.env.UPLOAD_DIR = uploadRoot
jest.mocked(getServerSession).mockResolvedValue({ user: { id: owner } })
})
afterEach(async () => {
if (previousUploadDir === undefined) delete process.env.UPLOAD_DIR
else process.env.UPLOAD_DIR = previousUploadDir
await rm(uploadRoot, { recursive: true, force: true })
})
async function upload(fileName: string) {
const response = await init(jsonRequest('init', {
fileName, fileSize: content.length, totalChunks: 1,
}))
const body = await response.json()
expect(body).toEqual({ uploadId: expect.any(String) })
expect(response.status).toBe(200)
const chunkResponse = await chunk(new NextRequest('http://localhost/api/materials/upload/chunk', {
method: 'POST',
headers: {
'content-type': 'application/octet-stream',
'content-length': String(content.length),
'x-upload-id': body.uploadId,
'x-chunk-index': '0',
'x-chunk-size': String(content.length),
'x-file-name': encodeURIComponent(fileName),
},
body: content,
}))
expect(chunkResponse.status).toBe(200)
return body.uploadId as string
}
test.each([
`ZH-GBSFY-${'SJ045004N1410V01-1-'.repeat(18)}组合款...psd`,
`${'文'.repeat(254)}ab.psb`,
'a..b.jpg',
])('init、分片、合并与重试完整保留名称 %s', async (fileName) => {
const uploadId = await upload(fileName)
const first = await complete(jsonRequest('complete', { uploadId }))
const firstBody = await first.json()
expect(firstBody).toMatchObject({ fileName, fileSize: content.length, uploadId })
expect(first.status).toBe(200)
const mergedPath = firstBody.existingFilePath
expect(Buffer.byteLength(path.basename(mergedPath))).toBeLessThanOrEqual(200)
expect(path.extname(mergedPath)).toBe(path.extname(fileName))
await expect(readFile(mergedPath)).resolves.toEqual(content)
const retry = await complete(jsonRequest('complete', { uploadId }))
expect(retry.status).toBe(200)
await expect(retry.json()).resolves.toEqual(firstBody)
await expect(resolveOwnedMergedUpload({ existingFilePath: mergedPath, userId: owner, uploadId }))
.resolves.toMatchObject({ session: { fileName } })
})
test('产品包组装后按会话名清理长中文文件', async () => {
const fileName = `${'组合源文件'.repeat(30)}...psd`
const uploadId = await upload(fileName)
await expect(getOwnedUploadSession(uploadId, owner)).resolves.toMatchObject({ fileName })
const assembledPath = await getUploadedFile(uploadId)
expect(assembledPath).toBe(path.join(uploadRoot, 'assembled', `${uploadId}.psd`))
await expect(readFile(assembledPath!)).resolves.toEqual(content)
await expect(getUploadedFile(uploadId)).resolves.toBe(assembledPath)
await cleanupConsumedUploadSession(uploadId)
await expect(readFile(assembledPath!)).rejects.toMatchObject({ code: 'ENOENT' })
})
})

View File

@ -4,6 +4,7 @@ import { POST } from '@/app/api/materials/upload/init/route'
import { getServerSession } from 'next-auth'
import { saveUploadSession } from '@/lib/upload-sessions'
import { ensureSafeDirectoryWithinRoot } from '@/lib/path-security'
import { MAX_UPLOAD_FILE_NAME_BYTES } from '@/lib/upload-file-name'
import { rm, statfs, writeFile } from 'fs/promises'
jest.mock('next-auth', () => ({
@ -228,21 +229,27 @@ describe('/api/materials/upload/init', () => {
}))
expect(response.status).toBe(400)
await expect(response.json()).resolves.toEqual({
error: '文件名包含不安全的路径或字符',
await expect(response.json()).resolves.toMatchObject({
code: 'FILE_NAME_INVALID',
error: `文件名包含不支持的路径或字符。请修改「${JSON.stringify(fileName).slice(1, -1)}」后重新选择`,
})
expect(ensureSafeDirectoryWithinRoot).not.toHaveBeenCalled()
expect(saveUploadSession).not.toHaveBeenCalled()
})
test('拒绝超过文件系统叶子名称上限的文件名', async () => {
test('文件名超出展示名上限时提示具体文件及长度限制', async () => {
const fileName = `组合款-${'文'.repeat(MAX_UPLOAD_FILE_NAME_BYTES / 3)}-源文件.psd`
const response = await POST(createRequest({
fileName: `${'文'.repeat(90)}.psd`,
fileName,
fileSize: 1024,
totalChunks: 1,
}))
expect(response.status).toBe(400)
await expect(response.json()).resolves.toMatchObject({
code: 'FILE_NAME_TOO_LONG',
error: expect.stringMatching(/^文件名过长.*请缩短「组合款-.*….*-源文件\.psd」/),
})
expect(saveUploadSession).not.toHaveBeenCalled()
})
})

View File

@ -1,11 +1,10 @@
import { PERFORMANCE_CASE_UPLOAD_PURPOSE, validatePerformanceCaseAttachments } from '@/lib/performance-survey-attachment-contract'
import { NextRequest, NextResponse } from 'next/server'
import { getAuthenticatedUploadUserId } from '@/lib/upload-auth'
import { getAuthenticatedUploadUserId, getDesktopDeliveryUploadUserId, isDesktopDeliveryPurpose } from '@/lib/upload-auth'
import { saveUploadSession } from '@/lib/upload-sessions'
import { getUploadRootDir } from '@/lib/upload-paths'
import {
ensureSafeDirectoryWithinRoot,
normalizeSafeFileName,
} from '@/lib/path-security'
import { ensureSafeDirectoryWithinRoot } from '@/lib/path-security'
import { validateUploadFileName } from '@/lib/upload-file-name'
import { randomBytes } from 'crypto'
import { rm, statfs, writeFile } from 'fs/promises'
import path from 'path'
@ -18,11 +17,12 @@ import {
const MEBIBYTE = 1024 * 1024
const GIBIBYTE = 1024 * MEBIBYTE
const MIN_FREE_SPACE_RESERVE_BYTES = 2 * GIBIBYTE
const ALLOWED_UPLOAD_PURPOSES = new Set(['brand-knowledge'])
const ALLOWED_UPLOAD_PURPOSES = new Set(['brand-knowledge', PERFORMANCE_CASE_UPLOAD_PURPOSE])
export async function POST(req: NextRequest) {
try {
const userId = await getAuthenticatedUploadUserId(req)
const desktopUserId = await getDesktopDeliveryUploadUserId(req, 'init')
const userId = desktopUserId || await getAuthenticatedUploadUserId(req)
if (!userId) {
return NextResponse.json({ error: '请先登录' }, { status: 401 })
}
@ -38,23 +38,29 @@ export async function POST(req: NextRequest) {
)
}
const rawFileName = typeof body?.fileName === 'string' ? body.fileName : ''
const normalizedFileName = normalizeSafeFileName(rawFileName)
const name = validateUploadFileName(body?.fileName)
if (name.fileName === null) {
return NextResponse.json(
{ error: name.error, ...(name.code !== 'FILE_NAME_EMPTY' ? { code: name.code } : {}) },
{ status: 400 },
)
}
const normalizedFileSize = Number(body?.fileSize)
const normalizedTotalChunks = Number(body?.totalChunks)
const uploadPurpose = typeof body?.uploadPurpose === 'string'
? body.uploadPurpose.trim()
: ''
if (!rawFileName.trim()) {
return NextResponse.json({ error: '文件名不能为空' }, { status: 400 })
}
if (!normalizedFileName) {
return NextResponse.json({ error: '文件名包含不安全的路径或字符' }, { status: 400 })
}
if (uploadPurpose && !ALLOWED_UPLOAD_PURPOSES.has(uploadPurpose)) {
if (uploadPurpose && !ALLOWED_UPLOAD_PURPOSES.has(uploadPurpose) && !(desktopUserId && isDesktopDeliveryPurpose(uploadPurpose))) {
return NextResponse.json({ error: '上传用途无效' }, { status: 400 })
}
if (uploadPurpose === PERFORMANCE_CASE_UPLOAD_PURPOSE) {
const failure = validatePerformanceCaseAttachments([{ name: name.fileName, size: normalizedFileSize }])
if (failure) return NextResponse.json({ error: failure }, { status: 400 })
}
if (desktopUserId && isDesktopDeliveryPurpose(uploadPurpose) && /\.(?:psd|psb|pcraft)$/i.test(name.fileName)) {
return NextResponse.json({ error: '只接收上架成品,不接收源文件' }, { status: 400 })
}
if (!Number.isSafeInteger(normalizedFileSize) || normalizedFileSize <= 0) {
return NextResponse.json({ error: '上传文件不能为空' }, { status: 400 })
@ -120,7 +126,7 @@ export async function POST(req: NextRequest) {
// 写入元数据,方便在Redis丢失时回溯
const metaPath = path.join(tempDir, 'meta.json')
const metaPayload = {
fileName: normalizedFileName,
fileName: name.fileName,
fileSize: normalizedFileSize,
totalChunks: normalizedTotalChunks,
chunkSize: normalizedChunkSize,
@ -133,7 +139,7 @@ export async function POST(req: NextRequest) {
// 保存会话(使用统一的接口,自动选择Redis或内存Map)
const now = Date.now()
await saveUploadSession(uploadId, {
fileName: normalizedFileName,
fileName: name.fileName,
fileSize: normalizedFileSize,
totalChunks: normalizedTotalChunks,
chunkSize: normalizedChunkSize,

View File

@ -32,6 +32,7 @@ jest.mock('next-auth', () => ({
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('fs', () => ({
...jest.requireActual('fs'),
promises: {
mkdir: jest.fn().mockResolvedValue(undefined),
rename: jest.fn().mockResolvedValue(undefined),

View File

@ -1,5 +1,6 @@
import { MaterialAccessScopeError, resolveMaterialUploadAccessScope, canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
// 素材上传API - 支持多种素材类型
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
@ -9,6 +10,7 @@ import { uploadToS3 } from '@/lib/s3';
import { promises as fs } from 'fs';
import path from 'path';
import { randomBytes, randomUUID } from 'crypto';
import { getUploadStorageExtension } from '@/lib/upload-paths';
import { parseAudioMetadata, isAudioFile } from '@/lib/audio-processor';
import { enqueueVideoTranscodeTask, USER_TRANSCODE_FAILURE_MESSAGE } from '@/lib/video-transcode-task';
import { AUTO_GENERAL_TYPES, requiresCategoryAndScene, requiresRenderer, getDefaultRenderer } from '@/lib/material-validation';
@ -474,6 +476,10 @@ export async function POST(request: NextRequest) {
const materialTypeRaw = formData.get('materialType') as string | null;
const materialType = normalizeMaterialType(materialTypeRaw);
if (isXiaoyiDeliveryMaterial(materialType)) {
return NextResponse.json({ error: '自动上架素材由小壹完结入库' }, { status: 400 });
}
if (materialType === '任务-详情' || materialType === '任务-页面') {
return NextResponse.json(
{
@ -941,7 +947,7 @@ export async function POST(request: NextRequest) {
let sourcePath = '';
if (zipFile) {
ext = path.extname(zipFile.name);
ext = getUploadStorageExtension(zipFile.name);
buffer = Buffer.from(await zipFile.arrayBuffer());
zipFileSize = BigInt(buffer.length);
console.log('[Upload] Using uploaded file buffer');
@ -974,7 +980,7 @@ export async function POST(request: NextRequest) {
'已合并的 canonical 源文件大小与上传会话不一致',
);
}
ext = path.extname(originalFileName || sourcePath);
ext = getUploadStorageExtension(originalFileName || ownedMergedUpload!.session.fileName || sourcePath);
console.log('[Upload] Using existing merged file:', sourcePath, 'size:', stat.size);
}

View File

@ -3,6 +3,8 @@ import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { getUserViewableMaterialTypes } from '@/lib/department-permission';
import { normalizeSelectableMaterialTypes } from '@/lib/material-query';
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access';
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material';
export async function GET(request: NextRequest) {
try {
@ -12,14 +14,18 @@ export async function GET(request: NextRequest) {
}
const user = session.user as any;
const types = await getUserViewableMaterialTypes(
user.department,
user.role,
user.managedDepartment,
user.id
);
const isUploadRequest = request.nextUrl.searchParams.get('intent') === 'upload';
const [types, canSelectOperationsGScope] = await Promise.all([
getUserViewableMaterialTypes(user.department, user.role, user.managedDepartment, user.id),
isUploadRequest ? canAccessOperationsGMaterials(user.id) : false,
]);
return NextResponse.json({ materialTypes: normalizeSelectableMaterialTypes(types) });
return NextResponse.json({
materialTypes: normalizeSelectableMaterialTypes(
isUploadRequest ? types.filter((type) => !isXiaoyiDeliveryMaterial(type)) : types,
),
...(isUploadRequest ? { canSelectOperationsGScope } : {}),
}, { headers: { 'Cache-Control': 'private, no-store' } });
} catch (error) {
console.error('[Viewable Material Types] Error:', error);
return NextResponse.json({ error: '获取可见素材类型失败' }, { status: 500 });

View File

@ -1,4 +1,4 @@
import { NextRequest, NextResponse } from 'next/server'
import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
@ -129,76 +129,4 @@ export async function GET() {
}
}
export async function PUT(request: NextRequest) {
try {
if (!(await requireSuperAdmin())) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 })
}
const body = await request.json()
const path = String(body?.path || '').trim()
const action = String(body?.action || 'save')
const incoming: Array<{
materialType: string
canView?: boolean
canDownload?: boolean
canDownloadSource?: boolean
canShare?: boolean
}> = Array.isArray(body?.permissions) ? body.permissions : []
const unit = await prisma.organizationUnit.findFirst({
where: { isActive: true, path },
select: { path: true, name: true },
})
if (!unit) {
return NextResponse.json({ error: '花名册里没有这个部门' }, { status: 400 })
}
if (action === 'inherit') {
await prisma.departmentMaterialPermission.deleteMany({
where: { department: unit.path },
})
return NextResponse.json({ ok: true })
}
if (incoming.length === 0) {
return NextResponse.json({ error: '素材类型列表不能为空' }, { status: 400 })
}
await prisma.$transaction(
incoming
.filter((item) => item.materialType)
.map((item) =>
prisma.departmentMaterialPermission.upsert({
where: {
department_materialType: {
department: unit.path,
materialType: item.materialType,
},
},
update: {
canView: item.canView ?? false,
canDownload: item.canDownload ?? false,
canDownloadSource: item.canDownloadSource ?? false,
canShare: item.canShare ?? true,
linkedToDepartment: null,
},
create: {
department: unit.path,
materialType: item.materialType,
canView: item.canView ?? false,
canDownload: item.canDownload ?? false,
canDownloadSource: item.canDownloadSource ?? false,
canShare: item.canShare ?? true,
linkedToDepartment: null,
},
}),
),
)
return NextResponse.json({ ok: true })
} catch (error) {
console.error('[organization material-permissions] PUT failed', error)
return NextResponse.json({ error: '保存部门权限配置失败' }, { status: 500 })
}
}
export { retiredDepartmentPermissionWrite as PUT } from '@/lib/retired-department-permission-write'

View File

@ -0,0 +1,109 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import ExcelJS from 'exceljs'
import { prisma } from '@/lib/prisma'
import { getPerformanceSalaryDetails } from '@/lib/performance-salary-details'
import { SALARY_XLSX_MIME, type SalaryDataSource, type SalaryDetails } from '@/lib/performance-salary-details-contract'
import { getPositionSalaryTemplate } from '@/lib/performance-salary-templates'
import { INITIAL_SALARY_POSITIONS } from '@/lib/salary-position-seeds'
import { GET } from './route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() } } }))
jest.mock('@/lib/performance-salary-details', () => ({ getPerformanceSalaryDetails: jest.fn() }))
const session = jest.mocked(getServerSession)
const user = jest.mocked(prisma.user.findUnique)
const getDetails = jest.mocked(getPerformanceSalaryDetails)
const request = (query = 'month=2026-11') => new NextRequest(`http://localhost/api/organization/performance-salary/details/export?${query}`)
const month = '2026-11'
const fixture = (): SalaryDetails => {
const position = { ...INITIAL_SALARY_POSITIONS[0].value, id: 'supervisor', revision: 3, updatedAt: '', personnelCount: 1 }
const row = {
employeeProfileId: 'private-employee-id', employeeLabel: '测试花名', positionGroupCode: 'salary:supervisor', hasSalaryBase: true,
values: { nickname: '测试花名', name: '测试姓名', currentTotal: '5045.00', previousTotal: '5048.01', salaryDifference: '-3.01' },
metrics: {}, totalScore: 103.04,
}
return {
scope: { role: 'all', phase: 'full', sources: [] },
displayMonth: month, sourceMonth: month, marketSourceMonth: '2026-10', isFallback: false,
roles: { 'ai-planning': [], photography: [], 'spatial-visual': [], management: [row], 'ai-technical': [] },
positionGroups: [{ position, template: getPositionSalaryTemplate(position, month), rows: [row] }],
}
}
beforeEach(() => {
jest.resetAllMocks()
session.mockResolvedValue({ user: { id: 'admin', isSuperAdmin: true } })
;(user as jest.Mock).mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true })
getDetails.mockResolvedValue(fixture())
})
test('匿名、撤权及停用账号不得读取薪资和下载', async () => {
session.mockResolvedValueOnce(null)
expect((await GET(request())).status).toBe(401)
;(user as jest.Mock).mockResolvedValueOnce({ isActive: true, status: 'active', archivedAt: null, isSuperAdmin: false })
const revoked = await GET(request())
expect(revoked.status).toBe(403)
expect(revoked.headers.get('cache-control')).toContain('private, no-store')
;(user as jest.Mock).mockResolvedValueOnce({ isActive: false, isSuperAdmin: true })
expect((await GET(request())).status).toBe(403)
expect(getDetails).not.toHaveBeenCalled()
})
test.each(['c156778c-307d-42aa-89d3-f785aeb3ef86', '463c5a60-c8a8-45dd-b4cd-4a31a6b1b84f', 'c041d8d8-93db-41f1-984d-5f76f114da48', '2b1ccc12-844c-4eff-8006-58607157efc1', 'admin'])('获准查看薪资的账号可下载同一完整计算结果', async id => {
session.mockResolvedValue({ user: { id } })
;(user as jest.Mock).mockResolvedValue({ id, isActive: true, status: 'active', archivedAt: null, isSuperAdmin: id === 'admin' })
const req = request()
const response = await GET(req)
expect(response.status).toBe(200)
expect(response.headers.get('cache-control')).toContain('private, no-store')
expect(response.headers.get('vary')).toContain('Cookie')
expect(response.headers.get('content-type')).toBe(SALARY_XLSX_MIME)
expect(decodeURIComponent(response.headers.get('content-disposition')!)).toBe("attachment; filename*=UTF-8''绩效薪资明细_2026-11.xlsx")
expect(getDetails).toHaveBeenCalledTimes(1)
expect(getDetails).toHaveBeenCalledWith(id, month, { role: 'all', phase: 'full', signal: req.signal })
const book = new ExcelJS.Workbook()
await book.xlsx.load(await response.arrayBuffer())
expect(book.worksheets).toHaveLength(1)
expect(book.worksheets[0].getCell('A4').value).toBe('测试花名')
expect(book.worksheets[0].getRow(4).values).toEqual(expect.arrayContaining([5045, 5048.01, -3.01]))
})
test.each(['', 'month=2026-13', 'month=2026-1', 'month=2026-11&month=2026-10'])('拒绝无效或歧义月份:%s', async query => {
expect((await GET(request(query))).status).toBe(400)
expect(getDetails).not.toHaveBeenCalled()
})
test.each<SalaryDataSource>(['survey', 'market-intent-top3', 'on-time', 'points'])('%s未成功读取时返回可重试错误,恢复后才生成文件', async source => {
const data = fixture()
data.scope!.sources.push({ source, salaryMonth: '2026-10', sourceMonth: '2026-09', status: 'failed', code: 'SOURCE_FAILED', message: 'private SQL and payroll' })
getDetails.mockResolvedValueOnce(data)
const failed = await GET(request())
expect(failed.status).toBe(503)
expect(failed.headers.get('cache-control')).toContain('private, no-store')
expect(failed.headers.get('content-disposition')).toBeNull()
const body = await failed.json()
expect(body).toMatchObject({ code: 'SALARY_EXPORT_SOURCES_UNAVAILABLE', error: expect.stringContaining('2026年10月') })
expect(JSON.stringify(body)).not.toContain('private')
expect((await GET(request())).status).toBe(200)
})
test('无人员、部分计算及内部异常均返回非下载响应', async () => {
const empty = fixture()
empty.positionGroups[0].rows = []
getDetails.mockResolvedValueOnce(empty)
const response = await GET(request())
expect(response.status).toBe(404)
expect(await response.json()).toMatchObject({ error: '该月暂无可导出的薪资明细。' })
const partial = fixture()
partial.scope!.phase = 'partial'
getDetails.mockResolvedValueOnce(partial)
expect((await GET(request())).status).toBe(503)
getDetails.mockRejectedValueOnce(new Error('SELECT private payroll'))
const failed = await GET(request())
expect(failed.status).toBe(500)
expect(await failed.text()).not.toContain('private')
})

View File

@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from 'next/server'
import { salaryIdentity, salaryFailure, salaryHeaders } from '@/lib/personnel-salary-http'
import { SalaryError } from '@/lib/personnel-salary'
import { getPerformanceSalaryDetails } from '@/lib/performance-salary-details'
import { buildSalaryDetailsWorkbook } from '@/lib/performance-salary-export'
import { salaryDetailsExportFileName, salarySourceNames, SALARY_XLSX_MIME } from '@/lib/performance-salary-details-contract'
import { isSalaryMonth, salaryMonthLabel } from '@/lib/performance-salary-templates'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest) {
try {
const userId = await salaryIdentity()
const months = request.nextUrl.searchParams.getAll('month')
const month = months[0]
if (months.length !== 1 || !isSalaryMonth(month)) {
throw new SalaryError('请选择有效月份后重试。', 400, 'INVALID_SALARY_MONTH')
}
const details = await getPerformanceSalaryDetails(userId, month, { role: 'all', phase: 'full', signal: request.signal })
const unavailable = details.scope?.sources.filter(source => source.status !== 'ready') ?? []
if (unavailable.length) {
const labels = unavailable.map(source => `${salaryMonthLabel(source.salaryMonth)}${salarySourceNames[source.source]}`).join('、')
throw new SalaryError(`${labels}暂时无法读取,请稍后重新导出。`, 503, 'SALARY_EXPORT_SOURCES_UNAVAILABLE')
}
if (details.displayMonth !== month || details.isFallback || details.scope?.role !== 'all' || details.scope.phase !== 'full') {
throw new SalaryError('薪资明细尚未完整读取,请稍后重新导出。', 503, 'SALARY_EXPORT_INCOMPLETE')
}
if (!details.positionGroups.some(group => group.rows.length > 0)) {
throw new SalaryError('该月暂无可导出的薪资明细。', 404, 'SALARY_EXPORT_EMPTY')
}
request.signal.throwIfAborted()
const workbook = await buildSalaryDetailsWorkbook(details)
const bytes = await workbook.xlsx.writeBuffer()
request.signal.throwIfAborted()
return new NextResponse(new Uint8Array(bytes), { headers: {
...salaryHeaders,
'Content-Type': SALARY_XLSX_MIME,
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(salaryDetailsExportFileName(month))}`,
'X-Content-Type-Options': 'nosniff',
} })
} catch (error) { return salaryFailure(error) }
}

View File

@ -0,0 +1,78 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { getPerformanceSalaryDetails } from '@/lib/performance-salary-details'
import { GET } from './route'
import { SalaryError } from '@/lib/personnel-salary'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() } } }))
jest.mock('@/lib/performance-salary-details', () => ({ getPerformanceSalaryDetails: jest.fn() }))
const session = getServerSession as jest.Mock, user = prisma.user.findUnique as jest.Mock, details = getPerformanceSalaryDetails as jest.Mock
const request = () => new NextRequest('http://localhost/api/organization/performance-salary/details?month=2026-10')
beforeEach(() => { jest.resetAllMocks(); session.mockResolvedValue({ user: { id: 'old-admin', isSuperAdmin: true } }); user.mockResolvedValue({ id: 'old-admin', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null }) })
test('旧超管会话被数据库当前状态拒绝,拒绝响应也不缓存', async () => {
const response = await GET(request())
expect(response.status).toBe(403)
expect(response.headers.get('cache-control')).toContain('no-store')
expect(response.headers.get('vary')).toContain('Cookie')
expect(details).not.toHaveBeenCalled()
})
test('未登录及停用账号无法访问', async () => {
session.mockResolvedValue(null); expect((await GET(request())).status).toBe(401)
session.mockResolvedValue({ user: { id: 'admin' } }); user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: false }); expect((await GET(request())).status).toBe(403)
})
test.each(['c156778c-307d-42aa-89d3-f785aeb3ef86', '463c5a60-c8a8-45dd-b4cd-4a31a6b1b84f', 'c041d8d8-93db-41f1-984d-5f76f114da48', '2b1ccc12-844c-4eff-8006-58607157efc1', 'admin'])('指定只读账号或超管允许查询:%s', async id => {
session.mockResolvedValue({ user: { id } }); user.mockResolvedValue({ id, isSuperAdmin: id === 'admin', isActive: true, status: 'active', archivedAt: null })
details.mockResolvedValue({ displayMonth: '2026-10', sourceMonth: '2026-10', marketSourceMonth: '2026-09', isFallback: false, roles: {} })
const response = await GET(request())
expect(response.status).toBe(200); expect(response.headers.get('cache-control')).toContain('private, no-store')
expect(details).toHaveBeenCalledWith(id, '2026-10')
expect(await response.json()).toMatchObject({ displayMonth: '2026-10', sourceMonth: '2026-10', marketSourceMonth: '2026-09', isFallback: false })
})
test('内部查询异常不泄露工资和SQL', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
details.mockRejectedValue(new Error('SELECT salary secret payroll'))
const response = await GET(request())
expect(response.status).toBe(500); expect(JSON.stringify(await response.json())).not.toContain('secret')
})
test('历史快照未补齐时返回可重试503且不缓存或返回部分积分', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
details.mockRejectedValue(new SalaryError('流程积分正在同步,请稍后重新加载。', 503, 'WORKFLOW_POINTS_SYNCING'))
const response = await GET(request())
expect(response.status).toBe(503)
expect(response.headers.get('cache-control')).toContain('no-store')
expect(await response.json()).toEqual({ error: '流程积分正在同步,请稍后重新加载。', code: 'WORKFLOW_POINTS_SYNCING' })
})
test('流式接口先发送基础快照,中途分项更新,最后完成;响应禁止缓存和代理缓冲', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
let finish!: () => void
details.mockImplementation(async (_id, _month, { onProgress }) => {
onProgress({ scope: { phase: 'base' } })
await new Promise<void>(resolve => { finish = resolve })
onProgress({ scope: { phase: 'partial' } })
return { scope: { phase: 'full' } }
})
const streamRequest = new NextRequest(`${request().url}&role=management`, { headers: { Accept: 'application/x-ndjson' } })
const response = await GET(streamRequest)
expect(response.headers.get('content-type')).toContain('application/x-ndjson')
expect(response.headers.get('cache-control')).toContain('private, no-store')
expect(response.headers.get('x-accel-buffering')).toBe('no')
const reader = response.body!.getReader()
const nextPhase = async () => JSON.parse(new TextDecoder().decode((await reader.read()).value)).data.scope.phase
expect(await nextPhase()).toBe('base')
finish()
expect(await nextPhase()).toBe('partial')
expect(await nextPhase()).toBe('full')
expect((await reader.read()).done).toBe(true)
})
test('非法岗位和无权限不会打开薪资响应流', async () => {
const streamRequest = new NextRequest(`${request().url}&role=invalid`, { headers: { Accept: 'application/x-ndjson' } })
expect((await GET(streamRequest)).status).toBe(403)
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
expect((await GET(streamRequest)).status).toBe(400)
expect(details).not.toHaveBeenCalled()
})

View File

@ -0,0 +1,57 @@
import { NextRequest } from 'next/server'
import { salaryIdentity, salaryJson, salaryFailure, salaryHeaders } from '@/lib/personnel-salary-http'
import { getPerformanceSalaryDetails } from '@/lib/performance-salary-details'
import { SALARY_STREAM_TYPE, type SalaryStreamEvent } from '@/lib/performance-salary-details-contract'
import type { SalaryRole } from '@/lib/performance-salary-roles'
import { SalaryError } from '@/lib/personnel-salary'
import { salaryRoleSchema } from '@/lib/salary-position-contract'
export const dynamic = 'force-dynamic'
function streamDetails(request: NextRequest, userId: string, month: string | null, role: SalaryRole) {
const encoder = new TextEncoder()
const disconnected = new AbortController()
const signal = AbortSignal.any([request.signal, disconnected.signal])
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const send = (event: SalaryStreamEvent) => {
if (!signal.aborted) controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`))
}
try {
const data = await getPerformanceSalaryDetails(userId, month, {
role, phase: 'full', signal, onProgress: data => send({ data }),
})
send({ data })
} catch (error) {
const failure = salaryFailure(error)
const body = await failure.json()
send({ error: body.error, status: failure.status })
} finally {
if (!disconnected.signal.aborted) controller.close()
}
},
cancel() { disconnected.abort() },
})
return new Response(stream, { headers: {
...salaryHeaders, Vary: `${salaryHeaders.Vary}, Accept`, 'Content-Type': `${SALARY_STREAM_TYPE}; charset=utf-8`, 'X-Accel-Buffering': 'no',
} })
}
export async function GET(request: NextRequest) {
try {
const userId = await salaryIdentity()
const { searchParams } = request.nextUrl
const month = searchParams.get('month')
const role = searchParams.get('role')
const phase = searchParams.get('phase')
if (role === null && phase === null) return salaryJson(await getPerformanceSalaryDetails(userId, month))
const parsed = salaryRoleSchema.safeParse(role)
if (!parsed.success || (phase !== null && phase !== 'base' && phase !== 'full')) {
throw new SalaryError('请选择有效薪资岗位及查询阶段。', 400, 'INVALID_SALARY_DETAILS_SCOPE')
}
if (phase !== 'base' && request.headers.get('accept') === SALARY_STREAM_TYPE) {
return streamDetails(request, userId, month, parsed.data)
}
return salaryJson(await getPerformanceSalaryDetails(userId, month, { role: parsed.data, phase: phase ?? 'full' }))
} catch (error) { return salaryFailure(error) }
}

View File

@ -0,0 +1,10 @@
import { NextRequest } from 'next/server'
import { updateSalaryPosition, deleteSalaryPosition } from '@/lib/salary-positions'
import { salaryBody, salaryFailure, salaryIdentity, salaryJson } from '@/lib/personnel-salary-http'
export const dynamic = 'force-dynamic'
export async function PUT(request: NextRequest, { params }: { params: { id: string } }) {
try { const actor = await salaryIdentity(true, request); return salaryJson(await updateSalaryPosition(params.id, await salaryBody(request, 200000), actor)) } catch (error) { return salaryFailure(error) }
}
export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
try { const actor = await salaryIdentity(true, request); return salaryJson(await deleteSalaryPosition(params.id, await salaryBody(request), actor)) } catch (error) { return salaryFailure(error) }
}

View File

@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from 'next/server'
import { listSalaryPositions, listSalaryScoreSources } from '@/lib/salary-positions'
import { performancePositions } from '@/lib/salary-position-contract'
import { buildPositionWorkbook } from '@/lib/salary-position-export'
import { SalaryError } from '@/lib/personnel-salary'
import { salaryFailure, salaryHeaders, salaryIdentity } from '@/lib/personnel-salary-http'
import { resolveSalaryMonth } from '@/lib/performance-salary-templates'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest) {
try {
const user = await salaryIdentity()
const month = resolveSalaryMonth(request.nextUrl.searchParams.get('month'))
const [{ positions }, sources] = await Promise.all([listSalaryPositions(user, month), listSalaryScoreSources(user)])
const id = request.nextUrl.searchParams.get('position')
const selected = id ? performancePositions(positions).filter(position => position.id === id) : performancePositions(positions)
if (!selected.length) throw new SalaryError('暂无可导出的岗位配置,请刷新后重试。', 404)
const workbook = await buildPositionWorkbook(selected, sources, month)
const buffer = await workbook.xlsx.writeBuffer()
return new NextResponse(new Uint8Array(buffer), { headers: { ...salaryHeaders, 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent('岗位绩效配置.xlsx')}` } })
} catch (error) { return salaryFailure(error) }
}

View File

@ -0,0 +1,60 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { GET, POST } from './route'
import { PUT, DELETE } from './[id]/route'
import { GET as SOURCES } from './sources/route'
import { GET as EXPORT } from './export/route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() }, personnelSalaryBase: { findMany: jest.fn() }, salaryPositionConfig: { findMany: jest.fn() }, performanceSurveyTemplate: { findMany: jest.fn() }, $transaction: jest.fn() } }))
const session = getServerSession as jest.Mock, user = prisma.user.findUnique as jest.Mock
const req = (method: string, body: unknown = {}, headers: Record<string, string> = {}) => new NextRequest('http://localhost/api/organization/performance-salary/positions', { method, body: JSON.stringify(body), headers })
const all = () => [GET(new NextRequest('http://localhost/api/organization/performance-salary/positions')), POST(req('POST')), PUT(req('PUT'), { params: { id: 'id' } }), DELETE(req('DELETE'), { params: { id: 'id' } }), SOURCES(), EXPORT(new NextRequest('http://localhost/api/organization/performance-salary/positions/export'))]
beforeEach(() => {
jest.resetAllMocks()
;(prisma.personnelSalaryBase.findMany as jest.Mock).mockResolvedValue([])
session.mockResolvedValue({ user: { id: 'old-admin', isSuperAdmin: true } })
user.mockResolvedValue({ id: 'old-admin', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null })
})
test('全部新接口独立拒绝旧超管会话且禁止缓存', async () => {
for (const response of await Promise.all(all())) {
expect(response.status).toBe(403)
expect(response.headers.get('cache-control')).toBe('private, no-store, max-age=0')
}
expect(prisma.$transaction).not.toHaveBeenCalled()
expect(prisma.salaryPositionConfig.findMany).not.toHaveBeenCalled()
})
test('未登录全部拒绝', async () => {
session.mockResolvedValue(null)
for (const response of await Promise.all(all())) expect(response.status).toBe(401)
})
test.each(['c156778c-307d-42aa-89d3-f785aeb3ef86', '463c5a60-c8a8-45dd-b4cd-4a31a6b1b84f', 'c041d8d8-93db-41f1-984d-5f76f114da48', '2b1ccc12-844c-4eff-8006-58607157efc1'])('指定账号%s仅可读和导出', async id => {
session.mockResolvedValue({ user: { id, isSuperAdmin: true } })
user.mockResolvedValue({ id, isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null })
;(prisma.salaryPositionConfig.findMany as jest.Mock).mockResolvedValue([{ id: 'job', name: '空岗位', salaryRole: 'ai-planning', description: '', dimensions: [], revision: 1, updatedAt: new Date(), _count: { people: 7 } }])
;(prisma.performanceSurveyTemplate.findMany as jest.Mock).mockResolvedValue([])
const responses = await Promise.all(all())
expect(responses.map(r => r.status)).toEqual([200, 403, 403, 403, 200, 200])
expect(responses[5].headers.get('content-type')).toContain('spreadsheetml')
expect(responses[5].headers.get('cache-control')).toContain('no-store')
})
test('跨站写拒绝;错误权重不进事务', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
expect((await POST(req('POST', {}, { origin: 'https://other.test' }))).status).toBe(403)
expect((await POST(req('POST', { name: '', dimensions: [] }))).status).toBe(400)
expect(prisma.$transaction).not.toHaveBeenCalled()
})
test.each(['same-origin', 'cross-site'])('代理后岗位新增、编辑、删除按%s来源校验,拒绝时不写库', async site => {
user.mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true })
const proxied = (method: string) => new NextRequest('https://0.0.0.0:3000/api/organization/performance-salary/positions', {
method, headers: { origin: 'https://sc.jiansun.vip', host: 'sc.jiansun.vip', 'x-forwarded-proto': 'https', 'sec-fetch-site': site }, body: '{}',
})
const responses = await Promise.all([POST(proxied('POST')), PUT(proxied('PUT'), { params: { id: 'id' } }), DELETE(proxied('DELETE'), { params: { id: 'id' } })])
for (const response of responses) {
expect(response.status).toBe(site === 'same-origin' ? 400 : 403)
expect(response.headers.get('cache-control')).toBe('private, no-store, max-age=0')
}
expect(prisma.$transaction).not.toHaveBeenCalled()
})

View File

@ -0,0 +1,11 @@
import { NextRequest } from 'next/server'
import { createSalaryPosition, listSalaryPositions } from '@/lib/salary-positions'
import { salaryBody, salaryFailure, salaryIdentity, salaryJson } from '@/lib/personnel-salary-http'
import { resolveSalaryMonth } from '@/lib/performance-salary-templates'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest) {
try { return salaryJson(await listSalaryPositions(await salaryIdentity(), resolveSalaryMonth(request?.nextUrl.searchParams.get('month')))) } catch (error) { return salaryFailure(error) }
}
export async function POST(request: NextRequest) {
try { const actor = await salaryIdentity(true, request); return salaryJson(await createSalaryPosition(await salaryBody(request, 200000), actor), 201) } catch (error) { return salaryFailure(error) }
}

View File

@ -0,0 +1,6 @@
import { listSalaryScoreSources } from '@/lib/salary-positions'
import { salaryFailure, salaryIdentity, salaryJson } from '@/lib/personnel-salary-http'
export const dynamic = 'force-dynamic'
export async function GET() {
try { return salaryJson({ sources: await listSalaryScoreSources(await salaryIdentity()) }) } catch (error) { return salaryFailure(error) }
}

View File

@ -0,0 +1,67 @@
/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import ExcelJS from 'exceljs'
import { Prisma } from '@prisma/client'
import { prisma } from '@/lib/prisma'
import { GET } from './route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() }, personnelSalaryBase: { findMany: jest.fn() }, salaryPositionConfig: { findMany: jest.fn() }, $transaction: jest.fn() } }))
const session = getServerSession as jest.Mock, user = prisma.user.findUnique as jest.Mock
const job = 'b9b80000-0000-4000-8000-000000001002', other = 'b9b80000-0000-4000-8000-000000001003'
const request = (position?: string) => new NextRequest(`http://localhost/api/organization/personnel-salary/export${position ? `?position=${position}` : ''}`)
const row = (positionId: string | null) => ({ id: 'private-record-id', employeeProfileId: 'private-person-id', positionId, name: positionId === job ? '测试甲' : '测试乙', flowerName: '', department: '测试部门', brand: '', baseSalary: new Prisma.Decimal('0'), gradeSalary: new Prisma.Decimal('100.01'), performanceSalary: new Prisma.Decimal('20.02'), revision: 1, updatedAt: new Date(), deletedAt: null })
beforeEach(() => {
jest.resetAllMocks()
session.mockResolvedValue({ user: { id: 'admin', isSuperAdmin: true } })
user.mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true })
;(prisma.$transaction as jest.Mock).mockImplementation(work => work(prisma))
;(prisma.salaryPositionConfig.findMany as jest.Mock).mockResolvedValue([{ id: job, name: '策划' }, { id: other, name: '技术' }])
;(prisma.personnelSalaryBase.findMany as jest.Mock).mockImplementation(({ where }) => Promise.resolve([row(job), row(other), row(null)].filter(item => !('positionId' in where) || where.positionId === item.positionId)))
})
test('匿名、未授权和伪造旧超管会话均拒绝,错误禁止共享缓存', async () => {
session.mockResolvedValueOnce(null)
expect((await GET(request())).status).toBe(401)
user.mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: false })
const denied = await GET(request())
expect(denied.status).toBe(403)
expect(denied.headers.get('cache-control')).toContain('private, no-store')
expect(prisma.$transaction).not.toHaveBeenCalled()
})
test.each(['c156778c-307d-42aa-89d3-f785aeb3ef86', '463c5a60-c8a8-45dd-b4cd-4a31a6b1b84f', 'c041d8d8-93db-41f1-984d-5f76f114da48', '2b1ccc12-844c-4eff-8006-58607157efc1'])('指定只读账号%s可导出当前岗位,无其他岗位数据', async id => {
session.mockResolvedValue({ user: { id } }); user.mockResolvedValue({ id, isActive: true, status: 'active', archivedAt: null, isSuperAdmin: false })
const response = await GET(request(job))
expect(response.status).toBe(200)
expect(response.headers.get('cache-control')).toBe('private, no-store, max-age=0')
expect(response.headers.get('vary')).toContain('Cookie')
const book = new ExcelJS.Workbook(); await book.xlsx.load(await response.arrayBuffer())
expect(book.worksheets.map(sheet => sheet.name)).toEqual(['策划'])
expect(book.worksheets[0].getCell('B4').value).toBe('测试甲')
expect(prisma.personnelSalaryBase.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { deletedAt: null, positionId: job } }))
expect(prisma.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead })
})
test('全部导出包含有效岗位和未分配;未分配筛选不带出已分配人员', async () => {
const all = await GET(request()), book = new ExcelJS.Workbook()
await book.xlsx.load(await all.arrayBuffer())
expect(book.worksheets.map(sheet => sheet.name)).toEqual(['策划', '技术', '未分配'])
const unassigned = await GET(request('unassigned')), single = new ExcelJS.Workbook()
await single.xlsx.load(await unassigned.arrayBuffer())
expect(single.worksheets.map(sheet => sheet.name)).toEqual(['未分配'])
expect(prisma.personnelSalaryBase.findMany).toHaveBeenLastCalledWith(expect.objectContaining({ where: { deletedAt: null, positionId: null } }))
})
test('非法参数、已删除岗位、读取失败均返回可见错误而非错误文件', async () => {
expect((await GET(request('invalid'))).status).toBe(400)
expect((await GET(request('b9b80000-0000-4000-8000-000000001099'))).status).toBe(404)
;(prisma.$transaction as jest.Mock).mockRejectedValueOnce(new Error('private database detail'))
const failed = await GET(request())
expect(failed.status).toBe(500)
expect(failed.headers.get('cache-control')).toContain('no-store')
expect(await failed.text()).not.toContain('private database detail')
})
test('事务内重新核对当前权限,撤权后不读取工资', async () => {
user.mockResolvedValueOnce({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true }).mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: false })
expect((await GET(request())).status).toBe(403)
expect(prisma.personnelSalaryBase.findMany).not.toHaveBeenCalled()
})

View File

@ -0,0 +1,19 @@
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { readPersonnelSalaryExport } from '@/lib/personnel-salary'
import { buildPersonnelSalaryWorkbook } from '@/lib/personnel-salary-export'
import { salaryFailure, salaryHeaders, salaryIdentity } from '@/lib/personnel-salary-http'
export const dynamic = 'force-dynamic'
const scope = z.union([z.literal('unassigned'), z.string().uuid()]).optional()
export async function GET(request: NextRequest) {
try {
const user = await salaryIdentity()
const position = scope.parse(request.nextUrl.searchParams.get('position') ?? undefined)
const groups = await readPersonnelSalaryExport(user, position)
const workbook = await buildPersonnelSalaryWorkbook(groups)
const bytes = await workbook.xlsx.writeBuffer()
const filename = position ? '人员薪资配置_当前岗位.xlsx' : '人员薪资配置_全部.xlsx'
return new NextResponse(new Uint8Array(bytes), { headers: { ...salaryHeaders, 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}` } })
} catch (error) { return salaryFailure(error) }
}

View File

@ -48,3 +48,16 @@ test('跨站写入拒绝,合法超管的非法金额返回字段错误且不
expect((await invalid.json()).fields.baseSalary).toBeTruthy()
expect(prisma.$transaction).not.toHaveBeenCalled()
})
test.each(['same-origin', 'cross-site'])('代理后人员新增、编辑、删除按%s来源校验,拒绝时不写库', async site => {
user.mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true })
const proxied = (method: string) => new NextRequest('https://0.0.0.0:3000/api/organization/personnel-salary', {
method, headers: { origin: 'https://sc.jiansun.vip', host: 'sc.jiansun.vip', 'x-forwarded-proto': 'https', 'sec-fetch-site': site }, body: '{}',
})
const responses = await Promise.all([POST(proxied('POST')), PUT(proxied('PUT'), { params: { id: 'id' } }), DELETE(proxied('DELETE'), { params: { id: 'id' } })])
for (const response of responses) {
// Trusted requests reach body validation; cross-site requests stop before it.
expect(response.status).toBe(site === 'same-origin' ? 400 : 403)
expect(response.headers.get('cache-control')).toBe('private, no-store, max-age=0')
}
expect(prisma.$transaction).not.toHaveBeenCalled()
})

View File

@ -1,3 +1,4 @@
import { performanceAttachmentFile, performanceAttachmentMetadata, retryPerformanceAttachment } from '@/lib/performance-survey-attachment-response'
import { getServerSession } from 'next-auth'
import type { Session } from 'next-auth'
import { NextResponse } from 'next/server'
@ -68,24 +69,24 @@ type RouteContext = {
}
function ok(data: unknown, init?: ResponseInit) {
return NextResponse.json({ success: true, data }, init)
return NextResponse.json({ success: true, data }, { ...init, headers: { ...init?.headers, 'Cache-Control': 'private, no-store' } })
}
function errorResponse(error: unknown) {
if (error instanceof PerformanceSurveyApiError) {
return NextResponse.json({ success: false, error: error.message }, { status: error.status })
return NextResponse.json({ success: false, error: error.message }, { status: error.status, headers: { 'Cache-Control': 'private, no-store' } })
}
if (error && typeof error === 'object' && typeof (error as { status?: unknown }).status === 'number') {
return NextResponse.json(
{ success: false, error: error instanceof Error ? error.message : '请求失败' },
{ status: (error as { status: number }).status },
{ status: (error as { status: number }).status, headers: { 'Cache-Control': 'private, no-store' } },
)
}
const message = error instanceof Error ? error.message : '服务器错误'
console.error('[performance-survey] API error:', error)
return NextResponse.json({ success: false, error: message }, { status: 500 })
return NextResponse.json({ success: false, error: message }, { status: 500, headers: { 'Cache-Control': 'private, no-store' } })
}
function readDingtalkPerformanceTokens(request: Request) {
@ -164,6 +165,8 @@ function assertScopedGetAccess(
if (!scope || scope.kind === 'workspace') return
if (path.length === 0 || (path.length === 1 && path[0] === 'me')) return
if (path[0] === 'case-attachments' && (path.length === 2 || (path.length === 3 && path[2] === 'file'))) return
const targetId = searchParams.get('targetId')?.trim() || ''
if (
scope.kind === 'assignment'
@ -187,6 +190,7 @@ function assertScopedGetAccess(
function assertScopedPostAccess(session: Session | null, path: string[]) {
const scope = getDingtalkPerformanceScope(session)
if (!scope || scope.kind === 'workspace') return null
if (path[0] === 'case-attachments' && path.length === 3 && path[2] === 'retry') return null
if (scope.kind !== 'assignment') {
throw new PerformanceSurveyApiError('当前钉钉通知不包含评分权限', 403)
}
@ -220,6 +224,10 @@ export async function GET(request: Request, context: RouteContext) {
const path = getPath(context)
const url = new URL(request.url)
assertScopedGetAccess(session, path, url.searchParams)
if (path[0] === 'case-attachments' && path[1]) {
if (path.length === 3 && path[2] === 'file') return await performanceAttachmentFile(session, path[1], request)
if (path.length === 2) return ok(await performanceAttachmentMetadata(session, path[1]))
}
if (path.length === 0 || path[0] === 'me') {
return ok(await getPerformanceSurveyMe(session))
@ -320,6 +328,7 @@ export async function POST(request: Request, context: RouteContext) {
const session = await getSession(request)
const path = getPath(context)
const assignmentScope = assertScopedPostAccess(session, path)
if (path[0] === 'case-attachments' && path.length === 3 && path[2] === 'retry') return ok(await retryPerformanceAttachment(session, path[1]))
if (path[0] === 'surveys' && path[1] && path[2] === 'work-items' && path.length === 3) {
return ok(await createPerformanceSurveyWorkItemFromRequest(session, path[1], request), { status: 201 })
@ -483,3 +492,9 @@ export async function DELETE(request: Request, context: RouteContext) {
return errorResponse(error)
}
}
export async function HEAD(request: Request, context: RouteContext) {
const response = await GET(request, context)
await response.body?.cancel()
return new Response(null, { status: response.status, headers: response.headers })
}

View File

@ -6,7 +6,7 @@ import { transcodeQueue } from '@/lib/video-transcode-queue'
import { prisma } from '@/lib/prisma'
import { getNetworkSpeed } from '@/lib/network-bandwidth-monitor'
import { authOptions } from '@/lib/auth'
import { hasSystemAdminPermission } from '@/lib/department-permission'
import { hasSystemAdminPermission, isSuperAdmin } from '@/lib/department-permission'
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
import {
classifyTranscodeMaterial,
@ -94,7 +94,8 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: '仅系统管理员可查看性能数据' }, { status: 403 })
}
const canAccessG = await canAccessOperationsGMaterials(user.id)
const organizationWhere = canAccessG ? {} : { accessScope: 'general' }
const canViewG = canAccessG || await isSuperAdmin(user.id)
const organizationWhere = canViewG ? {} : { accessScope: 'general' }
const rateLimitKey = `${String(user.id || 'unknown')}:${request.headers.get('x-forwarded-for') || ''}`
const retryAfter = consumeRateLimit(rateLimitKey)
@ -266,7 +267,7 @@ export async function GET(request: NextRequest) {
}
const canViewUploadTask = (task: any) => {
const scope = uploadMaterialInfoMap.get(task.uploadId)?.accessScope
if (scope === 'operations_g') return canAccessG
if (scope === 'operations_g') return canViewG
return canAccessG || task.userId === user.id || scope === 'general'
}
const uploadProcessingWithUsers = uploadProcessing.filter(canViewUploadTask).map(decorateUploadTask)

View File

@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { getTaskDetailChangePreview, TaskDetailChangeApprovalError } from '@/lib/task-detail-change-approval'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
try {
const session = await getServerSession(authOptions)
const user = session?.user as { id?: string; role?: string; isSuperAdmin?: boolean } | undefined
if (!user?.id) return NextResponse.json({ error: '未登录' }, { status: 401 })
const side = request.nextUrl.searchParams.get('side')
const operation = request.nextUrl.searchParams.get('operation') || ''
const image = request.nextUrl.searchParams.get('image') || ''
if ((side !== 'before' && side !== 'after') || !/^\d{1,4}$/.test(operation) || !/^\d{1,4}$/.test(image)) {
return NextResponse.json({ error: '图片位置无效' }, { status: 400 })
}
const preview = await getTaskDetailChangePreview(params.id, { id: user.id, role: user.role, isSuperAdmin: user.isSuperAdmin }, {
operationIndex: Number(operation), side, index: Number(image),
})
return new NextResponse(new Uint8Array(preview), {
headers: { 'Content-Type': 'image/jpeg', 'Cache-Control': 'private, no-store' },
})
} catch (error) {
if (error instanceof TaskDetailChangeApprovalError) {
return NextResponse.json({ error: error.message }, { status: error.statusCode })
}
return NextResponse.json({ error: '图片预览加载失败' }, { status: 500 })
}
}

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