fix(product-stop): 修复部署鉴权并增强图片导入
This commit is contained in:
parent
23e2f54a3a
commit
fb83fc3daf
86
furniture-3d-system/docs/使用说明/商品盘停管理-初始化与定时任务.md
Normal file
86
furniture-3d-system/docs/使用说明/商品盘停管理-初始化与定时任务.md
Normal file
@ -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。
|
||||
@ -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",
|
||||
|
||||
118
furniture-3d-system/scripts/init-product-stop.ts
Normal file
118
furniture-3d-system/scripts/init-product-stop.ts
Normal file
@ -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
|
||||
})
|
||||
@ -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
|
||||
|
||||
@ -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"
|
||||
|
||||
@ -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<string, unknown>([['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<string, unknown>([
|
||||
['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()
|
||||
})
|
||||
})
|
||||
@ -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<number, string>()
|
||||
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<Uint8Array>({
|
||||
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<number, string>()
|
||||
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 })
|
||||
}
|
||||
|
||||
@ -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<void>
|
||||
onImport: (
|
||||
file: File,
|
||||
handlers: {
|
||||
onProgress: (progress: ProductStopImageImportProgress) => void
|
||||
onRow: (row: ProductStopImageImportRowResult) => void
|
||||
},
|
||||
) => Promise<ProductStopImageImportProgress>
|
||||
}) {
|
||||
const mounted = useIsClient()
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [progress, setProgress] = useState<ProductStopImageImportProgress | null>(null)
|
||||
const [rows, setRows] = useState<ProductStopImageImportRowResult[]>([])
|
||||
const [completed, setCompleted] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(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 的图片会自动上传到对象存储后保存链接;链接方式则直接使用填写的地址。
|
||||
</p>
|
||||
{progress ? <ProductStopImageImportResult progress={progress} rows={rows} /> : null}
|
||||
{error ? <div className={workbench.formError}>{error}</div> : null}
|
||||
</div>
|
||||
<footer className={workbench.modalFooter}>
|
||||
<button type="button" className={workbench.secondaryButton} disabled={busy} onClick={onClose}>
|
||||
取消
|
||||
</button>
|
||||
<button type="submit" className={workbench.primaryButton} disabled={busy || !file}>
|
||||
<Upload size={14} />
|
||||
{busy ? '导入中…' : '确定导入'}
|
||||
</button>
|
||||
{completed ? (
|
||||
<button type="button" className={workbench.primaryButton} onClick={onClose}>
|
||||
关闭
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button type="button" className={workbench.secondaryButton} disabled={busy} onClick={onClose}>
|
||||
取消
|
||||
</button>
|
||||
<button type="submit" className={workbench.primaryButton} disabled={busy || !file}>
|
||||
<Upload size={14} />
|
||||
{busy ? '导入中…' : '确定导入'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</footer>
|
||||
</form>
|
||||
</div>,
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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<ProductStopImageImportRowResult['status'], string> = {
|
||||
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 (
|
||||
<>
|
||||
<div className={styles.liveRegion} aria-live="polite">
|
||||
<div className={styles.summary}>
|
||||
<div className={styles.summaryCard}><span>处理进度</span><strong>{progress.processed}/{progress.total}</strong></div>
|
||||
<div className={styles.summaryCard}><span>成功</span><strong>{progress.succeeded}</strong></div>
|
||||
<div className={styles.summaryCard}><span>失败</span><strong>{progress.failed}</strong></div>
|
||||
<div className={styles.summaryCard}><span>跳过</span><strong>{progress.skipped}</strong></div>
|
||||
</div>
|
||||
<div className={styles.progressBlock}>
|
||||
<div className={styles.progressMeta}>
|
||||
<span>{uploading ? '正在上传嵌入图片' : progress.phase === 'complete' ? '导入完成' : '正在逐行校验并保存'}</span>
|
||||
<span>{percent}%</span>
|
||||
</div>
|
||||
<div
|
||||
className={styles.progressTrack}
|
||||
role="progressbar"
|
||||
aria-label="图片导入进度"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={percent}
|
||||
>
|
||||
<div className={styles.progressBar} style={{ width: `${percent}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{rows.length ? (
|
||||
<div className={styles.resultSection}>
|
||||
<div className={styles.resultHeader}>
|
||||
<strong>逐行结果({rows.length} 条)</strong>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={issuesOnly}
|
||||
onChange={(event) => setIssuesOnly(event.target.checked)}
|
||||
/>
|
||||
仅看失败/跳过
|
||||
</label>
|
||||
</div>
|
||||
<div className={styles.resultTableWrap}>
|
||||
<table className={styles.resultTable}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Excel 行</th>
|
||||
<th>条码</th>
|
||||
<th>结果</th>
|
||||
<th>说明</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visibleRows.map((row, index) => (
|
||||
<tr key={`${row.rowNumber}:${row.barcode}:${index}`}>
|
||||
<td>{row.rowNumber || '-'}</td>
|
||||
<td>{row.barcode || '-'}</td>
|
||||
<td className={styles[row.status]}>{STATUS_LABELS[row.status]}</td>
|
||||
<td>{row.message}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!visibleRows.length ? (
|
||||
<p className="px-3 py-6 text-center text-[11px] text-[#7d8b89]">没有失败或跳过记录</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@ -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('导入图片上传失败')
|
||||
})
|
||||
})
|
||||
@ -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<string, unknown>
|
||||
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<string, unknown>
|
||||
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<string, unknown>
|
||||
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<ProductStopImageImportProgress> {
|
||||
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
|
||||
}
|
||||
@ -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));
|
||||
}
|
||||
}
|
||||
86
furniture-3d-system/src/lib/product-stop-image-import.ts
Normal file
86
furniture-3d-system/src/lib/product-stop-image-import.ts
Normal file
@ -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,
|
||||
}
|
||||
}
|
||||
@ -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<T = unknown>(
|
||||
const pool = getPool();
|
||||
const [rows] = await pool.query(
|
||||
{ sql: sqlText, timeout: timeoutMs },
|
||||
params as QueryValues,
|
||||
params,
|
||||
);
|
||||
return rows as T[];
|
||||
}
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@ -265,6 +265,37 @@ class ProductStopDetailRepository {
|
||||
return run?.snapshotDate ?? null
|
||||
}
|
||||
|
||||
async findLatestAdmissionByBarcodes(
|
||||
barcodes: readonly string[],
|
||||
): Promise<Map<string, string>> {
|
||||
const targets = [...new Set(
|
||||
barcodes.map((barcode) => barcode.trim().toUpperCase()).filter(Boolean),
|
||||
)]
|
||||
const result = new Map<string, string>()
|
||||
for (let index = 0; index < targets.length; index += 1000) {
|
||||
const chunk = targets.slice(index, index + 1000)
|
||||
if (!chunk.length) continue
|
||||
const rows = await prisma.$queryRaw<Array<{
|
||||
barcode: string | null
|
||||
admission: string | null
|
||||
}>>(Prisma.sql`
|
||||
SELECT DISTINCT ON (UPPER(BTRIM("barcode")))
|
||||
"barcode",
|
||||
"admission"
|
||||
FROM "ProductStopDetailSnapshot"
|
||||
WHERE UPPER(BTRIM("barcode")) = ANY(${chunk}::text[])
|
||||
ORDER BY UPPER(BTRIM("barcode")),
|
||||
"snapshotDate" DESC,
|
||||
"generatedAt" DESC
|
||||
`)
|
||||
rows.forEach((row) => {
|
||||
const barcode = String(row.barcode ?? '').trim().toUpperCase()
|
||||
if (barcode) result.set(barcode, String(row.admission ?? '').trim())
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async findLatestSnapshotByBarcode(
|
||||
barcode: string,
|
||||
): Promise<ProductStopDetailSnapshotRecord | null> {
|
||||
|
||||
@ -233,7 +233,9 @@ class ProductStopDetailXlsxService {
|
||||
styleHeader(guide.getRow(1))
|
||||
guide.addRow(['条码', '必填;按条码覆盖盘停明细图片,生成时人工图片优先于产品档案。'])
|
||||
guide.addRow(['图片', '可填写 http(s) 图片链接,也可直接把图片粘贴/插入 Excel 单元格;嵌入图片会先上传对象存储再保存链接。'])
|
||||
guide.addRow(['准入范围', '条码必须属于当前“盘停明细”或“未准入盘停明细”范围;跨范围条码会被拒绝,不会修改图片。'])
|
||||
guide.addRow(['支持格式', '仅支持 .xlsx;单次最多 5000 行;重复条码以最后一行为准。'])
|
||||
guide.addRow(['导入结果', '导入过程中显示实时进度、成功/失败/跳过统计,并按 Excel 行号反馈具体错误。'])
|
||||
guide.addRow(['导入后', '会更新图片维护记录及最新快照中的图片;下次重新生成仍保留人工图片。'])
|
||||
const buffer = await workbook.xlsx.writeBuffer()
|
||||
return {
|
||||
|
||||
@ -266,41 +266,6 @@ class ProductStopDetailService {
|
||||
user: user ? { id: user.id, name: user.name } : null,
|
||||
})
|
||||
}
|
||||
|
||||
async importImages(
|
||||
rows: Array<{ barcode: unknown; imageUrl: unknown }>,
|
||||
user: AuthUser,
|
||||
): Promise<{ imported: number }> {
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '导入文件没有可用的图片维护数据')
|
||||
}
|
||||
if (rows.length > 5000) {
|
||||
throw new AppError(ErrorCode.VALIDATION_OUT_OF_RANGE, '单次最多导入 5000 条图片维护数据')
|
||||
}
|
||||
const normalized = rows.map((row, index) => {
|
||||
const barcode = String(row.barcode ?? '').trim().toUpperCase()
|
||||
const imageUrl = String(row.imageUrl ?? '').trim()
|
||||
if (!barcode) {
|
||||
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, `第 ${index + 2} 行缺少条码`)
|
||||
}
|
||||
if (!imageUrl) {
|
||||
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, `第 ${index + 2} 行缺少图片链接`)
|
||||
}
|
||||
if (imageUrl.length > 2000) {
|
||||
throw new AppError(ErrorCode.VALIDATION_OUT_OF_RANGE, `第 ${index + 2} 行图片链接过长`)
|
||||
}
|
||||
return {
|
||||
barcode,
|
||||
imageUrl,
|
||||
updatedById: user.id,
|
||||
updatedByName: user.name || user.email || user.id,
|
||||
}
|
||||
})
|
||||
const unique = new Map<string, (typeof normalized)[number]>()
|
||||
for (const row of normalized) unique.set(row.barcode, row)
|
||||
const imported = await productStopDetailRepository.upsertImageOverrides([...unique.values()])
|
||||
return { imported }
|
||||
}
|
||||
}
|
||||
|
||||
export const productStopDetailService = new ProductStopDetailService()
|
||||
|
||||
@ -0,0 +1,102 @@
|
||||
jest.mock('@/server/repositories/product-stop-detail.repository', () => ({
|
||||
productStopDetailRepository: {
|
||||
findLatestAdmissionByBarcodes: jest.fn(),
|
||||
upsertImageOverrides: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { productStopDetailRepository } from '@/server/repositories/product-stop-detail.repository'
|
||||
import { productStopImageImportService } from './product-stop-image-import.service'
|
||||
|
||||
const repository = productStopDetailRepository as unknown as {
|
||||
findLatestAdmissionByBarcodes: jest.Mock
|
||||
upsertImageOverrides: jest.Mock
|
||||
}
|
||||
const user = {
|
||||
id: 'user-1',
|
||||
name: '维护人员',
|
||||
email: 'operator@example.com',
|
||||
} as AuthUser
|
||||
|
||||
describe('商品盘停图片导入', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
repository.findLatestAdmissionByBarcodes.mockResolvedValue(new Map([
|
||||
['A1', '是'],
|
||||
['B2', '否'],
|
||||
['D4', '是'],
|
||||
['E5', '是'],
|
||||
['F6', '是'],
|
||||
]))
|
||||
repository.upsertImageOverrides.mockImplementation(async (rows: unknown[]) => rows.length)
|
||||
})
|
||||
|
||||
it('blocks invalid admission scope values', async () => {
|
||||
await expect(productStopImageImportService.importRows({
|
||||
rows: [{ rowNumber: 2, barcode: 'A1', imageUrl: 'https://example.com/a.jpg' }],
|
||||
user,
|
||||
admissionScope: '全部' as never,
|
||||
})).rejects.toThrow('准入范围参数不合法')
|
||||
expect(repository.findLatestAdmissionByBarcodes).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('validates every row, blocks cross-scope updates and reports progress', async () => {
|
||||
const events: Array<{ status: string; rowNumber: number }> = []
|
||||
const result = await productStopImageImportService.importRows({
|
||||
rows: [
|
||||
{ rowNumber: 2, barcode: 'A1', imageUrl: 'https://example.com/a.jpg' },
|
||||
{ rowNumber: 3, barcode: 'B2', imageUrl: 'https://example.com/b.jpg' },
|
||||
{ rowNumber: 4, barcode: 'C3', imageUrl: 'https://example.com/c.jpg' },
|
||||
{ rowNumber: 5, barcode: 'D4', imageUrl: '' },
|
||||
{ rowNumber: 6, barcode: 'E5', imageUrl: 'https://example.com/e1.jpg' },
|
||||
{ rowNumber: 7, barcode: 'E5', imageUrl: 'https://example.com/e2.jpg' },
|
||||
{ rowNumber: 8, barcode: 'F6', imageUrl: 'ftp://example.com/f.jpg' },
|
||||
],
|
||||
user,
|
||||
admissionScope: '是',
|
||||
onProgress: (_progress, row) => {
|
||||
if (row) events.push({ status: row.status, rowNumber: row.rowNumber })
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.progress).toMatchObject({
|
||||
phase: 'complete',
|
||||
processed: 7,
|
||||
total: 7,
|
||||
succeeded: 2,
|
||||
failed: 3,
|
||||
skipped: 2,
|
||||
})
|
||||
expect(result.results).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ rowNumber: 3, status: 'failed', message: expect.stringContaining('已阻止跨范围修改') }),
|
||||
expect.objectContaining({ rowNumber: 4, status: 'skipped', message: '最新快照中未找到该条码' }),
|
||||
expect.objectContaining({ rowNumber: 5, status: 'failed', message: '缺少图片链接或嵌入图片' }),
|
||||
expect.objectContaining({ rowNumber: 6, status: 'skipped', message: expect.stringContaining('第 7 行') }),
|
||||
expect.objectContaining({ rowNumber: 8, status: 'failed', message: expect.stringContaining('http') }),
|
||||
]))
|
||||
expect(events).toHaveLength(7)
|
||||
expect(repository.upsertImageOverrides).toHaveBeenCalledTimes(1)
|
||||
expect(repository.upsertImageOverrides).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ barcode: 'A1', imageUrl: 'https://example.com/a.jpg' }),
|
||||
expect.objectContaining({ barcode: 'E5', imageUrl: 'https://example.com/e2.jpg' }),
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps row-level failures when a database batch fails', async () => {
|
||||
repository.findLatestAdmissionByBarcodes.mockResolvedValue(new Map([['A1', '是']]))
|
||||
repository.upsertImageOverrides.mockRejectedValue(new Error('database unavailable'))
|
||||
|
||||
const result = await productStopImageImportService.importRows({
|
||||
rows: [{ rowNumber: 2, barcode: 'A1', imageUrl: 'https://example.com/a.jpg' }],
|
||||
user,
|
||||
admissionScope: '是',
|
||||
})
|
||||
|
||||
expect(result.progress).toMatchObject({ succeeded: 0, failed: 1, skipped: 0 })
|
||||
expect(result.results[0]).toMatchObject({
|
||||
status: 'failed',
|
||||
message: '图片保存失败,请稍后重试',
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,205 @@
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import {
|
||||
applyProductStopImageImportRowResult,
|
||||
completeProductStopImageImportProgress,
|
||||
createProductStopImageImportProgress,
|
||||
parseProductStopAdmissionScope,
|
||||
type ProductStopAdmissionScope,
|
||||
type ProductStopImageImportProgress,
|
||||
type ProductStopImageImportRowInput,
|
||||
type ProductStopImageImportRowResult,
|
||||
} from '@/lib/product-stop-image-import'
|
||||
import { productStopDetailRepository } from '@/server/repositories/product-stop-detail.repository'
|
||||
|
||||
const MAX_IMPORT_ROWS = 5000
|
||||
const UPSERT_BATCH_SIZE = 200
|
||||
|
||||
type NormalizedRow = ProductStopImageImportRowInput & {
|
||||
barcode: string
|
||||
imageUrl: string
|
||||
}
|
||||
|
||||
type ProgressListener = (
|
||||
progress: ProductStopImageImportProgress,
|
||||
row?: ProductStopImageImportRowResult,
|
||||
) => void
|
||||
|
||||
function rowError(rowNumber: number, barcode: string, message: string): ProductStopImageImportRowResult {
|
||||
return {
|
||||
rowNumber,
|
||||
barcode,
|
||||
status: 'failed',
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
function rowSkipped(rowNumber: number, barcode: string, message: string): ProductStopImageImportRowResult {
|
||||
return {
|
||||
rowNumber,
|
||||
barcode,
|
||||
status: 'skipped',
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
function rowSucceeded(rowNumber: number, barcode: string): ProductStopImageImportRowResult {
|
||||
return {
|
||||
rowNumber,
|
||||
barcode,
|
||||
status: 'succeeded',
|
||||
message: '图片已保存',
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRow(row: ProductStopImageImportRowInput): NormalizedRow {
|
||||
return {
|
||||
rowNumber: Number.isInteger(row.rowNumber) && row.rowNumber > 0 ? row.rowNumber : 0,
|
||||
barcode: String(row.barcode ?? '').trim().toUpperCase(),
|
||||
imageUrl: String(row.imageUrl ?? '').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
function validateImageUrl(imageUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(imageUrl)
|
||||
return url.protocol === 'http:' || url.protocol === 'https:'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
class ProductStopImageImportService {
|
||||
async findLatestAdmissionByBarcodes(
|
||||
barcodes: readonly string[],
|
||||
): Promise<Map<string, string>> {
|
||||
return productStopDetailRepository.findLatestAdmissionByBarcodes(barcodes)
|
||||
}
|
||||
|
||||
async importRows(input: {
|
||||
rows: readonly ProductStopImageImportRowInput[]
|
||||
user: AuthUser
|
||||
admissionScope: ProductStopAdmissionScope
|
||||
initialProgress?: ProductStopImageImportProgress
|
||||
onProgress?: ProgressListener
|
||||
}): Promise<{
|
||||
progress: ProductStopImageImportProgress
|
||||
results: ProductStopImageImportRowResult[]
|
||||
}> {
|
||||
const admissionScope = parseProductStopAdmissionScope(input.admissionScope)
|
||||
if (!admissionScope) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
'准入范围参数不合法,只允许“是”或“否”',
|
||||
)
|
||||
}
|
||||
if (input.rows.length === 0) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_REQUIRED_FIELD,
|
||||
'导入文件没有可用的图片维护数据',
|
||||
)
|
||||
}
|
||||
if (input.rows.length > MAX_IMPORT_ROWS) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_OUT_OF_RANGE,
|
||||
'单次最多导入 5000 条图片维护数据',
|
||||
)
|
||||
}
|
||||
|
||||
const rows = input.rows.map(normalizeRow)
|
||||
const lastRowByBarcode = new Map<string, number>()
|
||||
rows.forEach((row) => {
|
||||
if (row.barcode) lastRowByBarcode.set(row.barcode, row.rowNumber)
|
||||
})
|
||||
|
||||
const pending: NormalizedRow[] = []
|
||||
const results: ProductStopImageImportRowResult[] = []
|
||||
let progress = input.initialProgress
|
||||
?? createProductStopImageImportProgress(rows.length, 0, 'importing')
|
||||
progress = { ...progress, phase: 'importing', total: rows.length }
|
||||
const finalize = (result: ProductStopImageImportRowResult) => {
|
||||
results.push(result)
|
||||
progress = applyProductStopImageImportRowResult(progress, result)
|
||||
input.onProgress?.(progress, result)
|
||||
}
|
||||
|
||||
rows.forEach((row) => {
|
||||
if (!row.rowNumber) {
|
||||
finalize(rowError(0, row.barcode, '缺少有效 Excel 行号'))
|
||||
return
|
||||
}
|
||||
if (!row.barcode) {
|
||||
finalize(rowError(row.rowNumber, '', '缺少条码'))
|
||||
return
|
||||
}
|
||||
if (lastRowByBarcode.get(row.barcode) !== row.rowNumber) {
|
||||
finalize(rowSkipped(
|
||||
row.rowNumber,
|
||||
row.barcode,
|
||||
`重复条码,以第 ${lastRowByBarcode.get(row.barcode)} 行为准`,
|
||||
))
|
||||
return
|
||||
}
|
||||
pending.push(row)
|
||||
})
|
||||
|
||||
const latestAdmissions = await this.findLatestAdmissionByBarcodes(
|
||||
pending.map((row) => row.barcode),
|
||||
)
|
||||
const valid: NormalizedRow[] = []
|
||||
pending.forEach((row) => {
|
||||
const latestAdmission = latestAdmissions.get(row.barcode)
|
||||
if (!latestAdmission) {
|
||||
finalize(rowSkipped(row.rowNumber, row.barcode, '最新快照中未找到该条码'))
|
||||
return
|
||||
}
|
||||
if (latestAdmission !== admissionScope) {
|
||||
finalize(rowError(
|
||||
row.rowNumber,
|
||||
row.barcode,
|
||||
`该条码属于“${latestAdmission}”准入范围,当前导入范围为“${admissionScope}”,已阻止跨范围修改`,
|
||||
))
|
||||
return
|
||||
}
|
||||
if (!row.imageUrl) {
|
||||
finalize(rowError(row.rowNumber, row.barcode, '缺少图片链接或嵌入图片'))
|
||||
return
|
||||
}
|
||||
if (row.imageUrl.length > 2000) {
|
||||
finalize(rowError(row.rowNumber, row.barcode, '图片链接超过 2000 个字符'))
|
||||
return
|
||||
}
|
||||
if (!validateImageUrl(row.imageUrl)) {
|
||||
finalize(rowError(row.rowNumber, row.barcode, '图片链接仅支持 http 或 https'))
|
||||
return
|
||||
}
|
||||
valid.push(row)
|
||||
})
|
||||
|
||||
const updatedByName = input.user.name || input.user.email || input.user.id
|
||||
for (let index = 0; index < valid.length; index += UPSERT_BATCH_SIZE) {
|
||||
const batch = valid.slice(index, index + UPSERT_BATCH_SIZE)
|
||||
try {
|
||||
await productStopDetailRepository.upsertImageOverrides(
|
||||
batch.map((row) => ({
|
||||
barcode: row.barcode,
|
||||
imageUrl: row.imageUrl,
|
||||
updatedById: input.user.id,
|
||||
updatedByName,
|
||||
})),
|
||||
)
|
||||
batch.forEach((row) => finalize(rowSucceeded(row.rowNumber, row.barcode)))
|
||||
} catch (error) {
|
||||
console.error('[product-stop-image-import] batch save failed', error)
|
||||
batch.forEach((row) => finalize(
|
||||
rowError(row.rowNumber, row.barcode, '图片保存失败,请稍后重试'),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
progress = completeProductStopImageImportProgress(progress)
|
||||
return { progress, results }
|
||||
}
|
||||
}
|
||||
|
||||
export const productStopImageImportService = new ProductStopImageImportService()
|
||||
@ -42,12 +42,74 @@ describe('supply chain permission settings service', () => {
|
||||
})
|
||||
|
||||
it('includes the clearance menu for administrators', async () => {
|
||||
await expect(
|
||||
supplyChainPermissionSettingsService.getVisibleTargetKeys({ role: 'ADMIN' }),
|
||||
).resolves.toContain('businessManagement')
|
||||
const targets = await supplyChainPermissionSettingsService
|
||||
.getVisibleTargetKeys({ role: 'ADMIN' })
|
||||
expect(targets).toEqual(expect.arrayContaining([
|
||||
'businessManagement',
|
||||
'productInventoryStop',
|
||||
]))
|
||||
expect(mockFindMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('applies default role access to every product stop action', async () => {
|
||||
const admin = await supplyChainPermissionSettingsService
|
||||
.getProductInventoryStopPermissions({ role: 'ADMIN' })
|
||||
expect(admin.detail.main).toEqual(expect.objectContaining({
|
||||
view: true,
|
||||
query: true,
|
||||
generate: true,
|
||||
import: true,
|
||||
export: true,
|
||||
manualPush: true,
|
||||
}))
|
||||
expect(admin.unadmitted.main.import).toBe(true)
|
||||
expect(admin.logicConfig).toEqual(expect.objectContaining({
|
||||
create: true,
|
||||
import: true,
|
||||
observationDays: true,
|
||||
}))
|
||||
expect(admin.warehouseMapping.create).toBe(true)
|
||||
|
||||
const supervisor = await supplyChainPermissionSettingsService
|
||||
.getProductInventoryStopPermissions({ role: 'SUPERVISOR', id: 'supervisor-1' })
|
||||
expect(supervisor.detail.main).toEqual(expect.objectContaining({
|
||||
view: true,
|
||||
query: true,
|
||||
import: false,
|
||||
export: false,
|
||||
manualPush: false,
|
||||
}))
|
||||
expect(supervisor.logicConfig.view).toBe(true)
|
||||
expect(supervisor.logicConfig.edit).toBe(false)
|
||||
expect(mockFindMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps fine-grained product stop controls for ordinary accounts', async () => {
|
||||
mockFindMany.mockResolvedValue([
|
||||
override('productStopDetailMainView', 'view'),
|
||||
override('productStopUnadmittedMainView', 'view'),
|
||||
override('productStopUnadmittedMainImport', 'edit'),
|
||||
override('productStopLogicConfigView', 'view'),
|
||||
])
|
||||
|
||||
const permissions = await supplyChainPermissionSettingsService
|
||||
.getProductInventoryStopPermissions(user)
|
||||
|
||||
expect(permissions.detail.main.view).toBe(true)
|
||||
expect(permissions.detail.main.import).toBe(false)
|
||||
expect(permissions.unadmitted.main.view).toBe(true)
|
||||
expect(permissions.unadmitted.main.import).toBe(true)
|
||||
expect(permissions.logicConfig.view).toBe(true)
|
||||
expect(permissions.logicConfig.create).toBe(false)
|
||||
await expect(
|
||||
supplyChainPermissionSettingsService.getUserAccess(user, 'productInventoryStop'),
|
||||
).resolves.toMatchObject({ view: true })
|
||||
const visibleTargets = await supplyChainPermissionSettingsService
|
||||
.getVisibleTargetKeys(user)
|
||||
expect(visibleTargets).toContain('productInventoryStop')
|
||||
expect(visibleTargets).not.toContain('productStopDetailMainView')
|
||||
})
|
||||
|
||||
it('does not grant freight maintenance to supervisors unless an administrator configures it', async () => {
|
||||
mockFindMany.mockResolvedValue([])
|
||||
await expect(
|
||||
|
||||
@ -18,11 +18,14 @@ import {
|
||||
resolveSupplyChainPermissionAccess,
|
||||
resolveSupplyChainPermissionSubjectKeys,
|
||||
sanitizeSupplyChainPermissionOverrides,
|
||||
buildProductInventoryStopPermissionsFromAccess,
|
||||
emptyProductInventoryStopPermissions,
|
||||
isProductStopPermissionTarget,
|
||||
summarizeProductInventoryStopPermissions,
|
||||
SUPPLY_CHAIN_PERMISSION_TARGET_KEYS,
|
||||
type ModularProductProcessingOrdersPermissions,
|
||||
type ProductInventoryStopPermissions,
|
||||
type ProductStopDetailPermissions,
|
||||
type ProductStopTablePermissions,
|
||||
type ProductionStopConfigPermissions,
|
||||
type ProductionStopDemandsPermissions,
|
||||
type SupplyChainPermissionAction,
|
||||
@ -119,39 +122,6 @@ function emptyProductionStopPermissions(): ProductionStopDemandsPermissions {
|
||||
}
|
||||
}
|
||||
|
||||
function emptyProductStopDetailPermissions(): ProductStopDetailPermissions {
|
||||
return {
|
||||
main: {
|
||||
view: false,
|
||||
query: false,
|
||||
reset: false,
|
||||
generate: false,
|
||||
import: false,
|
||||
export: false,
|
||||
settings: false,
|
||||
refresh: false,
|
||||
manualPush: false,
|
||||
changeHistory: false,
|
||||
},
|
||||
attachment: { view: false, query: false, reset: false },
|
||||
}
|
||||
}
|
||||
|
||||
function emptyProductStopTablePermissions(): ProductStopTablePermissions {
|
||||
return {
|
||||
view: false,
|
||||
query: false,
|
||||
reset: false,
|
||||
create: false,
|
||||
edit: false,
|
||||
delete: false,
|
||||
bulkEdit: false,
|
||||
import: false,
|
||||
export: false,
|
||||
observationDays: false,
|
||||
}
|
||||
}
|
||||
|
||||
function productionStopPermissionsFromDefaultAccess(
|
||||
access: SupplyChainPermissionAccess,
|
||||
): ProductionStopDemandsPermissions {
|
||||
@ -280,6 +250,20 @@ class SupplyChainPermissionSettingsService {
|
||||
}
|
||||
return resolveSupplyChainPermissionAccess(overrides, 'businessManagement', subjectKeys, userId)
|
||||
}
|
||||
if (targetKey !== 'productInventoryStop' && isProductStopPermissionTarget(targetKey)) {
|
||||
if (hasSupplyChainPermissionOverride(overrides, targetKey, subjectKeys, userId)) {
|
||||
return resolveSupplyChainPermissionAccess(overrides, targetKey, subjectKeys, userId)
|
||||
}
|
||||
if (hasSupplyChainPermissionOverride(overrides, 'productInventoryStop', subjectKeys, userId)) {
|
||||
return resolveSupplyChainPermissionAccess(
|
||||
overrides,
|
||||
'productInventoryStop',
|
||||
subjectKeys,
|
||||
userId,
|
||||
)
|
||||
}
|
||||
return emptyAccess()
|
||||
}
|
||||
if (targetKey === 'modularProductProcessingOrders') {
|
||||
return hasSupplyChainPermissionOverride(overrides, targetKey, subjectKeys, userId)
|
||||
? resolveSupplyChainPermissionAccess(overrides, targetKey, subjectKeys, userId)
|
||||
@ -500,13 +484,12 @@ class SupplyChainPermissionSettingsService {
|
||||
async getProductInventoryStopPermissions(
|
||||
user: SupplyChainPermissionUser,
|
||||
): Promise<ProductInventoryStopPermissions> {
|
||||
const roleDefaultAccess = getSupplyChainRoleDefaultAccess(user)
|
||||
if (roleDefaultAccess) {
|
||||
return buildProductInventoryStopPermissionsFromAccess(roleDefaultAccess)
|
||||
}
|
||||
if (isSupplyChainExcludedUser(user)) {
|
||||
return {
|
||||
detail: emptyProductStopDetailPermissions(),
|
||||
unadmitted: emptyProductStopDetailPermissions(),
|
||||
logicConfig: emptyProductStopTablePermissions(),
|
||||
warehouseMapping: emptyProductStopTablePermissions(),
|
||||
}
|
||||
return emptyProductInventoryStopPermissions()
|
||||
}
|
||||
try {
|
||||
const overrides = await this.readOverrides()
|
||||
@ -577,12 +560,7 @@ class SupplyChainPermissionSettingsService {
|
||||
}
|
||||
} catch (error) {
|
||||
if (isMissingPermissionTable(error)) {
|
||||
return {
|
||||
detail: emptyProductStopDetailPermissions(),
|
||||
unadmitted: emptyProductStopDetailPermissions(),
|
||||
logicConfig: emptyProductStopTablePermissions(),
|
||||
warehouseMapping: emptyProductStopTablePermissions(),
|
||||
}
|
||||
return emptyProductInventoryStopPermissions()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
@ -658,6 +636,11 @@ class SupplyChainPermissionSettingsService {
|
||||
this.buildProductionStopPermissions(overrides, subjectKeys, user.id),
|
||||
)
|
||||
}
|
||||
if (targetKey === 'productInventoryStop') {
|
||||
return summarizeProductInventoryStopPermissions(
|
||||
await this.getProductInventoryStopPermissions(user),
|
||||
)
|
||||
}
|
||||
return this.resolveAccessFromOverrides(overrides, targetKey, subjectKeys, user.id)
|
||||
} catch (error) {
|
||||
if (isMissingPermissionTable(error)) {
|
||||
@ -681,6 +664,7 @@ class SupplyChainPermissionSettingsService {
|
||||
!isSupplyChainPermissionTargetExcluded(user, targetKey)
|
||||
&& !isModularProcessingPermissionTarget(targetKey)
|
||||
&& !isProductionStopPermissionTarget(targetKey)
|
||||
&& !isProductStopPermissionTarget(targetKey)
|
||||
&& resolveExternalIntakeSupplyChainAccess(overrides, user, targetKey).view
|
||||
))
|
||||
} catch (error) {
|
||||
@ -695,6 +679,7 @@ class SupplyChainPermissionSettingsService {
|
||||
(targetKey) => (
|
||||
!isModularProcessingPermissionTarget(targetKey)
|
||||
&& !isProductionStopPermissionTarget(targetKey)
|
||||
&& !isProductStopPermissionTarget(targetKey)
|
||||
),
|
||||
)
|
||||
if (roleDefaultAccess.edit) return roleVisibleTargetKeys
|
||||
@ -730,17 +715,24 @@ class SupplyChainPermissionSettingsService {
|
||||
subjectKeys,
|
||||
user.id,
|
||||
)
|
||||
const productStopPermissions = await this.getProductInventoryStopPermissions(user)
|
||||
const targetKeys = SUPPLY_CHAIN_PERMISSION_TARGET_KEYS
|
||||
return targetKeys.filter((targetKey) => {
|
||||
if (isSupplyChainPermissionTargetExcluded(user, targetKey)) return false
|
||||
if (isModularProcessingPermissionTarget(targetKey)) return false
|
||||
if (isProductionStopPermissionTarget(targetKey)) return false
|
||||
if (isProductStopPermissionTarget(targetKey) && targetKey !== 'productInventoryStop') {
|
||||
return false
|
||||
}
|
||||
if (targetKey === 'modularProductProcessingOrders') {
|
||||
return this.summarizeModularProcessingPermissions(modularPermissions).view
|
||||
}
|
||||
if (targetKey === 'productionStopDemands') {
|
||||
return this.summarizeProductionStopPermissions(productionStopPermissions).view
|
||||
}
|
||||
if (targetKey === 'productInventoryStop') {
|
||||
return summarizeProductInventoryStopPermissions(productStopPermissions).view
|
||||
}
|
||||
return this.resolveAccessFromOverrides(overrides, targetKey, subjectKeys, user.id).view
|
||||
})
|
||||
} catch (error) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user