From 804b0c9b40529807aa10bed2f036b8cc2aa4bfb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Wed, 25 Nov 2026 16:45:06 +0800 Subject: [PATCH 01/16] =?UTF-8?q?fix(clearance):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E8=BF=90=E8=90=A5=E5=AF=BC=E5=85=A5=E6=9C=88=E4=BB=BD=E9=94=99?= =?UTF-8?q?=E7=94=A8=E5=8E=86=E5=8F=B2=E4=BB=BB=E5=8A=A1=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ClearanceTaskManualImportDialog.tsx | 1 + .../management/clearance/ClearanceView.tsx | 33 ++++++++++++++----- .../src/lib/clearance-task-period.test.ts | 23 ++++++++++++- .../src/lib/clearance-task-period.ts | 11 +++++++ ...hain-clearance-task-import.service.test.ts | 25 ++++++++++++++ ...ply-chain-clearance-task-import.service.ts | 18 +++++++++- 6 files changed, 101 insertions(+), 10 deletions(-) diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceTaskManualImportDialog.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceTaskManualImportDialog.tsx index b155569a..c7538a53 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceTaskManualImportDialog.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceTaskManualImportDialog.tsx @@ -7,6 +7,7 @@ import styles from './clearance-price-push.module.css' import { CLEARANCE_TASK_IMPORT_TEMPLATE_HEADERS } from '@/lib/clearance-task-manual-import-headers' type ImportResult = { + periodKey: string importedCount: number createdCount: number updatedCount: number diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx index 2217bb7f..0dd69aaa 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx @@ -17,7 +17,10 @@ import { } from '@/lib/clearance-period-lifecycle' import { isClearanceDiscountBlockedPriority } from '@/lib/clearance-discount-restrictions' import { formatClearanceDailySales } from '@/lib/clearance-number-format' -import { resolveClearanceTaskPeriod } from '@/lib/clearance-task-period' +import { + resolveClearanceTaskPeriod, + resolveClearanceTaskViewPeriod, +} from '@/lib/clearance-task-period' import { shouldPollClearanceProgressSync, shouldRefreshClearanceProgressData, @@ -1002,9 +1005,12 @@ export function ClearanceView({ setTaskLoading(true) setTaskError('') if (tab === 'tasks') setTasks(null) - const summaryPeriod = tab === 'pool' - ? pool?.periodKey ?? taskPeriod - : taskPeriod || currentPeriodKey() + const summaryPeriod = resolveClearanceTaskViewPeriod({ + view: tab === 'tasks' ? 'tasks' : 'pool', + poolPeriod: pool?.periodKey ?? '', + taskPeriod, + currentPeriod: currentPeriodKey(), + }) const taskParams = new URLSearchParams({ period: summaryPeriod }) taskParams.set('includeFreight', '0') taskParams.set('liveProgress', '0') @@ -1019,7 +1025,7 @@ export function ClearanceView({ if (!isCurrentRequest()) return setTasks(data) const resolvedTaskPeriod = resolveClearanceTaskPeriod({ - requestedPeriod: taskPeriod, + requestedPeriod: summaryPeriod, responsePeriod: data.periodKey, availablePeriods: data.periods ?? [], currentPeriod: currentPeriodKey(), @@ -2518,6 +2524,7 @@ export function ClearanceView({ aria-label="清货月份" onChange={(event) => { setPoolPeriod(event.target.value) + setTaskPeriod(event.target.value) setPoolReviewStatus('ALL') setPoolPage(1) setPoolFilterDraft([]) @@ -3895,7 +3902,12 @@ export function ClearanceView({ {taskImportOpen && ( setTaskImportOpen(false)} onImported={(result) => { setTaskImportOpen(false) @@ -3904,7 +3916,7 @@ export function ClearanceView({ setTaskRefreshKey((value) => value + 1) setPoolRefreshKey((value) => value + 1) setToast( - `已导入 ${result.importedCount} 条清货任务并进入待审核` + `已导入到${monthLabel(result.periodKey)} ${result.importedCount} 条清货任务并进入待审核` + `(新增 ${result.createdCount} 条,更新 ${result.updatedCount} 条)` + (result.adjustedToStockCount ? `;${result.adjustedToStockCount} 条任务量已按简尚库存截断:${result.adjustedBarcodes.slice(0, 8).join('、')}` @@ -3915,7 +3927,12 @@ export function ClearanceView({ )} {taskDirectImportOpen && ( setTaskDirectImportOpen(false)} onImported={(result) => { setTaskDirectImportOpen(false) diff --git a/furniture-3d-system/src/lib/clearance-task-period.test.ts b/furniture-3d-system/src/lib/clearance-task-period.test.ts index c1811990..d8d36601 100644 --- a/furniture-3d-system/src/lib/clearance-task-period.test.ts +++ b/furniture-3d-system/src/lib/clearance-task-period.test.ts @@ -1,6 +1,27 @@ -import { resolveClearanceTaskPeriod } from './clearance-task-period' +import { + resolveClearanceTaskPeriod, + resolveClearanceTaskViewPeriod, +} from './clearance-task-period' describe('resolveClearanceTaskPeriod', () => { + it('uses the selected pool period on pool pages instead of stale task state', () => { + expect(resolveClearanceTaskViewPeriod({ + view: 'pool', + poolPeriod: '2026-12', + taskPeriod: '2026-11', + currentPeriod: '2026-11', + })).toBe('2026-12') + }) + + it('uses the task page period when viewing the task list', () => { + expect(resolveClearanceTaskViewPeriod({ + view: 'tasks', + poolPeriod: '2026-12', + taskPeriod: '2026-11', + currentPeriod: '2026-11', + })).toBe('2026-11') + }) + it('keeps a requested period when the task response includes it', () => { expect(resolveClearanceTaskPeriod({ requestedPeriod: '2026-11', diff --git a/furniture-3d-system/src/lib/clearance-task-period.ts b/furniture-3d-system/src/lib/clearance-task-period.ts index 8d6d07b2..3898565d 100644 --- a/furniture-3d-system/src/lib/clearance-task-period.ts +++ b/furniture-3d-system/src/lib/clearance-task-period.ts @@ -16,3 +16,14 @@ export function resolveClearanceTaskPeriod(input: { if (response && periods.includes(response)) return response return periods[0] || response || requested || current } + +export function resolveClearanceTaskViewPeriod(input: { + view: 'pool' | 'tasks' + poolPeriod: string + taskPeriod: string + currentPeriod: string +}) { + const poolPeriod = input.poolPeriod.trim() + if (input.view === 'pool' && poolPeriod) return poolPeriod + return input.taskPeriod.trim() || poolPeriod || input.currentPeriod.trim() +} diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts index 04b1136c..7778ae0b 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts @@ -73,6 +73,13 @@ function repository() { { operationOwner: '运营G', profitCenter: '运营中心G' }, ]), latestTaskRound: jest.fn().mockResolvedValue(1), + findApplicationWindow: jest.fn().mockResolvedValue({ + periodKey: '2026-11', + round: 1, + startAt: new Date('2026-11-01T00:00:00.000Z'), + endAt: new Date('2026-11-30T23:59:59.000Z'), + status: 'CONFIRMED', + }), findReviewArchive: jest.fn().mockResolvedValue(null), writeTasksWithEvents: jest.fn().mockResolvedValue([]), } @@ -92,6 +99,24 @@ describe('SupplyChainClearanceTaskImportService', () => { expect(repo.writeTasksWithEvents).not.toHaveBeenCalled() }) + it('rejects operator imports outside the selected period application window', async () => { + const repo = repository() + repo.findApplicationWindow.mockResolvedValue(null) + const service = new SupplyChainClearanceTaskImportService( + repo as never, + () => new Date('2026-11-11T00:00:00.000Z'), + ) + + await expect(service.importTasks({ + periodKey: '2026-11', + user, + buffer: await workbookBuffer([ + ['SKU-A', '铁心兰', 100, '', ''], + ]), + })).rejects.toThrow('当前不在 2026-11 第 1 期清货任务申报窗口内') + expect(repo.writeTasksWithEvents).not.toHaveBeenCalled() + }) + it('imports pending tasks, clamps to Jianshang stock and updates existing tasks', async () => { const repo = repository() const service = new SupplyChainClearanceTaskImportService( diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts index a61e173f..a4b3886c 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts @@ -19,6 +19,7 @@ type TaskImportRepository = Pick< | 'listTasksForManualImport' | 'listOwnerProfitCenters' | 'latestTaskRound' + | 'findApplicationWindow' | 'findReviewArchive' | 'writeTasksWithEvents' > @@ -160,11 +161,27 @@ export class SupplyChainClearanceTaskImportService { } const importCodes = Array.from(new Set(rows.map((row) => row.barcode))) + const importedAt = this.now() const [poolItems, latestRound, ownerCenters] = await Promise.all([ this.repository.listPoolItemsForTaskPeriodByCodes(periodKey, importCodes), this.repository.latestTaskRound(periodKey), this.repository.listOwnerProfitCenters(), ]) + const applicationWindow = await this.repository.findApplicationWindow( + periodKey, + latestRound, + ) + if ( + !applicationWindow + || applicationWindow.status !== 'CONFIRMED' + || importedAt.getTime() < applicationWindow.startAt.getTime() + || importedAt.getTime() > applicationWindow.endAt.getTime() + ) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `当前不在 ${periodKey} 第 ${latestRound} 期清货任务申报窗口内,不能导入任务`, + ) + } const importCodeSet = new Set(importCodes) const poolItemsByImportCode = new Map() for (const item of poolItems) { @@ -342,7 +359,6 @@ export class SupplyChainClearanceTaskImportService { ) } - const importedAt = this.now() const writes: Parameters[0] = preparedRows.map((row) => { const existing = existingByKey.get(itemKey( periodKey, From 1b2f596052ab55ed6230cd36d7686d593346d02d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Wed, 25 Nov 2026 17:05:39 +0800 Subject: [PATCH 02/16] =?UTF-8?q?fix(supply-chain):=20=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E5=8F=91=E5=87=BA=E5=8D=B3=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E5=AE=A1=E6=89=B9=E9=80=9A=E7=9F=A5=E6=97=B6=E9=97=B4=EF=BC=88?= =?UTF-8?q?=E5=BE=85=E5=8A=9E=E5=A4=B1=E8=B4=A5=E4=B8=8D=E4=B8=A2=E5=A4=B1?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../supply-chain-brand-upgrade-approval.service.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/furniture-3d-system/src/server/services/supply-chain-brand-upgrade-approval.service.ts b/furniture-3d-system/src/server/services/supply-chain-brand-upgrade-approval.service.ts index f8e90a7e..a621c914 100644 --- a/furniture-3d-system/src/server/services/supply-chain-brand-upgrade-approval.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-brand-upgrade-approval.service.ts @@ -372,6 +372,11 @@ export class SupplyChainBrandUpgradeApprovalService { statusLine: `审批人:${vote.approverName}${url ? `\n审批链接:${url}` : ''}`, }) await dingtalkWorkNotificationService.sendText({ userIds: [vote.dingtalkUserId], content }) + // 工作通知已发出即记录通知时间(待办失败也保留) + await prisma.supplyChainBrandUpgradeApprovalVote.update({ + where: { id: vote.id }, + data: { notifiedAt: new Date() }, + }) const employee = await prisma.employeeDirectory.findFirst({ where: { name: vote.approverName }, select: { dingtalkUnionId: true }, @@ -393,16 +398,11 @@ export class SupplyChainBrandUpgradeApprovalService { }) await prisma.supplyChainBrandUpgradeApprovalVote.update({ where: { id: vote.id }, - data: { todoId: todo.taskId, notifiedAt: new Date() }, + data: { todoId: todo.taskId }, }) } catch { // 待办失败不影响工作通知 } - } else { - await prisma.supplyChainBrandUpgradeApprovalVote.update({ - where: { id: vote.id }, - data: { notifiedAt: new Date() }, - }) } } From 54068cee2869ebdfd00def77a0c566c5a1f65aab Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 25 Nov 2026 17:16:35 +0800 Subject: [PATCH 03/16] =?UTF-8?q?feat(supply-chain):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=AF=8F=E6=97=A5=E5=BF=AB=E9=80=92=E6=89=BF=E8=BF=90=E9=87=8F?= =?UTF-8?q?=E7=9C=8B=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workflow/每日快递承运量看板-实现与核查.md | 48 +++++ .../management/daily-express-volume/route.ts | 22 +++ .../components/supply-chain-tabs.tsx | 1 + .../supply-chain/config/supply-chain-menu.ts | 5 + .../DailyExpressVolumeView.test.tsx | 57 ++++++ .../DailyExpressVolumeView.tsx | 180 ++++++++++++++++++ .../daily-express-volume.module.css | 75 ++++++++ .../management/daily-express-volume/page.tsx | 13 ++ .../src/lib/daily-express-volume.test.ts | 66 +++++++ .../src/lib/daily-express-volume.ts | 81 ++++++++ .../src/lib/supply-chain-permission-paths.ts | 4 + .../lib/supply-chain-permission-targets.ts | 3 + .../daily-express-volume.repository.ts | 74 +++++++ .../daily-express-volume.service.test.ts | 48 +++++ .../services/daily-express-volume.service.ts | 43 +++++ 15 files changed, 720 insertions(+) create mode 100644 furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md create mode 100644 furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts create mode 100644 furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.test.tsx create mode 100644 furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.tsx create mode 100644 furniture-3d-system/src/app/supply-chain/management/daily-express-volume/daily-express-volume.module.css create mode 100644 furniture-3d-system/src/app/supply-chain/management/daily-express-volume/page.tsx create mode 100644 furniture-3d-system/src/lib/daily-express-volume.test.ts create mode 100644 furniture-3d-system/src/lib/daily-express-volume.ts create mode 100644 furniture-3d-system/src/server/repositories/daily-express-volume.repository.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/daily-express-volume.service.test.ts create mode 100644 furniture-3d-system/src/server/services/daily-express-volume.service.ts diff --git a/furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md b/furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md new file mode 100644 index 00000000..c02cd5e4 --- /dev/null +++ b/furniture-3d-system/docs/workflow/每日快递承运量看板-实现与核查.md @@ -0,0 +1,48 @@ +# 每日快递承运量看板 + +核查日期:2026-11-23。任务分支:`codex/mengxi-daily-express-volume`。 + +## 本次实现 + +- 入口:供应链中心 → 经营管理 → 每日快递承运量看板,路由 `/supply-chain/management/daily-express-volume`。 +- 每日趋势、快递承运排名和占比、快递 × 日期明细、区间总量、自然日日均、快递数量、单日峰值。 +- 日期、仓库、快递筛选;近 7 / 14 / 30 天快捷范围;单次最多 93 天;加载、空数据、失败重试状态。 +- 新增独立 `dailyExpressVolume` 权限节点,沿用现有用户管理、页面和 API 权限体系。页面进入前、API 网关、服务读取缓存前都检查查看权限。 +- 复用 `PlatformMetricStrip`、`PlatformSection` 和 `Button`;页面内使用实体浅色面板,覆盖旧组件的玻璃样式。 + +## 当前统计来源与口径 + +当前实现读取 `rpt.jst_order_express_details` 的 `send_time / logistic_company_name / logistic_id / warehouse_name`,日期按报表发货时间、北京时间展示。 + +在查询区间内,以快递名称和非空运单号去重;同一运单重复出现时归到区间内最早发货时间,仓库以该条记录为准。包括在途、签收及其他已有发货时间的物流记录,不以签收状态筛选。快递名称保留报表原值,地域/网点等不同配置名称不会合并为品牌。 + +Repository 在数据库端完成去重及按日期、仓库、快递聚合。Service 缓存相同日期范围 60 秒并合并并发请求,仓库和快递精确筛选复用同一份聚合数据。所有趋势、排名和明细来自该聚合结果,零发货自然日补零;源读取失败时显示错误,不生成虚假的零数据。 + +销售出库单是另一套可读取的数据:`rpt.jst_salesOutboundInfo`、`rpt.jst_qmcust_salesoutbound`。它们具有 `io_id / io_date / logistics_company / l_id / status` 等字段。前者有 `qty / wms_co_id`,后者有 `warehouse / wms_co_id`。两表可能存在同一 `io_id` 的重复记录;若后续要求与销售出库单页面对账,须核对同步时效、`Confirmed` 状态以及跨表去重,再明确改为出库口径。当前没有将两个来源混加。 + +本次进一步只读核查确认:两张销售出库单头视图均可读取列元数据;`rpt.jst_salesOutboundInfo` 可读到 2026-11-23 的待确认记录,按已确认日期排序的查询在 45 秒后超时,不能据此断言最新已确认时间。`rpt.jst_qmcust_salesoutbound` 在核查时返回的最新已确认日期为 2026-11-22 22:46:20,且该条为“无需物流”、无运单号。按物理快递运单统计时不能将这类记录计为有效承运票数。`rpt` 下两张销售出库单明细表返回对象不存在;这不代表底层业务库没有明细。 + +## 验证结果 + +- 相关 Jest 验证合计 57 项通过:首次执行 5 个测试文件 56 项通过;补充查询按钮键盘操作和小承运量日均展示后,重跑本次新增的 3 个测试文件,14 项通过。 +- 改动范围 ESLint 通过,无错误;`git diff --check` 通过。 +- 真实报表只读查询成功:2026-11-17 至 2026-11-23 返回 1,532 个日期/仓库/快递聚合,查询时区间总量 58,780 票。该数字为核查时点结果,不是固定业务基线。首次读取约 48 秒。 +- ego-browser 通过临时组件验证环境挂载真实组件、现有全局样式及刚读取的真实聚合,核查 1920×1080 和 390×844 视口;验证仓库查询、重置、排名、合计和表格横向滚动。390 像素视口下文档宽度仍为 390,表格在自己的容器内滚动。 +- 全项目类型检查和生产构建均受共享主线已有的 `src/lib/selection-market/mysql.ts:14` 阻塞:`mysql2/promise` 未导出 `QueryValues`。生产构建的 webpack 编译阶段已完成,后续 TypeScript 阶段失败;不能视为生产构建通过。本次未修改该模块。 +- Prisma Client 已按共享主线重新生成,未修改 schema 或执行迁移、数据写入。 +- 浏览器验证没有登录真实应用的本地会话,因此未完成已登录页面与实际 API 的端到端联调。临时组件环境不包含在交付路由中。 + +## 范围与交接 + +仅新增看板领域文件及菜单、标签、权限入口;没有修改其他业务模块、数据库结构或生产数据,没有合并主线或部署。 + +后续重点查看:`src/lib/daily-express-volume.ts`、同名 Repository 和 Service、`src/app/api/supply-chain/management/daily-express-volume/route.ts`、`src/app/supply-chain/management/daily-express-volume/`。发布前先解决既有类型阻塞,完成真实登录会话的联调;如用户要求与销售出库单页面一致,先核对销售出库源的日期、状态和跨表去重。 + +## 规范审查 + +结论:`passed with warnings`。这是自审,不是独立复审。 + +- 架构:符合 Route → Service → Repository;使用已有报表只读连接配置和权限体系,未改动主数据链与共享 schema。 +- 视觉:复用平台组件,采用浅色实体工作区;趋势、排名和明细层级清晰,桌面及移动端组件验证通过。 +- 根因与数据口径:在数据源端去重,所有展示共享聚合,不用签收子集推算承运量,不用假零值掩盖数据源错误。 +- 警告:全项目已有类型错误导致构建未通过,缺少真实登录会话的端到端验证,首次报表读取较慢;销售出库口径与物流发货口径需要按业务对账目标最终确定。 diff --git a/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts b/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts new file mode 100644 index 00000000..a8ad4dc6 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/management/daily-express-volume/route.ts @@ -0,0 +1,22 @@ +import type { NextRequest } from 'next/server' +import { expressVolumeDefaultRange } from '@/lib/daily-express-volume' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { dailyExpressVolumeService } from '@/server/services/daily-express-volume.service' + +export const dynamic = 'force-dynamic' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const params = request.nextUrl.searchParams + const defaults = expressVolumeDefaultRange() + const data = await dailyExpressVolumeService.getDashboard({ + dateFrom: params.get('dateFrom') ?? defaults.dateFrom, + dateTo: params.get('dateTo') ?? defaults.dateTo, + warehouse: params.get('warehouse') ?? '', + carrier: params.get('carrier') ?? '', + }, ctx.user) + const response = jsonSuccess(data, 200, ctx.requestId) + response.headers.set('Cache-Control', 'private, no-store') + return response + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/supply-chain/components/supply-chain-tabs.tsx b/furniture-3d-system/src/app/supply-chain/components/supply-chain-tabs.tsx index fbb8fcfb..2c2012c9 100644 --- a/furniture-3d-system/src/app/supply-chain/components/supply-chain-tabs.tsx +++ b/furniture-3d-system/src/app/supply-chain/components/supply-chain-tabs.tsx @@ -111,6 +111,7 @@ export const SUPPLY_CHAIN_ROUTE_TITLES: Record = { '/supply-chain/purchase/price-change': '产品变价', '/supply-chain/management/employee-hours': '员工工时统计', '/supply-chain/management/logistics-arrival-signing-duration': '物流到货签收时长看板', + '/supply-chain/management/daily-express-volume': '每日快递承运量看板', '/supply-chain/management/production-stop-demands': '停产需求管理', '/supply-chain/management/modular-product-processing-orders': '模块化商品加工单管理', '/supply-chain/management/front-warehouse-inventory': '前置仓进销存管理', diff --git a/furniture-3d-system/src/app/supply-chain/config/supply-chain-menu.ts b/furniture-3d-system/src/app/supply-chain/config/supply-chain-menu.ts index dd91004b..20b7c278 100644 --- a/furniture-3d-system/src/app/supply-chain/config/supply-chain-menu.ts +++ b/furniture-3d-system/src/app/supply-chain/config/supply-chain-menu.ts @@ -148,6 +148,11 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [ route: '/supply-chain/management/logistics-arrival-signing-duration', targetKey: 'logisticsArrivalSigningDuration', }, + { + label: '每日快递承运量看板', + route: '/supply-chain/management/daily-express-volume', + targetKey: 'dailyExpressVolume', + }, ], }, ], diff --git a/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.test.tsx b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.test.tsx new file mode 100644 index 00000000..fcd4fbe9 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.test.tsx @@ -0,0 +1,57 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { buildDailyExpressVolumeDashboard, expressVolumeDefaultRange } from '@/lib/daily-express-volume' +import { DailyExpressVolumeView } from './DailyExpressVolumeView' + +const filters = { ...expressVolumeDefaultRange(), warehouse: '', carrier: '' } +const board = buildDailyExpressVolumeDashboard([ + { date: filters.dateTo, warehouse: '睢宁仓', carrier: '圆通', volume: 128 }, +], filters, '2026-11-23T01:00:00Z') +const originalFetch = global.fetch +const fetchMock = jest.fn() +beforeEach(() => { global.fetch = fetchMock; fetchMock.mockReset() }) +afterAll(() => { global.fetch = originalFetch }) +const response = (data: unknown) => ({ ok: true, json: async () => ({ success: true, data }) }) + +it('查询使用所选仓库和快递,表格保留合计', async () => { + fetchMock.mockResolvedValue(response(board)) + render() + expect(await screen.findByRole('table')).toBeInTheDocument() + expect(screen.getByRole('rowheader', { name: '合计' })).toBeInTheDocument() + fireEvent.change(screen.getByLabelText('发货仓库'), { target: { value: '睢宁仓' } }) + fireEvent.change(screen.getByLabelText('快递公司'), { target: { value: '圆通' } }) + fireEvent.click(screen.getByRole('button', { name: /查询/ })) + await waitFor(() => expect(decodeURIComponent(fetchMock.mock.calls.at(-1)[0])).toContain('warehouse=睢宁仓&carrier=圆通')) +}) + +it('查询按钮可通过 Enter 提交筛选,低于一票的日均值保留小数', async () => { + const small = buildDailyExpressVolumeDashboard([{ date: filters.dateTo, warehouse: '睢宁仓', carrier: '圆通', volume: 2 }], filters, '2026-11-23T01:00:00Z') + fetchMock.mockResolvedValue(response(small)) + render() + await screen.findByRole('table') + expect(screen.getByText('0.3')).toBeInTheDocument() + fireEvent.change(screen.getByLabelText('发货仓库'), { target: { value: '睢宁仓' } }) + fireEvent.keyDown(screen.getByRole('button', { name: /查询/ }), { key: 'Enter' }) + await waitFor(() => expect(decodeURIComponent(fetchMock.mock.calls.at(-1)[0])).toContain('warehouse=睢宁仓')) +}) + +it('数据源错误清空旧结果,显示重试并可恢复', async () => { + fetchMock.mockResolvedValueOnce(response(board)).mockRejectedValueOnce(new Error('报表不可达')).mockResolvedValueOnce(response(board)) + render() + await screen.findByRole('table') + fireEvent.click(screen.getByRole('button', { name: /刷新数据/ })) + expect(await screen.findByText('报表不可达')).toBeInTheDocument() + expect(screen.queryByRole('table')).not.toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: '重新加载' })) + expect(await screen.findByRole('table')).toBeInTheDocument() +}) + +it('空数据明确显示空态,反向日期在发请求前拦截', async () => { + fetchMock.mockResolvedValue(response(buildDailyExpressVolumeDashboard([], filters, '2026-11-23T01:00:00Z'))) + render() + expect(await screen.findByText('当前条件下暂无承运记录')).toBeInTheDocument() + fireEvent.change(screen.getByLabelText('开始日期'), { target: { value: '2026-11-25' } }) + fireEvent.change(screen.getByLabelText('结束日期'), { target: { value: '2026-11-20' } }) + fireEvent.click(screen.getByRole('button', { name: /查询/ })) + expect(screen.getByRole('alert')).toHaveTextContent('结束日期不能早于开始日期') + expect(fetchMock).toHaveBeenCalledTimes(1) +}) diff --git a/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.tsx b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.tsx new file mode 100644 index 00000000..1205e095 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/DailyExpressVolumeView.tsx @@ -0,0 +1,180 @@ +'use client' + +import { useEffect, useState, type FormEvent } from 'react' +import { AlertCircle, BarChart3, Package, RefreshCw, RotateCcw, Search, Truck } from 'lucide-react' +import { PlatformMetricStrip } from '@/components/platform/PlatformMetricStrip' +import { PlatformSection } from '@/components/platform/PlatformSection' +import { Button } from '@/components/ui/Button' +import { + dailyExpressVolumeFiltersSchema, + expressVolumeDefaultRange, + expressVolumeToday, + type DailyExpressVolumeDashboard, + type DailyExpressVolumeFilters, +} from '@/lib/daily-express-volume' +import styles from './daily-express-volume.module.css' + +const number = new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 0 }) +const average = new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 1 }) +const percent = new Intl.NumberFormat('zh-CN', { style: 'percent', maximumFractionDigits: 1 }) +const updatedAt = (value: string) => new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) + +export function DailyExpressVolumeView() { + const [filters, setFilters] = useState(() => ({ ...expressVolumeDefaultRange(), warehouse: '', carrier: '' })) + const [draft, setDraft] = useState(filters) + const [data, setData] = useState(null) + const [options, setOptions] = useState<{ warehouses: string[]; carriers: string[] }>({ warehouses: [], carriers: [] }) + const [loading, setLoading] = useState(true) + const [error, setError] = useState('') + const [validationError, setValidationError] = useState('') + const [revision, setRevision] = useState(0) + + useEffect(() => { + const controller = new AbortController() + setLoading(true) + setError('') + setData(null) + async function load() { + try { + const response = await fetch(`/api/supply-chain/management/daily-express-volume?${new URLSearchParams(filters)}`, { cache: 'no-store', signal: controller.signal }) + const payload = await response.json() + if (!response.ok || !payload.success) throw new Error(payload.error?.message || '承运量数据读取失败,请重试') + if (controller.signal.aborted) return + const next = payload.data as DailyExpressVolumeDashboard + setData(next) + setOptions({ warehouses: next.warehouses, carriers: next.carrierOptions }) + } catch (cause) { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '承运量数据读取失败,请重试') + } finally { + if (!controller.signal.aborted) setLoading(false) + } + } + void load() + return () => controller.abort() + }, [filters, revision]) + + function apply(next: DailyExpressVolumeFilters) { + const parsed = dailyExpressVolumeFiltersSchema.safeParse(next) + if (!parsed.success) { + setValidationError(parsed.error.issues[0]?.message ?? '请检查筛选条件') + return + } + setValidationError('') + setDraft(parsed.data) + setFilters(parsed.data) + } + + function submit(event: FormEvent) { + event.preventDefault() + apply(draft) + } + + const maxVolume = Math.max(1, ...(data?.days.map((day) => day.volume) ?? [])) + const recentDays = data ? [...data.days].reverse() : [] + + return ( +
+
+
+
经营管理 / 物流分析
+

每日快递承运量看板

+

按发货日期统计运单量,查看每日趋势与各快递承运分布。

+
+ +
+ +
+ + — + + + +
+ + +
+
+ {[7, 14, 30].map((days) => )} +
+
+ {validationError ?

{validationError}

: null} + +
+ {loading ?
正在读取承运量数据报表首次查询可能需要一些时间。
: error ? ( +
承运量数据暂时无法读取{error}
+ ) : data ? ( + <> +
+ {data.filters.dateFrom} 至 {data.filters.dateTo}/{data.days.length} 天 + 读取时间 {updatedAt(data.dataAsOf)} +
+ }, + { label: '日均承运量', value: average.format(data.summary.dailyAverage), hint: '票 / 自然日' }, + { label: '承运快递数', value: data.summary.carrierCount, hint: '家' }, + { label: '单日峰值', value: number.format(data.summary.peakVolume), hint: data.summary.peakDate ?? '暂无发货' }, + ]} /> + + {data.summary.total === 0 ?
当前条件下暂无承运记录可调整日期、仓库或快递公司后重新查询。
: ( + <> +
+ 单位:票{data.days.some((day) => day.date === expressVolumeToday()) ? ' · 今日尚未结束' : ''}}> +
+
{number.format(maxVolume)}{number.format(maxVolume / 2)}0
+
+
+ {data.days.map((day) =>
+
+ {data.days.length <= 14 ? {number.format(day.volume)} : null} +
+
+ {day.date.slice(5).replace('-', '/')} +
)} +
+
+
+ + + 承运量 / 占比}> +
    + {data.carriers.map((carrier, index) =>
  1. + {String(index + 1).padStart(2, '0')} +
    +
    {carrier.name}{number.format(carrier.volume)}{percent.format(carrier.share)}
    +
    +
    +
  2. )} +
+
+
+ + 按总量排序 · 日期由近到远}> +
+ + + {recentDays.map((day) => )} + {data.carriers.map((carrier) => + + {recentDays.map((day) => )} + )} + {recentDays.map((day) => )} +
各快递每天的承运票数及区间占比
快递公司区间合计占比{day.date.slice(5).replace('-', '/')}
{carrier.name}{number.format(carrier.volume)}{percent.format(carrier.share)}{number.format(carrier.daily[day.date] ?? 0)}
合计{number.format(data.summary.total)}100%{number.format(day.volume)}
+
+
+ + )} +
按发货日期(北京时间),区间内同一快递、同一运单号计 1 票;无运单号不计入,包含在途及已签收运单。数据源:聚水潭报表。
+ + ) : null} +
+
+ ) +} diff --git a/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/daily-express-volume.module.css b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/daily-express-volume.module.css new file mode 100644 index 00000000..73245fe5 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/daily-express-volume.module.css @@ -0,0 +1,75 @@ +.workspace { padding: 24px; color: var(--sc-ink, #272e32); max-width: 2200px; margin: 0 auto; } +.header { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 22px; } +.eyebrow { display: flex; align-items: center; gap: 7px; font-size: 11px; letter-spacing: .04em; color: #69767c; margin-bottom: 8px; } +.header h1 { font-size: 23px; font-weight: 650; letter-spacing: -.04em; margin: 0; } +.header > button { white-space: nowrap; flex-shrink: 0; } +.header p { color: #69767c; font-size: 12px; margin: 7px 0 0; } +.filters { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; padding: 16px; border: 1px solid #e2e6e8; border-radius: 10px; background: #fff; } +.filters label { display: flex; flex-direction: column; gap: 7px; font-size: 11px; color: #637078; min-width: 145px; flex: 1; max-width: 230px; } +.filters input, .filters select { width: 100%; min-width: 0; border: 1px solid #dce1e4; border-radius: 6px; height: 34px; padding: 0 9px; color: #303a3f; background: #fff; font-size: 12px; color-scheme: light; } +.workspace :is(input, select, button, [tabindex]):focus-visible { outline: 2px solid #5c7c8a; outline-offset: 3px; } +.dateSeparator { color: #9aa4aa; padding-bottom: 8px; } +.filterActions { display: flex; gap: 4px; align-items: center; } +.presets { display: flex; gap: 3px; margin-left: auto; padding-bottom: 3px; } +.presets button { border: 0; border-radius: 5px; background: #f2f4f5; padding: 7px 9px; font-size: 11px; color: #53626a; cursor: pointer; white-space: nowrap; } +.presets button:hover { background: #e6ebee; } +.error { display: flex; gap: 8px; align-items: center; padding: 10px 12px; color: #9b3834; background: #fff2f0; border-radius: 6px; font-size: 12px; margin-top: 12px; } +.dataMeta { display: flex; gap: 12px; justify-content: space-between; flex-wrap: wrap; color: #7b858b; font-size: 11px; padding: 17px 1px 12px; } +.divider { margin: 0 9px; color: #b0b9be; } +.workspace .metrics { grid-template-columns: repeat(4, minmax(0, 1fr)); padding: 0; gap: 0; background: #fff; border: 1px solid #e2e6e8; border-radius: 10px; box-shadow: none; backdrop-filter: none; margin-bottom: 18px; overflow: hidden; } +.metrics > article { border: 0; border-radius: 0; padding: 17px 22px; min-height: 104px; background: #fff; box-shadow: none; gap: 12px; } +.metrics > article:first-child { border-radius: 10px 0 0 10px; } +.metrics > article:last-child { border-radius: 0 10px 10px 0; } +.metrics > article + article { border-left: 1px solid #edf0f2; } +.metrics > article p { color: #68767e; } +.metrics > article > div:last-child > p:first-child { font-size: 29px; font-weight: 650; color: #2b3940; font-variant-numeric: tabular-nums; letter-spacing: -.04em; } +.analysis { display: grid; grid-template-columns: minmax(0, 1.9fr) minmax(300px, 1fr); gap: 18px; margin-bottom: 18px; } +.workspace .panel { min-width: 0; border-radius: 10px; border: 1px solid #e2e6e8; background: #fff; box-shadow: none; backdrop-filter: none; } +.panel > header { padding: 14px 18px; border-color: #edf0f2; flex-direction: row; align-items: center; gap: 12px; } +.panel > header h2 { font-size: 13px; font-weight: 650; color: #354249; letter-spacing: 0; } +.panelHint { color: #8a959b; font-size: 10px; white-space: nowrap; } +.workspace .chartContent { padding: 20px 18px 14px; } +.chart { display: flex; height: 238px; gap: 10px; } +.axis { display: flex; flex-direction: column; justify-content: space-between; width: 42px; flex-shrink: 0; padding: 27px 0 29px; font-size: 10px; color: #8a959b; text-align: right; } +.chartScroll { flex: 1; min-width: 0; overflow-x: auto; } +.plot { display: flex; height: 100%; background-image: linear-gradient(to bottom, transparent calc(100% - 1px), #edf0f2 0); background-size: 100% calc((100% - 28px) / 2); background-position: 0 0; } +.day { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; height: 100%; } +.barTrack { width: 100%; height: calc(100% - 28px); display: flex; align-items: flex-end; justify-content: center; position: relative; border-bottom: 1px solid #dfe5e8; } +.bar { width: 35%; max-width: 34px; background: #8cabb6; border-radius: 3px 3px 0 0; } +.peakBar { background: #465f6b; } +.barValue { position: absolute; font-size: 10px; color: #4d626c; padding-bottom: 6px; font-variant-numeric: tabular-nums; white-space: nowrap; } +.dayLabel { height: 28px; padding-top: 10px; font-size: 10px; color: #7d8990; } +.workspace .rankContent { padding: 0 18px; height: 272px; overflow-y: auto; } +.ranking { padding: 0; margin: 0; list-style: none; } +.ranking li { display: flex; gap: 13px; align-items: center; padding: 13px 0; border-bottom: 1px solid #f1f3f4; } +.ranking li:last-child { border: 0; } +.rankNumber { font-size: 11px; color: #8a999f; font-variant-numeric: tabular-nums; } +.rankBody { flex: 1; min-width: 0; } +.rankLabel { display: flex; justify-content: space-between; align-items: baseline; gap: 14px; font-size: 12px; margin-bottom: 7px; } +.rankLabel > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rankLabel strong { white-space: nowrap; font-weight: 600; font-variant-numeric: tabular-nums; } +.rankLabel small { display: inline-block; min-width: 49px; padding-left: 9px; text-align: right; font-size: 10px; color: #8a959b; font-weight: 400; } +.rankTrack { height: 4px; background: #f0f3f4; border-radius: 3px; overflow: hidden; } +.rankTrack > div { height: 100%; background: #7995a1; border-radius: 3px; } +.workspace .tableContent { padding: 0; } +.tableScroll { overflow: auto; max-height: 480px; border-radius: 0 0 10px 10px; } +.tableScroll table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; } +.tableScroll :is(th, td) { text-align: right; padding: 12px 16px; border-bottom: 1px solid #edf0f2; min-width: 90px; } +.tableScroll tr > :first-child { text-align: left; position: sticky; left: 0; min-width: 180px; max-width: 280px; overflow: hidden; text-overflow: ellipsis; background: #fff; border-right: 1px solid #edf0f2; z-index: 1; } +.tableScroll thead th { color: #72818a; background: #f7f9fa; font-size: 11px; font-weight: 500; position: sticky; top: 0; z-index: 2; } +.tableScroll thead th:first-child { z-index: 3; background: #f7f9fa; } +.tableScroll tbody th { font-weight: 500; } +.tableScroll tbody tr:hover > * { background: #f7fafb; } +.tableScroll tfoot { position: sticky; bottom: 0; z-index: 2; } +.tableScroll tfoot :is(th, td) { font-weight: 650; color: #3c535f; background: #f3f6f7; border-top: 1px solid #e0e6e9; border-bottom: 0; } +.totalCell { font-weight: 600; } +.mutedCell { color: #7f8c94; } +.zeroCell { color: #b1bbc1; } +.footnote { display: flex; align-items: flex-start; gap: 6px; font-size: 10px; line-height: 1.8; color: #8b969d; padding: 13px 1px 0; } +.footnote svg { flex-shrink: 0; margin-top: 3px; } +.state { display: flex; align-items: center; flex-direction: column; justify-content: center; gap: 13px; min-height: 330px; padding: 36px 20px; color: #85949c; text-align: center; } +.state strong { font-size: 14px; color: #4a5a63; font-weight: 500; } +.state span { font-size: 12px; max-width: 620px; overflow-wrap: anywhere; } +.srOnly { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } +@media (max-width: 1100px) { .analysis { grid-template-columns: minmax(0, 1.5fr) minmax(260px, 1fr); } .presets { margin-left: 0; } } +@media (max-width: 760px) { .workspace { padding: 16px; } .header h1 { font-size: 19px; } .header { align-items: flex-start; } .header > button { flex-shrink: 0; } .header p { line-height: 1.8; } .analysis { grid-template-columns: minmax(0, 1fr); } .workspace .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } .metrics > article { border-radius: 0 !important; padding: 15px; } .metrics > article:nth-child(3) { border-left: 0; } .metrics > article:nth-child(n+3) { border-top: 1px solid #edf0f2; } .dateSeparator { display: none; } .filters label { max-width: none; min-width: calc(50% - 12px); } .presets { margin-left: auto; } .panelHint { font-size: 9px; white-space: normal; text-align: right; } } diff --git a/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/page.tsx b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/page.tsx new file mode 100644 index 00000000..9a22adb8 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/management/daily-express-volume/page.tsx @@ -0,0 +1,13 @@ +import { redirect } from 'next/navigation' +import { requireSession } from '@/lib/server-session' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' +import { DailyExpressVolumeView } from './DailyExpressVolumeView' + +export const dynamic = 'force-dynamic' + +export default async function DailyExpressVolumePage() { + const { authUser } = await requireSession('/login') + const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'dailyExpressVolume') + if (!access.view) redirect('/supply-chain') + return +} diff --git a/furniture-3d-system/src/lib/daily-express-volume.test.ts b/furniture-3d-system/src/lib/daily-express-volume.test.ts new file mode 100644 index 00000000..825f86b7 --- /dev/null +++ b/furniture-3d-system/src/lib/daily-express-volume.test.ts @@ -0,0 +1,66 @@ +import { + buildDailyExpressVolumeDashboard, + dailyExpressVolumeFiltersSchema, + expressVolumeDefaultRange, + type DailyExpressVolumeBucket, +} from './daily-express-volume' +import { getSupplyChainApiPermissionRequirement, getSupplyChainPermissionTargetForPath } from './supply-chain-permission-paths' +import { filterSupplyChainMenu, flattenSupplyChainMenu } from '@/app/supply-chain/config/supply-chain-menu' + +const filters = { dateFrom: '2026-11-20', dateTo: '2026-11-22', warehouse: '', carrier: '' } +const buckets: DailyExpressVolumeBucket[] = [ + { date: '2026-11-20', carrier: '圆通', warehouse: '睢宁仓', volume: 12 }, + { date: '2026-11-20', carrier: '圆通', warehouse: '新苏北仓', volume: 8 }, + { date: '2026-11-22', carrier: '圆通', warehouse: '睢宁仓', volume: 10 }, + { date: '2026-11-22', carrier: '中通', warehouse: '新苏北仓', volume: 30 }, +] + +describe('每日快递承运量口径', () => { + it('使用北京时间生成跨月默认范围', () => { + expect(expressVolumeDefaultRange(7, new Date('2026-10-31T17:00:00Z'))).toEqual({ dateFrom: '2026-10-26', dateTo: '2026-11-01' }) + }) + + it('拒绝无效日期、反向范围及超过 93 天的范围', () => { + for (const range of [ + { dateFrom: '2026-02-30', dateTo: '2026-03-03' }, + { dateFrom: '2026-11-23', dateTo: '2026-11-22' }, + { dateFrom: '2026-01-01', dateTo: '2026-04-04' }, + ]) expect(dailyExpressVolumeFiltersSchema.safeParse(range).success).toBe(false) + expect(dailyExpressVolumeFiltersSchema.safeParse({ dateFrom: '2026-01-01', dateTo: '2026-04-03' }).success).toBe(true) + }) + + it('补齐零发货日期并使趋势、快递排名和明细合计一致', () => { + const board = buildDailyExpressVolumeDashboard(buckets, filters, '2026-11-23T00:00:00Z') + expect(board.days.map((day) => day.volume)).toEqual([20, 0, 40]) + expect(board.summary).toEqual({ total: 60, dailyAverage: 20, carrierCount: 2, peakDate: '2026-11-22', peakVolume: 40 }) + expect(board.carriers.map((carrier) => carrier.volume)).toEqual([30, 30]) + expect(board.carriers.reduce((sum, carrier) => sum + carrier.share, 0)).toBe(1) + expect(board.carriers.reduce((sum, carrier) => sum + Object.values(carrier.daily).reduce((a, b) => a + b, 0), 0)).toBe(board.summary.total) + }) + + it('精确联动仓库与快递筛选并保留完整筛选选项', () => { + const board = buildDailyExpressVolumeDashboard(buckets, { ...filters, warehouse: '新苏北仓', carrier: '圆通' }, '') + expect(board.summary.total).toBe(8) + expect(board.days.map((day) => day.volume)).toEqual([8, 0, 0]) + expect(board.carriers[0].share).toBe(1) + expect(board.warehouses).toHaveLength(2) + expect(board.carrierOptions).toHaveLength(2) + }) + + it('空数据没有假峰值或无穷占比', () => { + const board = buildDailyExpressVolumeDashboard([], filters, '') + expect(board.summary).toEqual({ total: 0, dailyAverage: 0, carrierCount: 0, peakDate: null, peakVolume: 0 }) + expect(board.carriers).toEqual([]) + expect(board.days).toHaveLength(3) + }) + + it('页面、API 和菜单使用独立权限,其他权限不会暴露入口', () => { + const path = '/supply-chain/management/daily-express-volume' + expect(getSupplyChainPermissionTargetForPath(path)).toBe('dailyExpressVolume') + expect(getSupplyChainApiPermissionRequirement(`/api${path}`, 'GET')).toEqual({ targetKey: 'dailyExpressVolume', action: 'view' }) + expect(flattenSupplyChainMenu(filterSupplyChainMenu(['dailyExpressVolume']))).toEqual([ + expect.objectContaining({ route: path, label: '每日快递承运量看板', module: '经营管理' }), + ]) + expect(flattenSupplyChainMenu(filterSupplyChainMenu(['logisticsArrivalSigningDuration']))).not.toEqual(expect.arrayContaining([expect.objectContaining({ route: path })])) + }) +}) diff --git a/furniture-3d-system/src/lib/daily-express-volume.ts b/furniture-3d-system/src/lib/daily-express-volume.ts new file mode 100644 index 00000000..52532a0c --- /dev/null +++ b/furniture-3d-system/src/lib/daily-express-volume.ts @@ -0,0 +1,81 @@ +import { z } from 'zod' + +const DAY_MS = 86_400_000 +export const DAILY_EXPRESS_VOLUME_MAX_DAYS = 93 + +export function expressVolumeToday(now = new Date()) { + return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).format(now) +} + +export function expressVolumeDateOffset(date: string, days: number) { + return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10) +} + +export function expressVolumeDefaultRange(days = 7, now = new Date()) { + const dateTo = expressVolumeToday(now) + return { dateFrom: expressVolumeDateOffset(dateTo, 1 - days), dateTo } +} + +const dateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, '日期格式应为 YYYY-MM-DD').refine((value) => { + const parsed = Date.parse(`${value}T00:00:00Z`) + return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value +}, '请选择有效日期') + +export const dailyExpressVolumeFiltersSchema = z.object({ + dateFrom: dateSchema, + dateTo: dateSchema, + warehouse: z.string().trim().max(200).default(''), + carrier: z.string().trim().max(200).default(''), +}).superRefine((value, ctx) => { + if (value.dateFrom > value.dateTo) { + ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['dateTo'], message: '结束日期不能早于开始日期' }) + } + if ((Date.parse(value.dateTo) - Date.parse(value.dateFrom)) / DAY_MS >= DAILY_EXPRESS_VOLUME_MAX_DAYS) { + ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['dateTo'], message: `单次最多查询 ${DAILY_EXPRESS_VOLUME_MAX_DAYS} 天` }) + } +}) + +export type DailyExpressVolumeFilters = z.infer +export type DailyExpressVolumeBucket = { date: string; carrier: string; warehouse: string; volume: number } +export type DailyExpressVolumeCarrier = { name: string; volume: number; share: number; daily: Record } +export type DailyExpressVolumeDashboard = { + filters: DailyExpressVolumeFilters + dataAsOf: string + warehouses: string[] + carrierOptions: string[] + days: { date: string; volume: number }[] + carriers: DailyExpressVolumeCarrier[] + summary: { total: number; dailyAverage: number; carrierCount: number; peakDate: string | null; peakVolume: number } +} + +/** Input is already deduplicated by the report query, before any warehouse/carrier filtering. */ +export function buildDailyExpressVolumeDashboard( + buckets: DailyExpressVolumeBucket[], + filters: DailyExpressVolumeFilters, + dataAsOf: string, +): DailyExpressVolumeDashboard { + const dates: string[] = [] + for (let date = filters.dateFrom; date <= filters.dateTo; date = expressVolumeDateOffset(date, 1)) dates.push(date) + const totals = new Map(dates.map((date) => [date, 0])) + const carriers = new Map() + const scoped = buckets.filter((row) => totals.has(row.date)) + const warehouses = [...new Set(scoped.map((row) => row.warehouse))].sort((a, b) => a.localeCompare(b, 'zh-CN')) + const carrierOptions = [...new Set(scoped.map((row) => row.carrier))].sort((a, b) => a.localeCompare(b, 'zh-CN')) + for (const row of scoped) { + if ((filters.warehouse && row.warehouse !== filters.warehouse) || (filters.carrier && row.carrier !== filters.carrier)) continue + const carrier = carriers.get(row.carrier) ?? { name: row.carrier, volume: 0, share: 0, daily: {} } + carrier.volume += row.volume + carrier.daily[row.date] = (carrier.daily[row.date] ?? 0) + row.volume + carriers.set(row.carrier, carrier) + totals.set(row.date, totals.get(row.date)! + row.volume) + } + const days = dates.map((date) => ({ date, volume: totals.get(date)! })) + const total = days.reduce((sum, day) => sum + day.volume, 0) + const ranked = [...carriers.values()].sort((a, b) => b.volume - a.volume || a.name.localeCompare(b.name, 'zh-CN')) + for (const carrier of ranked) carrier.share = total ? carrier.volume / total : 0 + const peak = days.reduce<{ date: string; volume: number } | null>((best, day) => day.volume > (best?.volume ?? 0) ? day : best, null) + return { + filters, dataAsOf, warehouses, carrierOptions, days, carriers: ranked, + summary: { total, dailyAverage: total / dates.length, carrierCount: ranked.length, peakDate: peak?.date ?? null, peakVolume: peak?.volume ?? 0 }, + } +} diff --git a/furniture-3d-system/src/lib/supply-chain-permission-paths.ts b/furniture-3d-system/src/lib/supply-chain-permission-paths.ts index 039e4c2f..79cec763 100644 --- a/furniture-3d-system/src/lib/supply-chain-permission-paths.ts +++ b/furniture-3d-system/src/lib/supply-chain-permission-paths.ts @@ -26,6 +26,7 @@ export function getSupplyChainPermissionTargetForPath(pathname: string): SupplyC if (pathname === '/supply-chain/management/blank-pages/blank-page-2') return 'managementBlankPage2' as const if (pathname === '/supply-chain/management/employee-hours') return 'employeeHours' as const if (pathname === '/supply-chain/management/logistics-arrival-signing-duration') return 'logisticsArrivalSigningDuration' as const + if (pathname === '/supply-chain/management/daily-express-volume') return 'dailyExpressVolume' as const if (pathname === '/supply-chain/management/production-stop-demands') return 'productionStopDemands' as const if (pathname === '/supply-chain/database/product-archive') return 'productArchive' as const if (pathname === '/supply-chain/database/category-config') return 'categoryConfig' as const @@ -110,6 +111,9 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method: } return undefined } + if (pathname === '/api/supply-chain/management/daily-express-volume') { + return { targetKey: 'dailyExpressVolume' as const, action } + } if (pathname.startsWith('/api/supply-chain/management/logistics-arrival-signing-duration')) { if (pathname.endsWith('/export')) { // 导出独立校验下载权限。 diff --git a/furniture-3d-system/src/lib/supply-chain-permission-targets.ts b/furniture-3d-system/src/lib/supply-chain-permission-targets.ts index e327a0b0..c9988638 100644 --- a/furniture-3d-system/src/lib/supply-chain-permission-targets.ts +++ b/furniture-3d-system/src/lib/supply-chain-permission-targets.ts @@ -34,6 +34,7 @@ export type SupplyChainPermissionTargetKey = | 'frontWarehouseInventory' | 'productionStopDemands' | 'logisticsArrivalSigningDuration' + | 'dailyExpressVolume' | 'managementBlankPage1' | 'managementBlankPage2' | 'finishedProductProgress' @@ -114,6 +115,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [ { key: 'clearanceReview', label: '清货管理 · 经管审核', description: '审核、驳回和调整清货任务,查看清货复盘' }, { key: 'productionStopDemands', label: '停产需求管理', description: '停产需求提单与处理' }, { key: 'logisticsArrivalSigningDuration', label: '物流到货签收时长看板', description: '物流签收查询与明细导出' }, + { key: 'dailyExpressVolume', label: '每日快递承运量看板', description: '按发货日期查看每日运单量、快递占比与仓库分布' }, { key: 'managementBlankPage1', label: '空白页 1', description: '经营管理空白页 1' }, { key: 'managementBlankPage2', label: '空白页 2', description: '经营管理空白页 2' }, { key: 'finishedProductProgress', label: '成品进度明细', description: '成品进度查看、导出与维护' }, @@ -192,6 +194,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGET_ROUTES: Partial< frontWarehouseInventory: '/supply-chain/management/front-warehouse-inventory', productionStopDemands: '/supply-chain/management/production-stop-demands', logisticsArrivalSigningDuration: '/supply-chain/management/logistics-arrival-signing-duration', + dailyExpressVolume: '/supply-chain/management/daily-express-volume', managementBlankPage1: '/supply-chain/management/blank-pages/blank-page-1', managementBlankPage2: '/supply-chain/management/blank-pages/blank-page-2', finishedProductProgress: '/supply-chain/purchase/finished-product-progress', diff --git a/furniture-3d-system/src/server/repositories/daily-express-volume.repository.ts b/furniture-3d-system/src/server/repositories/daily-express-volume.repository.ts new file mode 100644 index 00000000..478878a4 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/daily-express-volume.repository.ts @@ -0,0 +1,74 @@ +import sql from 'mssql' +import type { DailyExpressVolumeBucket } from '@/lib/daily-express-volume' + +type ReportGlobal = typeof globalThis & { dailyExpressVolumePool?: sql.ConnectionPool } + +function requiredEnv(name: string) { + const value = process.env[name]?.trim() + if (!value) throw new Error(`Missing required environment variable: ${name}`) + return value +} + +function boolEnv(name: string, defaultValue: boolean) { + const value = process.env[name]?.trim().toLowerCase() + return value ? value === 'true' || value === '1' : defaultValue +} + +function reportPool() { + const shared = globalThis as ReportGlobal + if (!shared.dailyExpressVolumePool) { + shared.dailyExpressVolumePool = new sql.ConnectionPool({ + server: requiredEnv('JST_REPORT_DB_HOST'), + port: Number(process.env.JST_REPORT_DB_PORT?.trim() || '1433'), + database: requiredEnv('JST_REPORT_DB_NAME'), + user: requiredEnv('JST_REPORT_DB_USER'), + password: requiredEnv('JST_REPORT_DB_PASSWORD'), + options: { + encrypt: boolEnv('JST_REPORT_DB_ENCRYPT', true), + trustServerCertificate: boolEnv('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE', true), + readOnlyIntent: true, + appName: 'furniture-daily-express-volume-readonly', + }, + pool: { min: 0, max: 2, idleTimeoutMillis: 60_000 }, + connectionTimeout: 20_000, + requestTimeout: 120_000, + }) + } + return shared.dailyExpressVolumePool +} + +export class DailyExpressVolumeRepository { + async listDailyBuckets(dateFrom: string, dateTo: string): Promise { + const schema = process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt' + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) throw new Error('JST_REPORT_DB_SCHEMA is not a valid SQL identifier') + const pool = await reportPool().connect() + const request = pool.request() + request.input('dateFrom', sql.VarChar(10), dateFrom) + request.input('dateTo', sql.VarChar(10), dateTo) + // One waybill can appear in multiple order rows. Count it once per carrier, + // assigning it to its earliest dispatch in the requested interval. Keep all + // shipment statuses: signed-only data would omit today's in-transit volume. + const result = await request.query<{ date: string; carrier: string; warehouse: string; volume: string | number }>(` + WITH normalized AS ( + SELECT e.[send_time], + COALESCE(NULLIF(LTRIM(RTRIM(e.[logistic_company_name])), N''), N'未标注快递') AS carrier, + COALESCE(NULLIF(LTRIM(RTRIM(e.[warehouse_name])), N''), N'未标注仓库') AS warehouse, + LTRIM(RTRIM(e.[logistic_id])) AS waybill + FROM [${schema}].[jst_order_express_details] AS e + WHERE e.[send_time] >= CONVERT(datetime2, @dateFrom, 23) + AND e.[send_time] < DATEADD(day, 1, CONVERT(datetime2, @dateTo, 23)) + AND NULLIF(LTRIM(RTRIM(e.[logistic_id])), N'') IS NOT NULL + ), deduplicated AS ( + SELECT [send_time], carrier, warehouse, + ROW_NUMBER() OVER (PARTITION BY carrier, waybill ORDER BY [send_time], warehouse) AS row_number + FROM normalized + ) + SELECT CONVERT(varchar(10), [send_time], 23) AS [date], carrier, warehouse, COUNT_BIG(*) AS volume + FROM deduplicated WHERE row_number = 1 + GROUP BY CONVERT(varchar(10), [send_time], 23), carrier, warehouse + `) + return result.recordset.map((row) => ({ ...row, volume: Number(row.volume) })) + } +} + +export const dailyExpressVolumeRepository = new DailyExpressVolumeRepository() diff --git a/furniture-3d-system/src/server/services/__tests__/daily-express-volume.service.test.ts b/furniture-3d-system/src/server/services/__tests__/daily-express-volume.service.test.ts new file mode 100644 index 00000000..22fc0c61 --- /dev/null +++ b/furniture-3d-system/src/server/services/__tests__/daily-express-volume.service.test.ts @@ -0,0 +1,48 @@ +/** @jest-environment node */ +import { DailyExpressVolumeService } from '../daily-express-volume.service' +import { dailyExpressVolumeRepository } from '@/server/repositories/daily-express-volume.repository' +import { supplyChainPermissionSettingsService } from '../supply-chain-permission-settings.service' +import type { AuthUser } from '@/server/core/types' + +jest.mock('@/server/repositories/daily-express-volume.repository', () => ({ dailyExpressVolumeRepository: { listDailyBuckets: jest.fn() } })) +jest.mock('../supply-chain-permission-settings.service', () => ({ supplyChainPermissionSettingsService: { getUserAccess: jest.fn() } })) + +const list = jest.mocked(dailyExpressVolumeRepository.listDailyBuckets) +const access = jest.mocked(supplyChainPermissionSettingsService.getUserAccess) +const user = { id: 'test', role: 'USER' } as AuthUser +const service = new DailyExpressVolumeService() + +beforeEach(() => { jest.clearAllMocks(); access.mockResolvedValue({ view: true, edit: false, download: false }) }) + +it('没有权限时不访问报表源,即便其他用户已经查询', async () => { + const input = { dateFrom: '2026-11-01', dateTo: '2026-11-02' } + list.mockResolvedValue([]) + await service.getDashboard(input, user) + list.mockClear() + access.mockResolvedValue({ view: false, edit: false, download: false }) + await expect(service.getDashboard(input, user)).rejects.toThrow('没有每日快递承运量看板查看权限') + expect(list).not.toHaveBeenCalled() +}) + +it('拒绝无效筛选,不发起全表查询', async () => { + await expect(service.getDashboard({ dateFrom: '', dateTo: '' }, user)).rejects.toThrow() + expect(list).not.toHaveBeenCalled() +}) + +it('相同日期的并发查询共享一次读取,随后仓库筛选复用聚合源', async () => { + const input = { dateFrom: '2026-11-03', dateTo: '2026-11-04' } + list.mockResolvedValue([{ date: '2026-11-03', warehouse: '睢宁仓', carrier: '圆通', volume: 5 }]) + const [first, second] = await Promise.all([service.getDashboard(input, user), service.getDashboard(input, user)]) + expect(first.summary.total).toBe(5) + expect(second).toEqual(first) + expect((await service.getDashboard({ ...input, warehouse: '其他仓' }, user)).summary.total).toBe(0) + expect(list).toHaveBeenCalledTimes(1) +}) + +it('源失败不伪造零数据、不缓存失败,允许重试', async () => { + const input = { dateFrom: '2026-11-05', dateTo: '2026-11-06' } + list.mockRejectedValueOnce(new Error('报表连接失败')).mockResolvedValueOnce([]) + await expect(service.getDashboard(input, user)).rejects.toThrow('报表连接失败') + expect((await service.getDashboard(input, user)).summary.total).toBe(0) + expect(list).toHaveBeenCalledTimes(2) +}) diff --git a/furniture-3d-system/src/server/services/daily-express-volume.service.ts b/furniture-3d-system/src/server/services/daily-express-volume.service.ts new file mode 100644 index 00000000..f6d8d7a0 --- /dev/null +++ b/furniture-3d-system/src/server/services/daily-express-volume.service.ts @@ -0,0 +1,43 @@ +import { + buildDailyExpressVolumeDashboard, + dailyExpressVolumeFiltersSchema, + type DailyExpressVolumeBucket, +} from '@/lib/daily-express-volume' +import type { AuthUser } from '@/server/core/types' +import { AppError, ErrorCode } from '@/server/core/errors' +import { dailyExpressVolumeRepository } from '@/server/repositories/daily-express-volume.repository' +import { supplyChainPermissionSettingsService } from './supply-chain-permission-settings.service' + +type SourceData = { buckets: DailyExpressVolumeBucket[]; dataAsOf: string } +const cache = new Map() +const inFlight = new Map>() + +export class DailyExpressVolumeService { + async getDashboard(input: unknown, user: AuthUser) { + const access = await supplyChainPermissionSettingsService.getUserAccess(user, 'dailyExpressVolume') + if (!access.view) throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '没有每日快递承运量看板查看权限') + const parsed = dailyExpressVolumeFiltersSchema.safeParse(input) + if (!parsed.success) throw new AppError(ErrorCode.VALIDATION_FAILED, parsed.error.issues[0]?.message ?? '筛选条件无效') + const filters = parsed.data + const key = `${filters.dateFrom}:${filters.dateTo}` + const cached = cache.get(key) + let source = cached && cached.expiresAt > Date.now() ? cached.data : undefined + if (!source) { + let pending = inFlight.get(key) + if (!pending) { + pending = dailyExpressVolumeRepository.listDailyBuckets(filters.dateFrom, filters.dateTo).then((buckets) => { + const data = { buckets, dataAsOf: new Date().toISOString() } + cache.delete(key) + cache.set(key, { data, expiresAt: Date.now() + 60_000 }) + while (cache.size > 20) cache.delete(cache.keys().next().value!) + return data + }).finally(() => inFlight.delete(key)) + inFlight.set(key, pending) + } + source = await pending + } + return buildDailyExpressVolumeDashboard(source.buckets, filters, source.dataAsOf) + } +} + +export const dailyExpressVolumeService = new DailyExpressVolumeService() From 9ac355948753fa4a19157944cca00c2c62a712b9 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Wed, 25 Nov 2026 17:31:24 +0800 Subject: [PATCH 04/16] fix(estimator): preserve explicit bookshelf side notches --- .../__tests__/cabinet-workflow.test.ts | 72 +++++++++++++++++++ .../standard/bookshelf-learning.ts | 3 + .../standard/cabinet-contracts.ts | 2 + .../standard/cabinet-model.ts | 4 +- .../standard/cabinet-side-notches.ts | 57 +++++++++++++++ .../standard/recognition.ts | 31 ++++++-- .../cabinet-recognition-prompt.ts | 3 + 7 files changed, 165 insertions(+), 7 deletions(-) create mode 100644 furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts diff --git a/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts b/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts index ddae4111..c7408e16 100644 --- a/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts +++ b/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts @@ -12,6 +12,10 @@ import { completeStandardCosts } from '../standard/cabinet-costs' import { samplingDocumentHtml } from '../standard/cabinet-drawing' import { matchCabinetMaterial, quotaHardware, quotaLabor,quotaConsumableOptions } from '../standard/cabinet-quota' import { applyStandardRecognition } from '../standard/recognition' +import { isKnownStructureCorrection } from '../standard/bookshelf-learning' +import { sideProfile } from '../standard/cabinet-sampling-geometry' +import { recognizeStandardImage } from '@/app/reference-estimator/standard/recognize-image' +import { recordModelTurn } from '@/app/reference-estimator/standard/model-conversation-actions' import JSZip from 'jszip' import { parseReferenceImageEstimateResult } from '@/server/services/reference-image-estimate/reference-image-estimate-contracts' import { buildReferenceImageEstimatePrompt } from '@/server/services/reference-image-estimate/reference-image-estimate-prompt' @@ -19,6 +23,74 @@ import fs from 'node:fs' import path from 'node:path' const input=()=>cabinetInputSchema.parse({referenceCase:'6G-960-B',name:'六格书柜',grade:'E1级',material:'生态板',topColor:'经典北美黑胡桃色',bodyColor:'荷花白色'}) +const notchNote = '给 02、04 号旁板各在后下角开一个深 15、高 120 mm 的圆角缺口,贯穿板厚,09 不动。' +const ordinaryBookcase = (depth = 300) => applyStandardRecognition(newStandardDocument(), + parseReferenceImageEstimateResult(JSON.stringify({ + recognition:{classification:{materialType:'板式',primaryCategory:'柜类',secondaryCategory:'书柜',placement:'落地'}, + hasDoors:false,hasDrawers:false}, + cabinet:{...input(),referenceCase:null,width:960,depth,height:725,columns:3,rows:2,thickness:15, + hasFrontKick:true,kickHeight:60,hasRearRail:false,hasBackPanel:false}, + }))) + +describe('ordinary bookcase side notches', () => { + test('the model conversation cuts only 02 and 04, then keeps the cut after saving and rebuilding', async () => { + const before = ordinaryBookcase() + const model = before.standardTemplate!.cabinet! + const data = await recognizeStandardImage(before, notchNote) + const {next,turn} = recordModelTurn(before,notchNote,data,{rules:[],correctionNote:notchNote}) + expect(turn.outcome).toBe('updated') + expect(turn.appliedChanges?.join(' ')).toContain('缺口有调整') + const updated = next.standardTemplate!.cabinet! + const notch = {depth:15,height:120,radius:15} + expect(updated.parts).toEqual(model.parts.map(part => + ['02','04'].includes(part.code) ? {...part,notch} : part)) + expect(updated.parts.find(part=>part.code==='09')).toMatchObject({size:[930,15,60],notch:null}) + expect(updated.connections).toEqual(model.connections) + expect(next.standardTemplate!.bookshelfMemory?.case).toBeUndefined() + const saved = estimateDocumentSchema.parse(JSON.parse(JSON.stringify(next))) + const rebuilt = applyCabinetWorkflow(saved,{...saved.standardTemplate!.cabinet!.input,bodyColor:'新花色'}) + const side = rebuilt.standardTemplate!.cabinet!.parts.find(part=>part.code==='02')! + expect(side).toMatchObject({size:[15,300,710],notch,color:'新花色'}) + expect(sideProfile(side.width,side.length,side.notch)).toEqual( + expect.arrayContaining([[285,0],[300,120]])) + }) + + test('a later single-side adjustment preserves the other side and applies other fields in the same turn', async () => { + const before = ordinaryBookcase(380) + const first = await recognizeStandardImage(before, notchNote) + const updated = applyStandardRecognition(before,first,{rules:[],correctionNote:notchNote}) + const correctionNote = '02 号旁板后下角的圆角缺口调整为深 20、高 90 mm,R5,柜身改成白橡木色。' + expect(isKnownStructureCorrection(correctionNote)).toBe(false) + const data=parseReferenceImageEstimateResult(JSON.stringify({ + recognition:{hasDoors:false,hasDrawers:false}, + cabinetCorrection:{sideNotches:{'02':{depth:20,height:90,radius:5}},bodyColor:'白橡木色'}, + })) + const next=applyStandardRecognition(updated,data,{rules:[],correctionNote}) + const model=next.standardTemplate!.cabinet! + expect(model.parts.find(part=>part.code==='02')).toMatchObject({ + width:380,color:'白橡木色',notch:{depth:20,height:90,radius:5}, + }) + expect(model.parts.find(part=>part.code==='04')?.notch).toEqual({depth:15,height:120,radius:15}) + expect(next.standardTemplate!.bookshelfMemory?.case?.changes).not.toHaveProperty('sideNotches') + }) + + test('keeps original sample behavior and rejects edits to 09 or cuts larger than a side panel', async () => { + expect(buildCabinetModel(input()).parts.find(part=>part.code==='02')?.notch) + .toEqual({depth:15,height:120,radius:15}) + const before = ordinaryBookcase() + expect(isKnownStructureCorrection(notchNote.replace('02、04','09'))).toBe(false) + expect(parseReferenceImageEstimateResult(JSON.stringify({boardPieces:[],cabinetCorrection:{ + sideNotches:{'09':{depth:15,height:120}}, + }})).cabinetCorrection).toBeUndefined() + const correctionNote=notchNote.replace('深 15','深 300') + const data=await recognizeStandardImage(before,correctionNote) + const {next,turn}=recordModelTurn(before,correctionNote,data,{rules:[],correctionNote}) + expect(turn.outcome).toBe('failed') + expect(turn.reply).toContain('板件进深') + expect(next.standardTemplate!.cabinet).toBe(before.standardTemplate!.cabinet) + }) +}) + describe('cabinet standard v0.24 shared model workflow',()=>{ test('reproduces the supplied six-grid drawing without using the historical cabinet algorithm',()=>{ const m=buildCabinetModel(input()) diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts b/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts index a22a5773..f4a4d7f7 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import type { SkillRecognition } from '../skill-routing' import { cabinetInputSchema, slottedBookcaseBack, type CabinetInput } from './cabinet-contracts' import { imageObservationSchema } from './cabinet-image-memory' +import { readSideNotchCommand } from './cabinet-side-notches' export const bookshelfCategory = 'bookshelf' as const export const bookcaseCategory = 'bookcase' as const @@ -34,6 +35,7 @@ export const cabinetCorrectionSchema = z.object({ screwCode:input.screwCode.removeDefault(), clipCode:input.clipCode.removeDefault(), drillFeet:input.drillFeet.removeDefault(), packingLabor:input.packingLabor.removeDefault(), hasFrontKick:input.hasFrontKick, hasRearRail:input.hasRearRail, bodyHeight:input.bodyHeight, + sideNotches:input.sideNotches, backPanelCount:input.backPanelCount, backPanelSplit:input.backPanelSplit, hasUnplacedPullRail:input.hasUnplacedPullRail, hasLegs:input.hasLegs, legHeight:input.legHeight, legCount:input.legCount, legShape:input.legShape, legPlacement:input.legPlacement, legInsetX:input.legInsetX, legInsetY:input.legInsetY, legSize:input.legSize, rearPullRail:input.rearPullRail, @@ -148,6 +150,7 @@ const hasSlottedBackNote = (note:string) => simpleBackAssembly.test(note) || backAssemblyNote.test(note) && !/(?:不是|不加|不用|不要|去掉)/.test(note) export function isKnownStructureCorrection(note:string) { + if(readSideNotchCommand(note))return true const items=normalizedCorrections(note) return items.length>0 && items.every(part=>addMissingLegs.test(part)||simpleBackAssembly.test(part)||addMissingBack.test(part)) } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts index c1487739..193f8dba 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts @@ -3,6 +3,7 @@ import { cadCylinderSchema, cylinderFrame } from './cad-geometry' import { cadOutputSchema, cadSolidSchema } from './cad-solid-contract' import { cabinetSupportRuleSchema, cabinetSupportsSchema, supportShapeSchema, supportSizeSchema } from './cabinet-supports' import { boardProfileSchema, boardRoleSchema, imageAssemblySchema } from './cabinet-image-contract' +import { sideNotchesSchema } from './cabinet-side-notches' const mm=z.number().finite().positive().max(10000) export const slottedBookcaseBack = '一块后拉板分隔两片槽装三合板' as const @@ -21,6 +22,7 @@ export const cabinetInputSchema=z.object({ width:mm.nullable().default(null),depth:mm.nullable().default(null),height:mm.nullable().default(null), columns:z.number().int().min(1).max(12).nullable().default(null),rows:z.number().int().min(1).max(12).nullable().default(null), hasFrontKick:z.boolean().nullish(),hasRearRail:z.boolean().nullish(), + sideNotches:sideNotchesSchema.optional(), backPanelCount:z.number().int().min(1).max(12).nullish(), backPanelSplit:z.enum(['上下', '左右']).nullish(), hasUnplacedPullRail:z.boolean().nullish(), diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts index 7eba1f35..720477c1 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts @@ -4,6 +4,7 @@ import { matchCabinetMaterial } from './cabinet-quota' import { selectedCabinetPartMaterial } from './cabinet-material-selection' import { bookcaseEnvelope, bookcasePreviewParts } from './bookcase-preview' import { buildImageCabinet } from './cabinet-image-model' +import { resolveSideNotch } from './cabinet-side-notches' import type { EstimateDocument } from '../contracts' export function resolveCabinetInput(raw:CabinetInput):CabinetInput { @@ -104,7 +105,8 @@ export function buildCabinetModel(raw:CabinetInput,materials?:Pick[x,y,z+lift]):positions,material,color,grooveMeters,notch}) } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts new file mode 100644 index 00000000..896b9754 --- /dev/null +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts @@ -0,0 +1,57 @@ +import { z } from 'zod' + +const mm = z.number().finite().positive().max(10000) +const sideNotchSchema = z.object({ depth: mm, height: mm, radius: mm.optional() }).strict() + .refine(value => value.radius == null || value.radius <= Math.min(value.depth, value.height), { + message: '圆角半径不能大于缺口的深度或高度。', + }) + +export const sideNotchesSchema = z.object({ + '02': sideNotchSchema.optional(), + '04': sideNotchSchema.optional(), +}).strict().refine(value => Boolean(value['02'] || value['04']), { message: '请指定 02 或 04 号旁板。' }) + +type SideNotches = z.infer + +export function resolveSideNotch(notches: SideNotches | undefined, code: string, depth: number, height: number) { + const notch = code === '02' || code === '04' ? notches?.[code] : undefined + if (!notch) return undefined + if (notch.depth >= depth || notch.height >= height) { + throw new Error(code + ' 号旁板的缺口深度和高度必须小于板件进深和高度。') + } + // Use the largest inside radius that fits when the user only specifies a rounded corner. + return { ...notch, radius: notch.radius ?? Math.min(notch.depth, notch.height) } +} + +const target = String.raw`(?:02(?:号)?(?:左)?|04(?:号)?(?:右)?)(?:旁板|侧板)?` +const command = new RegExp(String.raw`^(?:请)?(?:给|将|把)?(?${target}(?:[、,/和及与]${target})?)(?:各|两块|分别)?,?(?:在)?(?:后下角|后底角)开(?:一个|一处)?(?.+)$`) +const length = String.raw`(-?\d+(?:\.\d+)?)(mm|cm|毫米|厘米)?` +const size = String.raw`深(?:度)?[::为]?${length}[、,,]?(?:高|高度)[::为]?${length}` +const cut = '(?:圆角)?(?:踢脚线)?缺口' +const suffix = String.raw`(?:[,、]?(?:做成)?圆角)?(?:[,、]?(?:圆角半径|内圆角|R)[::=为]?${length})?$` +const sizeFirst = new RegExp('^' + size + '(?:的)?' + cut + suffix, 'i') +const cutFirst = new RegExp('^' + cut + '[,::]?' + size + suffix, 'i') +const inMm = (amount: string, unit?: string) => Number(amount) * (/^(cm|厘米)$/i.test(unit ?? '') ? 10 : 1) + +// Match a complete text instruction. Extra requests go through normal recognition. +export function readSideNotchCommand(note: string): SideNotches | undefined { + const text = note.normalize('NFKC').replace(/\s/g, '').replace(/[。;;]/g, ',') + .replace(/[,!]+$/, '') + .replace(/,(?:另外,?)?09(?:号)?(?:前)?(?:踢脚板|踢脚线)?(?:保持原样|不动|不改)$/, '') + .replace(/,(?:贯穿|贯通)(?:整个)?板厚$/, '') + const matched = command.exec(text)?.groups + if (!matched) return undefined + const sizeMatch = sizeFirst.exec(matched.spec) ?? cutFirst.exec(matched.spec) + if (!sizeMatch) return undefined + const [, depth, depthUnit, height, heightUnit, radius, radiusUnit] = sizeMatch + if (!matched.spec.includes('圆角') && radius == null) return undefined + const value = { + depth: inMm(depth, depthUnit ?? heightUnit), + height: inMm(height, heightUnit), + ...(radius == null ? {} : { radius: inMm(radius, radiusUnit) }), + } + return { + ...(matched.targets.includes('02') ? { '02': value } : {}), + ...(matched.targets.includes('04') ? { '04': value } : {}), + } +} diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts b/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts index 53bfa436..fd4e4049 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts @@ -19,6 +19,7 @@ import { import type { CabinetInput } from './cabinet-contracts' import { bookcaseEnvelope } from './bookcase-preview' import { applyImageAssembly } from './cabinet-image-workflow' +import { readSideNotchCommand } from './cabinet-side-notches' type RecognitionOptions = { rules: SharedBookshelfRule[]; correctionNote?: string; rulesUnavailable?: boolean } @@ -36,16 +37,29 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag options?:RecognitionOptions):EstimateDocument { const prior=document.standardTemplate?.cabinet?.input const correctionNote=options?.correctionNote + const ordinaryCorrection=correctionNote && prior && !prior.imageAssembly + const explicitNotches=ordinaryCorrection ? readSideNotchCommand(correctionNote) : undefined + const sideNotches=ordinaryCorrection ? explicitNotches ?? result.cabinetCorrection?.sideNotches : undefined + // An explicit text command also works when an earlier turn included attachments. + if(sideNotches && prior && (explicitNotches || + Object.keys(result.cabinetCorrection??{}).every(key=>key==='sideNotches'))) { + const standard=document.standardTemplate! + const memory=standard.bookshelfMemory + return applyCabinetWorkflow({...document,standardTemplate:{...standard, + bookshelfMemory:memory?{...memory,case:undefined}:undefined}}, { + ...prior,sideNotches:{...prior.sideNotches,...sideNotches}, + }) + } if (result.draftIssue && prior && document.standardTemplate?.bookshelfMemory?.reviewedImageUrl === document.imageUrl) { return document } - if((prior?.imageAssembly && correctionNote) || (result.imageAssembly && !result.cabinet?.referenceCase)) { + if((prior?.imageAssembly && correctionNote) || (!sideNotches && result.imageAssembly && !result.cabinet?.referenceCase)) { const next=applyImageAssembly(document,result,correctionNote) if(next)return next } const explicit=explicitBookshelfCorrections(correctionNote??document.imageNote) const changes:CabinetCorrection=Object.fromEntries(Object.entries({ - ...(correctionNote?result.cabinetCorrection:{}),...explicit, + ...(correctionNote?result.cabinetCorrection:{}),...explicit,sideNotches, }).filter(([,value])=>value!=null && value!=='')) if(changes.kickHeight === 0) changes.hasFrontKick=false if(changes.railHeight === 0) changes.hasRearRail=false @@ -59,7 +73,8 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag const recognizedRoute=correctingPrior&&document.skillRouting?document.skillRouting:result.skillRouting if(correctingPrior&&(result.skillRouting.hasDoors===true||result.skillRouting.hasDrawers===true)) throw new Error('门和抽屉的结构暂未接入,保留当前模型。') - const recognized={...base,...changes} + const recognized={...base,...changes, + ...(sideNotches?{sideNotches:{...base.sideNotches,...sideNotches}}:{})} if(recognized.hasLegs==null && (recognized.legSupports || recognized.legSupportRule))recognized.hasLegs=true if(correctionNote && changes.hasLegs===true && recognized.legHeight==null && result.cabinet?.legHeight!=null && (recognized.bodyHeight==null || recognized.height===recognized.bodyHeight)) { @@ -144,12 +159,16 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag const model=next.standardTemplate!.cabinet! const scope=learn?bookshelfScope(model.input):null const appliedChanges=Object.fromEntries(Object.entries(changes) - .filter(([key,value])=>sameCorrectionValue(model.input[key as keyof CabinetInput],value))) + .filter(([key,value])=>key==='sideNotches' + ? Object.entries(sideNotches??{}).every(([code,notch])=> + sameCorrectionValue(model.input.sideNotches?.[code as '02'|'04'],notch)) + : sameCorrectionValue(model.input[key as keyof CabinetInput],value))) if(correctionNote&&Object.keys(changes).length&&!Object.keys(appliedChanges).length) throw new Error('补充内容与现有结构或所选板材不一致,请核对后重试。') - if(correctionNote&&memory&&scope&&Object.keys(appliedChanges).length){ + const {sideNotches: _oneOff, ...learnableChanges}=appliedChanges + if(correctionNote&&memory&&scope&&Object.keys(learnableChanges).length){ next.standardTemplate!.bookshelfMemory={...memory,case:{ - scope,changes:appliedChanges,autoPublish:automaticBookshelfRules(correctionNote,appliedChanges,scope), + scope,changes:learnableChanges,autoPublish:automaticBookshelfRules(correctionNote,learnableChanges,scope), }} } if(correctionNote){ diff --git a/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts b/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts index 7d62c9f8..11ee7ad5 100644 --- a/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts +++ b/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts @@ -23,6 +23,9 @@ export function cabinetRecognitionPrompt(p:Omit part.code === '02' && part.name === '左旁板') ? [ + '对于已有普通公式书柜,当用户明确要求 02 左旁板和/或 04 右旁板后下角开贯穿板厚的圆角缺口,在 cabinetCorrection.sideNotches 下用对应板号作为键,每块填 {depth, height, radius?},单位 mm。只返回指定旁板;半径未给可省略。09 是前踢脚板;不要当作开缺口的目标。前角、非贯穿或未明确部件及深高时先核对。该修改只对本款生效,无需 imageAssemblyEdit,也不要重新生成 imageAssembly。', + ] : []), ...imageAssemblyInstructions(p), `本轮纠正(产品说明):${JSON.stringify(p.correctionNote??'')}`, ...(p.currentModelParts ? [ From f6bdce53b4155274da27523d546431cdd0714eb7 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Wed, 25 Nov 2026 17:31:24 +0800 Subject: [PATCH 05/16] fix(estimator): preserve explicit bookshelf side notches --- .../__tests__/cabinet-workflow.test.ts | 72 +++++++++++++++++++ .../standard/bookshelf-learning.ts | 3 + .../standard/cabinet-contracts.ts | 2 + .../standard/cabinet-model.ts | 4 +- .../standard/cabinet-side-notches.ts | 57 +++++++++++++++ .../standard/recognition.ts | 31 ++++++-- .../cabinet-recognition-prompt.ts | 3 + 7 files changed, 165 insertions(+), 7 deletions(-) create mode 100644 furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts diff --git a/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts b/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts index ddae4111..c7408e16 100644 --- a/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts +++ b/furniture-3d-system/src/lib/reference-estimator/__tests__/cabinet-workflow.test.ts @@ -12,6 +12,10 @@ import { completeStandardCosts } from '../standard/cabinet-costs' import { samplingDocumentHtml } from '../standard/cabinet-drawing' import { matchCabinetMaterial, quotaHardware, quotaLabor,quotaConsumableOptions } from '../standard/cabinet-quota' import { applyStandardRecognition } from '../standard/recognition' +import { isKnownStructureCorrection } from '../standard/bookshelf-learning' +import { sideProfile } from '../standard/cabinet-sampling-geometry' +import { recognizeStandardImage } from '@/app/reference-estimator/standard/recognize-image' +import { recordModelTurn } from '@/app/reference-estimator/standard/model-conversation-actions' import JSZip from 'jszip' import { parseReferenceImageEstimateResult } from '@/server/services/reference-image-estimate/reference-image-estimate-contracts' import { buildReferenceImageEstimatePrompt } from '@/server/services/reference-image-estimate/reference-image-estimate-prompt' @@ -19,6 +23,74 @@ import fs from 'node:fs' import path from 'node:path' const input=()=>cabinetInputSchema.parse({referenceCase:'6G-960-B',name:'六格书柜',grade:'E1级',material:'生态板',topColor:'经典北美黑胡桃色',bodyColor:'荷花白色'}) +const notchNote = '给 02、04 号旁板各在后下角开一个深 15、高 120 mm 的圆角缺口,贯穿板厚,09 不动。' +const ordinaryBookcase = (depth = 300) => applyStandardRecognition(newStandardDocument(), + parseReferenceImageEstimateResult(JSON.stringify({ + recognition:{classification:{materialType:'板式',primaryCategory:'柜类',secondaryCategory:'书柜',placement:'落地'}, + hasDoors:false,hasDrawers:false}, + cabinet:{...input(),referenceCase:null,width:960,depth,height:725,columns:3,rows:2,thickness:15, + hasFrontKick:true,kickHeight:60,hasRearRail:false,hasBackPanel:false}, + }))) + +describe('ordinary bookcase side notches', () => { + test('the model conversation cuts only 02 and 04, then keeps the cut after saving and rebuilding', async () => { + const before = ordinaryBookcase() + const model = before.standardTemplate!.cabinet! + const data = await recognizeStandardImage(before, notchNote) + const {next,turn} = recordModelTurn(before,notchNote,data,{rules:[],correctionNote:notchNote}) + expect(turn.outcome).toBe('updated') + expect(turn.appliedChanges?.join(' ')).toContain('缺口有调整') + const updated = next.standardTemplate!.cabinet! + const notch = {depth:15,height:120,radius:15} + expect(updated.parts).toEqual(model.parts.map(part => + ['02','04'].includes(part.code) ? {...part,notch} : part)) + expect(updated.parts.find(part=>part.code==='09')).toMatchObject({size:[930,15,60],notch:null}) + expect(updated.connections).toEqual(model.connections) + expect(next.standardTemplate!.bookshelfMemory?.case).toBeUndefined() + const saved = estimateDocumentSchema.parse(JSON.parse(JSON.stringify(next))) + const rebuilt = applyCabinetWorkflow(saved,{...saved.standardTemplate!.cabinet!.input,bodyColor:'新花色'}) + const side = rebuilt.standardTemplate!.cabinet!.parts.find(part=>part.code==='02')! + expect(side).toMatchObject({size:[15,300,710],notch,color:'新花色'}) + expect(sideProfile(side.width,side.length,side.notch)).toEqual( + expect.arrayContaining([[285,0],[300,120]])) + }) + + test('a later single-side adjustment preserves the other side and applies other fields in the same turn', async () => { + const before = ordinaryBookcase(380) + const first = await recognizeStandardImage(before, notchNote) + const updated = applyStandardRecognition(before,first,{rules:[],correctionNote:notchNote}) + const correctionNote = '02 号旁板后下角的圆角缺口调整为深 20、高 90 mm,R5,柜身改成白橡木色。' + expect(isKnownStructureCorrection(correctionNote)).toBe(false) + const data=parseReferenceImageEstimateResult(JSON.stringify({ + recognition:{hasDoors:false,hasDrawers:false}, + cabinetCorrection:{sideNotches:{'02':{depth:20,height:90,radius:5}},bodyColor:'白橡木色'}, + })) + const next=applyStandardRecognition(updated,data,{rules:[],correctionNote}) + const model=next.standardTemplate!.cabinet! + expect(model.parts.find(part=>part.code==='02')).toMatchObject({ + width:380,color:'白橡木色',notch:{depth:20,height:90,radius:5}, + }) + expect(model.parts.find(part=>part.code==='04')?.notch).toEqual({depth:15,height:120,radius:15}) + expect(next.standardTemplate!.bookshelfMemory?.case?.changes).not.toHaveProperty('sideNotches') + }) + + test('keeps original sample behavior and rejects edits to 09 or cuts larger than a side panel', async () => { + expect(buildCabinetModel(input()).parts.find(part=>part.code==='02')?.notch) + .toEqual({depth:15,height:120,radius:15}) + const before = ordinaryBookcase() + expect(isKnownStructureCorrection(notchNote.replace('02、04','09'))).toBe(false) + expect(parseReferenceImageEstimateResult(JSON.stringify({boardPieces:[],cabinetCorrection:{ + sideNotches:{'09':{depth:15,height:120}}, + }})).cabinetCorrection).toBeUndefined() + const correctionNote=notchNote.replace('深 15','深 300') + const data=await recognizeStandardImage(before,correctionNote) + const {next,turn}=recordModelTurn(before,correctionNote,data,{rules:[],correctionNote}) + expect(turn.outcome).toBe('failed') + expect(turn.reply).toContain('板件进深') + expect(next.standardTemplate!.cabinet).toBe(before.standardTemplate!.cabinet) + }) +}) + describe('cabinet standard v0.24 shared model workflow',()=>{ test('reproduces the supplied six-grid drawing without using the historical cabinet algorithm',()=>{ const m=buildCabinetModel(input()) diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts b/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts index a22a5773..f4a4d7f7 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/bookshelf-learning.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import type { SkillRecognition } from '../skill-routing' import { cabinetInputSchema, slottedBookcaseBack, type CabinetInput } from './cabinet-contracts' import { imageObservationSchema } from './cabinet-image-memory' +import { readSideNotchCommand } from './cabinet-side-notches' export const bookshelfCategory = 'bookshelf' as const export const bookcaseCategory = 'bookcase' as const @@ -34,6 +35,7 @@ export const cabinetCorrectionSchema = z.object({ screwCode:input.screwCode.removeDefault(), clipCode:input.clipCode.removeDefault(), drillFeet:input.drillFeet.removeDefault(), packingLabor:input.packingLabor.removeDefault(), hasFrontKick:input.hasFrontKick, hasRearRail:input.hasRearRail, bodyHeight:input.bodyHeight, + sideNotches:input.sideNotches, backPanelCount:input.backPanelCount, backPanelSplit:input.backPanelSplit, hasUnplacedPullRail:input.hasUnplacedPullRail, hasLegs:input.hasLegs, legHeight:input.legHeight, legCount:input.legCount, legShape:input.legShape, legPlacement:input.legPlacement, legInsetX:input.legInsetX, legInsetY:input.legInsetY, legSize:input.legSize, rearPullRail:input.rearPullRail, @@ -148,6 +150,7 @@ const hasSlottedBackNote = (note:string) => simpleBackAssembly.test(note) || backAssemblyNote.test(note) && !/(?:不是|不加|不用|不要|去掉)/.test(note) export function isKnownStructureCorrection(note:string) { + if(readSideNotchCommand(note))return true const items=normalizedCorrections(note) return items.length>0 && items.every(part=>addMissingLegs.test(part)||simpleBackAssembly.test(part)||addMissingBack.test(part)) } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts index c1487739..193f8dba 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-contracts.ts @@ -3,6 +3,7 @@ import { cadCylinderSchema, cylinderFrame } from './cad-geometry' import { cadOutputSchema, cadSolidSchema } from './cad-solid-contract' import { cabinetSupportRuleSchema, cabinetSupportsSchema, supportShapeSchema, supportSizeSchema } from './cabinet-supports' import { boardProfileSchema, boardRoleSchema, imageAssemblySchema } from './cabinet-image-contract' +import { sideNotchesSchema } from './cabinet-side-notches' const mm=z.number().finite().positive().max(10000) export const slottedBookcaseBack = '一块后拉板分隔两片槽装三合板' as const @@ -21,6 +22,7 @@ export const cabinetInputSchema=z.object({ width:mm.nullable().default(null),depth:mm.nullable().default(null),height:mm.nullable().default(null), columns:z.number().int().min(1).max(12).nullable().default(null),rows:z.number().int().min(1).max(12).nullable().default(null), hasFrontKick:z.boolean().nullish(),hasRearRail:z.boolean().nullish(), + sideNotches:sideNotchesSchema.optional(), backPanelCount:z.number().int().min(1).max(12).nullish(), backPanelSplit:z.enum(['上下', '左右']).nullish(), hasUnplacedPullRail:z.boolean().nullish(), diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts index 7eba1f35..720477c1 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-model.ts @@ -4,6 +4,7 @@ import { matchCabinetMaterial } from './cabinet-quota' import { selectedCabinetPartMaterial } from './cabinet-material-selection' import { bookcaseEnvelope, bookcasePreviewParts } from './bookcase-preview' import { buildImageCabinet } from './cabinet-image-model' +import { resolveSideNotch } from './cabinet-side-notches' import type { EstimateDocument } from '../contracts' export function resolveCabinetInput(raw:CabinetInput):CabinetInput { @@ -104,7 +105,8 @@ export function buildCabinetModel(raw:CabinetInput,materials?:Pick[x,y,z+lift]):positions,material,color,grooveMeters,notch}) } diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts new file mode 100644 index 00000000..896b9754 --- /dev/null +++ b/furniture-3d-system/src/lib/reference-estimator/standard/cabinet-side-notches.ts @@ -0,0 +1,57 @@ +import { z } from 'zod' + +const mm = z.number().finite().positive().max(10000) +const sideNotchSchema = z.object({ depth: mm, height: mm, radius: mm.optional() }).strict() + .refine(value => value.radius == null || value.radius <= Math.min(value.depth, value.height), { + message: '圆角半径不能大于缺口的深度或高度。', + }) + +export const sideNotchesSchema = z.object({ + '02': sideNotchSchema.optional(), + '04': sideNotchSchema.optional(), +}).strict().refine(value => Boolean(value['02'] || value['04']), { message: '请指定 02 或 04 号旁板。' }) + +type SideNotches = z.infer + +export function resolveSideNotch(notches: SideNotches | undefined, code: string, depth: number, height: number) { + const notch = code === '02' || code === '04' ? notches?.[code] : undefined + if (!notch) return undefined + if (notch.depth >= depth || notch.height >= height) { + throw new Error(code + ' 号旁板的缺口深度和高度必须小于板件进深和高度。') + } + // Use the largest inside radius that fits when the user only specifies a rounded corner. + return { ...notch, radius: notch.radius ?? Math.min(notch.depth, notch.height) } +} + +const target = String.raw`(?:02(?:号)?(?:左)?|04(?:号)?(?:右)?)(?:旁板|侧板)?` +const command = new RegExp(String.raw`^(?:请)?(?:给|将|把)?(?${target}(?:[、,/和及与]${target})?)(?:各|两块|分别)?,?(?:在)?(?:后下角|后底角)开(?:一个|一处)?(?.+)$`) +const length = String.raw`(-?\d+(?:\.\d+)?)(mm|cm|毫米|厘米)?` +const size = String.raw`深(?:度)?[::为]?${length}[、,,]?(?:高|高度)[::为]?${length}` +const cut = '(?:圆角)?(?:踢脚线)?缺口' +const suffix = String.raw`(?:[,、]?(?:做成)?圆角)?(?:[,、]?(?:圆角半径|内圆角|R)[::=为]?${length})?$` +const sizeFirst = new RegExp('^' + size + '(?:的)?' + cut + suffix, 'i') +const cutFirst = new RegExp('^' + cut + '[,::]?' + size + suffix, 'i') +const inMm = (amount: string, unit?: string) => Number(amount) * (/^(cm|厘米)$/i.test(unit ?? '') ? 10 : 1) + +// Match a complete text instruction. Extra requests go through normal recognition. +export function readSideNotchCommand(note: string): SideNotches | undefined { + const text = note.normalize('NFKC').replace(/\s/g, '').replace(/[。;;]/g, ',') + .replace(/[,!]+$/, '') + .replace(/,(?:另外,?)?09(?:号)?(?:前)?(?:踢脚板|踢脚线)?(?:保持原样|不动|不改)$/, '') + .replace(/,(?:贯穿|贯通)(?:整个)?板厚$/, '') + const matched = command.exec(text)?.groups + if (!matched) return undefined + const sizeMatch = sizeFirst.exec(matched.spec) ?? cutFirst.exec(matched.spec) + if (!sizeMatch) return undefined + const [, depth, depthUnit, height, heightUnit, radius, radiusUnit] = sizeMatch + if (!matched.spec.includes('圆角') && radius == null) return undefined + const value = { + depth: inMm(depth, depthUnit ?? heightUnit), + height: inMm(height, heightUnit), + ...(radius == null ? {} : { radius: inMm(radius, radiusUnit) }), + } + return { + ...(matched.targets.includes('02') ? { '02': value } : {}), + ...(matched.targets.includes('04') ? { '04': value } : {}), + } +} diff --git a/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts b/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts index 53bfa436..fd4e4049 100644 --- a/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts +++ b/furniture-3d-system/src/lib/reference-estimator/standard/recognition.ts @@ -19,6 +19,7 @@ import { import type { CabinetInput } from './cabinet-contracts' import { bookcaseEnvelope } from './bookcase-preview' import { applyImageAssembly } from './cabinet-image-workflow' +import { readSideNotchCommand } from './cabinet-side-notches' type RecognitionOptions = { rules: SharedBookshelfRule[]; correctionNote?: string; rulesUnavailable?: boolean } @@ -36,16 +37,29 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag options?:RecognitionOptions):EstimateDocument { const prior=document.standardTemplate?.cabinet?.input const correctionNote=options?.correctionNote + const ordinaryCorrection=correctionNote && prior && !prior.imageAssembly + const explicitNotches=ordinaryCorrection ? readSideNotchCommand(correctionNote) : undefined + const sideNotches=ordinaryCorrection ? explicitNotches ?? result.cabinetCorrection?.sideNotches : undefined + // An explicit text command also works when an earlier turn included attachments. + if(sideNotches && prior && (explicitNotches || + Object.keys(result.cabinetCorrection??{}).every(key=>key==='sideNotches'))) { + const standard=document.standardTemplate! + const memory=standard.bookshelfMemory + return applyCabinetWorkflow({...document,standardTemplate:{...standard, + bookshelfMemory:memory?{...memory,case:undefined}:undefined}}, { + ...prior,sideNotches:{...prior.sideNotches,...sideNotches}, + }) + } if (result.draftIssue && prior && document.standardTemplate?.bookshelfMemory?.reviewedImageUrl === document.imageUrl) { return document } - if((prior?.imageAssembly && correctionNote) || (result.imageAssembly && !result.cabinet?.referenceCase)) { + if((prior?.imageAssembly && correctionNote) || (!sideNotches && result.imageAssembly && !result.cabinet?.referenceCase)) { const next=applyImageAssembly(document,result,correctionNote) if(next)return next } const explicit=explicitBookshelfCorrections(correctionNote??document.imageNote) const changes:CabinetCorrection=Object.fromEntries(Object.entries({ - ...(correctionNote?result.cabinetCorrection:{}),...explicit, + ...(correctionNote?result.cabinetCorrection:{}),...explicit,sideNotches, }).filter(([,value])=>value!=null && value!=='')) if(changes.kickHeight === 0) changes.hasFrontKick=false if(changes.railHeight === 0) changes.hasRearRail=false @@ -59,7 +73,8 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag const recognizedRoute=correctingPrior&&document.skillRouting?document.skillRouting:result.skillRouting if(correctingPrior&&(result.skillRouting.hasDoors===true||result.skillRouting.hasDrawers===true)) throw new Error('门和抽屉的结构暂未接入,保留当前模型。') - const recognized={...base,...changes} + const recognized={...base,...changes, + ...(sideNotches?{sideNotches:{...base.sideNotches,...sideNotches}}:{})} if(recognized.hasLegs==null && (recognized.legSupports || recognized.legSupportRule))recognized.hasLegs=true if(correctionNote && changes.hasLegs===true && recognized.legHeight==null && result.cabinet?.legHeight!=null && (recognized.bodyHeight==null || recognized.height===recognized.bodyHeight)) { @@ -144,12 +159,16 @@ function applyRecognitionGeometry(document:EstimateDocument,result:ReferenceImag const model=next.standardTemplate!.cabinet! const scope=learn?bookshelfScope(model.input):null const appliedChanges=Object.fromEntries(Object.entries(changes) - .filter(([key,value])=>sameCorrectionValue(model.input[key as keyof CabinetInput],value))) + .filter(([key,value])=>key==='sideNotches' + ? Object.entries(sideNotches??{}).every(([code,notch])=> + sameCorrectionValue(model.input.sideNotches?.[code as '02'|'04'],notch)) + : sameCorrectionValue(model.input[key as keyof CabinetInput],value))) if(correctionNote&&Object.keys(changes).length&&!Object.keys(appliedChanges).length) throw new Error('补充内容与现有结构或所选板材不一致,请核对后重试。') - if(correctionNote&&memory&&scope&&Object.keys(appliedChanges).length){ + const {sideNotches: _oneOff, ...learnableChanges}=appliedChanges + if(correctionNote&&memory&&scope&&Object.keys(learnableChanges).length){ next.standardTemplate!.bookshelfMemory={...memory,case:{ - scope,changes:appliedChanges,autoPublish:automaticBookshelfRules(correctionNote,appliedChanges,scope), + scope,changes:learnableChanges,autoPublish:automaticBookshelfRules(correctionNote,learnableChanges,scope), }} } if(correctionNote){ diff --git a/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts b/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts index 7d62c9f8..11ee7ad5 100644 --- a/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts +++ b/furniture-3d-system/src/server/services/reference-image-estimate/cabinet-recognition-prompt.ts @@ -23,6 +23,9 @@ export function cabinetRecognitionPrompt(p:Omit part.code === '02' && part.name === '左旁板') ? [ + '对于已有普通公式书柜,当用户明确要求 02 左旁板和/或 04 右旁板后下角开贯穿板厚的圆角缺口,在 cabinetCorrection.sideNotches 下用对应板号作为键,每块填 {depth, height, radius?},单位 mm。只返回指定旁板;半径未给可省略。09 是前踢脚板;不要当作开缺口的目标。前角、非贯穿或未明确部件及深高时先核对。该修改只对本款生效,无需 imageAssemblyEdit,也不要重新生成 imageAssembly。', + ] : []), ...imageAssemblyInstructions(p), `本轮纠正(产品说明):${JSON.stringify(p.correctionNote??'')}`, ...(p.currentModelParts ? [ From 1768530721cc0f381bacf3de3d88c241a61d1c65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Wed, 25 Nov 2026 17:33:50 +0800 Subject: [PATCH 06/16] =?UTF-8?q?feat(supply-chain):=20=E5=93=81=E7=89=8C?= =?UTF-8?q?=E5=8D=87=E7=BA=A7=E5=AE=A1=E6=A0=B8=E7=8B=AC=E7=AB=8B=E6=9D=83?= =?UTF-8?q?=E9=99=90=EF=BC=88=E7=BB=8F=E7=AE=A1/=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=91=98/=E8=BF=90=E8=90=A5=E6=80=BB=E7=9B=91=EF=BC=8C?= =?UTF-8?q?=E5=90=8E=E5=8F=B0=E5=8F=AF=E9=85=8D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增权限节点「商品SABC打标 · 品牌升级审核」,默认关闭;经管默认可见/可操作,管理员全开 - 页面与接口改为独立节点校验;未开通且非配置审批人的账号看不到页签、接口返回 403 - 配置的运营总监即使未开节点也可查看/审批自己的单据 - 审批人配置、生成审核单仍仅管理员可用 - 修正权限矩阵测试中两处既有漂移(菜单数量、已下线跟单交接视图) --- .../brand-upgrade-approvals/[id]/route.ts | 11 +++++-- .../brand-upgrade-approvals/config/route.ts | 7 ++++- .../brand-upgrade-approvals/route.ts | 11 +++++-- .../DepartmentDistributionView.tsx | 5 ++-- .../blank-pages/ProductSabcView.tsx | 5 ++-- .../management/blank-pages/SabcTabNav.tsx | 7 +++-- .../blank-pages/[pageKey]/approvals/page.tsx | 6 ++-- .../[pageKey]/departments/page.tsx | 3 ++ .../management/blank-pages/[pageKey]/page.tsx | 3 ++ .../components/permissionMatrixGroups.test.ts | 2 ++ .../lib/supply-chain-page-permissions.test.ts | 2 +- .../src/lib/supply-chain-permission-paths.ts | 6 ++-- .../lib/supply-chain-permission-settings.ts | 3 ++ .../lib/supply-chain-permission-targets.ts | 4 +++ ...ly-chain-brand-upgrade-approval.service.ts | 29 +++++++++++++++++++ 15 files changed, 85 insertions(+), 19 deletions(-) diff --git a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts index cbb391bd..3912121f 100644 --- a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/[id]/route.ts @@ -1,9 +1,16 @@ import { NextRequest } from 'next/server' -import { handleRequest, jsonSuccess } from '@/server/core/response' -import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { + hasBrandUpgradeApprovalAccess, + supplyChainBrandUpgradeApprovalService, +} from '@/server/services/supply-chain-brand-upgrade-approval.service' export async function GET(request: NextRequest, context: { params: Promise<{ id: string }> }) { return handleRequest(request, async (ctx) => { + if (!(await hasBrandUpgradeApprovalAccess(ctx.user))) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有品牌升级审核查看权限', 403, ctx.requestId) + } const { id } = await context.params return jsonSuccess(await supplyChainBrandUpgradeApprovalService.get(id), 200, ctx.requestId) }, { requireAuth: true }) diff --git a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts index e992d45c..5ae967a5 100644 --- a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/config/route.ts @@ -1,9 +1,14 @@ import { NextRequest } from 'next/server' -import { handleRequest, jsonSuccess } from '@/server/core/response' +import { isAdmin } from '@/lib/role-scope' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service' export async function GET(request: NextRequest) { return handleRequest(request, async (ctx) => { + if (!isAdmin(ctx.user)) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '只有管理员可以配置审批人', 403, ctx.requestId) + } return jsonSuccess(await supplyChainBrandUpgradeApprovalService.getConfig(), 200, ctx.requestId) }, { requireAuth: true }) } diff --git a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts index ed2e5160..d3bba845 100644 --- a/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/brand-upgrade-approvals/route.ts @@ -1,9 +1,16 @@ import { NextRequest } from 'next/server' -import { handleRequest, jsonSuccess } from '@/server/core/response' -import { supplyChainBrandUpgradeApprovalService } from '@/server/services/supply-chain-brand-upgrade-approval.service' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { + hasBrandUpgradeApprovalAccess, + supplyChainBrandUpgradeApprovalService, +} from '@/server/services/supply-chain-brand-upgrade-approval.service' export async function GET(request: NextRequest) { return handleRequest(request, async (ctx) => { + if (!(await hasBrandUpgradeApprovalAccess(ctx.user))) { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有品牌升级审核查看权限', 403, ctx.requestId) + } const periodKey = request.nextUrl.searchParams.get('period')?.trim() || undefined const status = request.nextUrl.searchParams.get('status')?.trim() || undefined return jsonSuccess({ diff --git a/furniture-3d-system/src/app/supply-chain/management/blank-pages/DepartmentDistributionView.tsx b/furniture-3d-system/src/app/supply-chain/management/blank-pages/DepartmentDistributionView.tsx index aa3c8580..75f703f6 100644 --- a/furniture-3d-system/src/app/supply-chain/management/blank-pages/DepartmentDistributionView.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/blank-pages/DepartmentDistributionView.tsx @@ -103,12 +103,13 @@ function summarize(profitCenters: DepartmentProfitCenterBlock[]) { } export function DepartmentDistributionView({ - definition, canExport, canConfigure, canViewDetail = true, + definition, canExport, canConfigure, canViewDetail = true, canViewApprovals = false, }: { definition: ManagementBlankPageDefinition canExport: boolean canConfigure: boolean canViewDetail?: boolean + canViewApprovals?: boolean }) { const initial = useMemo(() => previousMonth(), []) const [year, setYear] = useState(initial.year) @@ -318,7 +319,7 @@ export function DepartmentDistributionView({

{definition.label} · 各部门数据分类

SupplyChainProductArchive 商品主表 · 按利润中心汇总(生成后冻结)

- +
{ event.preventDefault(); void load() }}>