merge: 同步最新共享主线后合入清货生成优化

This commit is contained in:
居居 2026-11-25 14:50:17 +08:00
commit dcbba780ae
11 changed files with 671 additions and 46 deletions

View File

@ -0,0 +1,347 @@
/**
* 修正历史 0 级重放把兜底人落入三级节点的 8 条需求。
*
* 该脚本只修正节点和预警归属,不发送钉钉通知:
* npx tsx scripts/correct-production-stop-stage3-fallback.ts
* npx tsx scripts/correct-production-stop-stage3-fallback.ts \
* --apply --confirm=correct-production-stop-stage3-fallback
*/
import 'dotenv/config'
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import {
OperationLogAction,
OperationLogStatus,
} from '@prisma/client'
import { prisma } from '../src/lib/prisma'
import { productionStopDemandRepository } from '../src/server/repositories/production-stop-demands.repository'
import { operationLogService } from '../src/server/services/operation-log.service'
const APPLY_CONFIRMATION = 'correct-production-stop-stage3-fallback'
const EXPECTED_TARGET_COUNT = 8
const TARGETS = [
{ demandNo: 'TC20261121-606', barcode: 'GBPM-AD030901N1280V01' },
{ demandNo: 'TC20261121-607', barcode: 'GBPM-AD030902N1280V01' },
{ demandNo: 'TC20261121-614', barcode: 'GBPM-BJ019101N1280V01' },
{ demandNo: 'TC20261121-615', barcode: 'GBPM-BJ019201N1280V01' },
{ demandNo: 'TC20261121-617', barcode: 'GBPM-DSG011801N1280V01' },
{ demandNo: 'TC20261121-620', barcode: 'GBPM-SJZ002301N1439V01' },
{ demandNo: 'TC20261121-623', barcode: 'GBPM-SJZ002802N1439V01' },
{ demandNo: 'TC20261121-624', barcode: 'GBPM-SJZ002902N1439V01' },
] as const
function argumentValue(name: string) {
const prefix = `--${name}=`
return process.argv.find((argument) => argument.startsWith(prefix))?.slice(prefix.length)
}
function replaceStageLabel(value: string, fallbackName: string) {
return value
.split('三级需求确认').join(fallbackName)
.split('第三级需求确认').join(fallbackName)
}
function replaceWarningKeyStage(
key: string,
demandId: string,
sourceStage: number,
targetStage: number,
) {
return key.replace(
`:${demandId}:${sourceStage}:`,
`:${demandId}:${targetStage}:`,
)
}
async function main() {
const apply = process.argv.includes('--apply')
if (apply && argumentValue('confirm') !== APPLY_CONFIRMATION) {
throw new Error(`正式执行必须追加 --confirm=${APPLY_CONFIRMATION};未写入任何数据`)
}
const workflowNodes = await productionStopDemandRepository.listConfirmationWorkflowNodes()
const fallbackNodes = workflowNodes.filter((node) => (
node.isActive && node.confirmerRole === 'FIXED_APPROVER'
))
if (fallbackNodes.length !== 1) {
throw new Error(`兜底需求确认节点必须唯一且启用,当前数量为 ${fallbackNodes.length}`)
}
const fallbackNode = fallbackNodes[0]
if (!fallbackNode.fixedApproverName.trim()) {
throw new Error('兜底需求确认节点未配置固定确认人')
}
const demands = await prisma.productionStopDemand.findMany({
where: {
OR: TARGETS.map((target) => ({
demandNo: target.demandNo,
items: { some: { barcode: target.barcode } },
})),
},
select: {
id: true,
demandNo: true,
confirmationStage: true,
confirmationStatus: true,
demandStatus: true,
demandStatusNote: true,
confirmationStageEnteredAt: true,
confirmationDeadline: true,
confirmationDeadlineNote: true,
confirmationPushedAt: true,
confirmationPushMessage: true,
items: { select: { barcode: true } },
confirmationVotes: {
select: {
id: true,
approverId: true,
approverName: true,
decision: true,
confirmationStage: true,
},
},
confirmationWarnings: {
select: {
id: true,
demandId: true,
confirmationStage: true,
warningType: true,
status: true,
idempotencyKey: true,
title: true,
content: true,
},
},
confirmationAssignments: {
select: { id: true },
},
},
})
if (demands.length !== EXPECTED_TARGET_COUNT) {
throw new Error(
`目标需求数量不一致:预期 ${EXPECTED_TARGET_COUNT},实际 ${demands.length}`,
)
}
const byDemandNo = new Map(demands.map((demand) => [demand.demandNo, demand]))
const changes = TARGETS.map((target) => {
const demand = byDemandNo.get(target.demandNo)
if (!demand) throw new Error(`找不到需求 ${target.demandNo}`)
if (!demand.items.some((item) => item.barcode.trim().toUpperCase() === target.barcode)) {
throw new Error(`需求 ${target.demandNo} 的条码不匹配 ${target.barcode}`)
}
const alreadyCorrected = demand.confirmationStage === fallbackNode.sortOrder
&& demand.confirmationWarnings
.filter((warning) => warning.confirmationStage === 3)
.length === 0
if (alreadyCorrected) {
return {
demandId: demand.id,
demandNo: demand.demandNo,
barcode: target.barcode,
status: 'ALREADY_CORRECTED' as const,
beforeStage: demand.confirmationStage,
afterStage: fallbackNode.sortOrder,
warningUpdates: [],
}
}
if (demand.confirmationStatus !== 'PENDING') {
throw new Error(`需求 ${demand.demandNo} 已不是待确认状态`)
}
if (demand.confirmationStage !== 3) {
throw new Error(`需求 ${demand.demandNo} 当前阶段为 ${demand.confirmationStage},不是三级`)
}
if (demand.confirmationVotes.length) {
throw new Error(`需求 ${demand.demandNo} 已有确认票,停止自动修正`)
}
const stageThreeWarnings = demand.confirmationWarnings.filter((warning) => (
warning.confirmationStage === 3
))
if (!stageThreeWarnings.length) {
throw new Error(`需求 ${demand.demandNo} 没有三级预警记录,停止自动修正`)
}
const existingFallbackWarnings = demand.confirmationWarnings.filter((warning) => (
warning.confirmationStage === fallbackNode.sortOrder
))
if (existingFallbackWarnings.length) {
throw new Error(`需求 ${demand.demandNo} 已存在兜底节点预警,停止自动修正`)
}
return {
demandId: demand.id,
demandNo: demand.demandNo,
barcode: target.barcode,
status: 'PLANNED' as const,
beforeStage: demand.confirmationStage,
afterStage: fallbackNode.sortOrder,
warningUpdates: stageThreeWarnings.map((warning) => ({
id: warning.id,
warningType: warning.warningType,
status: warning.status,
beforeKey: warning.idempotencyKey,
afterKey: replaceWarningKeyStage(
warning.idempotencyKey,
demand.id,
3,
fallbackNode.sortOrder,
),
beforeTitle: warning.title,
afterTitle: replaceStageLabel(warning.title, fallbackNode.name),
beforeContent: warning.content,
afterContent: replaceStageLabel(warning.content, fallbackNode.name),
})),
}
})
const planned = changes.filter((change) => change.status === 'PLANNED')
const alreadyCorrected = changes.filter((change) => change.status === 'ALREADY_CORRECTED')
const outputPath = resolve(
argumentValue('output')
?? '.master-data-audits/production-stop-stage3-fallback-correction-current.json',
)
await mkdir(dirname(outputPath), { recursive: true })
if (!apply) {
const summary = {
mode: 'DRY_RUN',
fallbackNode: {
id: fallbackNode.id,
name: fallbackNode.name,
sortOrder: fallbackNode.sortOrder,
fixedApproverName: fallbackNode.fixedApproverName,
},
expectedTargetCount: EXPECTED_TARGET_COUNT,
planned: planned.length,
alreadyCorrected: alreadyCorrected.length,
notificationsSent: 0,
changes,
outputPath,
}
await writeFile(outputPath, JSON.stringify(summary, null, 2), 'utf8')
console.log(JSON.stringify({ ...summary, changes: undefined }, null, 2))
return
}
if (planned.length !== EXPECTED_TARGET_COUNT) {
throw new Error(
`正式修正数量不一致:预期 ${EXPECTED_TARGET_COUNT},可修正 ${planned.length},`
+ `已正确 ${alreadyCorrected.length};未写入任何数据`,
)
}
const plannedIds = planned.map((change) => change.demandId)
const backupPath = resolve(
argumentValue('backup')
?? `.master-data-audits/production-stop-stage3-fallback-backup-${Date.now()}.json`,
)
const [demandRows, voteRows, warningRows, assignmentRows] = await Promise.all([
prisma.productionStopDemand.findMany({ where: { id: { in: plannedIds } } }),
prisma.productionStopDemandConfirmationVote.findMany({
where: { demandId: { in: plannedIds } },
}),
prisma.productionStopConfirmationWarning.findMany({
where: { demandId: { in: plannedIds } },
}),
prisma.productionStopDemandConfirmationAssignment.findMany({
where: { demandId: { in: plannedIds } },
}),
])
await mkdir(dirname(backupPath), { recursive: true })
await writeFile(backupPath, JSON.stringify({
generatedAt: new Date().toISOString(),
operation: 'CORRECT_PRODUCTION_STOP_STAGE3_TO_FALLBACK',
demandIds: plannedIds,
demands: demandRows,
votes: voteRows,
warnings: warningRows,
assignments: assignmentRows,
}, null, 2), 'utf8')
const updated = await prisma.$transaction(async (tx) => {
let demandUpdates = 0
let warningUpdates = 0
for (const change of planned) {
const demand = byDemandNo.get(change.demandNo)!
const result = await tx.productionStopDemand.updateMany({
where: {
id: change.demandId,
confirmationStatus: 'PENDING',
confirmationStage: 3,
},
data: {
confirmationStage: fallbackNode.sortOrder,
demandStatusNote: replaceStageLabel(demand.demandStatusNote, fallbackNode.name),
},
})
if (result.count !== 1) {
throw new Error(`需求 ${change.demandNo} 状态已变化,停止本批次`)
}
demandUpdates += result.count
for (const warning of change.warningUpdates) {
const warningResult = await tx.productionStopConfirmationWarning.updateMany({
where: { id: warning.id, confirmationStage: 3 },
data: {
confirmationStage: fallbackNode.sortOrder,
idempotencyKey: warning.afterKey,
title: warning.afterTitle,
content: warning.afterContent,
},
})
if (warningResult.count !== 1) {
throw new Error(`需求 ${change.demandNo} 的预警已变化,停止本批次`)
}
warningUpdates += warningResult.count
}
}
return { demandUpdates, warningUpdates }
}, {
maxWait: 15_000,
timeout: 120_000,
})
await operationLogService.record({
action: OperationLogAction.PRODUCTION_STOP_DEMAND_UPDATE,
status: OperationLogStatus.SUCCESS,
source: 'SYSTEM',
actorId: null,
actorName: '系统管理员',
workspaceCategory: '停产需求管理',
message: `修正 ${updated.demandUpdates} 条兜底确认需求节点,未重复推送`,
details: {
mode: 'APPLY',
targetStage: fallbackNode.sortOrder,
targetNode: fallbackNode.name,
fixedApproverName: fallbackNode.fixedApproverName,
demandUpdates: updated.demandUpdates,
warningUpdates: updated.warningUpdates,
notificationsSent: 0,
backupPath,
},
})
const summary = {
mode: 'APPLY',
fallbackNode: {
id: fallbackNode.id,
name: fallbackNode.name,
sortOrder: fallbackNode.sortOrder,
fixedApproverName: fallbackNode.fixedApproverName,
},
planned: planned.length,
alreadyCorrected: alreadyCorrected.length,
updated,
notificationsSent: 0,
backupPath,
outputPath,
changes,
}
await writeFile(outputPath, JSON.stringify(summary, null, 2), 'utf8')
console.log(JSON.stringify({ ...summary, changes: undefined }, null, 2))
}
main()
.catch((error) => {
console.error('[production-stop-stage3-fallback] FAILED:', error)
process.exitCode = 1
})
.finally(async () => {
await prisma.$disconnect().catch(() => null)
})

View File

@ -335,9 +335,9 @@ async function planReplay() {
fallbackUser,
)
if (!selected) {
if (fallbackUser && stageThreeNode) {
if (fallbackUser && fallbackNode) {
selected = {
node: stageThreeNode,
node: fallbackNode,
recipients: [fallbackUser.name],
routingFallbacks: [],
blockingReason: '',

View File

@ -1629,8 +1629,26 @@ describe('停产需求管理视图', () => {
json: async () => ({
success: true,
data: {
confirmed: ['TC20260930-001'],
confirmed: ['TC20260930-001', 'TC20260930-001'],
skipped: [],
updates: [
{
demandId: 'demand-1',
demandNo: 'TC20260930-001',
confirmationStatus: 'REJECTED',
confirmationStage: 1,
confirmationStageName: '一级需求确认',
demandStatus: 'REJECTED',
},
{
demandId: 'demand-2',
demandNo: 'TC20260930-001',
confirmationStatus: 'REJECTED',
confirmationStage: 1,
confirmationStageName: '一级需求确认',
demandStatus: 'REJECTED',
},
],
},
}),
}
@ -1686,6 +1704,11 @@ describe('停产需求管理视图', () => {
reason: '库存策略调整',
}))
})
await waitFor(() => {
expect(screen.queryByText('A1')).not.toBeInTheDocument()
expect(screen.queryByText('A2')).not.toBeInTheDocument()
})
expect(screen.getByText(/已提交 2 条不同意停产/)).toBeInTheDocument()
})
it('需求确认人可在统一界面切换批量同意和批量不同意导入', () => {

View File

@ -2907,6 +2907,8 @@ export function ProductionStopDemandsView({
) => {
const ids = selectedDemandIds()
if (!ids.length) return
const selectedDemandIdSet = new Set(ids)
const requestStartedAt = performance.now()
const requestId = ++batchConfirmRequestRef.current
setNotice('')
setActionError('')
@ -2938,13 +2940,35 @@ export function ProductionStopDemandsView({
},
)
if (requestId !== batchConfirmRequestRef.current) return
const clientDurationMs = Math.round(performance.now() - requestStartedAt)
const confirmedDemandNos = new Set(result.confirmed)
const confirmedDemandIds = new Set(
data.rows
.filter((row) => (
selectedDemandIdSet.has(row.demandId)
&& confirmedDemandNos.has(row.demandNo)
))
.map((row) => row.demandId),
)
const updatesByDemand = new Map(
(result.updates ?? []).map((row) => [row.demandId, row]),
)
if (updatesByDemand.size) {
setData((current) => ({
...current,
rows: current.rows.map((row) => {
setData((current) => {
const removePersonalPendingRows = filters.myPendingConfirmation
|| (
filters.myConfirmationStatuses.length === 1
&& filters.myConfirmationStatuses[0] === 'PENDING'
)
|| (
!filters.myConfirmationStatuses.length
&& filters.myConfirmationStatus === 'PENDING'
)
const rows = current.rows
.filter((row) => (
!removePersonalPendingRows
|| !confirmedDemandIds.has(row.demandId)
))
.map((row) => {
const updated = updatesByDemand.get(row.demandId)
return updated
? {
@ -2955,9 +2979,22 @@ export function ProductionStopDemandsView({
demandStatus: updated.demandStatus,
}
: row
}),
}))
}
})
const removed = current.rows.length - rows.length
const total = Math.max(0, current.total - removed)
return {
...current,
rows,
total,
totalPages: Math.max(1, Math.ceil(total / current.pageSize)),
}
})
console.info('[production-stop-demands] batch confirmation client timing', {
requestId,
requested: ids.length,
confirmed: result.confirmed.length,
durationMs: clientDurationMs,
})
setSelectedIds(new Set())
setBatchRejectionCategory('')
setStatusNote('')

View File

@ -84,6 +84,41 @@ describe('停产需求三级确认流程', () => {
)).toEqual(['海棠'])
})
it('固定兜底节点只返回配置的兜底确认人', () => {
const approvers = [
{ id: 'a1', userName: '普通确认人' },
{ id: 'a-haitang', userName: '海棠' },
]
expect(resolveProductionStopConfirmationNodeNames(
'FIXED_APPROVER',
{
opsDeptHead: [],
opsDirector: [],
shopBusinessUnitHead: [],
},
'海棠',
)).toEqual(['海棠'])
expect(resolveProductionStopConfirmationRoutingNames(
'FIXED_APPROVER',
{
opsDeptHead: [],
opsDirector: [],
shopBusinessUnitHead: [],
},
'海棠',
)).toEqual(['海棠'])
expect(resolveProductionStopConfirmationNodeApprovers(
approvers,
'FIXED_APPROVER',
{
opsDeptHead: [],
opsDirector: [],
shopBusinessUnitHead: [],
},
'海棠',
)).toEqual([{ id: 'a-haitang', userName: '海棠' }])
})
it('一级不同意进入二级,二级不同意结束,二级同意进入三级', () => {
expect(evaluateProductionStopConfirmationStage({
stage: 1,

View File

@ -112,6 +112,7 @@ export function splitProductionStopOwnerNames(values: readonly string[]) {
export function resolveProductionStopConfirmationNodeNames(
confirmerRole: ProductionStopConfirmationConfirmerRole,
owners: ProductionStopConfirmationRoutingOwners,
fixedApproverName = '',
) {
if (confirmerRole === 'OPS_DEPT_HEAD') {
return splitProductionStopOwnerNames(owners.opsDeptHead)
@ -119,7 +120,9 @@ export function resolveProductionStopConfirmationNodeNames(
if (confirmerRole === 'OPS_DIRECTOR') {
return splitProductionStopOwnerNames(owners.opsDirector)
}
if (confirmerRole === 'FIXED_APPROVER') return []
if (confirmerRole === 'FIXED_APPROVER') {
return splitProductionStopOwnerNames([fixedApproverName])
}
const directors = new Set(
splitProductionStopOwnerNames(owners.opsDirector).map(normalizeName),
)
@ -145,6 +148,7 @@ export function resolveProductionStopConfirmationRoutingNames(
owners,
)
const fixedNames = splitProductionStopOwnerNames([fixedApproverName])
if (confirmerRole === 'FIXED_APPROVER') return fixedNames
if (confirmerRole === 'OPS_DEPT_HEAD') {
if (departmentNames.length) return departmentNames
if (directorNames.length) return directorNames
@ -165,8 +169,13 @@ export function resolveProductionStopConfirmationNodeApprovers<T extends Approve
approvers: readonly T[],
confirmerRole: ProductionStopConfirmationConfirmerRole,
owners: ProductionStopConfirmationRoutingOwners,
fixedApproverName = '',
) {
const names = resolveProductionStopConfirmationNodeNames(confirmerRole, owners)
const names = resolveProductionStopConfirmationNodeNames(
confirmerRole,
owners,
fixedApproverName,
)
if (!names.length) return []
const targets = new Set(names.map(normalizeName))
return approvers.filter((approver) => targets.has(normalizeName(approver.userName)))

View File

@ -3358,15 +3358,17 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit
}
async ensureConfirmationWorkflowDefaults() {
await prisma.$transaction(
PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS.map((node) => (
prisma.productionStopConfirmationWorkflowNode.upsert({
where: { sortOrder: node.sortOrder },
create: node,
update: {},
})
)),
)
const existing = await prisma.productionStopConfirmationWorkflowNode.findMany({
select: { sortOrder: true },
})
const existingSortOrders = new Set(existing.map((node) => node.sortOrder))
const missing = PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS
.filter((node) => !existingSortOrders.has(node.sortOrder))
if (!missing.length) return
await prisma.productionStopConfirmationWorkflowNode.createMany({
data: missing.map((node) => ({ ...node })),
skipDuplicates: true,
})
}
async listConfirmationWorkflowNodes() {

View File

@ -1629,6 +1629,48 @@ describe('停产需求:是否同意停产确认', () => {
])
})
it('固定兜底节点将海棠识别为当前有效确认人', async () => {
repo.listConfirmationWorkflowNodes.mockResolvedValue([
workflowNode(1, 'OPS_DEPT_HEAD'),
workflowNode(2, 'OPS_DIRECTOR'),
workflowNode(3, 'OTHER_SHOP_BUSINESS_UNIT_HEADS'),
workflowNode(4, 'FIXED_APPROVER', {
fixedApproverUserId: 'u-haitang',
fixedApproverName: '海棠',
}),
])
repo.findDemandById.mockResolvedValue(demandRecord({ confirmationStage: 4 }))
repo.listActiveApprovers.mockResolvedValue([
approver({
id: 'approver-haitang',
userId: 'u-haitang',
userName: '海棠',
}),
approver({ id: 'approver-user', userId: 'u9', userName: '普通确认人' }),
])
repo.findApproverByUserId.mockResolvedValue(approver({
id: 'approver-haitang',
userId: 'u-haitang',
userName: '海棠',
}))
repo.findDemandConfirmationRoutingOwners.mockResolvedValue({
barcodes: [],
opsDeptHead: [],
opsDirector: [],
})
const info = await productionStopDemandsService.getConfirmationInfo(
'demand1',
{ id: 'u-haitang', name: '海棠' },
)
expect(info.canConfirm).toBe(true)
expect(info.stage).toBe(4)
expect(info.approvers).toEqual([
{ id: 'approver-haitang', name: '海棠' },
])
})
it('驳回需求改为特殊停产原因后重新提交会跳过全部确认节点', async () => {
repo.findDemandById.mockResolvedValue(demandRecord({
reasonCategory: '有替换新款,老款公司要求停产',
@ -1773,6 +1815,57 @@ describe('停产需求:是否同意停产确认', () => {
expect(repo.upsertConfirmationVote).not.toHaveBeenCalled()
})
it('固定兜底节点允许配置的兜底人完成最终确认', async () => {
const haitang = approver({
id: 'approver-haitang',
userId: 'u-haitang',
userName: '海棠',
})
repo.listConfirmationWorkflowNodes.mockResolvedValue([
workflowNode(1, 'OPS_DEPT_HEAD'),
workflowNode(2, 'OPS_DIRECTOR'),
workflowNode(3, 'OTHER_SHOP_BUSINESS_UNIT_HEADS'),
workflowNode(4, 'FIXED_APPROVER', {
fixedApproverUserId: 'u-haitang',
fixedApproverName: '海棠',
}),
])
repo.listActiveApprovers.mockResolvedValue([haitang])
repo.findApproverByUserId.mockResolvedValue(haitang)
repo.findDemandsByIds.mockResolvedValue(new Map([
['demand1', demandRecord({ id: 'demand1', confirmationStage: 4 })],
]))
repo.findDemandConfirmationRoutingOwnersByIds.mockResolvedValue(new Map([
['demand1', {
barcodes: ['A1'],
opsDeptHead: [],
opsDirector: [],
}],
]))
repo.ensureConfirmationApproversByUserNames.mockResolvedValue([haitang])
const result = await productionStopDemandsService.submitConfirmationsBatch(
['demand1'],
{ decision: 'AGREED', rejectionCategory: '', reason: '' },
{ id: 'u-haitang', name: '海棠' },
)
expect(result.confirmed).toEqual(['TC20260930-001'])
expect(result.updates[0]).toMatchObject({
demandId: 'demand1',
confirmationStage: 4,
confirmationStatus: 'AGREED',
})
expect(repo.applyConfirmationBatch).toHaveBeenCalledWith(expect.objectContaining({
votes: [expect.objectContaining({
demandId: 'demand1',
approverId: 'approver-haitang',
confirmationStage: 4,
decision: 'AGREED',
})],
}))
})
it('历史待确认单 dry-run 能识别运营总负责人同意并指向三级', async () => {
repo.listConfirmationWorkflowNodes.mockResolvedValue([
workflowNode(1, 'OPS_DEPT_HEAD'),

View File

@ -848,11 +848,14 @@ class ProductionStopDemandsService {
}))
}
private async activeConfirmationWorkflowNodes() {
private async activeConfirmationWorkflowNodes(options: {
includeFallback?: boolean
} = {}) {
await this.ensureConfirmationWorkflowDefaults()
const rows = await productionStopDemandRepository.listConfirmationWorkflowNodes()
return rows.filter((node) => (
node.isActive && node.confirmerRole !== 'FIXED_APPROVER'
node.isActive
&& (options.includeFallback || node.confirmerRole !== 'FIXED_APPROVER')
))
}
@ -1004,7 +1007,11 @@ class ProductionStopDemandsService {
}
}
}
const names = resolveProductionStopConfirmationNodeNames(confirmerRole, routingOwners)
const names = resolveProductionStopConfirmationNodeNames(
confirmerRole,
routingOwners,
fixedApproverName,
)
const ensured = names.length
? await productionStopDemandRepository.ensureConfirmationApproversByUserNames(names)
: []
@ -1015,6 +1022,7 @@ class ProductionStopDemandsService {
candidates,
confirmerRole,
routingOwners,
fixedApproverName,
)
}
@ -1045,15 +1053,18 @@ class ProductionStopDemandsService {
const demand = await productionStopDemandRepository.findDemandById(demandId)
if (!demand || demand.confirmationStage <= 0) return null
const [nodes, votes] = await Promise.all([
this.activeConfirmationWorkflowNodes(),
this.activeConfirmationWorkflowNodes({ includeFallback: true }),
productionStopDemandRepository.listConfirmationVotes(demandId),
])
const node = nodes.find((item) => item.sortOrder === demand.confirmationStage)
if (!node) return null
const contextNodes = node.confirmerRole === 'FIXED_APPROVER'
? nodes
: nodes.filter((item) => item.confirmerRole !== 'FIXED_APPROVER')
const owners = await this.confirmationRoutingOwners(demandId)
const stageApproverSet = await this.resolveConfirmationStageApproverSet(
node,
nodes,
contextNodes,
owners,
activeApprovers,
votes,
@ -1135,7 +1146,10 @@ class ProductionStopDemandsService {
}
}
if (!selectedStatuses.has('PENDING')) return [...result]
const workflowNodes = await this.activeConfirmationWorkflowNodes()
const workflowNodes = await this.activeConfirmationWorkflowNodes({ includeFallback: true })
const normalWorkflowNodes = workflowNodes.filter((node) => (
node.confirmerRole !== 'FIXED_APPROVER'
))
const nodeBySortOrder = new Map(workflowNodes.map((node) => [node.sortOrder, node]))
let afterId: string | null = null
while (true) {
@ -1178,6 +1192,9 @@ class ProductionStopDemandsService {
const node = demand.confirmationStage > 0
? nodeBySortOrder.get(demand.confirmationStage)
: null
const nodesForDemand = node?.confirmerRole === 'FIXED_APPROVER'
? workflowNodes
: normalWorkflowNodes
const applicableApprovers = node && owners
? excludeConfirmedApproversFromFinalStage({
approvers: await this.resolveConfirmationNodeApprovers(
@ -1192,7 +1209,7 @@ class ProductionStopDemandsService {
activeApprovers,
),
stage: node.sortOrder,
finalStage: workflowNodes.at(-1)?.sortOrder ?? node.sortOrder,
finalStage: nodesForDemand.at(-1)?.sortOrder ?? node.sortOrder,
confirmerRole: node.confirmerRole,
votes: votesByDemand.get(demandId) ?? [],
})
@ -1621,7 +1638,7 @@ class ProductionStopDemandsService {
productionStopDemandRepository.findDemandConfirmationRoutingOwnersByIds(ids),
productionStopDemandRepository.listConfirmationVotesByDemandIds(ids),
productionStopDemandRepository.listDemandConfirmationAssignments(ids),
this.activeConfirmationWorkflowNodes(),
this.activeConfirmationWorkflowNodes({ includeFallback: true }),
productionStopDemandRepository.listWorkCalendarDays(),
this.resolveConfirmationActorCandidates(user),
])
@ -1639,6 +1656,9 @@ class ProductionStopDemandsService {
&& node.confirmerRole === 'FIXED_APPROVER'
&& node.fixedApproverName
))?.fixedApproverName ?? ''
const normalWorkflowNodes = workflowNodes.filter((node) => (
node.confirmerRole !== 'FIXED_APPROVER'
))
const routingOwnerNames = [...ownersByDemand.values()].flatMap((owners) => [
...owners.opsDeptHead,
...owners.opsDirector,
@ -1670,8 +1690,6 @@ class ProductionStopDemandsService {
typeof productionStopDemandRepository.applyConfirmationBatch
>[0]['votes'] = []
const updates: NonNullable<ProductionStopBatchConfirmResult['updates']> = []
const finalStage = workflowNodes.at(-1)?.sortOrder ?? null
for (const demandId of ids) {
const demand = demandsById.get(demandId)
if (!demand) {
@ -1700,12 +1718,17 @@ class ProductionStopDemandsService {
const currentNode = demand.confirmationStage > 0
? workflowNodes.find((node) => node.sortOrder === demand.confirmationStage)
: null
const nodesForDemand = currentNode?.confirmerRole === 'FIXED_APPROVER'
? workflowNodes
: normalWorkflowNodes
const finalStage = nodesForDemand.at(-1)?.sortOrder ?? null
const existingVotes = votesByDemand.get(demandId) ?? []
const stageCandidates = currentNode
? resolveProductionStopConfirmationNodeApprovers(
allApprovers,
currentNode.confirmerRole,
routingOwners,
fixedApproverName,
)
: resolveProductionStopConfirmationApprovers(
allApprovers,
@ -1806,21 +1829,21 @@ class ProductionStopDemandsService {
.map((item) => item.id)
const partialRoute = resolveProductionStopPartialConfirmationRoute({
stage: currentNode.sortOrder,
firstStage: workflowNodes[0]?.sortOrder ?? currentNode.sortOrder,
firstStage: nodesForDemand[0]?.sortOrder ?? currentNode.sortOrder,
lastStage: finalStage ?? currentNode.sortOrder,
requiredApproverIds: applicableApprovers.map((item) => item.id),
opsDirectorApproverIds: directorApproverIds,
votes: nextVotes,
})
const currentIndex = workflowNodes.findIndex(
const currentIndex = nodesForDemand.findIndex(
(node) => node.sortOrder === currentNode.sortOrder,
)
const nextNode = workflowNodes[currentIndex + 1] ?? null
const nextNode = nodesForDemand[currentIndex + 1] ?? null
const evaluation = evaluateProductionStopConfirmationStage({
stage: currentNode.sortOrder,
requiredApproverIds: applicableApprovers.map((item) => item.id),
votes: nextVotes,
firstStage: workflowNodes[0]?.sortOrder ?? currentNode.sortOrder,
firstStage: nodesForDemand[0]?.sortOrder ?? currentNode.sortOrder,
lastStage: finalStage ?? currentNode.sortOrder,
nextStage: nextNode?.sortOrder ?? null,
})
@ -1832,10 +1855,10 @@ class ProductionStopDemandsService {
)))
} else if (evaluation.status === 'AGREED') {
targetStatus = 'AGREED'
} else if (partialRoute === 'SKIP_TO_FINAL_STAGE' && workflowNodes.at(-1)) {
targetStage = workflowNodes.at(-1)!.sortOrder
} else if (partialRoute === 'RESTART_FIRST_STAGE' && workflowNodes[0]) {
targetStage = workflowNodes[0].sortOrder
} else if (partialRoute === 'SKIP_TO_FINAL_STAGE' && nodesForDemand.at(-1)) {
targetStage = nodesForDemand.at(-1)!.sortOrder
} else if (partialRoute === 'RESTART_FIRST_STAGE' && nodesForDemand[0]) {
targetStage = nodesForDemand[0].sortOrder
resetCurrentStageSchedule = true
} else if (evaluation.targetStage !== currentNode.sortOrder) {
targetStage = evaluation.targetStage
@ -1862,7 +1885,7 @@ class ProductionStopDemandsService {
|| resetCurrentStageSchedule
)
) {
const targetNode = workflowNodes.find((node) => node.sortOrder === targetStage)
const targetNode = nodesForDemand.find((node) => node.sortOrder === targetStage)
if (targetNode) {
const schedule = resolveProductionStopConfirmationDeadlineDetails(
now,
@ -1882,11 +1905,13 @@ class ProductionStopDemandsService {
const targetNames = resolveProductionStopConfirmationNodeNames(
targetNode.confirmerRole,
effectiveTargetOwners,
fixedApproverName,
)
const targetCandidates = resolveProductionStopConfirmationNodeApprovers(
allApprovers,
targetNode.confirmerRole,
effectiveTargetOwners,
fixedApproverName,
)
if (
(targetNames.length > 0 && targetCandidates.length === 0)
@ -2688,6 +2713,7 @@ class ProductionStopDemandsService {
const targetNames = resolveProductionStopConfirmationNodeNames(
input.targetNode.confirmerRole,
effectiveOwners,
fixedApproverName,
)
if (
input.targetNode.sortOrder !== finalStage
@ -2753,9 +2779,8 @@ class ProductionStopDemandsService {
const demand = await productionStopDemandRepository.findDemandById(demandId)
if (!demand) return 'PENDING'
if (demand.confirmationStage > 0) {
const nodes = await this.activeConfirmationWorkflowNodes()
const currentIndex = nodes.findIndex((node) => node.sortOrder === demand.confirmationStage)
const currentNode = nodes[currentIndex]
const allNodes = await this.activeConfirmationWorkflowNodes({ includeFallback: true })
const currentNode = allNodes.find((node) => node.sortOrder === demand.confirmationStage)
if (!currentNode) {
console.error('[production-stop-demands] confirmation node missing', {
demandId,
@ -2763,6 +2788,10 @@ class ProductionStopDemandsService {
})
return 'PENDING'
}
const nodes = currentNode.confirmerRole === 'FIXED_APPROVER'
? allNodes
: allNodes.filter((node) => node.confirmerRole !== 'FIXED_APPROVER')
const currentIndex = nodes.findIndex((node) => node.sortOrder === currentNode.sortOrder)
const [activeApprovers, votes, owners] = await Promise.all([
productionStopDemandRepository.listActiveApprovers(),
productionStopDemandRepository.listConfirmationVotes(demandId),
@ -2979,7 +3008,10 @@ class ProductionStopDemandsService {
)
if (!overdue.length) return 0
const approvers = await productionStopDemandRepository.listActiveApprovers()
const workflowNodes = await this.activeConfirmationWorkflowNodes()
const workflowNodes = await this.activeConfirmationWorkflowNodes({ includeFallback: true })
const normalWorkflowNodes = workflowNodes.filter((node) => (
node.confirmerRole !== 'FIXED_APPROVER'
))
const applicableByDemand = await this.applicableApproversByDemandIds(
approvers,
overdue.map((demand) => demand.id),
@ -2998,6 +3030,9 @@ class ProductionStopDemandsService {
continue
}
const owners = await this.confirmationRoutingOwners(demand.id)
const nodesForDemand = node.confirmerRole === 'FIXED_APPROVER'
? workflowNodes
: normalWorkflowNodes
const applicableApprovers = excludeConfirmedApproversFromFinalStage({
approvers: await this.resolveConfirmationNodeApprovers(
node.confirmerRole,
@ -3005,7 +3040,7 @@ class ProductionStopDemandsService {
approvers,
),
stage: node.sortOrder,
finalStage: workflowNodes.at(-1)?.sortOrder ?? node.sortOrder,
finalStage: nodesForDemand.at(-1)?.sortOrder ?? node.sortOrder,
confirmerRole: node.confirmerRole,
votes,
})
@ -3274,6 +3309,7 @@ class ProductionStopDemandsService {
allApprovers,
targetNode.confirmerRole,
effectiveRoutingOwners,
fixedApproverName,
)
const priorAgreedIds = new Set(
votes.filter((vote) => vote.decision === 'AGREED').map((vote) => vote.approverId),
@ -3297,6 +3333,7 @@ class ProductionStopDemandsService {
allApprovers,
targetNode.confirmerRole,
effectiveRoutingOwners,
fixedApproverName,
)
applicableApprovers = candidates.filter(
(approver) => !priorAgreedIds.has(approver.id),
@ -3305,6 +3342,7 @@ class ProductionStopDemandsService {
const targetNames = resolveProductionStopConfirmationNodeNames(
targetNode.confirmerRole,
effectiveRoutingOwners,
fixedApproverName,
)
const isFinalTargetNode = targetNode.sortOrder === nodes.at(-1)?.sortOrder
if (
@ -3542,7 +3580,7 @@ class ProductionStopDemandsService {
}
const setting = await productionStopDemandRepository.getConfirmationSetting()
const workflowNodes = demand.confirmationStage > 0
? await this.activeConfirmationWorkflowNodes()
? await this.activeConfirmationWorkflowNodes({ includeFallback: true })
: []
const currentNode = workflowNodes.find((node) => (
node.sortOrder === demand.confirmationStage

View File

@ -767,6 +767,46 @@ describe('停产需求通知中心编排', () => {
expect(harness.sends.map((send) => send.recipientAlias)).not.toContain('张三')
})
it('固定兜底节点只推送给配置的兜底确认人', async () => {
const harness = createHarness([{
id: 'd1',
demandNo: 'TC20261020-002',
barcodes: ['A1'],
confirmationStage: 4,
opsDeptHead: [],
opsDirector: [],
}])
harness.repository.listActiveApprovers.mockResolvedValue([
{ id: 'a1', userId: 'u1', userName: '张三' },
{ id: 'a-haitang', userId: 'u-haitang', userName: '海棠' },
])
harness.repository.ensureConfirmationApproversByUserNames.mockImplementation(
async (names: string[]) => names.includes('海棠')
? [{ id: 'a-haitang', userId: 'u-haitang', userName: '海棠' }]
: [],
)
harness.repository.listConfirmationWorkflowNodes.mockResolvedValue([{
id: 'stage-fallback',
name: '兜底需求确认',
confirmerRole: 'FIXED_APPROVER',
timeNode: '14:00',
delayDays: 2,
timeoutAutoAgree: false,
nearDueWarningHours: 6,
note: '',
sortOrder: 4,
isActive: true,
fixedApproverUserId: 'u-haitang',
fixedApproverName: '海棠',
createdAt: new Date(),
updatedAt: new Date(),
}])
await harness.service.refreshAll()
expect(harness.sends.map((send) => send.recipientAlias)).toEqual(['海棠'])
})
it('账号已绑定钉钉 userId 时优先按 userId 发送,不再依赖花名', async () => {
const harness = createHarness([{
id: 'd1',

View File

@ -400,6 +400,7 @@ export class ProductionStopNotificationsService {
stageRecipients,
node.confirmerRole,
routedStageOwners,
fixedApproverName,
)
const finalStageRecipients = excludeConfirmedApproversFromFinalStage({
approvers: routedRecipients,