From fb83fc3daf79f720ae13fc3def51b32b95c9af2d Mon Sep 17 00:00:00 2001
From: apple
Date: Tue, 17 Nov 2026 14:23:52 +0800
Subject: [PATCH] =?UTF-8?q?fix(product-stop):=20=E4=BF=AE=E5=A4=8D?=
=?UTF-8?q?=E9=83=A8=E7=BD=B2=E9=89=B4=E6=9D=83=E5=B9=B6=E5=A2=9E=E5=BC=BA?=
=?UTF-8?q?=E5=9B=BE=E7=89=87=E5=AF=BC=E5=85=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../使用说明/商品盘停管理-初始化与定时任务.md | 86 ++++++++
furniture-3d-system/package.json | 1 +
.../scripts/init-product-stop.ts | 118 ++++++++++
...install-product-stop-detail-timer.macos.sh | 5 +
.../install-product-stop-detail-timer.sh | 5 +
.../images/import/route.test.ts | 164 ++++++++++++++
.../images/import/route.ts | 162 +++++++++++---
.../ProductStopDetailImportDialog.tsx | 50 ++++-
.../ProductStopDetailView.tsx | 32 ++-
.../ProductStopImageImportResult.tsx | 100 +++++++++
.../product-stop-image-import-stream.test.ts | 105 +++++++++
.../product-stop-image-import-stream.ts | 112 ++++++++++
.../product-stop-image-import.module.css | 137 ++++++++++++
.../src/lib/product-stop-image-import.ts | 86 ++++++++
.../src/lib/selection-market/mysql.ts | 4 +-
.../lib/supply-chain-page-permissions.test.ts | 4 +-
.../supply-chain-product-stop-permissions.ts | 110 ++++++++++
.../product-stop-detail.repository.ts | 31 +++
.../product-stop-detail-xlsx.service.ts | 2 +
.../services/product-stop-detail.service.ts | 35 ---
.../product-stop-image-import.service.test.ts | 102 +++++++++
.../product-stop-image-import.service.ts | 205 ++++++++++++++++++
...-chain-permission-settings.service.test.ts | 68 +++++-
...upply-chain-permission-settings.service.ts | 84 ++++---
24 files changed, 1671 insertions(+), 137 deletions(-)
create mode 100644 furniture-3d-system/docs/使用说明/商品盘停管理-初始化与定时任务.md
create mode 100644 furniture-3d-system/scripts/init-product-stop.ts
create mode 100644 furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.test.ts
create mode 100644 furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopImageImportResult.tsx
create mode 100644 furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.test.ts
create mode 100644 furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.ts
create mode 100644 furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import.module.css
create mode 100644 furniture-3d-system/src/lib/product-stop-image-import.ts
create mode 100644 furniture-3d-system/src/server/services/product-stop-image-import.service.test.ts
create mode 100644 furniture-3d-system/src/server/services/product-stop-image-import.service.ts
diff --git a/furniture-3d-system/docs/使用说明/商品盘停管理-初始化与定时任务.md b/furniture-3d-system/docs/使用说明/商品盘停管理-初始化与定时任务.md
new file mode 100644
index 00000000..96276fc2
--- /dev/null
+++ b/furniture-3d-system/docs/使用说明/商品盘停管理-初始化与定时任务.md
@@ -0,0 +1,86 @@
+# 商品盘停管理:首次初始化与定时任务
+
+## 1. 部署前检查
+
+1. 执行数据库迁移,确认 `ProductStopRuleGroup`、`ProductStopDetailSnapshot`、`ProductStopWarehouseMapping` 等表已创建。
+2. 确认 `.env` 中的主数据库、销售数据库和产品档案只读库连接均可用。
+3. 执行:
+
+```bash
+npm run init:product-stop
+```
+
+该命令可重复执行,不会覆盖用户已维护的规则或仓库名称。默认会:
+
+- 幂等创建留观天数配置和默认盘停规则;
+- 当天没有快照或现有最新快照早于目标日期时,生成首次快照;
+- 基于最新快照补建缺失的仓库映射。
+
+常用参数:
+
+```bash
+# 初始化已有配置和仓库映射,不生成快照
+npm run init:product-stop -- --skip-snapshot
+
+# 指定首次快照日期
+npm run init:product-stop -- --snapshot-date=2026-11-17
+
+# 明确替换目标日期已有快照
+npm run init:product-stop -- --force-snapshot
+```
+
+## 2. 手动生成与补跑
+
+```bash
+npm run generate:product-stop-detail -- --apply --skip-if-current
+npm run retry:product-stop-push-outbox
+```
+
+`--skip-if-current` 会在当天已有成功快照时直接跳过,适合定时任务重复执行。
+
+## 3. Linux/systemd 安装
+
+先由应用账号完成依赖安装和初始化,再由 root 安装 timer:
+
+```bash
+cd /path/to/furniture-3d-system
+npm ci
+npm run init:product-stop
+
+sudo FURNITURE_PROD_BASE=/opt/furniture-3d-system-prod \
+ bash scripts/install-product-stop-detail-timer.sh
+```
+
+验证:
+
+```bash
+systemctl status furniture-product-stop-detail.timer
+systemctl list-timers --all furniture-product-stop-detail.timer
+journalctl -u furniture-product-stop-detail.service -n 100 --no-pager
+```
+
+安装脚本会覆盖同名 unit 后重新加载,因此可安全重复执行。默认每天北京时间 01:00 执行;失败后由 `run-product-stop-detail-until-success.sh` 每小时补跑。
+
+## 4. macOS/launchd 安装
+
+```bash
+npm run init:product-stop
+bash scripts/install-product-stop-detail-timer.macos.sh
+```
+
+验证:
+
+```bash
+launchctl print "gui/$(id -u)/com.furniture.product-stop-detail"
+tail -n 100 "$HOME/Library/Logs/furniture-product-stop-detail.log"
+```
+
+安装脚本会先 `bootout` 同名任务再 `bootstrap`,可重复执行。
+
+## 5. 幂等与并发说明
+
+- 默认规则通过版本状态防止并发重复写入,也不会在用户主动清空后回灌。
+- 仓库映射只自动补建缺失项;人工维护的仓库名称不会被自动值覆盖。
+- 快照生成和补跑共用日期唯一键;定时器执行时使用 `--skip-if-current`。
+- 调度器使用文件锁,避免每小时补跑与手动任务并发。
+- 正式环境只安装一种调度器:Linux 使用 systemd,macOS 使用 launchd。
diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json
index 997cec49..5901df2b 100644
--- a/furniture-3d-system/package.json
+++ b/furniture-3d-system/package.json
@@ -35,6 +35,7 @@
"backfill:product-archive-production-type": "tsx scripts/backfill-product-archive-production-type.ts",
"backfill:product-archive-production-type:apply": "tsx scripts/backfill-product-archive-production-type.ts --apply",
"sync:supply-chain-product-archive-sales-performance": "tsx scripts/sync-supply-chain-product-archive-sales-performance.ts",
+ "init:product-stop": "tsx scripts/init-product-stop.ts",
"generate:product-stop-detail": "tsx scripts/generate-product-stop-detail.ts",
"retry:product-stop-push-outbox": "tsx scripts/retry-product-stop-push-outbox.ts",
"run:product-sabc": "tsx scripts/run-product-sabc.ts",
diff --git a/furniture-3d-system/scripts/init-product-stop.ts b/furniture-3d-system/scripts/init-product-stop.ts
new file mode 100644
index 00000000..65885b76
--- /dev/null
+++ b/furniture-3d-system/scripts/init-product-stop.ts
@@ -0,0 +1,118 @@
+import { loadEnvConfig } from '@next/env'
+import { shanghaiToday } from '../src/lib/product-archive-sales-period'
+
+loadEnvConfig(process.cwd())
+
+function arg(name: string) {
+ const prefix = `--${name}=`
+ return process.argv.slice(2).find((value) => value.startsWith(prefix))?.slice(prefix.length) ?? ''
+}
+
+function hasFlag(name: string) {
+ return process.argv.includes(`--${name}`)
+}
+
+function printHelp() {
+ console.log(`商品盘停幂等初始化
+
+用法:
+ npm run init:product-stop
+ npm run init:product-stop -- --snapshot-date=2026-11-17
+ npm run init:product-stop -- --skip-snapshot
+ npm run init:product-stop -- --force-snapshot
+
+默认行为:
+ 1. 幂等创建留观天数、默认规则和状态版本;
+ 2. 当天或指定日期没有快照时生成首次快照;
+ 3. 按最新快照补建仓库映射。
+
+--skip-snapshot 只初始化配置和已有快照的仓库映射
+--force-snapshot 明确替换指定日期已有快照
+`)
+}
+
+async function main() {
+ if (hasFlag('help')) {
+ printHelp()
+ return
+ }
+ const snapshotDateArg = arg('snapshot-date')
+ if (snapshotDateArg && !/^\d{4}-\d{2}-\d{2}$/.test(snapshotDateArg)) {
+ throw new Error('--snapshot-date 格式应为 YYYY-MM-DD')
+ }
+ if (hasFlag('skip-snapshot') && hasFlag('force-snapshot')) {
+ throw new Error('--skip-snapshot 与 --force-snapshot 不能同时使用')
+ }
+
+ const { prisma } = await import('../src/lib/prisma')
+ try {
+ const { productStopObservationConfigService } = await import(
+ '../src/server/services/product-stop-observation-config.service'
+ )
+ const { productStopRuleService } = await import(
+ '../src/server/services/product-stop-rule.service'
+ )
+ const { productStopWarehouseMappingService } = await import(
+ '../src/server/services/product-stop-warehouse-mapping.service'
+ )
+
+ const observation = await productStopObservationConfigService.get()
+ const rules = await productStopRuleService.list()
+ const targetSnapshotDate = snapshotDateArg || shanghaiToday()
+ const latestSnapshot = await prisma.productStopDetailSnapshot.findFirst({
+ orderBy: { snapshotDate: 'desc' },
+ select: { snapshotDate: true },
+ })
+ let snapshot: {
+ status: 'SKIPPED' | 'GENERATED'
+ snapshotDate: string
+ rowCount?: number
+ warnings?: string[]
+ }
+
+ if (hasFlag('skip-snapshot')) {
+ snapshot = { status: 'SKIPPED', snapshotDate: latestSnapshot?.snapshotDate ?? '' }
+ } else if (
+ !hasFlag('force-snapshot')
+ && latestSnapshot?.snapshotDate
+ && latestSnapshot.snapshotDate >= targetSnapshotDate
+ ) {
+ snapshot = {
+ status: 'SKIPPED',
+ snapshotDate: latestSnapshot.snapshotDate,
+ }
+ } else {
+ const { productStopDetailGenerationService } = await import(
+ '../src/server/services/product-stop-detail-generation.service'
+ )
+ const result = await productStopDetailGenerationService.generate({
+ snapshotDate: targetSnapshotDate,
+ user: { id: 'product-stop-initializer', name: '商品盘停初始化任务' },
+ })
+ snapshot = {
+ status: 'GENERATED',
+ snapshotDate: result.snapshotDate,
+ rowCount: result.rowCount,
+ warnings: result.warnings,
+ }
+ }
+
+ await productStopWarehouseMappingService.ensureMappingsFromDetail()
+ const mappings = await productStopWarehouseMappingService.list()
+ console.log(JSON.stringify({
+ status: 'READY',
+ targetSnapshotDate,
+ observationDays: observation.observationDays,
+ ruleGroups: rules.length,
+ snapshot,
+ warehouseMappings: mappings.length,
+ }, null, 2))
+ } finally {
+ await prisma.$disconnect()
+ }
+}
+
+void main().catch((error) => {
+ console.error(error instanceof Error ? error.message : String(error))
+ process.exitCode = 1
+})
diff --git a/furniture-3d-system/scripts/install-product-stop-detail-timer.macos.sh b/furniture-3d-system/scripts/install-product-stop-detail-timer.macos.sh
index b962959f..cbb4e085 100755
--- a/furniture-3d-system/scripts/install-product-stop-detail-timer.macos.sh
+++ b/furniture-3d-system/scripts/install-product-stop-detail-timer.macos.sh
@@ -32,6 +32,10 @@ if [ ! -f "$APP_ROOT/scripts/generate-product-stop-detail.ts" ]; then
echo "缺少盘停明细生成脚本:$APP_ROOT/scripts/generate-product-stop-detail.ts" >&2
exit 1
fi
+if [ ! -f "$APP_ROOT/scripts/init-product-stop.ts" ]; then
+ echo "缺少商品盘停初始化入口:$APP_ROOT/scripts/init-product-stop.ts" >&2
+ exit 1
+fi
if [ ! -f "$APP_ROOT/scripts/product-stop-detail-scheduler.mjs" ]; then
echo "缺少补跑调度器:$APP_ROOT/scripts/product-stop-detail-scheduler.mjs" >&2
exit 1
@@ -96,5 +100,6 @@ echo " 补跑:生成失败后每 ${RETRY_INTERVAL_SECONDS} 秒重试;开机
echo " 调度器:$RUNTIME_SCRIPT"
echo " 项目目录:$APP_ROOT"
echo " 日志文件:$LOG_FILE"
+echo " 首次初始化:cd \"$APP_ROOT\" && npm run init:product-stop"
echo " 手动立刻跑一次:launchctl kickstart -k \"gui/$(id -u)/$LABEL\""
launchctl print "gui/$(id -u)/$LABEL" 2>/dev/null | grep -E "state =|runs =|last exit code" | head -5 || true
diff --git a/furniture-3d-system/scripts/install-product-stop-detail-timer.sh b/furniture-3d-system/scripts/install-product-stop-detail-timer.sh
index e82b7228..58db859e 100644
--- a/furniture-3d-system/scripts/install-product-stop-detail-timer.sh
+++ b/furniture-3d-system/scripts/install-product-stop-detail-timer.sh
@@ -14,6 +14,10 @@ if [ ! -f "$APP_ROOT/scripts/generate-product-stop-detail.ts" ]; then
echo "Missing deployed script: $APP_ROOT/scripts/generate-product-stop-detail.ts" >&2
exit 1
fi
+if [ ! -f "$APP_ROOT/scripts/init-product-stop.ts" ]; then
+ echo "Missing initialization entry: $APP_ROOT/scripts/init-product-stop.ts" >&2
+ exit 1
+fi
if [ ! -f "$BASE/shared/.env" ]; then
echo "Missing production environment file: $BASE/shared/.env" >&2
exit 1
@@ -52,3 +56,4 @@ EOF
systemctl daemon-reload
systemctl enable --now "$SERVICE_NAME.timer"
systemctl list-timers --all "$SERVICE_NAME.timer" --no-pager
+echo "首次部署未执行初始化时,请在应用账号下运行:cd $APP_ROOT && npm run init:product-stop"
diff --git a/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.test.ts
new file mode 100644
index 00000000..e60a7335
--- /dev/null
+++ b/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.test.ts
@@ -0,0 +1,164 @@
+import { ReadableStream as NodeReadableStream } from 'node:stream/web'
+import { ErrorCode } from '@/server/core/errors'
+
+export {}
+
+const mockHandleRequest = jest.fn()
+const mockJsonError = jest.fn()
+const mockParseImageImport = jest.fn()
+const mockFindLatestAdmissionByBarcodes = jest.fn()
+const mockImportRows = jest.fn()
+const mockGetPermissions = jest.fn()
+const mockUpload = jest.fn()
+const mockDeleteObject = jest.fn()
+
+jest.mock('@/server/core/response', () => ({
+ handleRequest: (...args: unknown[]) => mockHandleRequest(...args),
+ jsonError: (...args: unknown[]) => mockJsonError(...args),
+}))
+
+jest.mock('@/server/services/product-stop-detail-xlsx.service', () => ({
+ productStopDetailXlsxService: {
+ parseImageImport: (...args: unknown[]) => mockParseImageImport(...args),
+ },
+}))
+
+jest.mock('@/server/services/product-stop-image-import.service', () => ({
+ productStopImageImportService: {
+ findLatestAdmissionByBarcodes: (...args: unknown[]) => mockFindLatestAdmissionByBarcodes(...args),
+ importRows: (...args: unknown[]) => mockImportRows(...args),
+ },
+}))
+
+jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({
+ supplyChainPermissionSettingsService: {
+ getProductInventoryStopPermissions: (...args: unknown[]) => mockGetPermissions(...args),
+ },
+}))
+
+jest.mock('@/lib/storage', () => ({
+ uploadBufferToObjectStorageWithMetadata: (...args: unknown[]) => mockUpload(...args),
+ deleteObjectWithResult: (...args: unknown[]) => mockDeleteObject(...args),
+}))
+
+class MockFile {
+ name = 'images.xlsx'
+ size = 16
+
+ async arrayBuffer() {
+ return new ArrayBuffer(16)
+ }
+}
+
+const { POST } = require('./route')
+
+describe('商品盘停图片导入接口', () => {
+ const originalFile = global.File
+ const originalReadableStream = global.ReadableStream
+
+ beforeAll(() => {
+ Object.defineProperty(global, 'File', { configurable: true, value: MockFile })
+ Object.defineProperty(global, 'ReadableStream', { configurable: true, value: NodeReadableStream })
+ })
+
+ afterAll(() => {
+ Object.defineProperty(global, 'File', { configurable: true, value: originalFile })
+ Object.defineProperty(global, 'ReadableStream', { configurable: true, value: originalReadableStream })
+ })
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockHandleRequest.mockImplementation(async (_request: unknown, handler: (ctx: unknown) => unknown) => handler({
+ requestId: 'image-import-test',
+ user: { id: 'admin-1', name: '管理员', role: 'ADMIN' },
+ }))
+ mockJsonError.mockReturnValue({ error: 'mocked' })
+ mockGetPermissions.mockResolvedValue({
+ detail: { main: { import: true } },
+ unadmitted: { main: { import: true } },
+ })
+ mockDeleteObject.mockResolvedValue({ status: 'missing' })
+ })
+
+ it('rejects an illegal admission scope before reading permissions or the file', async () => {
+ const values = new Map([['admissionScope', '全部']])
+ const request = {
+ formData: async () => ({ get: (key: string) => values.get(key) }),
+ }
+
+ await POST(request)
+
+ expect(mockJsonError).toHaveBeenCalledWith(
+ ErrorCode.VALIDATION_INVALID_FORMAT,
+ expect.stringContaining('准入范围参数不合法'),
+ 400,
+ 'image-import-test',
+ )
+ expect(mockGetPermissions).not.toHaveBeenCalled()
+ expect(mockParseImageImport).not.toHaveBeenCalled()
+ })
+
+ it('does not upload an embedded image when its barcode belongs to another scope', async () => {
+ const values = new Map([
+ ['admissionScope', '是'],
+ ['file', new MockFile()],
+ ])
+ mockParseImageImport.mockResolvedValue({
+ rows: [
+ { rowNumber: 2, barcode: 'A1', imageUrl: '' },
+ { rowNumber: 3, barcode: 'B2', imageUrl: 'https://example.com/b.jpg' },
+ ],
+ embeddedImages: [{
+ rowNumber: 2,
+ buffer: Buffer.from('image'),
+ extension: 'png',
+ contentType: 'image/png',
+ }],
+ })
+ mockFindLatestAdmissionByBarcodes.mockResolvedValue(new Map([
+ ['A1', '否'],
+ ['B2', '是'],
+ ]))
+ mockImportRows.mockImplementation(async (input: {
+ initialProgress: unknown
+ onProgress: (progress: unknown, row: unknown) => void
+ }) => {
+ const progress = {
+ phase: 'complete', processed: 2, total: 2, succeeded: 1,
+ failed: 1, skipped: 0, uploaded: 0, uploadTotal: 0,
+ }
+ input.onProgress(progress, {
+ rowNumber: 2, barcode: 'A1', status: 'failed', message: '跨范围修改',
+ })
+ input.onProgress(progress, {
+ rowNumber: 3, barcode: 'B2', status: 'succeeded', message: '图片已保存',
+ })
+ return {
+ progress,
+ results: [
+ { rowNumber: 2, barcode: 'A1', status: 'failed', message: '跨范围修改' },
+ { rowNumber: 3, barcode: 'B2', status: 'succeeded', message: '图片已保存' },
+ ],
+ }
+ })
+ const request = {
+ formData: async () => ({ get: (key: string) => values.get(key) }),
+ }
+
+ const response = await POST(request)
+ const reader = response.body.getReader()
+ while (!(await reader.read()).done) {
+ // Drain the NDJSON stream so completion and cleanup finish.
+ }
+
+ expect(mockUpload).not.toHaveBeenCalled()
+ expect(mockImportRows).toHaveBeenCalledWith(expect.objectContaining({
+ admissionScope: '是',
+ rows: [
+ { rowNumber: 2, barcode: 'A1', imageUrl: '' },
+ { rowNumber: 3, barcode: 'B2', imageUrl: 'https://example.com/b.jpg' },
+ ],
+ }))
+ expect(mockDeleteObject).not.toHaveBeenCalled()
+ })
+})
diff --git a/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.ts
index bc74e594..9378aab1 100644
--- a/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.ts
+++ b/furniture-3d-system/src/app/api/supply-chain/management/product-inventory-stop/images/import/route.ts
@@ -1,10 +1,15 @@
import { randomUUID } from 'node:crypto'
-import { NextRequest } from 'next/server'
-import { ErrorCode } from '@/server/core/errors'
-import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
+import { NextRequest, NextResponse } from 'next/server'
+import {
+ createProductStopImageImportProgress,
+ parseProductStopAdmissionScope,
+ type ProductStopImageImportStreamEvent,
+} from '@/lib/product-stop-image-import'
+import { ErrorCode, isAppError } from '@/server/core/errors'
+import { handleRequest, jsonError } from '@/server/core/response'
import { deleteObjectWithResult, uploadBufferToObjectStorageWithMetadata } from '@/lib/storage'
-import { productStopDetailService } from '@/server/services/product-stop-detail.service'
import { productStopDetailXlsxService } from '@/server/services/product-stop-detail-xlsx.service'
+import { productStopImageImportService } from '@/server/services/product-stop-image-import.service'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
const MAX_FILE_SIZE = 10 * 1024 * 1024
@@ -18,10 +23,26 @@ async function cleanupUploadedImages(storageKeys: string[], requestId: string) {
})
}
+function importErrorMessage(error: unknown) {
+ if (isAppError(error)) return error.message
+ if (error instanceof Error && /storage|object storage|upload/i.test(error.message)) {
+ return '导入图片上传失败,请稍后重试'
+ }
+ return '导入过程中发生错误'
+}
+
export async function POST(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const form = await request.formData()
- const admissionScope = String(form.get('admissionScope') ?? '是')
+ const admissionScope = parseProductStopAdmissionScope(form.get('admissionScope'))
+ if (!admissionScope) {
+ return jsonError(
+ ErrorCode.VALIDATION_INVALID_FORMAT,
+ '准入范围参数不合法,只允许“是”或“否”',
+ 400,
+ ctx.requestId,
+ )
+ }
const permissions = await supplyChainPermissionSettingsService
.getProductInventoryStopPermissions(ctx.user)
const canImport = admissionScope === '否'
@@ -43,32 +64,111 @@ export async function POST(request: NextRequest) {
const parsed = await productStopDetailXlsxService.parseImageImport(
Buffer.from(await file.arrayBuffer()),
)
- const uploadedKeys: string[] = []
- const embeddedUrls = new Map()
- try {
- for (const image of parsed.embeddedImages) {
- const uploaded = await uploadBufferToObjectStorageWithMetadata(
- image.buffer,
- `product-stop-detail/import-images/${randomUUID()}-${image.rowNumber}.${image.extension}`,
- image.contentType,
+ const barcodeByRow = new Map(parsed.rows.map((row) => [
+ row.rowNumber,
+ row.barcode.trim().toUpperCase(),
+ ]))
+ const latestAdmissions = await productStopImageImportService
+ .findLatestAdmissionByBarcodes(parsed.rows.map((row) => row.barcode))
+ const uploadableImages = parsed.embeddedImages.filter((image) => (
+ latestAdmissions.get(barcodeByRow.get(image.rowNumber) ?? '') === admissionScope
+ ))
+
+ const encoder = new TextEncoder()
+ const stream = new ReadableStream({
+ start(controller) {
+ let closed = false
+ let progress = createProductStopImageImportProgress(
+ parsed.rows.length,
+ uploadableImages.length,
)
- uploadedKeys.push(uploaded.storageKey)
- embeddedUrls.set(image.rowNumber, uploaded.url)
- }
- const rows = parsed.rows.map((row) => ({
- barcode: row.barcode,
- imageUrl: embeddedUrls.get(row.rowNumber) ?? row.imageUrl,
- }))
- const result = await productStopDetailService.importImages(rows, ctx.user)
- return jsonSuccess(result, 200, ctx.requestId)
- } catch (error) {
- if (uploadedKeys.length > 0) {
- await cleanupUploadedImages(uploadedKeys, ctx.requestId)
- }
- if (error instanceof Error && /storage|object storage|upload/i.test(error.message)) {
- return jsonError(ErrorCode.SYSTEM_STORAGE, '导入图片上传失败,请稍后重试', 500, ctx.requestId)
- }
- throw error
- }
+ const uploadedImages: Array<{ storageKey: string; rowNumber: number }> = []
+ const send = (event: ProductStopImageImportStreamEvent) => {
+ if (closed) return
+ try {
+ controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`))
+ } catch {
+ closed = true
+ }
+ }
+ const close = () => {
+ if (closed) return
+ closed = true
+ controller.close()
+ }
+
+ send({ type: 'progress', progress })
+ void (async () => {
+ try {
+ const embeddedUrls = new Map()
+ for (const image of uploadableImages) {
+ const uploaded = await uploadBufferToObjectStorageWithMetadata(
+ image.buffer,
+ `product-stop-detail/import-images/${randomUUID()}-${image.rowNumber}.${image.extension}`,
+ image.contentType,
+ )
+ uploadedImages.push({
+ storageKey: uploaded.storageKey,
+ rowNumber: image.rowNumber,
+ })
+ embeddedUrls.set(image.rowNumber, uploaded.url)
+ progress = { ...progress, uploaded: progress.uploaded + 1 }
+ send({ type: 'progress', progress })
+ }
+ progress = { ...progress, phase: 'importing' }
+ send({ type: 'progress', progress })
+
+ const result = await productStopImageImportService.importRows({
+ rows: parsed.rows.map((row) => ({
+ rowNumber: row.rowNumber,
+ barcode: row.barcode,
+ imageUrl: embeddedUrls.get(row.rowNumber) ?? row.imageUrl,
+ })),
+ user: ctx.user,
+ admissionScope,
+ initialProgress: progress,
+ onProgress: (next, row) => {
+ progress = next
+ send({ type: 'progress', progress, row })
+ },
+ })
+ const succeededRows = new Set(
+ result.results
+ .filter((row) => row.status === 'succeeded')
+ .map((row) => row.rowNumber),
+ )
+ await cleanupUploadedImages(
+ uploadedImages
+ .filter((image) => !succeededRows.has(image.rowNumber))
+ .map((image) => image.storageKey),
+ ctx.requestId,
+ )
+ send({ type: 'complete', progress: result.progress })
+ close()
+ } catch (error) {
+ await cleanupUploadedImages(
+ uploadedImages.map((image) => image.storageKey),
+ ctx.requestId,
+ )
+ console.error(`[${ctx.requestId}] Product stop image import failed:`, error)
+ send({
+ type: 'error',
+ progress,
+ message: importErrorMessage(error),
+ })
+ close()
+ }
+ })()
+ },
+ })
+
+ return new NextResponse(stream, {
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/x-ndjson; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ 'X-Accel-Buffering': 'no',
+ },
+ })
}, { requireAuth: true })
}
diff --git a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailImportDialog.tsx b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailImportDialog.tsx
index 0456f84b..e47ee8ad 100644
--- a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailImportDialog.tsx
+++ b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailImportDialog.tsx
@@ -3,7 +3,12 @@
import { useEffect, useRef, useState, type FormEvent } from 'react'
import { createPortal } from 'react-dom'
import { Download, FileSpreadsheet, Upload, X } from 'lucide-react'
+import type {
+ ProductStopImageImportProgress,
+ ProductStopImageImportRowResult,
+} from '@/lib/product-stop-image-import'
import workbench from './logic-config/product-stop-logic-config.module.css'
+import { ProductStopImageImportResult } from './ProductStopImageImportResult'
import { useIsClient } from './useIsClient'
function fileSizeText(size: number) {
@@ -19,12 +24,21 @@ export function ProductStopDetailImportDialog({
}: {
onClose: () => void
onDownloadTemplate: () => void
- onImport: (file: File) => Promise
+ onImport: (
+ file: File,
+ handlers: {
+ onProgress: (progress: ProductStopImageImportProgress) => void
+ onRow: (row: ProductStopImageImportRowResult) => void
+ },
+ ) => Promise
}) {
const mounted = useIsClient()
const [file, setFile] = useState(null)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
+ const [progress, setProgress] = useState(null)
+ const [rows, setRows] = useState([])
+ const [completed, setCompleted] = useState(false)
const inputRef = useRef(null)
useEffect(() => {
@@ -43,9 +57,16 @@ export function ProductStopDetailImportDialog({
}
setError('')
setBusy(true)
+ setProgress(null)
+ setRows([])
+ setCompleted(false)
try {
- await onImport(file)
- onClose()
+ const result = await onImport(file, {
+ onProgress: setProgress,
+ onRow: (row) => setRows((current) => [...current, row]),
+ })
+ setProgress(result)
+ setCompleted(true)
} catch (submitError) {
setError(submitError instanceof Error ? submitError.message : '导入失败,请检查文件内容')
} finally {
@@ -112,16 +133,25 @@ export function ProductStopDetailImportDialog({
导入后会更新图片维护记录和最新快照中的图片;重复条码以最后一行为准。
嵌入 Excel 的图片会自动上传到对象存储后保存链接;链接方式则直接使用填写的地址。
+ {progress ? : null}
{error ? {error}
: null}
,
diff --git a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailView.tsx b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailView.tsx
index 13e90380..e753515b 100644
--- a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailView.tsx
+++ b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopDetailView.tsx
@@ -46,6 +46,10 @@ import {
type ProductStopDetailTextFilter,
} from '@/lib/product-stop-detail'
import type { ProductStopDetailPermissions } from '@/lib/supply-chain-permission-settings'
+import type {
+ ProductStopImageImportProgress,
+ ProductStopImageImportRowResult,
+} from '@/lib/product-stop-image-import'
import workbench from './logic-config/product-stop-logic-config.module.css'
import {
ProductStopBatchSearchDialog,
@@ -61,6 +65,7 @@ import { ProductStopQuickFilters } from './ProductStopQuickFilters'
import { ProductStopDetailSettingsDialog } from './ProductStopDetailSettingsDialog'
import { ProductStopChangeHistoryDialog } from './ProductStopChangeHistoryDialog'
import { ProductStopShopDetailTable } from './ProductStopShopDetailTable'
+import { importProductStopImages } from './product-stop-image-import-stream'
import {
PRODUCT_STOP_DETAIL_SETTINGS_STORAGE_KEY,
defaultProductStopDetailSettings,
@@ -404,16 +409,27 @@ export function ProductStopDetailView({
}
}
- async function importImages(file: File) {
- const form = new FormData()
- form.append('file', file)
- form.append('admissionScope', admissionScope)
- const data = await requestJson<{ imported: number }>(`${API_BASE}/images/import`, {
- method: 'POST',
- body: form,
+ async function importImages(
+ file: File,
+ handlers: {
+ onProgress: (progress: ProductStopImageImportProgress) => void
+ onRow: (row: ProductStopImageImportRowResult) => void
+ },
+ ) {
+ const progress = await importProductStopImages({
+ file,
+ admissionScope,
+ onEvent: (event) => {
+ handlers.onProgress(event.progress)
+ if (event.type !== 'error' && event.row) handlers.onRow(event.row)
+ },
})
await fetchPage({ page, pageSize, filters: appliedFilters, sort })
- setNotice({ type: 'success', text: `已维护 ${data.imported} 条盘停明细图片` })
+ setNotice({
+ type: progress.failed ? 'error' : 'success',
+ text: `图片导入完成:成功 ${progress.succeeded} 条,失败 ${progress.failed} 条,跳过 ${progress.skipped} 条`,
+ })
+ return progress
}
async function exportDetail(
diff --git a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopImageImportResult.tsx b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopImageImportResult.tsx
new file mode 100644
index 00000000..7109f4d2
--- /dev/null
+++ b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/ProductStopImageImportResult.tsx
@@ -0,0 +1,100 @@
+'use client'
+
+import { useState } from 'react'
+import type {
+ ProductStopImageImportProgress,
+ ProductStopImageImportRowResult,
+} from '@/lib/product-stop-image-import'
+import styles from './product-stop-image-import.module.css'
+
+const STATUS_LABELS: Record = {
+ succeeded: '成功',
+ failed: '失败',
+ skipped: '跳过',
+}
+
+export function ProductStopImageImportResult({
+ progress,
+ rows,
+}: {
+ progress: ProductStopImageImportProgress
+ rows: readonly ProductStopImageImportRowResult[]
+}) {
+ const [issuesOnly, setIssuesOnly] = useState(false)
+ const uploading = progress.phase === 'uploading'
+ const completedCount = uploading ? progress.uploaded : progress.processed
+ const total = uploading ? progress.uploadTotal : progress.total
+ const percent = total ? Math.min(100, Math.round(completedCount / total * 100)) : 0
+ const visibleRows = issuesOnly
+ ? rows.filter((row) => row.status !== 'succeeded')
+ : rows
+
+ return (
+ <>
+
+
+
处理进度{progress.processed}/{progress.total}
+
成功{progress.succeeded}
+
失败{progress.failed}
+
跳过{progress.skipped}
+
+
+
+ {uploading ? '正在上传嵌入图片' : progress.phase === 'complete' ? '导入完成' : '正在逐行校验并保存'}
+ {percent}%
+
+
+
+
+ {rows.length ? (
+
+
+ 逐行结果({rows.length} 条)
+
+
+
+
+
+
+ | Excel 行 |
+ 条码 |
+ 结果 |
+ 说明 |
+
+
+
+ {visibleRows.map((row, index) => (
+
+ | {row.rowNumber || '-'} |
+ {row.barcode || '-'} |
+ {STATUS_LABELS[row.status]} |
+ {row.message} |
+
+ ))}
+
+
+ {!visibleRows.length ? (
+
没有失败或跳过记录
+ ) : null}
+
+
+ ) : null}
+ >
+ )
+}
diff --git a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.test.ts b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.test.ts
new file mode 100644
index 00000000..80840a3e
--- /dev/null
+++ b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.test.ts
@@ -0,0 +1,105 @@
+import { ReadableStream as NodeReadableStream } from 'node:stream/web'
+import { importProductStopImages } from './product-stop-image-import-stream'
+
+const originalReadableStream = global.ReadableStream
+const originalFetch = global.fetch
+
+beforeAll(() => {
+ Object.defineProperty(global, 'ReadableStream', {
+ configurable: true,
+ value: NodeReadableStream,
+ })
+})
+
+afterAll(() => {
+ Object.defineProperty(global, 'ReadableStream', {
+ configurable: true,
+ value: originalReadableStream,
+ })
+ global.fetch = originalFetch
+})
+
+describe('商品盘停图片导入流', () => {
+ it('reports upload progress, row results and completion', async () => {
+ const encoder = new TextEncoder()
+ const events = [
+ {
+ type: 'progress',
+ progress: {
+ phase: 'uploading', processed: 0, total: 2, succeeded: 0,
+ failed: 0, skipped: 0, uploaded: 0, uploadTotal: 1,
+ },
+ },
+ {
+ type: 'progress',
+ progress: {
+ phase: 'importing', processed: 1, total: 2, succeeded: 1,
+ failed: 0, skipped: 0, uploaded: 1, uploadTotal: 1,
+ },
+ row: {
+ rowNumber: 2, barcode: 'A1', status: 'succeeded', message: '图片已保存',
+ },
+ },
+ {
+ type: 'complete',
+ progress: {
+ phase: 'complete', processed: 2, total: 2, succeeded: 1,
+ failed: 1, skipped: 0, uploaded: 1, uploadTotal: 1,
+ },
+ },
+ ]
+ global.fetch = jest.fn(async () => ({
+ ok: true,
+ status: 200,
+ body: new NodeReadableStream({
+ start(controller) {
+ controller.enqueue(encoder.encode(events.map((event) => `${JSON.stringify(event)}\n`).join('')))
+ controller.close()
+ },
+ }),
+ json: async () => null,
+ }) as unknown as Response) as jest.Mock
+
+ const received: string[] = []
+ const result = await importProductStopImages({
+ file: new File(['xlsx'], 'images.xlsx'),
+ admissionScope: '是',
+ onEvent: (event) => {
+ received.push(event.type === 'progress' && event.row
+ ? `${event.type}:${event.row.status}`
+ : event.type)
+ },
+ })
+
+ expect(received).toEqual(['progress', 'progress:succeeded', 'complete'])
+ expect(result).toMatchObject({ phase: 'complete', succeeded: 1, failed: 1 })
+ })
+
+ it('surfaces a server-side stream error', async () => {
+ const encoder = new TextEncoder()
+ global.fetch = jest.fn(async () => ({
+ ok: true,
+ status: 200,
+ body: new NodeReadableStream({
+ start(controller) {
+ controller.enqueue(encoder.encode(`${JSON.stringify({
+ type: 'error',
+ progress: {
+ phase: 'uploading', processed: 0, total: 2, succeeded: 0,
+ failed: 0, skipped: 0, uploaded: 0, uploadTotal: 1,
+ },
+ message: '导入图片上传失败,请稍后重试',
+ })}\n`))
+ controller.close()
+ },
+ }),
+ json: async () => null,
+ }) as unknown as Response) as jest.Mock
+
+ await expect(importProductStopImages({
+ file: new File(['xlsx'], 'images.xlsx'),
+ admissionScope: '是',
+ onEvent: () => undefined,
+ })).rejects.toThrow('导入图片上传失败')
+ })
+})
diff --git a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.ts b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.ts
new file mode 100644
index 00000000..9c79103f
--- /dev/null
+++ b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import-stream.ts
@@ -0,0 +1,112 @@
+import type {
+ ProductStopAdmissionScope,
+ ProductStopImageImportProgress,
+ ProductStopImageImportRowResult,
+ ProductStopImageImportStreamEvent,
+} from '@/lib/product-stop-image-import'
+
+function parseProgress(value: unknown): ProductStopImageImportProgress {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error('图片导入进度响应格式不正确')
+ }
+ const progress = value as Record
+ const numericKeys = [
+ 'processed',
+ 'total',
+ 'succeeded',
+ 'failed',
+ 'skipped',
+ 'uploaded',
+ 'uploadTotal',
+ ]
+ if (
+ !['uploading', 'importing', 'complete'].includes(String(progress.phase))
+ || !numericKeys.every((key) => (
+ typeof progress[key] === 'number'
+ && Number.isFinite(progress[key])
+ && Number(progress[key]) >= 0
+ ))
+ ) {
+ throw new Error('图片导入进度响应格式不正确')
+ }
+ return progress as ProductStopImageImportProgress
+}
+
+function parseRow(value: unknown): ProductStopImageImportRowResult | undefined {
+ if (value === undefined) return undefined
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error('图片导入逐行结果格式不正确')
+ }
+ const row = value as Record
+ if (
+ typeof row.rowNumber !== 'number'
+ || typeof row.barcode !== 'string'
+ || !['succeeded', 'failed', 'skipped'].includes(String(row.status))
+ || typeof row.message !== 'string'
+ ) {
+ throw new Error('图片导入逐行结果格式不正确')
+ }
+ return row as ProductStopImageImportRowResult
+}
+
+function parseEvent(line: string): ProductStopImageImportStreamEvent {
+ const value = JSON.parse(line) as Record
+ const progress = parseProgress(value.progress)
+ if (value.type === 'progress' || value.type === 'complete') {
+ return {
+ type: value.type,
+ progress,
+ row: parseRow(value.row),
+ }
+ }
+ if (value.type === 'error' && typeof value.message === 'string') {
+ return { type: 'error', progress, message: value.message }
+ }
+ throw new Error('图片导入进度响应格式不正确')
+}
+
+export async function importProductStopImages(input: {
+ file: File
+ admissionScope: ProductStopAdmissionScope
+ onEvent: (event: ProductStopImageImportStreamEvent) => void
+}): Promise {
+ const form = new FormData()
+ form.append('file', input.file)
+ form.append('admissionScope', input.admissionScope)
+ const response = await fetch('/api/supply-chain/management/product-inventory-stop/images/import', {
+ method: 'POST',
+ body: form,
+ credentials: 'same-origin',
+ })
+ if (!response.ok) {
+ const payload = await response.json().catch(() => null) as {
+ error?: { message?: string }
+ } | null
+ throw new Error(payload?.error?.message || `请求失败(${response.status})`)
+ }
+ if (!response.body) throw new Error('浏览器无法读取图片导入进度')
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let buffer = ''
+ let completed: ProductStopImageImportProgress | null = null
+ const consume = (line: string) => {
+ if (!line.trim()) return
+ const event = parseEvent(line)
+ input.onEvent(event)
+ if (event.type === 'complete') completed = event.progress
+ if (event.type === 'error') throw new Error(event.message)
+ }
+
+ while (true) {
+ const { done, value } = await reader.read()
+ buffer += decoder.decode(value, { stream: !done })
+ const lines = buffer.split('\n')
+ buffer = lines.pop() ?? ''
+ lines.forEach(consume)
+ if (done) break
+ }
+ consume(buffer)
+ if (!completed) throw new Error('导入连接提前结束,请重新导入并检查逐行结果')
+ return completed
+}
diff --git a/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import.module.css b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import.module.css
new file mode 100644
index 00000000..d314adef
--- /dev/null
+++ b/furniture-3d-system/src/app/supply-chain/management/product-inventory-stop/product-stop-image-import.module.css
@@ -0,0 +1,137 @@
+.summary {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.liveRegion {
+ display: grid;
+ gap: 12px;
+}
+
+.summaryCard {
+ border: 1px solid #e2e8e6;
+ border-radius: 8px;
+ background: #f8faf9;
+ padding: 10px 12px;
+}
+
+.summaryCard span {
+ display: block;
+ color: #7a8986;
+ font-size: 10px;
+ font-weight: 700;
+}
+
+.summaryCard strong {
+ display: block;
+ margin-top: 4px;
+ color: #273d39;
+ font-size: 18px;
+ font-weight: 900;
+}
+
+.progressBlock {
+ display: grid;
+ gap: 7px;
+}
+
+.progressMeta {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ color: #647572;
+ font-size: 11px;
+ font-weight: 700;
+}
+
+.progressTrack {
+ height: 8px;
+ overflow: hidden;
+ border-radius: 999px;
+ background: #e8eeec;
+}
+
+.progressBar {
+ height: 100%;
+ border-radius: inherit;
+ background: #3f756a;
+ transition: width 180ms ease;
+}
+
+.resultSection {
+ display: grid;
+ gap: 8px;
+}
+
+.resultHeader {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.resultHeader strong {
+ color: #314944;
+ font-size: 12px;
+}
+
+.resultHeader label {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ color: #6e7f7b;
+ font-size: 10px;
+ font-weight: 700;
+}
+
+.resultTableWrap {
+ max-height: 230px;
+ overflow: auto;
+ border: 1px solid #e2e8e6;
+ border-radius: 8px;
+}
+
+.resultTable {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 11px;
+}
+
+.resultTable th,
+.resultTable td {
+ border-bottom: 1px solid #edf1ef;
+ padding: 7px 9px;
+ text-align: left;
+ vertical-align: top;
+}
+
+.resultTable th {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ background: #f5f8f7;
+ color: #657572;
+ font-weight: 800;
+}
+
+.succeeded {
+ color: #25705d;
+ font-weight: 800;
+}
+
+.failed {
+ color: #b42318;
+ font-weight: 800;
+}
+
+.skipped {
+ color: #9a6700;
+ font-weight: 800;
+}
+
+@media (max-width: 720px) {
+ .summary {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
diff --git a/furniture-3d-system/src/lib/product-stop-image-import.ts b/furniture-3d-system/src/lib/product-stop-image-import.ts
new file mode 100644
index 00000000..299b3e3d
--- /dev/null
+++ b/furniture-3d-system/src/lib/product-stop-image-import.ts
@@ -0,0 +1,86 @@
+export type ProductStopAdmissionScope = '是' | '否'
+
+export type ProductStopImageImportRowInput = {
+ rowNumber: number
+ barcode: string
+ imageUrl: string
+}
+
+export type ProductStopImageImportRowStatus = 'succeeded' | 'failed' | 'skipped'
+
+export type ProductStopImageImportRowResult = {
+ rowNumber: number
+ barcode: string
+ status: ProductStopImageImportRowStatus
+ message: string
+}
+
+export type ProductStopImageImportProgress = {
+ phase: 'uploading' | 'importing' | 'complete'
+ processed: number
+ total: number
+ succeeded: number
+ failed: number
+ skipped: number
+ uploaded: number
+ uploadTotal: number
+}
+
+export type ProductStopImageImportStreamEvent =
+ | {
+ type: 'progress' | 'complete'
+ progress: ProductStopImageImportProgress
+ row?: ProductStopImageImportRowResult
+ }
+ | {
+ type: 'error'
+ progress: ProductStopImageImportProgress
+ message: string
+ }
+
+export function parseProductStopAdmissionScope(value: unknown): ProductStopAdmissionScope | null {
+ const normalized = String(value ?? '').trim()
+ return normalized === '是' || normalized === '否' ? normalized : null
+}
+
+export function createProductStopImageImportProgress(
+ total: number,
+ uploadTotal: number,
+ phase: ProductStopImageImportProgress['phase'] = 'uploading',
+): ProductStopImageImportProgress {
+ return {
+ phase,
+ processed: 0,
+ total,
+ succeeded: 0,
+ failed: 0,
+ skipped: 0,
+ uploaded: 0,
+ uploadTotal,
+ }
+}
+
+export function applyProductStopImageImportRowResult(
+ progress: ProductStopImageImportProgress,
+ row: ProductStopImageImportRowResult,
+): ProductStopImageImportProgress {
+ const counted = progress.processed < progress.total
+ return {
+ ...progress,
+ phase: 'importing',
+ processed: counted ? progress.processed + 1 : progress.processed,
+ succeeded: progress.succeeded + Number(row.status === 'succeeded'),
+ failed: progress.failed + Number(row.status === 'failed'),
+ skipped: progress.skipped + Number(row.status === 'skipped'),
+ }
+}
+
+export function completeProductStopImageImportProgress(
+ progress: ProductStopImageImportProgress,
+): ProductStopImageImportProgress {
+ return {
+ ...progress,
+ phase: 'complete',
+ processed: progress.total,
+ }
+}
diff --git a/furniture-3d-system/src/lib/selection-market/mysql.ts b/furniture-3d-system/src/lib/selection-market/mysql.ts
index 96a5a3e3..ec929ae6 100644
--- a/furniture-3d-system/src/lib/selection-market/mysql.ts
+++ b/furniture-3d-system/src/lib/selection-market/mysql.ts
@@ -11,7 +11,7 @@
* - 交付包路由使用命名占位符(:period / :cat),需开 namedPlaceholders。
* - 远程慢库(单查 2~7s、聚合更久):连接数收紧为 3,单查询超时 60s。
*/
-import { createPool, type Pool, type QueryValues } from 'mysql2/promise';
+import { createPool, type Pool } from 'mysql2/promise';
type GlobalMysql = typeof globalThis & { __selectionMarketMysqlPoolV2?: Pool };
const globalForMysql = globalThis as GlobalMysql;
@@ -72,7 +72,7 @@ export async function mysqlQuery(
const pool = getPool();
const [rows] = await pool.query(
{ sql: sqlText, timeout: timeoutMs },
- params as QueryValues,
+ params,
);
return rows as T[];
}
diff --git a/furniture-3d-system/src/lib/supply-chain-page-permissions.test.ts b/furniture-3d-system/src/lib/supply-chain-page-permissions.test.ts
index 33eaa2d9..926490de 100644
--- a/furniture-3d-system/src/lib/supply-chain-page-permissions.test.ts
+++ b/furniture-3d-system/src/lib/supply-chain-page-permissions.test.ts
@@ -14,8 +14,8 @@ describe('independent supply-chain page permissions', () => {
])
it('gives every menu page its own target, route mapping and permission row', () => {
- // 菜单页数量随功能迭代增长(新增「外销销量」「应发未发」「各平台账单」后为 35)
- expect(pages).toHaveLength(35)
+ // 菜单页数量随功能迭代增长(新增「外销销量」「应发未发」「各平台账单」后为 36)
+ expect(pages).toHaveLength(36)
expect(new Set(pages.map((page) => page.targetKey)).size).toBe(pages.length)
const matrixRows = PERMISSION_MATRIX_SECTIONS.find((section) => section.id === 'supply')!.groups.flatMap((group) => group.rows)
for (const page of pages) {
diff --git a/furniture-3d-system/src/lib/supply-chain-product-stop-permissions.ts b/furniture-3d-system/src/lib/supply-chain-product-stop-permissions.ts
index 183d56f3..cd5139c3 100644
--- a/furniture-3d-system/src/lib/supply-chain-product-stop-permissions.ts
+++ b/furniture-3d-system/src/lib/supply-chain-product-stop-permissions.ts
@@ -163,3 +163,113 @@ export const PRODUCT_STOP_PERMISSION_TARGET_KEYS =
...group.items.map((item) => item.targetKey),
]),
]))
+
+const PRODUCT_STOP_PERMISSION_TARGET_KEY_SET = new Set(
+ PRODUCT_STOP_PERMISSION_TARGET_KEYS,
+)
+
+type PermissionAccess = {
+ view: boolean
+ download: boolean
+ edit: boolean
+}
+
+function detailPermissions(access: PermissionAccess): ProductStopDetailPermissions {
+ return {
+ main: {
+ view: access.view,
+ query: access.view,
+ reset: access.view,
+ refresh: access.view,
+ changeHistory: access.view,
+ generate: access.edit,
+ import: access.edit,
+ settings: access.edit,
+ manualPush: access.edit,
+ export: access.download,
+ },
+ attachment: {
+ view: access.view,
+ query: access.view,
+ reset: access.view,
+ },
+ }
+}
+
+function tablePermissions(
+ access: PermissionAccess,
+ options: { observationDays?: boolean } = {},
+): ProductStopTablePermissions {
+ return {
+ view: access.view,
+ query: access.view,
+ reset: access.view,
+ create: access.edit,
+ edit: access.edit,
+ delete: access.edit,
+ bulkEdit: access.edit,
+ import: access.edit,
+ export: access.download,
+ ...(options.observationDays === undefined
+ ? {}
+ : { observationDays: options.observationDays && access.edit }),
+ }
+}
+
+/**
+ * 将供应链统一默认权限转换为商品盘停的细粒度权限。
+ * 管理员得到全量权限,主管得到只读权限;普通账号仍由配置表逐项控制。
+ */
+export function buildProductInventoryStopPermissionsFromAccess(
+ access: PermissionAccess,
+): ProductInventoryStopPermissions {
+ return {
+ detail: detailPermissions(access),
+ unadmitted: detailPermissions(access),
+ logicConfig: tablePermissions(access, { observationDays: true }),
+ warehouseMapping: tablePermissions(access),
+ }
+}
+
+export function emptyProductInventoryStopPermissions(): ProductInventoryStopPermissions {
+ return buildProductInventoryStopPermissionsFromAccess({
+ view: false,
+ download: false,
+ edit: false,
+ })
+}
+
+export function isProductStopPermissionTarget(
+ targetKey: SupplyChainPermissionTargetKey,
+) {
+ return targetKey !== 'productInventoryStop'
+ && PRODUCT_STOP_PERMISSION_TARGET_KEY_SET.has(targetKey)
+}
+
+export function summarizeProductInventoryStopPermissions(
+ permissions: ProductInventoryStopPermissions,
+): PermissionAccess {
+ const tables = [permissions.logicConfig, permissions.warehouseMapping]
+ return {
+ view: permissions.detail.main.view
+ || permissions.detail.attachment.view
+ || permissions.unadmitted.main.view
+ || permissions.unadmitted.attachment.view
+ || tables.some((table) => table.view),
+ download: permissions.detail.main.export
+ || permissions.unadmitted.main.export
+ || tables.some((table) => table.export),
+ edit: permissions.detail.main.generate
+ || permissions.detail.main.import
+ || permissions.detail.main.settings
+ || permissions.detail.main.manualPush
+ || permissions.unadmitted.main.generate
+ || permissions.unadmitted.main.import
+ || permissions.unadmitted.main.settings
+ || permissions.unadmitted.main.manualPush
+ || tables.some((table) => (
+ table.create || table.edit || table.delete || table.bulkEdit
+ || table.import || table.observationDays
+ )),
+ }
+}
diff --git a/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts b/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts
index 1d6243e7..1f9acf70 100644
--- a/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts
+++ b/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts
@@ -265,6 +265,37 @@ class ProductStopDetailRepository {
return run?.snapshotDate ?? null
}
+ async findLatestAdmissionByBarcodes(
+ barcodes: readonly string[],
+ ): Promise