Compare commits
No commits in common. "main" and "codex/material-operations-g" have entirely different histories.
main
...
codex/mate
@ -153,7 +153,6 @@ 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
|
||||
@ -224,6 +223,8 @@ 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
|
||||
|
||||
@ -532,7 +532,6 @@
|
||||
"自动化工作流在 Department Shell 内使用 232px 二级业务栏与同源真实操作面,移动端改为顶部两列菜单。",
|
||||
"数据口径在 Department Shell 内使用 232px 二级栏直接显示“公司组织架构”,右侧复用真实组织树和人员明细,不增加折叠层。",
|
||||
"人员架构在 Department Shell 内直接复用真实组织工作面,并将组织树根节点限定为“品牌中心”。",
|
||||
"绩效薪资沿用 232px 二级栏,在“薪资明细”下固定展开 AI全案策划岗、摄影中心岗、空间视觉岗、管理岗、AI技术设计师岗五个入口;选中态与 URL、右侧标题同步,月份随岗位切换保留。“后台配置”以分隔线独立分组,下设平级的“人员薪资配置”和“岗位绩效配置”;人员配置再展开岗位及“未分配”子层级;岗位绩效配置也展开共用岗位子列表,仅显示岗位名称,不含全部、未分配或人数。绩效岗位子导航、选择器与方案通过 `config=performance&position=稳定ID` 同步并保留月份;缺省或无效岗位进入首岗,新增后选中、改名后同步,删除当前岗位后回到首岗或空状态。手机子导航为两列,长岗位名换行。人员与绩效方案按稳定岗位 ID 关联,明细按岗位分表并由配置生成绩效列,表旁明确提示最新配置适用于所有月份。人员配置最顶部为独立公共工具栏,先选择“全部人员 / 现有岗位 / 未分配”,再提供“导出当前岗位人员”“导出全部人员”和主按钮“新增岗位”;选择与路由、左侧岗位高亮受控同步,并保留月份。下方独立岗位人员区展示岗位标题、人数、“新增人员”、条件显示的“删除岗位”及人员列表;“全部人员”和“未分配”不显示删除岗位。手机工具栏纵向排列、自然换行;此处新增共用岗位只填写名称、薪资展示入口和说明,考核维度仍在岗位绩效配置维护。有人员的岗位禁止确认删除,删除保留审计。仅超级管理员维护,获准查看的指定账号也可导出当前岗位或全部人员的已保存长期基础档案,Excel 每岗一表,包含岗位和七项基础字段。明细只读展示已接入数据,缺失值用“——”表示;“导出薪资模板”仍只输出空白模板,岗位配置导出只包含已保存方案。分区表头左对齐、字段表头换行,明细固定表头和首个身份列。手机岗位入口为顶部两列、后台配置独立一行,表单纵向排列,人员基础信息转为纵向列表;宽表只在表格区域滚动,不撑宽页面。维护使用原生模态弹窗,保留键盘焦点,关闭后返回触发按钮;保存、加载和导出显示状态,错误可重试,版本冲突保留草稿,未保存关闭须确认。",
|
||||
"素材资产库按权威组织归属选择外壳:品牌中心成员保留 Department Shell,外部普通用户只显示 64px 中性顶栏、素材工作面与退出入口。"
|
||||
],
|
||||
"rules": [
|
||||
|
||||
@ -40,9 +40,3 @@
|
||||
|
||||
- `README.md`
|
||||
- `.private\gongxiangp2-完整敏感接管清单-2026-08-13.md`
|
||||
|
||||
## 7. Git 协作与发布
|
||||
|
||||
- 开发和验证可使用独立功能分支,所有部署必须从权威仓库的 `main` 分支发布。
|
||||
- 同事提供的分支用于补齐和整合源码;相关改动验证后必须合并并推送到 `main`,再按 `main` 上的明确提交执行构建和部署。
|
||||
- 发布前确认目标提交已包含在远端 `main` 历史中,不直接部署功能分支或同事分支。
|
||||
|
||||
@ -154,7 +154,7 @@ components:
|
||||
- 自动化工作流在 Department Shell 内使用 232px 二级业务栏与同源真实操作面,移动端改为顶部两列菜单。
|
||||
- 组织架构复用真实组织树与人员明细,提供“品牌中心 / 全公司”范围切换,沿用原管理员权限。
|
||||
- 权限管理提供“权限组 / 人员权限”两个视图,侧栏只有一个入口。
|
||||
- 绩效薪资沿用 232px 二级栏,在“薪资明细”下固定展开 AI全案策划岗、摄影中心岗、空间视觉岗、管理岗、AI技术设计师岗五个入口;选中态与 URL、右侧标题同步,月份随岗位切换保留。“后台配置”以分隔线独立分组,下设平级的“人员薪资配置”和“岗位绩效配置”两个独立折叠组;组标题为带展开箭头的原生按钮,支持 Enter / Space 和明确焦点,aria-expanded、aria-controls 与子列表显隐同步。默认展开当前配置组;手动收起不切换页面或重置右侧表单,访问其它配置或岗位时展开目标组。人员组包含“全部人员”、共用岗位及“未分配”子层级;岗位绩效配置也展开共用岗位子列表,仅显示岗位名称,不含全部、未分配或人数。绩效岗位子导航、选择器与方案通过 `config=performance&position=稳定ID` 同步并保留月份;缺省或无效岗位进入首岗,新增后选中、改名后同步,删除当前岗位后回到首岗或空状态。手机子导航为两列,长岗位名换行。人员与绩效方案按稳定岗位 ID 关联,明细按岗位分表并由配置生成绩效列,表旁明确提示最新配置适用于所有月份。人员配置最顶部为独立公共工具栏,先选择“全部人员 / 现有岗位 / 未分配”,再提供“导出当前岗位人员”“导出全部人员”和主按钮“新增岗位”;选择与路由、左侧岗位高亮受控同步,并保留月份。下方独立岗位人员区展示岗位标题、人数、“新增人员”、条件显示的“删除岗位”及人员列表;“全部人员”和“未分配”不显示删除岗位。手机工具栏纵向排列、自然换行;此处新增共用岗位只填写名称、薪资展示入口和说明,考核维度仍在岗位绩效配置维护。有人员的岗位禁止确认删除,删除保留审计。仅超级管理员维护,获准查看的指定账号也可导出当前岗位或全部人员的已保存长期基础档案,Excel 每岗一表,包含岗位和七项基础字段。明细只读展示已接入数据,缺失值用“——”表示;市场验证专用指标按薪资月上月完结流程取数,表头标注“上月”,来源提示与可展开计算明细展示实际考核月份和跨月观察窗口,其他指标保留所选薪资月;“导出薪资明细”按所选月份汇总全部岗位的真实人员与计算值,按当月方案分表,岗位配置导出只包含已保存方案。分区表头左对齐、字段表头换行,明细固定表头和首个身份列。手机岗位入口为顶部两列、后台配置独立一行,表单纵向排列,人员基础信息转为纵向列表;宽表只在表格区域滚动,不撑宽页面。维护使用原生模态弹窗,保留键盘焦点,关闭后返回触发按钮;保存、加载和导出显示状态,错误可重试,版本冲突保留草稿,未保存关闭须确认。
|
||||
- 绩效薪资使用 232px 二级栏,在“薪资明细”分组下固定展开 AI全案策划岗、摄影中心岗、空间视觉岗、管理岗,后台配置以分隔线区分为独立入口。岗位选中态与 URL、右侧标题同步;手机岗位入口为两列,后台配置独立一行,各项最小高度 44px。四岗按确认的 Excel 结构展示只读空模板,月份选择后查询,当前月份与岗位保存在 URL;四岗整套模板可一次导出。分区表头左对齐,字段表头换行、首列固定,桌面和手机均在表格内部横向滚动;不带入真实工资或预设计算公式。
|
||||
- 素材资产库按权威组织归属选择外壳:品牌中心成员保留 Department Shell,外部普通用户只显示 64px 中性顶栏、素材工作面与退出入口。
|
||||
- 进行中项目明细采用可键盘聚焦的横向滚动数据表:桌面固定“审批单标题”首列并保留 14 项业务字段,移动端转换为同字段的语义化定义列表;节点时间在数值下方标注对应流程节点名称。
|
||||
- 按时交付明细使用紧凑的三项流程筛选条;当前项用浅蓝底和蓝字表达,未选项悬停为灰底,切换时同步更新公式、数量和横向明细表。
|
||||
|
||||
49
Dockerfile
49
Dockerfile
@ -22,10 +22,9 @@ 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 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
|
||||
RUN --mount=type=cache,target=/root/.npm CXXFLAGS="-include cstdint" npm_config_build_from_source=canvas npm ci --no-audit --no-fund
|
||||
COPY workers/detail-renderer/ ./
|
||||
RUN chmod -R a+rX /opt/detail-renderer && \
|
||||
node -e "require('canvas').createCanvas(1,1); console.log('isolated Canvas smoke passed')"
|
||||
RUN node -e "require('canvas').createCanvas(1,1); console.log('isolated Canvas smoke passed')"
|
||||
|
||||
# 安装依赖阶段
|
||||
FROM base AS deps
|
||||
@ -49,19 +48,11 @@ 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 libreoffice font-noto-cjk
|
||||
RUN apk add --no-cache ffmpeg openssl poppler-utils
|
||||
|
||||
ENV NODE_ENV=development
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
@ -136,14 +127,6 @@ 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" && \
|
||||
@ -168,8 +151,7 @@ RUN --mount=type=cache,target=/app/.next/cache \
|
||||
CIRCLE_NODE_TOTAL=2 NODE_ENV=production npm run build
|
||||
|
||||
# 清理 standalone 目录中不需要的文件(减少 1GB+ 体积)
|
||||
RUN chmod -R a+rX .next/standalone .next/static app public lib prisma scripts && \
|
||||
echo "清理 standalone 目录..." && \
|
||||
RUN echo "清理 standalone 目录..." && \
|
||||
rm -rf .next/standalone/uploads && \
|
||||
rm -rf .next/standalone/.build-cache && \
|
||||
rm -rf .next/standalone/.docker-cache && \
|
||||
@ -221,9 +203,7 @@ 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/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/
|
||||
COPY --from=builder --chown=root:root /app/lib/personnel-salary.ts /app/lib/personnel-salary-contract.ts /app/lib/performance-salary-access.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
|
||||
@ -239,7 +219,6 @@ 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
|
||||
@ -247,7 +226,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 libreoffice font-noto-cjk && \
|
||||
apk add --no-cache ffmpeg python3 cairo jpeg pango giflib openssl poppler-utils flock && \
|
||||
command -v flock >/dev/null && \
|
||||
flock --exclusive --timeout 1 --conflict-exit-code 75 --no-fork \
|
||||
/tmp/material-upload-flock-probe.lock sh -c 'true' && \
|
||||
@ -321,21 +300,10 @@ 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 写入,代码权限保持只读。
|
||||
@ -346,12 +314,11 @@ 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
|
||||
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)})"
|
||||
|
||||
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
431
README.md
@ -1,111 +1,390 @@
|
||||
# 共享素材库与小壹桌面端(gongxiangp2)
|
||||
# 由壹点 3D 素材平台
|
||||
|
||||
> 更新日期:2026-12-04(已按当前线上架构与仓库结构重写)
|
||||
当前仓库对应的是一个已经在线上运行的业务项目,不是演示性质的素材站。项目围绕素材上传、管理、下载、分享、权限控制和运维诊断构建,当前代码已经明显超出早期 README 里那种“注册登录 + 预览图 + 压缩包”的简单形态。
|
||||
|
||||
本仓库包含两条核心产品线:
|
||||
1. **共享素材库主站(Web)**:面向企业内部创意、视觉、电商与运营团队的素材资产管理、分发下载、组织权限治理、品牌中心与绩效协同平台。
|
||||
2. **小壹桌面客户端(Windows)**:面向商品详情页、主图与 SKU 视觉生产的桌面工作台,集成原生画布编辑、智能体制作引擎、企业模板库与在线热更新体系。
|
||||
> 本 README 已于 2026-03-06 按当前代码结构重写,优先反映现状。
|
||||
|
||||
---
|
||||
## 项目概览
|
||||
|
||||
## 核心能力
|
||||
- 基于 Next.js 14 App Router 的素材协作与分发系统
|
||||
- 默认以新素材流程为主,不再把“新老素材兼容”作为日常主路径
|
||||
- 同时使用 PostgreSQL、Prisma、S3/MinIO、本地 `uploads` 目录,以及可选 Redis 上传会话
|
||||
- 已覆盖首页浏览、素材上传、分享下载、后台管理、外部接口、内外网状态识别、健康检查等完整链路
|
||||
- 当前项目已经在线上运行,涉及权限、下载、上传、转码、批量删除等改动时需要先验证再发布
|
||||
|
||||
### 1. 创意资产库与分发(Web)
|
||||
- **素材类型全覆盖**:3D 原图、AI 原图、实拍图、任务-详情、商品套包、视频与直播切片、证书/检测报告、标准模特白底图等。
|
||||
- **上传与转码链路**:分片上传与断点续传、SKU 维度资产管理、视频异步转码与封面/10 秒预览片段生成(PostgreSQL 租约恢复)。
|
||||
- **下载与分享**:权限前置校验、源文件(PSD / 3D 原文件)分级控制、视频保护等待期策略、分享链接与外部授权下载、内外网访问自适应。
|
||||
- **回收站与审计**:基于数据库 Outbox 任务与独立清理机制的安全永久删除、引用检查与完整操作/下载审计日志。
|
||||
## 当前核心能力
|
||||
|
||||
### 2. 组织架构与权限体系
|
||||
- **认证体系**:账号密码登录 + 钉钉登录与花名册组织绑定(NextAuth)。
|
||||
- **权限治理**:
|
||||
- 组织架构与素材权限包(按组织生效 + 个人权限继承 + 超级管理员兜底);
|
||||
- 内容级保护规则:私人素材权限、专属/限定可见范围素材权限、视频等待期、PSD/3D 源文件下载权限。
|
||||
- **协同与管理**:品牌中心、团队职能与绩效协同、AI 模型接入注册表、系统设置与诊断监控。
|
||||
### 1. 用户与登录
|
||||
|
||||
### 3. 小壹桌面客户端(`apps/`)
|
||||
- **原生画布与图层引擎(`apps/detail-photocraft`)**:Rust 桌面应用,支持 GPU 渲染画布、分层工程文件(`.pcraft`)、模板图层映射、候选图预览/采纳、整图与分屏导出、三步建项向导与草稿续接。
|
||||
- **智能体制作运行时(`apps/detail-agent-pi`)**:Node.js 后台服务,负责商品资料汇总、企业模板解析、文案与出图编排、画布原子工具调度与完整性校验。
|
||||
- **在线更新发布**:仅发布 Windows `stable` 在线更新包(`.zip` + `release.json`),支持启动器自动检测更新、版本切换与 `--previous` 一键回滚。
|
||||
- 账号密码登录
|
||||
- 钉钉登录与账号补全流程
|
||||
- NextAuth 会话管理
|
||||
- 个人资料页、个人素材、收藏与点赞
|
||||
|
||||
---
|
||||
### 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`(自带依赖锁,与主应用隔离)
|
||||
|
||||
## 技术栈
|
||||
|
||||
| 模块 | 技术栈 |
|
||||
| :--- | :--- |
|
||||
| **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` |
|
||||
|
||||
---
|
||||
- 前端: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
|
||||
|
||||
## 目录结构
|
||||
|
||||
```text
|
||||
gongxiangp2/
|
||||
├── 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/ # 静态资源与公共字体
|
||||
├── 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/ # 本地上传与处理中间文件
|
||||
└── 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
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
### 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
|
||||
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
|
||||
cd apps/detail-agent-pi
|
||||
node --test test/*.test.mjs
|
||||
export GONGXIANGP2_UPLOADS_MOUNT=/mnt/PoolOne/youyidian-uploads
|
||||
docker compose config
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### 小壹客户端发布与线上校验脚本
|
||||
- 发布在线更新:`scripts/publish-xiaoyi-client.ts`(默认预演,确认后追加 `--apply`)
|
||||
- 线上版本验通:`scripts/verify-xiaoyi-client.ts <版本号> [提交SHA]`
|
||||
- 回滚稳定版本:`scripts/publish-xiaoyi-client.ts --set-latest <上一稳定版> --channel stable --apply`
|
||||
- 当前生产宿主机的真实独立 ZFS 数据集路径是 `/mnt/PoolOne/youyidian-uploads`;先在宿主机用 `findmnt` 核验它确实是预期挂载,不能只确认目录存在。
|
||||
- 容器内统一使用 `UPLOAD_DIR=/app/uploads`,不要把宿主机路径写进容器环境变量。
|
||||
- `create_host_path: false` 会在路径缺失时直接失败,避免 Docker 静默新建空目录后让素材写入错误磁盘。
|
||||
- 相对 `./uploads` 只允许用于明确的非容器开发;影子环境使用其独立的 `uploads-shadow`,本地集成测试使用命名卷,二者都不能当作生产数据目录。
|
||||
|
||||
---
|
||||
默认访问地址:
|
||||
|
||||
## 仓库协作与问题反馈闭环
|
||||
```text
|
||||
http://localhost:3000
|
||||
```
|
||||
|
||||
本仓库托管于 GitHub 私有仓库,统一承载代码、PR 与用户问题反馈流转:
|
||||
登录后的一级入口为“品牌中心部门看板”,当前页面路由如下:
|
||||
|
||||
- **分支与提交**:功能开发与缺陷修复均在独立分支完成,通过对应定向测试与检查后再合入 `main`。
|
||||
- **问题反馈 Issue 标签约定**:
|
||||
- `feedback`:小壹用户提交的问题反馈
|
||||
- `status:triage`:新反馈待排查
|
||||
- `status:investigating`:正在定位或修复中
|
||||
- `status:needs-owner`:需要负责人拍板或确认方向
|
||||
- `status:ready-to-release`:已完成修复并测通,待确认发布
|
||||
- `status:fixed`:已修复并上线验证
|
||||
- `severity:p0`:严重阻断问题
|
||||
```text
|
||||
品牌中心部门看板:http://localhost:3000/
|
||||
小项二级框架示例:http://localhost:3000/workspaces/dashboard/core-metrics
|
||||
由壹点3D素材:http://localhost:3000/assets/material-library
|
||||
```
|
||||
|
||||
---
|
||||
### 无本机 Node 环境时使用 Docker 开发
|
||||
|
||||
## 安全与红线提醒
|
||||
- 严禁将 `.env`、凭据文件、密钥或内网敏感配置提交到 Git 历史;
|
||||
- 涉及数据库 Schema(`prisma/`)或迁移脚本变更前,必须先评估影响范围并做备份与灰度验证;
|
||||
- 客户端发版前必须完成版本元信息、PE 导入表、启动参数、运行时依赖与后台心跳校验后再切换 `stable` 通道。
|
||||
仓库提供一套隔离的 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` 说法
|
||||
- 项目已在线上运行,任何会影响上传、下载、权限、批量删除、资源链路的改动,都应先验证再发布
|
||||
|
||||
@ -383,7 +383,7 @@ export default function AdminPage() {
|
||||
: 'text-[#6b7075] hover:text-[#1a1c1d]'
|
||||
}`}
|
||||
>
|
||||
旧部门权限
|
||||
部门权限配置
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
@ -31,7 +31,6 @@ 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)}...`),
|
||||
@ -62,17 +61,6 @@ 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 },
|
||||
|
||||
@ -13,7 +13,6 @@ import {
|
||||
createApiKey,
|
||||
getApiKeyPreview,
|
||||
getApiKeys,
|
||||
XIAOYI_LISTING_KEY_SCOPE,
|
||||
} from '@/lib/external-api';
|
||||
|
||||
/**
|
||||
@ -82,7 +81,7 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, scope } = body;
|
||||
const { name } = body;
|
||||
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
@ -91,13 +90,7 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
const apiKey = await createApiKey(name.trim(), userId);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@ -1,161 +0,0 @@
|
||||
/** @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)
|
||||
})
|
||||
@ -1,81 +0,0 @@
|
||||
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) })
|
||||
})
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
@ -1 +1,92 @@
|
||||
export { retiredDepartmentPermissionWrite as POST } from '@/lib/retired-department-permission-write'
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1 +1,76 @@
|
||||
export { retiredDepartmentPermissionWrite as POST } from '@/lib/retired-department-permission-write'
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1 +1,136 @@
|
||||
export { retiredDepartmentPermissionWrite as POST, retiredDepartmentPermissionWrite as DELETE } from '@/lib/retired-department-permission-write'
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1 +1,118 @@
|
||||
export { retiredDepartmentPermissionWrite as POST, retiredDepartmentPermissionWrite as DELETE } from '@/lib/retired-department-permission-write'
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,79 +0,0 @@
|
||||
/** @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()
|
||||
})
|
||||
@ -5,6 +5,7 @@ import { prisma } from '@/lib/prisma';
|
||||
import {
|
||||
getAllMaterialTypes,
|
||||
getDepartmentPermissions,
|
||||
createDefaultPermissionsForDepartment,
|
||||
isSuperAdmin,
|
||||
} from '@/lib/department-permission';
|
||||
import { filterSelectableMaterialTypes } from '@/lib/material-type-options';
|
||||
@ -89,4 +90,72 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
export { retiredDepartmentPermissionWrite as POST } from '@/lib/retired-department-permission-write'
|
||||
/**
|
||||
* 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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
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, summarizeExternalNotificationDelivery } from '@/lib/external-auto-listing'
|
||||
import { listExternalNotificationDeliveries } from '@/lib/external-auto-listing'
|
||||
|
||||
async function assertAdminPermission() {
|
||||
const session = await getServerSession(authOptions)
|
||||
@ -26,26 +27,21 @@ 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: true,
|
||||
canAccessOperationsG: await canAccessOperationsGMaterials(operatorUserId),
|
||||
status: searchParams.get('status') || undefined,
|
||||
targetId: searchParams.get('targetId') || undefined,
|
||||
materialId: searchParams.get('materialId') || undefined,
|
||||
query,
|
||||
limit,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: deliveries.map(summarizeExternalNotificationDelivery),
|
||||
data: deliveries,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[admin/external-notification-deliveries] GET error:', error)
|
||||
|
||||
@ -2,10 +2,11 @@ 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() {
|
||||
@ -22,6 +23,50 @@ 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 } },
|
||||
@ -38,30 +83,28 @@ 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:
|
||||
body?.authConfig && typeof body.authConfig === 'object' && !Array.isArray(body.authConfig)
|
||||
? body.authConfig
|
||||
: undefined,
|
||||
authConfig: normalizeAuthConfigInput(body?.authConfig, existing, nextAuthType),
|
||||
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 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 })
|
||||
console.error('[admin/external-notification-targets/[id]] PUT error:', error)
|
||||
return toErrorResponse(error)
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@ 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,
|
||||
@ -24,9 +23,16 @@ async function assertAdminPermission() {
|
||||
}
|
||||
|
||||
function toErrorResponse(error: unknown) {
|
||||
return error instanceof AutoListingCallbackError
|
||||
? NextResponse.json({ success: false, error: error.message }, { status: error.status })
|
||||
: NextResponse.json({ success: false, error: '服务器错误' }, { status: 500 })
|
||||
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 })
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@ -42,7 +48,7 @@ export async function GET(request: NextRequest) {
|
||||
data: targets.map(buildExternalNotificationTargetAdminView),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[admin/external-notification-targets] GET error:', error instanceof Error ? error.name : 'UnknownError')
|
||||
console.error('[admin/external-notification-targets] GET error:', error)
|
||||
return toErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@ -73,7 +79,7 @@ export async function POST(request: NextRequest) {
|
||||
message: '通知目标创建成功',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[admin/external-notification-targets] POST error:', error instanceof Error ? error.name : 'UnknownError')
|
||||
console.error('[admin/external-notification-targets] POST error:', error)
|
||||
return toErrorResponse(error)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { canUseOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access'
|
||||
import { canAccessOperationsGMaterials, 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 canUseOperationsGMaterials((session.user as any).id) ? [] : await getOperationsGMaterialIds()
|
||||
const excludedIds = await canAccessOperationsGMaterials((session.user as any).id) ? [] : await getOperationsGMaterialIds()
|
||||
const materialLogWhere: any = { ...(excludedIds.length ? { materialId: { notIn: excludedIds } } : {}) }
|
||||
const downloadLogWhere: any = { ...(excludedIds.length ? { materialId: { notIn: excludedIds } } : {}) }
|
||||
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
|
||||
import { isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
import { buildMaterialPrivacyWhere, TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
|
||||
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
|
||||
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 { isSystemAdmin } from '@/lib/department-permission'
|
||||
import { createMaterialLog } from '@/lib/material-log'
|
||||
import { enqueueMaterialPurge, ensureMaterialPurgeWorkerStarted, MaterialPurgeError } from '@/lib/material-purge'
|
||||
|
||||
@ -26,18 +25,19 @@ export async function POST(request: NextRequest) {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
// 使用统一的权限检查函数(与单条删除保持一致)
|
||||
const operatorId = (session?.user as any)?.id
|
||||
if (!session || (!isSystemAdmin(session.user?.role) && !(await isSuperAdmin(operatorId)))) {
|
||||
if (!session || !isSystemAdmin((session.user as any)?.role)) {
|
||||
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,19 +63,15 @@ 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, ...TASK_DETAIL_PRIVACY_SELECT }
|
||||
select: { id: true, taskNo: true, productModel: true, materialType: true, accessScope: true }
|
||||
})
|
||||
|
||||
if (materials.length === 0) {
|
||||
return NextResponse.json({ error: '未找到要删除的素材' }, { status: 404 })
|
||||
}
|
||||
|
||||
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 })
|
||||
}
|
||||
if (materials.some((material) => material.accessScope === 'operations_g') && !(await canAccessOperationsGMaterials(operatorId))) {
|
||||
return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 })
|
||||
}
|
||||
|
||||
const deletedAt = new Date()
|
||||
|
||||
@ -1,18 +1,17 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { isSuperAdmin, isSystemAdmin } from '@/lib/department-permission'
|
||||
import { isSystemAdmin } from '@/lib/department-permission'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { canUseOperationsGMaterials, getOperationsGMaterialIds } from '@/lib/material-organization-access'
|
||||
import { canAccessOperationsGMaterials, 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)
|
||||
const user = session?.user
|
||||
if (!user?.id) return null
|
||||
return isSystemAdmin(user.role) || await isSuperAdmin(user.id) ? user.id : null
|
||||
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
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@ -23,7 +22,7 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: '清理任务无效' }, { status: 400 })
|
||||
}
|
||||
try {
|
||||
const excludedIds = await canUseOperationsGMaterials(operatorId) ? [] : await getOperationsGMaterialIds()
|
||||
const excludedIds = await canAccessOperationsGMaterials(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 }),
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
|
||||
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
|
||||
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 (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) {
|
||||
if (isRestrictedMaterial(material) && !(await canAccessOperationsGMaterials((session?.user as any)?.id))) {
|
||||
throw new RegeneratePdfPreviewInputError('无权限操作此素材', 403)
|
||||
}
|
||||
if (material.materialType !== '品牌VI灵感') {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { buildMaterialPrivacyWhere } from '@/lib/task-detail-privacy'
|
||||
import { buildMaterialOrganizationWhere } from '@/lib/material-organization-access'
|
||||
/**
|
||||
* 回收站 API - 获取已删除的素材
|
||||
*
|
||||
@ -9,15 +9,13 @@ 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)
|
||||
|
||||
const user = session?.user
|
||||
if (!user?.id || (!isSystemAdmin(user.role) && !(await isSuperAdmin(user.id)))) {
|
||||
if (!session || (session.user as any).role !== 'ADMIN') {
|
||||
return NextResponse.json(
|
||||
{ error: '无权限' },
|
||||
{ status: 403 }
|
||||
@ -29,7 +27,7 @@ export async function GET(req: NextRequest) {
|
||||
const pageSize = parseInt(searchParams.get('pageSize') || '20')
|
||||
const skip = (page - 1) * pageSize
|
||||
|
||||
const scopeWhere = await buildMaterialPrivacyWhere(user.id)
|
||||
const scopeWhere = await buildMaterialOrganizationWhere((session.user as any).id)
|
||||
|
||||
// 获取已删除的素材
|
||||
const [deletedMaterials, total] = await Promise.all([
|
||||
|
||||
@ -21,6 +21,7 @@ export async function GET() {
|
||||
role: true,
|
||||
isActive: true, // 保留,向后兼容
|
||||
status: true, // 新增:用户状态(阶段一)
|
||||
canDownload: true,
|
||||
department: true, // 保留,向后兼容
|
||||
departmentId: true, // 新增:部门ID(阶段二)
|
||||
managedDepartment: true, // 管理员负责的部门
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
/** @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',
|
||||
},
|
||||
})
|
||||
})
|
||||
@ -38,7 +38,7 @@ export async function POST(request: NextRequest) {
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
targetStatus = status === 'pending' ? 'suspended' : status;
|
||||
targetStatus = status;
|
||||
targetIsActive = status === 'active';
|
||||
} else if (isActive !== undefined) {
|
||||
// 旧格式:使用 isActive 参数(向后兼容)
|
||||
@ -49,7 +49,7 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
targetIsActive = isActive;
|
||||
targetStatus = isActive ? 'active' : 'suspended';
|
||||
targetStatus = isActive ? 'active' : 'pending';
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: '缺少参数:需要 isActive 或 status' },
|
||||
@ -73,19 +73,27 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
// 双写:同时更新 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;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
isActive: targetIsActive,
|
||||
status: targetStatus,
|
||||
archivedAt: targetStatus === 'archived' ? now : null,
|
||||
statusChangedAt: now,
|
||||
statusChangedBy: sessionUserId,
|
||||
},
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
const statusMessages: Record<string, string> = {
|
||||
'pending': '用户已设置为待激活',
|
||||
'active': '用户已激活',
|
||||
'suspended': '用户已暂停',
|
||||
'archived': '用户已归档',
|
||||
|
||||
@ -1,13 +1,82 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { isSystemAdmin } from '@/lib/department-permission'
|
||||
// 切换用户下载权限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';
|
||||
|
||||
// 给还在使用旧页面的管理员返回配置位置,旧字段保留供回滚兼容。
|
||||
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 })
|
||||
// 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 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: '请在「权限管理」中按素材类型配置下载权限' }, { status: 410 })
|
||||
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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@ 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() }))
|
||||
@ -81,7 +80,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(path.resolve('/uploads/brand-knowledge/guide.pdf'))
|
||||
expect(createReadStream).toHaveBeenCalledWith('/uploads/brand-knowledge/guide.pdf')
|
||||
expect(prisma.brandKnowledge.updateMany).not.toHaveBeenCalled()
|
||||
expect(await response.text()).toBe('test')
|
||||
expect(prisma.brandKnowledge.updateMany).toHaveBeenCalledWith({
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
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() }))
|
||||
@ -65,7 +64,7 @@ describe('brand knowledge preview route', () => {
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(readFile).toHaveBeenCalledWith(path.resolve('/uploads/brand-knowledge/part-002.webp'))
|
||||
expect(readFile).toHaveBeenCalledWith('/uploads/brand-knowledge/part-002.webp')
|
||||
expect(response.headers.get('content-type')).toBe('image/webp')
|
||||
await expect(response.text()).resolves.toBe('slice-02')
|
||||
})
|
||||
@ -104,7 +103,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(path.resolve('/uploads/brand-knowledge/legacy.png'))
|
||||
expect(readFile).toHaveBeenCalledWith('/uploads/brand-knowledge/legacy.png')
|
||||
expect(response.headers.get('content-type')).toBe('image/png')
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,5 +1,3 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { assertBrandCenterDashboardAccess } from '@/lib/brand-center-dashboard-access'
|
||||
@ -16,7 +14,7 @@ jest.mock('@/lib/brand-center-dashboard-access', () => ({
|
||||
jest.mock('@/lib/department-permission', () => ({ isSuperAdmin: jest.fn(async () => false) }))
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
brandKnowledge: { count: jest.fn().mockResolvedValue(1), findMany: jest.fn(), findFirst: jest.fn(), updateMany: jest.fn() },
|
||||
brandKnowledge: { 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() },
|
||||
},
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
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'
|
||||
@ -79,7 +78,7 @@ const previewFile = {
|
||||
arrayBuffer: async () => Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]).buffer,
|
||||
}
|
||||
|
||||
function uploadRequest(originalFileName = 'knowledge.pdf') {
|
||||
function uploadRequest() {
|
||||
const values = new Map<string, unknown>([
|
||||
['title', '长图规范'],
|
||||
['knowledgeType', '主图模板'],
|
||||
@ -87,7 +86,7 @@ function uploadRequest(originalFileName = 'knowledge.pdf') {
|
||||
['productCategoryName', '衣柜'],
|
||||
['uploadId', 'upload-1'],
|
||||
['existingFilePath', '/uploads/temp/upload-1/merged-knowledge.pdf'],
|
||||
['originalFileName', originalFileName],
|
||||
['originalFileName', 'knowledge.pdf'],
|
||||
['fileSize', '4'],
|
||||
['previewImage', previewFile],
|
||||
])
|
||||
@ -235,24 +234,6 @@ 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]
|
||||
@ -285,8 +266,8 @@ describe('brand knowledge upload route', () => {
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/source-upload-1.pdf')
|
||||
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(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/upload-1-preview-part-001.webp')
|
||||
expect(unlink).toHaveBeenCalledWith('/uploads/brand-knowledge/upload-1-preview-part-002.webp')
|
||||
expect(cleanupConsumedUploadSession).not.toHaveBeenCalled()
|
||||
expect(errorSpy).toHaveBeenCalled()
|
||||
expect(releaseRequestSlot).toHaveBeenCalledTimes(1)
|
||||
|
||||
@ -10,7 +10,6 @@ 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'
|
||||
@ -287,7 +286,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 = normalizeUploadFileName(formData.get('originalFileName'))
|
||||
const safeOriginalName = normalizeSafeFileName(normalizeText(formData.get('originalFileName'), 255))
|
||||
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 })
|
||||
@ -356,7 +355,7 @@ export async function POST(request: Request) {
|
||||
)
|
||||
}
|
||||
if (
|
||||
normalizeUploadFileName(ownedMergedUpload.session.fileName) !== safeOriginalName
|
||||
normalizeSafeFileName(ownedMergedUpload.session.fileName) !== safeOriginalName
|
||||
|| ownedMergedUpload.session.fileSize !== declaredFileSize
|
||||
|| ownedMergedUpload.session.uploadPurpose !== 'brand-knowledge'
|
||||
) {
|
||||
|
||||
@ -50,14 +50,4 @@ 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')
|
||||
})
|
||||
})
|
||||
|
||||
@ -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 { isSystemAdmin } from '@/lib/department-permission';
|
||||
import { createDefaultPermissionsForDepartment, isSystemAdmin } from '@/lib/department-permission';
|
||||
|
||||
// GET /api/departments - 获取部门列表
|
||||
export async function GET(request: NextRequest) {
|
||||
@ -163,6 +163,14 @@ 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);
|
||||
|
||||
@ -1,89 +0,0 @@
|
||||
/** @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' })
|
||||
})
|
||||
@ -3,7 +3,6 @@ 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'
|
||||
@ -34,25 +33,8 @@ 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,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()
|
||||
}
|
||||
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)}
|
||||
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])
|
||||
@ -62,10 +44,6 @@ 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)
|
||||
@ -87,34 +65,11 @@ 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&¤t.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'){
|
||||
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==='GET')value=await getDesktopProject(ownerId,parts[1],parts[2])
|
||||
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(auth.account,parts[2],JSON.parse((await body(request)).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===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}
|
||||
@ -133,7 +88,6 @@ 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})
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,22 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@ -1,38 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
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 })
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
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 }
|
||||
26
app/api/desktop/template-packs/route.ts
Normal file
26
app/api/desktop/template-packs/route.ts
Normal file
@ -0,0 +1,26 @@
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,3 @@
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
@ -182,7 +181,7 @@ export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const matchedMaterial = await prisma.material.findFirst({
|
||||
where: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
taskDetailPrivate: false, accessScope: 'general',
|
||||
deletedAt: null,
|
||||
productModel: trace.normalizedSpu,
|
||||
...(materialType ? { materialType } : {}),
|
||||
|
||||
169
app/api/external/download/route.ts
vendored
169
app/api/external/download/route.ts
vendored
@ -1,7 +1,4 @@
|
||||
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'
|
||||
import { isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
/**
|
||||
* 外部接口:文件下载
|
||||
* GET - 通过 Token 下载文件
|
||||
@ -22,7 +19,6 @@ 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';
|
||||
@ -70,32 +66,9 @@ 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: { ...EXTERNAL_MATERIAL_SCOPE_WHERE, id: materialId, deletedAt: null },
|
||||
where: { accessScope: 'general', id: materialId, deletedAt: null },
|
||||
include: {
|
||||
assets: true,
|
||||
},
|
||||
@ -161,37 +134,9 @@ async function handleDownload(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
// TODO: 权限检查(暂时保留接口,后续扩展)
|
||||
// 后续需要实现:根据 API Key 或用户权限检查下载权限
|
||||
// 参考:/api/materials/download 中的权限检查逻辑
|
||||
|
||||
// 任务类型素材:使用assets逻辑
|
||||
const isTaskMaterial = ['任务-详情', '任务-页面', '任务-其他', '任务-3D原图', '任务-AI原图', '任务-实拍原图', '任务-视频截图'].includes(material.materialType);
|
||||
@ -374,7 +319,7 @@ async function downloadStandardModelWhiteBackground(
|
||||
}
|
||||
|
||||
const sku = await prisma.materialSku.findFirst({
|
||||
where: { material: EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { material: { accessScope: 'general' },
|
||||
id: skuId,
|
||||
materialId: material.id,
|
||||
deletedAt: null,
|
||||
@ -460,22 +405,9 @@ 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 }
|
||||
@ -700,43 +632,10 @@ 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,
|
||||
prefetchedStreams?: Map<string, { body: Readable; contentLength?: number }>,
|
||||
) {
|
||||
async function downloadAsZip(assets: any[], taskNo: string, downloadType: string) {
|
||||
console.log(`[downloadAsZip] ========== 开始打包下载 ==========`);
|
||||
console.log(`[downloadAsZip] taskNo: ${taskNo}, downloadType: ${downloadType}`);
|
||||
console.log(`[downloadAsZip] 待打包资产数量: ${assets.length}`);
|
||||
@ -749,40 +648,10 @@ async function downloadAsZip(
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
|
||||
const skuNames = new Map<string, number>();
|
||||
const skuResolutions = new Set<string>();
|
||||
const files = assets.map(asset => {
|
||||
for (const asset of assets) {
|
||||
const fileUrl = normalizeAssetFileUrl(asset.fileUrl);
|
||||
const fileName = asset.fileName || path.basename(fileUrl);
|
||||
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}`;
|
||||
}
|
||||
const entryName = `${asset.assetType}/${fileName}`;
|
||||
|
||||
try {
|
||||
const localPath = resolveAssetLocalPath(fileUrl);
|
||||
@ -791,20 +660,8 @@ async function downloadAsZip(
|
||||
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) {
|
||||
const remote = await openRemoteFallbackStream(fileUrl);
|
||||
if (remote) {
|
||||
archive.append(archiveDownload.trackSource(remote.body), { name: entryName });
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
console.error(`[downloadAsZip] ❌ 本地与远程文件均不存在: ${localPath}`);
|
||||
console.error(`[downloadAsZip] ❌ 本地文件不存在: ${localPath}`);
|
||||
failCount++;
|
||||
continue;
|
||||
}
|
||||
@ -905,8 +762,8 @@ function resolveAssetLocalPath(fileUrl?: string | null): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (/^(?:\.\/|\/)?uploads\//i.test(normalizedUrl)) {
|
||||
return resolveStoredUploadPath(normalizedUrl.replace(/^\/+/, ''));
|
||||
if (normalizedUrl.startsWith('/uploads/')) {
|
||||
return path.join(process.cwd(), normalizedUrl.slice(1));
|
||||
}
|
||||
|
||||
if (path.isAbsolute(fileUrl)) {
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
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'
|
||||
@ -277,8 +276,7 @@ export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const searchOrConditions = await buildMaterialSearchOrConditions(trace.normalizedSpu)
|
||||
const materials = await prisma.material.findMany({
|
||||
where: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
deletedAt: null,
|
||||
...(searchOrConditions ? { OR: searchOrConditions } : {}),
|
||||
materialType: {
|
||||
|
||||
@ -37,9 +37,7 @@ export async function POST(request: NextRequest) {
|
||||
let taskNo: string | undefined
|
||||
|
||||
try {
|
||||
const body = await request.json().catch(() => {
|
||||
throw new ExternalMaterialImportError(400, 'INVALID_REQUEST', '请求体必须为 JSON')
|
||||
})
|
||||
const body = await request.json()
|
||||
taskNo = body?.formData?.taskNo
|
||||
|
||||
const result = await createExternalMaterialImportJob({
|
||||
@ -72,7 +70,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 ExternalMaterialImportError ? error.message : '服务器内部错误'
|
||||
const message = error instanceof Error ? error.message : '服务器内部错误'
|
||||
|
||||
await logApiCall({
|
||||
apiKeyId: keyRecord.id,
|
||||
|
||||
163
app/api/external/product-assets/route.ts
vendored
163
app/api/external/product-assets/route.ts
vendored
@ -1,11 +1,4 @@
|
||||
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'
|
||||
|
||||
/**
|
||||
* 外部接口:产品全案素材查询和删除
|
||||
@ -28,7 +21,7 @@ import {
|
||||
getMaterialById,
|
||||
getMaterialByTaskNo,
|
||||
updateTaskStatus,
|
||||
softDeleteExternalMaterial,
|
||||
softDeleteByTaskNo,
|
||||
TASK_STATUS,
|
||||
ASSET_TYPE,
|
||||
} from '@/lib/product-package';
|
||||
@ -62,14 +55,11 @@ export async function GET(request: NextRequest) {
|
||||
const materialId = request.nextUrl.searchParams.get('materialId')
|
||||
|
||||
// 验证 API Key
|
||||
const keyRecord = await validateApiKey(apiKey, true);
|
||||
const keyRecord = await validateApiKey(apiKey);
|
||||
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,
|
||||
@ -114,14 +104,7 @@ 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);
|
||||
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;
|
||||
}
|
||||
const material = found && !isRestrictedMaterial(found) ? found : null;
|
||||
console.log('[external/product-assets] Material found:', material ? {
|
||||
id: material.id,
|
||||
taskNo: material.taskNo,
|
||||
@ -159,6 +142,13 @@ 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,
|
||||
@ -168,103 +158,6 @@ 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)) {
|
||||
// 任务-详情
|
||||
@ -476,36 +369,6 @@ 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 - 删除素材
|
||||
*/
|
||||
@ -569,7 +432,7 @@ export async function DELETE(request: NextRequest) {
|
||||
}
|
||||
|
||||
// 软删除
|
||||
const deleted = await softDeleteExternalMaterial(material.id);
|
||||
await softDeleteByTaskNo(taskNo);
|
||||
|
||||
// 记录日志
|
||||
await logApiCall({
|
||||
@ -577,14 +440,12 @@ export async function DELETE(request: NextRequest) {
|
||||
endpoint: '/api/external/product-assets',
|
||||
method: 'DELETE',
|
||||
taskNo,
|
||||
statusCode: deleted.count ? 200 : 404,
|
||||
statusCode: 200,
|
||||
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(),
|
||||
|
||||
35
app/api/external/product-barcode-images/route.ts
vendored
35
app/api/external/product-barcode-images/route.ts
vendored
@ -1,10 +1,6 @@
|
||||
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,
|
||||
@ -24,14 +20,7 @@ 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
|
||||
@ -72,12 +61,10 @@ export async function GET(request: NextRequest) {
|
||||
where: {
|
||||
barcode,
|
||||
asset: {
|
||||
OR: [
|
||||
{ assetType: 'sku-preview', material: { materialType: '任务-详情' } },
|
||||
{ assetType: 'sku', material: { materialType: XIAOYI_DELIVERY_MATERIAL_TYPES.detail } },
|
||||
],
|
||||
assetType: 'sku-preview',
|
||||
material: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
materialType: '任务-详情',
|
||||
taskDetailPrivate: false, accessScope: 'general',
|
||||
deletedAt: null,
|
||||
},
|
||||
},
|
||||
@ -88,7 +75,6 @@ export async function GET(request: NextRequest) {
|
||||
asset: {
|
||||
select: {
|
||||
id: true,
|
||||
assetType: true,
|
||||
fileUrl: true,
|
||||
fileName: true,
|
||||
sortOrder: true,
|
||||
@ -103,7 +89,6 @@ export async function GET(request: NextRequest) {
|
||||
material: {
|
||||
select: {
|
||||
id: true,
|
||||
materialType: true,
|
||||
taskNo: true,
|
||||
productModel: true,
|
||||
categoryName: true,
|
||||
@ -139,16 +124,10 @@ 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 => item.barcode.trim()).filter(Boolean)),
|
||||
new Set((asset.barcodes || []).map((item: any) => String(item.barcode || '').trim()).filter(Boolean)),
|
||||
),
|
||||
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 || ''),
|
||||
previewUrl: rewriteStorageUrlForClient(asset.fileUrl, request) || String(asset.fileUrl || ''),
|
||||
fileName: String(asset.fileName || ''),
|
||||
sortOrder: Number(asset.sortOrder || 0),
|
||||
uploadedAt: asset.createdAt.toISOString(),
|
||||
@ -207,9 +186,7 @@ export async function GET(request: NextRequest) {
|
||||
userAgent: request.headers.get('user-agent') || undefined,
|
||||
})
|
||||
|
||||
const response = successResponse(responseData)
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
return successResponse(responseData)
|
||||
} catch (error) {
|
||||
console.error('[external/product-barcode-images] GET error:', error)
|
||||
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
|
||||
import path from 'path'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
@ -292,8 +291,7 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace
|
||||
deletedAt: null,
|
||||
skuName: normalizedSkuName,
|
||||
material: {
|
||||
is: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
is: { accessScope: 'general',
|
||||
materialType: '标准模型',
|
||||
deletedAt: null,
|
||||
},
|
||||
@ -356,7 +354,6 @@ async function handleSkuQuery(normalizedSkuName: string, logBase: LogBase, trace
|
||||
prisma.materialAsset.findMany({
|
||||
where: {
|
||||
materialId: matchedSku.materialId,
|
||||
material: EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
...getWhiteBackgroundAssetWhereForSku(matchedSku.id),
|
||||
},
|
||||
select: {
|
||||
@ -418,8 +415,7 @@ 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: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
productModel: normalizedSpu,
|
||||
materialType: '标准模型',
|
||||
deletedAt: null,
|
||||
@ -468,7 +464,6 @@ 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: {
|
||||
|
||||
@ -7,7 +7,6 @@ import {
|
||||
validateApiKey,
|
||||
} from '@/lib/external-api'
|
||||
import {
|
||||
assertExternalWhiteBackgroundReplayVisible,
|
||||
completeExternalApiIdempotencyRecord,
|
||||
ExternalWhiteBackgroundBarcodeError,
|
||||
failExternalApiIdempotencyRecord,
|
||||
@ -18,7 +17,6 @@ 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'
|
||||
|
||||
@ -158,7 +156,6 @@ 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, {
|
||||
@ -171,16 +168,11 @@ export async function POST(request: NextRequest) {
|
||||
const activeIdempotencyRecordId = String(idempotency.record.id)
|
||||
idempotencyRecordId = activeIdempotencyRecordId
|
||||
|
||||
const targets = []
|
||||
for (const barcode of barcodes) {
|
||||
targets.push({ barcode, resolved: await resolveStandardModelSkuByBarcode(barcode) })
|
||||
}
|
||||
|
||||
const results = []
|
||||
for (const { barcode, resolved } of targets) {
|
||||
for (const barcode of barcodes) {
|
||||
const resolved = await resolveStandardModelSkuByBarcode(barcode)
|
||||
const cleanup = await cleanupStandardModelWhiteBackgroundForSku({
|
||||
materialId: resolved.materialId,
|
||||
externalOnly: true,
|
||||
skuId: resolved.skuId,
|
||||
operatorUserId: keyRecord.createdBy,
|
||||
reason,
|
||||
@ -217,7 +209,7 @@ export async function POST(request: NextRequest) {
|
||||
await failExternalApiIdempotencyRecord(idempotencyRecordId)
|
||||
}
|
||||
|
||||
if (error instanceof ExternalWhiteBackgroundBarcodeError || error instanceof MaterialUploadRequestError) {
|
||||
if (error instanceof ExternalWhiteBackgroundBarcodeError) {
|
||||
await writeApiLog({ apiKeyId: keyRecord.id, trace, statusCode: error.status })
|
||||
return finalizeResponse(buildErrorResponse(error.status, error.code, error.message), trace)
|
||||
}
|
||||
|
||||
@ -7,7 +7,6 @@ import {
|
||||
validateApiKey,
|
||||
} from '@/lib/external-api'
|
||||
import {
|
||||
assertExternalWhiteBackgroundReplayVisible,
|
||||
completeExternalApiIdempotencyRecord,
|
||||
ExternalWhiteBackgroundBarcodeError,
|
||||
failExternalApiIdempotencyRecord,
|
||||
@ -269,7 +268,6 @@ 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, {
|
||||
@ -285,7 +283,6 @@ 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,
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
@ -8,7 +7,6 @@ import {
|
||||
validateApiKey,
|
||||
} from '@/lib/external-api'
|
||||
import {
|
||||
assertExternalWhiteBackgroundReplayVisible,
|
||||
completeExternalApiIdempotencyRecord,
|
||||
ExternalWhiteBackgroundBarcodeError,
|
||||
failExternalApiIdempotencyRecord,
|
||||
@ -18,7 +16,6 @@ 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,
|
||||
@ -236,8 +233,7 @@ async function findDuplicateStandardModelSkuName(skuName: string, excludeMateria
|
||||
},
|
||||
...(excludeMaterialId ? { NOT: { materialId: excludeMaterialId } } : {}),
|
||||
material: {
|
||||
is: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
is: { accessScope: 'general',
|
||||
materialType: '标准模型',
|
||||
deletedAt: null,
|
||||
},
|
||||
@ -303,7 +299,7 @@ async function createStandardModelSku(input: {
|
||||
skuName: string
|
||||
}) {
|
||||
const maxSortOrder = await prisma.materialSku.aggregate({
|
||||
where: { material: EXTERNAL_MATERIAL_SCOPE_WHERE, materialId: input.materialId },
|
||||
where: { material: { accessScope: 'general' }, materialId: input.materialId },
|
||||
_max: { sortOrder: true },
|
||||
})
|
||||
|
||||
@ -329,7 +325,7 @@ async function ensureProductBarcodeBinding(input: {
|
||||
skuId: string
|
||||
}) {
|
||||
const existing = await prisma.materialSkuBarcode.findFirst({
|
||||
where: { sku: { material: EXTERNAL_MATERIAL_SCOPE_WHERE },
|
||||
where: { sku: { material: { accessScope: 'general' } },
|
||||
barcode: input.barcode,
|
||||
deletedAt: null,
|
||||
},
|
||||
@ -384,7 +380,7 @@ async function ensureProductBarcodeBinding(input: {
|
||||
} catch (error: any) {
|
||||
if (error?.code === 'P2002') {
|
||||
const current = await prisma.materialSkuBarcode.findFirst({
|
||||
where: { sku: { material: EXTERNAL_MATERIAL_SCOPE_WHERE },
|
||||
where: { sku: { material: { accessScope: 'general' } },
|
||||
barcode: input.barcode,
|
||||
deletedAt: null,
|
||||
},
|
||||
@ -433,8 +429,7 @@ async function resolveStandardModelTargetBySpu(input: {
|
||||
operatorUserId: string
|
||||
}): Promise<ResolvedStandardModelTarget> {
|
||||
const matches = await prisma.material.findMany({
|
||||
where: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
productModel: {
|
||||
equals: input.spu,
|
||||
mode: 'insensitive',
|
||||
@ -444,6 +439,17 @@ 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,
|
||||
@ -458,16 +464,28 @@ async function resolveStandardModelTargetBySpu(input: {
|
||||
}
|
||||
|
||||
const existingMaterial = matches[0]
|
||||
let materialId = existingMaterial?.id
|
||||
if (!materialId) {
|
||||
if (!input.productCategoryName) {
|
||||
throw new ExternalWhiteBackgroundBySpuError(
|
||||
400,
|
||||
'PRODUCT_CATEGORY_REQUIRED',
|
||||
'该 SPU 尚未在标准模型内存在,新建标准模型 SPU 时必须传 productCategoryName',
|
||||
)
|
||||
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,
|
||||
})),
|
||||
}
|
||||
}
|
||||
const duplicateSku = await findDuplicateStandardModelSkuName(input.skuName)
|
||||
|
||||
const duplicateSku = await findDuplicateStandardModelSkuName(input.skuName, existingMaterial.id)
|
||||
if (duplicateSku) {
|
||||
throw new ExternalWhiteBackgroundBySpuError(
|
||||
409,
|
||||
@ -475,58 +493,67 @@ async function resolveStandardModelTargetBySpu(input: {
|
||||
`SKU 名称 ${input.skuName} 已被标准模型 SPU ${duplicateSku.material.productModel} 占用`,
|
||||
)
|
||||
}
|
||||
const created = await createStandardModelMaterial({
|
||||
spu: input.spu,
|
||||
productCategoryName: input.productCategoryName,
|
||||
platformName: input.platformName,
|
||||
operatorUserId: input.operatorUserId,
|
||||
|
||||
const sku = await createStandardModelSku({
|
||||
materialId: existingMaterial.id,
|
||||
skuName: input.skuName,
|
||||
})
|
||||
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', '素材不存在或不可访问')
|
||||
}
|
||||
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,
|
||||
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,
|
||||
...binding,
|
||||
}
|
||||
} finally {
|
||||
await release()
|
||||
skuId: sku.id,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
@ -674,7 +701,6 @@ 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, {
|
||||
@ -697,7 +723,6 @@ export async function POST(request: NextRequest) {
|
||||
})
|
||||
const uploadResult = await uploadStandardModelWhiteBackground({
|
||||
materialId: resolved.materialId,
|
||||
externalOnly: true,
|
||||
skuId: resolved.skuId,
|
||||
skuName: resolved.resolvedSkuName,
|
||||
sourceType,
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
|
||||
import path from 'path'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
@ -302,8 +301,7 @@ export async function GET(request: NextRequest) {
|
||||
deletedAt: null,
|
||||
skuName: normalizedSkuName,
|
||||
material: {
|
||||
is: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
is: { accessScope: 'general',
|
||||
materialType: '标准模型',
|
||||
deletedAt: null,
|
||||
},
|
||||
@ -360,7 +358,6 @@ 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: {
|
||||
@ -503,8 +500,7 @@ async function handleSpuQuery(
|
||||
try {
|
||||
// 通过 productModel(SPU)查找标准模型素材
|
||||
const material = await prisma.material.findFirst({
|
||||
where: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
productModel: normalizedSpu,
|
||||
materialType: '标准模型',
|
||||
deletedAt: null,
|
||||
@ -552,7 +548,6 @@ 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}:` } },
|
||||
@ -647,7 +642,7 @@ async function getTaskDetailMaterialsBySpu(normalizedSpu: string) {
|
||||
where: {
|
||||
productModel: normalizedSpu,
|
||||
materialType: '任务-详情',
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
taskDetailPrivate: false, accessScope: 'general',
|
||||
deletedAt: null,
|
||||
},
|
||||
select: {
|
||||
@ -748,8 +743,7 @@ async function handleTaskDetailSkuQuery(
|
||||
deletedAt: null,
|
||||
skuName: normalizedSkuName,
|
||||
material: {
|
||||
is: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
is: { accessScope: 'general',
|
||||
materialType: '标准模型',
|
||||
deletedAt: null,
|
||||
},
|
||||
|
||||
39
app/api/external/task-details/route.ts
vendored
39
app/api/external/task-details/route.ts
vendored
@ -1,39 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
14
app/api/external/video-assets/route.ts
vendored
14
app/api/external/video-assets/route.ts
vendored
@ -1,4 +1,3 @@
|
||||
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'
|
||||
@ -240,7 +239,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
|
||||
where: {
|
||||
barcode: { equals: keyword, mode: 'insensitive' },
|
||||
deletedAt: null,
|
||||
sku: { material: EXTERNAL_MATERIAL_SCOPE_WHERE, deletedAt: null },
|
||||
sku: { material: { accessScope: 'general' }, deletedAt: null },
|
||||
},
|
||||
select: { sku: { select: { materialId: true } } },
|
||||
})
|
||||
@ -251,8 +250,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
|
||||
)
|
||||
|
||||
const materials = await prisma.material.findMany({
|
||||
where: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
id: { in: materialIds },
|
||||
deletedAt: null,
|
||||
materialType: { in: VIDEO_MATERIAL_TYPES },
|
||||
@ -268,7 +266,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
|
||||
|
||||
// ── Layer 2: SKU-name contains match ──────────────────────────────────
|
||||
const skuRecords = await prisma.materialSku.findMany({
|
||||
where: { material: EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { material: { accessScope: 'general' },
|
||||
skuName: { contains: keyword, mode: 'insensitive' },
|
||||
deletedAt: null,
|
||||
},
|
||||
@ -279,8 +277,7 @@ 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: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
id: { in: materialIds },
|
||||
deletedAt: null,
|
||||
materialType: { in: VIDEO_MATERIAL_TYPES },
|
||||
@ -296,8 +293,7 @@ async function findVideoMaterials(keyword: string): Promise<MaterialRow[]> {
|
||||
|
||||
// ── Layer 3: SPU (productModel) contains match ────────────────────────
|
||||
const materials = await prisma.material.findMany({
|
||||
where: {
|
||||
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
||||
where: { accessScope: 'general',
|
||||
productModel: { contains: keyword, mode: 'insensitive' },
|
||||
deletedAt: null,
|
||||
materialType: { in: VIDEO_MATERIAL_TYPES },
|
||||
|
||||
@ -2,7 +2,6 @@ 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,
|
||||
@ -23,7 +22,7 @@ function actor(session: unknown) {
|
||||
}
|
||||
|
||||
function errorResponse(error: unknown) {
|
||||
if (error instanceof TaskDetailChangeApprovalError || error instanceof TaskDetailAssetEditError) {
|
||||
if (error instanceof TaskDetailChangeApprovalError) {
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode })
|
||||
}
|
||||
console.error('[task-detail-change] request error:', error)
|
||||
|
||||
@ -1,55 +0,0 @@
|
||||
/** @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()
|
||||
})
|
||||
@ -1,60 +0,0 @@
|
||||
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 })
|
||||
}
|
||||
@ -1,101 +0,0 @@
|
||||
/** @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')
|
||||
})
|
||||
@ -1,41 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,4 @@
|
||||
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
|
||||
import { isPreviewAssetType, isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
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';
|
||||
@ -11,7 +9,6 @@ import {
|
||||
canUserDownloadMaterial,
|
||||
canUserDownloadSource,
|
||||
canUserViewMaterial,
|
||||
isSuperAdmin,
|
||||
isSystemAdmin,
|
||||
} from '@/lib/department-permission';
|
||||
import { updateMaterialWithSharedRules, type MaterialUpdateInput } from '@/lib/material-update';
|
||||
@ -133,6 +130,15 @@ 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,
|
||||
@ -140,7 +146,7 @@ export async function GET(
|
||||
) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: '请先登录' },
|
||||
{ status: 401 }
|
||||
@ -319,15 +325,11 @@ export async function GET(
|
||||
if (!material) {
|
||||
return NextResponse.json({ error: '素材不存在' }, { status: 404 });
|
||||
}
|
||||
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) {
|
||||
if (!(await canAccessMaterialPrivacy(material as any, (session.user as any).id))) {
|
||||
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,
|
||||
@ -347,8 +349,18 @@ 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 ||
|
||||
@ -403,12 +415,11 @@ 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) && !(isXiaoyiDeliveryMaterial((material as any).materialType) && material.userId === userId)) {
|
||||
if (!userIsSuperAdmin && !isRestrictedMaterial(material as any)) {
|
||||
const canView = await canUserViewMaterial(
|
||||
userDepartment,
|
||||
userRole,
|
||||
@ -429,18 +440,36 @@ export async function GET(
|
||||
return buildVideoPreviewBlockedResponse();
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
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 formattedAssets = (materialWithUser.assets || []).map((asset: any) =>
|
||||
formatTaskDetailAsset(asset, displayAuthorName),
|
||||
|
||||
@ -19,8 +19,7 @@ import {
|
||||
} from '@/lib/standard-model-white-background'
|
||||
import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths'
|
||||
import { isPathInAllowedDirs } from '@/lib/path-security'
|
||||
import { TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
|
||||
import { getSkuDownloadDenial } from '../../authorization'
|
||||
import { canDownloadSkuMaterial } from '../../authorization'
|
||||
import { nodeReadableToWebStream } from '@/lib/node-readable-stream'
|
||||
import { createArchiveDownloadStream } from '@/lib/archive-download-stream'
|
||||
|
||||
@ -89,12 +88,21 @@ 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, ...TASK_DETAIL_PRIVACY_SELECT },
|
||||
select: { id: true, userId: true, materialType: true },
|
||||
})
|
||||
|
||||
if (!material) {
|
||||
@ -105,9 +113,8 @@ export async function GET(
|
||||
return NextResponse.json({ error: '只有标准模型类型才支持 SKU 下载' }, { status: 400 })
|
||||
}
|
||||
|
||||
const denial = await getSkuDownloadDenial(session.user as any, material)
|
||||
if (denial) {
|
||||
return NextResponse.json(denial, { status: 403, headers: { 'Cache-Control': 'private, no-store' } })
|
||||
if (!(await canDownloadSkuMaterial(session.user as any, material))) {
|
||||
return NextResponse.json({ error: '无权限下载此素材' }, { status: 403 })
|
||||
}
|
||||
|
||||
const sku = await prisma.materialSku.findFirst({
|
||||
|
||||
@ -52,8 +52,7 @@ export async function GET(
|
||||
return NextResponse.json({ error: '素材不存在' }, { status: 404 })
|
||||
}
|
||||
const session = await getServerSession(authOptions)
|
||||
const userId = (session?.user as any)?.id
|
||||
if (!(await canAccessMaterialPrivacy(material, userId))) {
|
||||
if (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) {
|
||||
return NextResponse.json({ error: '无权限访问此素材' }, {
|
||||
status: session?.user ? 403 : 401,
|
||||
headers: { 'Cache-Control': 'private, no-store' },
|
||||
|
||||
@ -6,7 +6,6 @@ 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
|
||||
@ -28,25 +27,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)) {
|
||||
if (material.userId === user.id || isSystemAdmin(user.role) || user.isSuperAdmin === true) {
|
||||
return true
|
||||
}
|
||||
|
||||
return isSuperAdmin(user.id)
|
||||
}
|
||||
|
||||
export async function getSkuDownloadDenial(
|
||||
export async function canDownloadSkuMaterial(
|
||||
user: SkuRouteSessionUser,
|
||||
material: SkuRouteMaterial,
|
||||
): Promise<DownloadErrorResponse | null> {
|
||||
if (!(await canAccessMaterialPrivacy(material, user.id))) return createDownloadPrivacyError(material)
|
||||
if (isRestrictedMaterial(material)) return null
|
||||
const allowed = await canUserDownloadMaterial(
|
||||
): 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(
|
||||
user.department,
|
||||
user.role || 'USER',
|
||||
user.managedDepartment,
|
||||
material.materialType,
|
||||
user.id,
|
||||
)
|
||||
return allowed ? null : createDownloadPermissionError('materialType')
|
||||
}
|
||||
|
||||
@ -15,8 +15,7 @@ import {
|
||||
} from '@/lib/standard-model-white-background'
|
||||
import { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths'
|
||||
import { isPathInAllowedDirs } from '@/lib/path-security'
|
||||
import { TASK_DETAIL_PRIVACY_SELECT } from '@/lib/task-detail-privacy'
|
||||
import { getSkuDownloadDenial } from '../authorization'
|
||||
import { canDownloadSkuMaterial } from '../authorization'
|
||||
import { createArchiveDownloadStream } from '@/lib/archive-download-stream'
|
||||
|
||||
type DownloadType = 'model' | 'white-background'
|
||||
@ -79,6 +78,15 @@ 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 : []
|
||||
@ -90,7 +98,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, ...TASK_DETAIL_PRIVACY_SELECT },
|
||||
select: { id: true, productModel: true, materialType: true, userId: true },
|
||||
})
|
||||
|
||||
if (!material) {
|
||||
@ -101,9 +109,8 @@ export async function POST(
|
||||
return NextResponse.json({ error: '只有标准模型类型才支持 SKU 批量下载' }, { status: 400 })
|
||||
}
|
||||
|
||||
const denial = await getSkuDownloadDenial(session.user as any, material)
|
||||
if (denial) {
|
||||
return NextResponse.json(denial, { status: 403, headers: { 'Cache-Control': 'private, no-store' } })
|
||||
if (!(await canDownloadSkuMaterial(session.user as any, material))) {
|
||||
return NextResponse.json({ error: '无权限下载此素材' }, { status: 403 })
|
||||
}
|
||||
|
||||
const skus = await prisma.materialSku.findMany({
|
||||
|
||||
@ -65,8 +65,7 @@ export async function GET(
|
||||
return NextResponse.json({ error: '素材不存在' }, { status: 404 })
|
||||
}
|
||||
const session = await getServerSession(authOptions)
|
||||
const userId = (session?.user as any)?.id
|
||||
if (!(await canAccessMaterialPrivacy(material, userId))) {
|
||||
if (!(await canAccessMaterialPrivacy(material, (session?.user as any)?.id))) {
|
||||
return NextResponse.json({ error: '无权限访问该私密素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } })
|
||||
}
|
||||
|
||||
@ -166,7 +165,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 })
|
||||
|
||||
@ -14,17 +14,14 @@ 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 { getUploadRootDir, resolveStoredUploadPath } from '@/lib/upload-paths';
|
||||
import { resolveStoredUploadPath } from '@/lib/upload-paths';
|
||||
import {
|
||||
getVideoDownloadAvailability,
|
||||
getVideoDownloadUnavailableMessage,
|
||||
@ -41,15 +38,30 @@ function normalizeStoredLocalPath(filePath: string) {
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
createDownloadError(DownloadErrorCode.UNAUTHORIZED),
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id: userId, role: userRole, department: userDepartment, managedDepartment } = session.user;
|
||||
const userIsSuperAdmin = await isSuperAdmin(userId);
|
||||
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 { searchParams } = new URL(request.url);
|
||||
const materialId = searchParams.get('id');
|
||||
@ -90,7 +102,7 @@ export async function GET(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
if (!(await canAccessMaterialPrivacy(material, userId))) {
|
||||
return NextResponse.json(createDownloadPrivacyError(material), { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
|
||||
return NextResponse.json(createDownloadError(DownloadErrorCode.NO_PERMISSION, '无权限下载此素材'), { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
|
||||
}
|
||||
|
||||
const videoDownloadAvailability = getVideoDownloadAvailability(
|
||||
@ -109,9 +121,13 @@ export async function GET(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
// 通用素材查下载权限包,已通过准入的私密及专属素材沿用范围授权。
|
||||
// 超级管理员可跳过权限包,视频保护期仍由上面的规则判定。
|
||||
if (!userIsSuperAdmin) {
|
||||
// 所有下载请求都必须检查部门和源文件权限,查询参数不能绕过。
|
||||
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))) {
|
||||
const canDownload = isRestrictedMaterial(material) || await canUserDownloadMaterial(
|
||||
userDepartment,
|
||||
userRole,
|
||||
@ -122,7 +138,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
if (!canDownload) {
|
||||
return NextResponse.json(
|
||||
createDownloadPermissionError('materialType'),
|
||||
createDownloadError(DownloadErrorCode.NO_PERMISSION),
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
@ -142,7 +158,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
if (!canDownloadSourceFile) {
|
||||
return NextResponse.json(
|
||||
createDownloadPermissionError('sourceFile'),
|
||||
createDownloadError(DownloadErrorCode.NO_PERMISSION, '无权限下载该源文件'),
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
@ -245,7 +261,7 @@ async function serveFile(filePath: string, material: any, fileNameSuffix: string
|
||||
);
|
||||
}
|
||||
|
||||
const allowedDirs = [getUploadRootDir(), ...getAllowedFileDirectories()];
|
||||
const allowedDirs = getAllowedFileDirectories();
|
||||
if (!isPathInAllowedDirs(filePath, allowedDirs)) {
|
||||
console.error('[Download] 路径越界:', filePath, '允许的目录:', allowedDirs);
|
||||
return NextResponse.json(
|
||||
|
||||
@ -217,7 +217,6 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const responseData = {
|
||||
total,
|
||||
canFilterOperationsGScope: context.canAccessOperationsGMaterials === true,
|
||||
categories: categoryResult.items,
|
||||
scenes: sceneResult.items,
|
||||
platforms: platformResult.items,
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
|
||||
import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy'
|
||||
import { isSuperAdmin, isSystemAdmin } from '@/lib/department-permission'
|
||||
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
@ -16,8 +15,7 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||||
}
|
||||
const userRole = (session.user as any).role;
|
||||
const userId = (session.user as any).id;
|
||||
if (!isSystemAdmin(userRole) && !(await isSuperAdmin(userId))) {
|
||||
if (userRole !== 'ADMIN') {
|
||||
return NextResponse.json({ error: '无权限' }, { status: 403 });
|
||||
}
|
||||
|
||||
@ -36,8 +34,8 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: '素材不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (!(await canAccessMaterialPrivacy(material, userId))) {
|
||||
return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 });
|
||||
if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials((session.user as any).id))) {
|
||||
return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 });
|
||||
}
|
||||
|
||||
const restoredTaskNo = getOriginalTaskNo((material as any).taskNo);
|
||||
@ -145,6 +143,7 @@ export async function POST(request: NextRequest) {
|
||||
]);
|
||||
|
||||
// 记录操作日志
|
||||
const userId = (session.user as any).id;
|
||||
await createMaterialLog({
|
||||
materialId: id,
|
||||
userId,
|
||||
|
||||
@ -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 { canUserViewMaterial, isSuperAdmin, isSystemAdmin } from '@/lib/department-permission';
|
||||
import { 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,7 +14,6 @@ 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';
|
||||
@ -175,8 +174,7 @@ export async function GET(request: NextRequest) {
|
||||
if (!material) {
|
||||
return NextResponse.json({ material: null });
|
||||
}
|
||||
const userId = (session.user as any).id;
|
||||
if (!(await canAccessMaterialPrivacy(material, userId))) {
|
||||
if (!(await canAccessMaterialPrivacy(material, (session.user as any).id))) {
|
||||
return NextResponse.json({ error: '无权限查看此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
|
||||
}
|
||||
|
||||
@ -184,8 +182,10 @@ 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,12 +263,13 @@ 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,
|
||||
@ -302,9 +303,10 @@ export async function GET(request: NextRequest) {
|
||||
console.warn(`[Materials API] pageSize 超过限制:${rawPageSize} > ${MAX_PAGE_SIZE},已自动限制为 ${MAX_PAGE_SIZE}`);
|
||||
}
|
||||
|
||||
const user = session.user as any;
|
||||
const context = await createMaterialQueryContext(searchParams, user);
|
||||
const { where, empty } = await buildMaterialWhereFromSearchParams(searchParams, user, { context });
|
||||
const { where, empty } = await buildMaterialWhereFromSearchParams(
|
||||
searchParams,
|
||||
session.user as any,
|
||||
);
|
||||
|
||||
if (empty) {
|
||||
return NextResponse.json({
|
||||
@ -766,29 +768,9 @@ 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 || deliveryCoverMap.get(material.id) || '';
|
||||
let previewUrl = material.previewUrl || material.videoCoverUrl || '';
|
||||
|
||||
if (!previewUrl && material.materialType === '任务-页面') {
|
||||
const coverUrl = coverUrlMap.get(material.id);
|
||||
@ -823,12 +805,13 @@ 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,
|
||||
@ -871,7 +854,7 @@ export async function GET(request: NextRequest) {
|
||||
const rewrittenMaterial = {
|
||||
...formatted,
|
||||
// 图片:使用统一规则(内网用户直接访问内网MinIO,外网用户根据文件大小决定是否走代理)
|
||||
previewUrl: isXiaoyiDeliveryMaterial(formatted.materialType) ? formatted.previewUrl : rewriteMediaUrlForClient(formatted.previewUrl, request, 'image'),
|
||||
previewUrl: rewriteMediaUrlForClient(formatted.previewUrl, request, 'image'),
|
||||
videoCoverUrl: rewriteMediaUrlForClient(formatted.videoCoverUrl, request, 'image'),
|
||||
displayImages: formatted.displayImages?.map((img: string) =>
|
||||
rewriteMediaUrlForClient(img, request, 'image')
|
||||
@ -929,8 +912,7 @@ export async function DELETE(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
const userRole = (session.user as any).role;
|
||||
const userId = (session.user as any).id;
|
||||
if (!isSystemAdmin(userRole) && !(await isSuperAdmin(userId))) {
|
||||
if (!isSystemAdmin(userRole)) {
|
||||
return NextResponse.json(
|
||||
{ error: '无权限' },
|
||||
{ status: 403 }
|
||||
@ -966,8 +948,10 @@ export async function DELETE(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
if (!(await canAccessMaterialPrivacy(material, userId))) {
|
||||
return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 });
|
||||
const userId = (session.user as any).id;
|
||||
|
||||
if (material.accessScope === 'operations_g' && !(await canAccessOperationsGMaterials(userId))) {
|
||||
return NextResponse.json({ error: '无权限操作运营中心 G 专属素材' }, { status: 403 });
|
||||
}
|
||||
|
||||
// 软删除
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material'
|
||||
import { isPreviewAssetType, isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
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';
|
||||
@ -8,10 +7,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';
|
||||
@ -97,6 +96,15 @@ 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 {
|
||||
@ -164,14 +172,6 @@ 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,6 +263,7 @@ export async function GET(request: NextRequest) {
|
||||
role: string;
|
||||
department: string | null;
|
||||
managedDepartment: string | null;
|
||||
canDownload: boolean;
|
||||
isSuperAdmin: boolean;
|
||||
} | null = null;
|
||||
|
||||
@ -286,6 +287,7 @@ export async function GET(request: NextRequest) {
|
||||
role: true,
|
||||
department: true,
|
||||
managedDepartment: true,
|
||||
canDownload: true,
|
||||
isSuperAdmin: true,
|
||||
},
|
||||
}),
|
||||
@ -296,19 +298,33 @@ export async function GET(request: NextRequest) {
|
||||
currentUser = user;
|
||||
}
|
||||
|
||||
// 任务-详情 PSD 和任务原图 ZIP 按各自素材类型检查源文件权限。
|
||||
let canAccessSource = false;
|
||||
if (userId && currentUser) {
|
||||
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)
|
||||
);
|
||||
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 capabilities = {
|
||||
@ -321,7 +337,8 @@ export async function GET(request: NextRequest) {
|
||||
hasSystemAdminPermission(currentUser.role, Boolean(currentUser.isSuperAdmin))
|
||||
)
|
||||
),
|
||||
canDelete: Boolean(currentUser && hasSystemAdminPermission(currentUser.role, currentUser.isSuperAdmin)),
|
||||
// 与 DELETE /api/materials 当前契约保持一致:仅系统管理员角色可删除。
|
||||
canDelete: Boolean(currentUser && isSystemAdmin(currentUser.role)),
|
||||
};
|
||||
|
||||
// 任务-详情单图编辑(替换/改名/删除)与元数据编辑权限口径不同:
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { canUseOperationsGMaterials } from '@/lib/material-organization-access'
|
||||
import { canAccessOperationsGMaterials } 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, isSuperAdmin } from '@/lib/department-permission';
|
||||
import { canUserViewMaterial, hasSystemAdminPermission } from '@/lib/department-permission';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const maxDuration = 3600; // 1小时
|
||||
@ -69,7 +69,10 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
const sessionUser = session.user as any;
|
||||
const isSystemAdministrator = hasSystemAdminPermission(sessionUser.role) || await isSuperAdmin(sessionUser.id);
|
||||
const isSystemAdministrator = hasSystemAdminPermission(
|
||||
sessionUser.role,
|
||||
Boolean(sessionUser.isSuperAdmin),
|
||||
);
|
||||
const retryAfter = consumeRateLimit(`status:${String(sessionUser.id || 'unknown')}`, STATUS_RATE_LIMIT);
|
||||
if (retryAfter) {
|
||||
return rateLimitResponse(retryAfter);
|
||||
@ -108,7 +111,7 @@ export async function GET(request: NextRequest) {
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
const canAccessG = await canUseOperationsGMaterials(sessionUser.id);
|
||||
const canAccessG = await canAccessOperationsGMaterials(sessionUser.id);
|
||||
if (material.accessScope === 'operations_g' && !canAccessG) {
|
||||
return NextResponse.json({ error: '无权限访问此素材' }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } });
|
||||
}
|
||||
@ -170,7 +173,10 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const sessionUser = session.user as any;
|
||||
const isSystemAdministrator = hasSystemAdminPermission(sessionUser.role) || await isSuperAdmin(sessionUser.id);
|
||||
const isSystemAdministrator = hasSystemAdminPermission(
|
||||
sessionUser.role,
|
||||
Boolean(sessionUser.isSuperAdmin),
|
||||
);
|
||||
|
||||
const retryAfter = consumeRateLimit(`start:${String(sessionUser.id || 'unknown')}`, START_RATE_LIMIT);
|
||||
if (retryAfter) {
|
||||
@ -217,7 +223,7 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const canAccessG = await canUseOperationsGMaterials(sessionUser.id);
|
||||
const canAccessG = await canAccessOperationsGMaterials(sessionUser.id);
|
||||
if (material.accessScope === 'operations_g' && !canAccessG) {
|
||||
return NextResponse.json({ error: '无权限操作此素材' }, { status: 403 });
|
||||
}
|
||||
|
||||
@ -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, getDesktopDeliveryUploadUserId } from '@/lib/upload-auth'
|
||||
import { getAuthenticatedUploadUserId } 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 getDesktopDeliveryUploadUserId(req, 'chunk') || await getAuthenticatedUploadUserId(req)
|
||||
const userId = await getAuthenticatedUploadUserId(req)
|
||||
const authTime = Date.now() - authStartedAt
|
||||
console.log(`[UploadChunk] 🔐 认证完成: ${authTime}ms`)
|
||||
|
||||
|
||||
@ -11,7 +11,7 @@ import {
|
||||
mergeUploadChunksAtomically,
|
||||
} from '@/lib/material-upload-merge'
|
||||
import { MaterialUploadStorageReservationManager } from '@/lib/material-upload-storage-reservation'
|
||||
import { beginUploadCompletionSeal, cancelUploadSessionSeal, completeUploadCompletionSeal } from '@/lib/material-upload-session-seal'
|
||||
import { cancelUploadSessionSeal } from '@/lib/material-upload-session-seal'
|
||||
import {
|
||||
deleteUploadSession,
|
||||
getOwnedUploadSession,
|
||||
@ -87,21 +87,6 @@ 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)
|
||||
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
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,
|
||||
@ -25,9 +24,8 @@ import {
|
||||
getOwnedUploadSession,
|
||||
isSafeUploadId,
|
||||
} from '@/lib/upload-sessions'
|
||||
import { getUploadRootDir, inspectUploadOutput } from '@/lib/upload-paths'
|
||||
import { resolveStrictChildPath } from '@/lib/path-security'
|
||||
import { normalizeUploadFileName } from '@/lib/upload-file-name'
|
||||
import { getUploadRootDir } from '@/lib/upload-paths'
|
||||
import { normalizeSafeFileName, resolveStrictChildPath } from '@/lib/path-security'
|
||||
import {
|
||||
acquireMaterialUploadStorageLock,
|
||||
type MaterialUploadStorageLockRelease,
|
||||
@ -51,9 +49,8 @@ export async function POST(req: NextRequest) {
|
||||
let completionSealFinalized = false
|
||||
|
||||
try {
|
||||
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()
|
||||
const session = await getServerSession(authOptions)
|
||||
const userId = String((session?.user as { id?: unknown } | undefined)?.id || '').trim()
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 })
|
||||
}
|
||||
@ -71,14 +68,13 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: '上传会话不存在、已过期或无权访问' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (uploadSession.uploadPurpose === PERFORMANCE_CASE_UPLOAD_PURPOSE) {
|
||||
return NextResponse.json({ error: '请从考核调研提交附件' }, { status: 403 })
|
||||
}
|
||||
|
||||
const mergedFileName = normalizeUploadFileName(uploadSession.fileName)
|
||||
const mergedFileName = normalizeSafeFileName(uploadSession.fileName)
|
||||
const uploadRoot = getUploadRootDir()
|
||||
const tempDir = resolveStrictChildPath(uploadRoot, 'temp', uploadId)
|
||||
if (!tempDir || !mergedFileName) {
|
||||
const mergedPath = mergedFileName
|
||||
? resolveStrictChildPath(tempDir || '', `merged-${mergedFileName}`)
|
||||
: null
|
||||
if (!tempDir || !mergedFileName || !mergedPath) {
|
||||
return NextResponse.json({ error: '上传会话路径无效' }, { status: 400 })
|
||||
}
|
||||
|
||||
@ -121,10 +117,11 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
// 第一次请求可能已经成功,只是响应在公网链路中丢失。完整且大小一致的
|
||||
// merged 文件是同一会话的确定结果,重复调用直接返回同一路径。
|
||||
const { outputPath: mergedPath, existing } = await inspectUploadOutput(
|
||||
tempDir, 'merged-file', 'merged-', mergedFileName,
|
||||
const existingMerged = await inspectExistingMergedFile(
|
||||
mergedPath,
|
||||
uploadSession.fileSize,
|
||||
)
|
||||
if (existing?.stats.isFile() && existing.stats.size === uploadSession.fileSize) {
|
||||
if (existingMerged === 'valid') {
|
||||
if (completionSealHandle) {
|
||||
await completeUploadCompletionSeal(completionSealHandle)
|
||||
completionSealFinalized = true
|
||||
@ -132,7 +129,7 @@ export async function POST(req: NextRequest) {
|
||||
await cleanupCompletedUpload(uploadId, chunks.map((chunk) => chunk.path))
|
||||
return createCompletedResponse({
|
||||
uploadId,
|
||||
mergedPath: existing.filePath,
|
||||
mergedPath,
|
||||
mergedFileName,
|
||||
fileSize: uploadSession.fileSize,
|
||||
})
|
||||
@ -144,8 +141,8 @@ export async function POST(req: NextRequest) {
|
||||
'UPLOAD_COMPLETED_FILE_INVALID',
|
||||
)
|
||||
}
|
||||
if (existing) {
|
||||
await rm(existing.filePath, { force: true })
|
||||
if (existingMerged === 'invalid') {
|
||||
await rm(mergedPath, { force: true })
|
||||
}
|
||||
|
||||
for (let index = 0; index < chunks.length; index += 1) {
|
||||
@ -225,6 +222,25 @@ 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 {
|
||||
|
||||
@ -1,102 +0,0 @@
|
||||
/** @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' })
|
||||
})
|
||||
})
|
||||
@ -4,7 +4,6 @@ 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', () => ({
|
||||
@ -229,27 +228,21 @@ describe('/api/materials/upload/init', () => {
|
||||
}))
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
code: 'FILE_NAME_INVALID',
|
||||
error: `文件名包含不支持的路径或字符。请修改「${JSON.stringify(fileName).slice(1, -1)}」后重新选择`,
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
error: '文件名包含不安全的路径或字符',
|
||||
})
|
||||
expect(ensureSafeDirectoryWithinRoot).not.toHaveBeenCalled()
|
||||
expect(saveUploadSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('文件名超出展示名上限时提示具体文件及长度限制', async () => {
|
||||
const fileName = `组合款-${'文'.repeat(MAX_UPLOAD_FILE_NAME_BYTES / 3)}-源文件.psd`
|
||||
test('拒绝超过文件系统叶子名称上限的文件名', async () => {
|
||||
const response = await POST(createRequest({
|
||||
fileName,
|
||||
fileName: `${'文'.repeat(90)}.psd`,
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
import { PERFORMANCE_CASE_UPLOAD_PURPOSE, validatePerformanceCaseAttachments } from '@/lib/performance-survey-attachment-contract'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getAuthenticatedUploadUserId, getDesktopDeliveryUploadUserId, isDesktopDeliveryPurpose } from '@/lib/upload-auth'
|
||||
import { getAuthenticatedUploadUserId } from '@/lib/upload-auth'
|
||||
import { saveUploadSession } from '@/lib/upload-sessions'
|
||||
import { getUploadRootDir } from '@/lib/upload-paths'
|
||||
import { ensureSafeDirectoryWithinRoot } from '@/lib/path-security'
|
||||
import { validateUploadFileName } from '@/lib/upload-file-name'
|
||||
import {
|
||||
ensureSafeDirectoryWithinRoot,
|
||||
normalizeSafeFileName,
|
||||
} from '@/lib/path-security'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { rm, statfs, writeFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
@ -17,12 +18,11 @@ 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', PERFORMANCE_CASE_UPLOAD_PURPOSE])
|
||||
const ALLOWED_UPLOAD_PURPOSES = new Set(['brand-knowledge'])
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const desktopUserId = await getDesktopDeliveryUploadUserId(req, 'init')
|
||||
const userId = desktopUserId || await getAuthenticatedUploadUserId(req)
|
||||
const userId = await getAuthenticatedUploadUserId(req)
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 })
|
||||
}
|
||||
@ -38,29 +38,23 @@ export async function POST(req: NextRequest) {
|
||||
)
|
||||
}
|
||||
|
||||
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 rawFileName = typeof body?.fileName === 'string' ? body.fileName : ''
|
||||
const normalizedFileName = normalizeSafeFileName(rawFileName)
|
||||
const normalizedFileSize = Number(body?.fileSize)
|
||||
const normalizedTotalChunks = Number(body?.totalChunks)
|
||||
const uploadPurpose = typeof body?.uploadPurpose === 'string'
|
||||
? body.uploadPurpose.trim()
|
||||
: ''
|
||||
|
||||
if (uploadPurpose && !ALLOWED_UPLOAD_PURPOSES.has(uploadPurpose) && !(desktopUserId && isDesktopDeliveryPurpose(uploadPurpose))) {
|
||||
if (!rawFileName.trim()) {
|
||||
return NextResponse.json({ error: '文件名不能为空' }, { status: 400 })
|
||||
}
|
||||
if (!normalizedFileName) {
|
||||
return NextResponse.json({ error: '文件名包含不安全的路径或字符' }, { status: 400 })
|
||||
}
|
||||
if (uploadPurpose && !ALLOWED_UPLOAD_PURPOSES.has(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 })
|
||||
@ -126,7 +120,7 @@ export async function POST(req: NextRequest) {
|
||||
// 写入元数据,方便在Redis丢失时回溯
|
||||
const metaPath = path.join(tempDir, 'meta.json')
|
||||
const metaPayload = {
|
||||
fileName: name.fileName,
|
||||
fileName: normalizedFileName,
|
||||
fileSize: normalizedFileSize,
|
||||
totalChunks: normalizedTotalChunks,
|
||||
chunkSize: normalizedChunkSize,
|
||||
@ -139,7 +133,7 @@ export async function POST(req: NextRequest) {
|
||||
// 保存会话(使用统一的接口,自动选择Redis或内存Map)
|
||||
const now = Date.now()
|
||||
await saveUploadSession(uploadId, {
|
||||
fileName: name.fileName,
|
||||
fileName: normalizedFileName,
|
||||
fileSize: normalizedFileSize,
|
||||
totalChunks: normalizedTotalChunks,
|
||||
chunkSize: normalizedChunkSize,
|
||||
|
||||
@ -32,7 +32,6 @@ 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),
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
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';
|
||||
@ -10,7 +9,6 @@ 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';
|
||||
@ -476,10 +474,6 @@ 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(
|
||||
{
|
||||
@ -947,7 +941,7 @@ export async function POST(request: NextRequest) {
|
||||
let sourcePath = '';
|
||||
|
||||
if (zipFile) {
|
||||
ext = getUploadStorageExtension(zipFile.name);
|
||||
ext = path.extname(zipFile.name);
|
||||
buffer = Buffer.from(await zipFile.arrayBuffer());
|
||||
zipFileSize = BigInt(buffer.length);
|
||||
console.log('[Upload] Using uploaded file buffer');
|
||||
@ -980,7 +974,7 @@ export async function POST(request: NextRequest) {
|
||||
'已合并的 canonical 源文件大小与上传会话不一致',
|
||||
);
|
||||
}
|
||||
ext = getUploadStorageExtension(originalFileName || ownedMergedUpload!.session.fileName || sourcePath);
|
||||
ext = path.extname(originalFileName || sourcePath);
|
||||
console.log('[Upload] Using existing merged file:', sourcePath, 'size:', stat.size);
|
||||
}
|
||||
|
||||
|
||||
@ -3,8 +3,6 @@ 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 {
|
||||
@ -14,18 +12,14 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
const user = session.user as any;
|
||||
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,
|
||||
]);
|
||||
const types = await getUserViewableMaterialTypes(
|
||||
user.department,
|
||||
user.role,
|
||||
user.managedDepartment,
|
||||
user.id
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
materialTypes: normalizeSelectableMaterialTypes(
|
||||
isUploadRequest ? types.filter((type) => !isXiaoyiDeliveryMaterial(type)) : types,
|
||||
),
|
||||
...(isUploadRequest ? { canSelectOperationsGScope } : {}),
|
||||
}, { headers: { 'Cache-Control': 'private, no-store' } });
|
||||
return NextResponse.json({ materialTypes: normalizeSelectableMaterialTypes(types) });
|
||||
} catch (error) {
|
||||
console.error('[Viewable Material Types] Error:', error);
|
||||
return NextResponse.json({ error: '获取可见素材类型失败' }, { status: 500 });
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
@ -129,4 +129,76 @@ export async function GET() {
|
||||
}
|
||||
}
|
||||
|
||||
export { retiredDepartmentPermissionWrite as PUT } from '@/lib/retired-department-permission-write'
|
||||
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 })
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,109 +0,0 @@
|
||||
/** @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')
|
||||
})
|
||||
@ -1,42 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -1,78 +0,0 @@
|
||||
/** @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()
|
||||
})
|
||||
@ -1,57 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -1,10 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -1,60 +0,0 @@
|
||||
/** @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()
|
||||
})
|
||||
@ -1,11 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -1,67 +0,0 @@
|
||||
/** @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()
|
||||
})
|
||||
@ -1,19 +0,0 @@
|
||||
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) }
|
||||
}
|
||||
@ -48,16 +48,3 @@ 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()
|
||||
})
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
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'
|
||||
@ -69,24 +68,24 @@ type RouteContext = {
|
||||
}
|
||||
|
||||
function ok(data: unknown, init?: ResponseInit) {
|
||||
return NextResponse.json({ success: true, data }, { ...init, headers: { ...init?.headers, 'Cache-Control': 'private, no-store' } })
|
||||
return NextResponse.json({ success: true, data }, init)
|
||||
}
|
||||
|
||||
function errorResponse(error: unknown) {
|
||||
if (error instanceof PerformanceSurveyApiError) {
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: error.status, headers: { 'Cache-Control': 'private, no-store' } })
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: error.status })
|
||||
}
|
||||
|
||||
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, headers: { 'Cache-Control': 'private, no-store' } },
|
||||
{ status: (error as { status: number }).status },
|
||||
)
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : '服务器错误'
|
||||
console.error('[performance-survey] API error:', error)
|
||||
return NextResponse.json({ success: false, error: message }, { status: 500, headers: { 'Cache-Control': 'private, no-store' } })
|
||||
return NextResponse.json({ success: false, error: message }, { status: 500 })
|
||||
}
|
||||
|
||||
function readDingtalkPerformanceTokens(request: Request) {
|
||||
@ -165,8 +164,6 @@ 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'
|
||||
@ -190,7 +187,6 @@ 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)
|
||||
}
|
||||
@ -224,10 +220,6 @@ 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))
|
||||
@ -328,7 +320,6 @@ 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 })
|
||||
@ -492,9 +483,3 @@ 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 })
|
||||
}
|
||||
|
||||
@ -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, isSuperAdmin } from '@/lib/department-permission'
|
||||
import { hasSystemAdminPermission } from '@/lib/department-permission'
|
||||
import { canAccessOperationsGMaterials } from '@/lib/material-organization-access'
|
||||
import {
|
||||
classifyTranscodeMaterial,
|
||||
@ -94,8 +94,7 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: '仅系统管理员可查看性能数据' }, { status: 403 })
|
||||
}
|
||||
const canAccessG = await canAccessOperationsGMaterials(user.id)
|
||||
const canViewG = canAccessG || await isSuperAdmin(user.id)
|
||||
const organizationWhere = canViewG ? {} : { accessScope: 'general' }
|
||||
const organizationWhere = canAccessG ? {} : { accessScope: 'general' }
|
||||
|
||||
const rateLimitKey = `${String(user.id || 'unknown')}:${request.headers.get('x-forwarded-for') || ''}`
|
||||
const retryAfter = consumeRateLimit(rateLimitKey)
|
||||
@ -267,7 +266,7 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
const canViewUploadTask = (task: any) => {
|
||||
const scope = uploadMaterialInfoMap.get(task.uploadId)?.accessScope
|
||||
if (scope === 'operations_g') return canViewG
|
||||
if (scope === 'operations_g') return canAccessG
|
||||
return canAccessG || task.userId === user.id || scope === 'general'
|
||||
}
|
||||
const uploadProcessingWithUsers = uploadProcessing.filter(canViewUploadTask).map(decorateUploadTask)
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
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
Loading…
x
Reference in New Issue
Block a user