Merge branch 'codex/wuyongjie-production-stop-stage0-replay-20261125' into codex/xuxiake-mainline-stage0-replay-integration-20261125

This commit is contained in:
apple 2026-11-25 12:01:23 +08:00
commit 2e6fcb6f06
6 changed files with 745 additions and 71 deletions

View File

@ -43,6 +43,7 @@
"backfill:production-stop-archive-snapshot": "tsx scripts/backfill-production-stop-archive-snapshot.ts",
"audit:production-stop-owner-coverage": "tsx scripts/backfill-production-stop-archive-snapshot.ts --fail-on-pending-missing-owners",
"replay:production-stop-confirmation-workflow": "tsx scripts/replay-production-stop-confirmation-workflow.ts",
"replay:production-stop-stage0-confirmations": "tsx scripts/replay-production-stop-stage0-confirmations.ts",
"dispatch:production-stop-confirmation-warnings": "tsx scripts/dispatch-production-stop-confirmation-warnings.ts",
"run:product-sabc": "tsx scripts/run-product-sabc.ts",
"compare:product-sabc-xlsx": "tsx scripts/compare-product-sabc-xlsx.ts",

View File

@ -0,0 +1,670 @@
/**
* 正式站历史 stage=0 停产待确认单按新规则重新路由并推送。
*
* 默认 dry-run:
* npx tsx scripts/replay-production-stop-stage0-confirmations.ts
*
* 指定条码预演:
* npx tsx scripts/replay-production-stop-stage0-confirmations.ts \
* --barcodes=BG001436N66V01,BG001435N66V01
*
* 正式执行:
* npx tsx scripts/replay-production-stop-stage0-confirmations.ts \
* --apply --confirm=replay-production-stop-stage0-confirmations
*/
import 'dotenv/config'
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import {
OperationLogAction,
OperationLogStatus,
} from '@prisma/client'
import {
resolveProductionStopConfirmationDeadlineDetails,
type ProductionStopConfirmationWorkflowNode,
} from '../src/lib/production-stop-demands'
import { splitProductionStopOwnerNames } from '../src/lib/production-stop-confirmation-workflow'
import { prisma } from '../src/lib/prisma'
import { productionStopDemandRepository } from '../src/server/repositories/production-stop-demands.repository'
import { closeSupplyChainArchiveReadPool } from '../src/server/repositories/supply-chain-archive-read-pool'
import { productionStopFlowRepository } from '../src/server/repositories/production-stop-flow.repository'
import { operationLogService } from '../src/server/services/operation-log.service'
import { productionStopNotificationsService } from '../src/server/services/production-stop-notifications.service'
import { resolveProductionStopLiveRoutingOwnersByBarcodes } from '../src/server/services/production-stop-owner-resolver'
const APPLY_CONFIRMATION = 'replay-production-stop-stage0-confirmations'
type ActiveUser = {
id: string
name: string
dingtalkUserId: string | null
dingtalkUnionId: string | null
}
type ExistingVote = {
approverId: string
approverName: string
decision: string
confirmationStage: number
}
type RoutingFallback = {
originalUserId: string
originalUserName: string
fallbackUserId: string
fallbackUserName: string
}
type DemandPlan = {
demandId: string
demandNo: string
barcodes: string[]
existingVotes: ExistingVote[]
ownerNames: {
opsDeptHead: string[]
opsDirector: string[]
shopBusinessUnitHead: string[]
fallback: string[]
}
routeBranch: 'ZERO_VOTE' | 'NON_DIRECTOR_VOTE' | 'DIRECTOR_VOTE'
targetNode: string
targetStage: number
recipients: string[]
routingFallbacks: RoutingFallback[]
targetStatus: 'PENDING' | 'AGREED'
targetDemandStatus: 'PENDING_CONFIRMATION' | 'CONFIRMED_WAIT_FLOW'
targetDeadline: string
targetDeadlineNote: string
reason: string
blockingReason: string
}
type ApplyResult = {
processed: number
pendingPushes: number
sent: number
failed: number
confirmedWaitFlow: number
failures: Array<{ demandNo: string; error: string }>
}
function argumentValue(name: string) {
const prefix = `--${name}=`
return process.argv.find((argument) => argument.startsWith(prefix))?.slice(prefix.length)
}
function normalizeName(value: unknown) {
return String(value ?? '').trim().toLocaleLowerCase('zh-CN')
}
function uniqueNames(values: readonly string[]) {
return splitProductionStopOwnerNames(values)
}
function isDingtalkBound(user: ActiveUser | undefined) {
return Boolean(user?.dingtalkUserId || user?.dingtalkUnionId)
}
async function resolveSalesShopOwnersByBarcode(barcodes: readonly string[]) {
const shops = await prisma.supplyChainProductStopShopPerformance.findMany({
where: { barcode: { in: [...barcodes] } },
select: {
barcode: true,
shopName: true,
netQty: true,
realPerformance: true,
},
})
const salesShops = shops.filter((row) => (
Number(row.netQty) !== 0 || Number(row.realPerformance) !== 0
))
const storeNames = [...new Set(salesShops.map((row) => row.shopName.trim()).filter(Boolean))]
const accounts = storeNames.length
? await prisma.storeAccount.findMany({
where: { storeName: { in: storeNames } },
select: {
id: true,
storeName: true,
accountType: true,
operationDirector: true,
updatedAt: true,
},
})
: []
const accountByStore = new Map<string, typeof accounts[number]>()
for (const account of [...accounts].sort((left, right) => (
(left.accountType === 'MAIN' ? 0 : 1) - (right.accountType === 'MAIN' ? 0 : 1)
|| right.updatedAt.getTime() - left.updatedAt.getTime()
|| right.id.localeCompare(left.id)
))) {
const key = normalizeName(account.storeName)
if (!accountByStore.has(key) && account.operationDirector.trim()) {
accountByStore.set(key, account)
}
}
const result = new Map<string, string[]>()
for (const shop of salesShops) {
const barcode = shop.barcode.trim().toUpperCase()
const director = accountByStore.get(normalizeName(shop.shopName))?.operationDirector ?? ''
if (!barcode || !director.trim()) continue
const current = result.get(barcode) ?? []
if (!current.some((name) => normalizeName(name) === normalizeName(director))) {
current.push(director.trim())
}
result.set(barcode, current)
}
return result
}
function evaluateNode(
node: ProductionStopConfirmationWorkflowNode | null,
ownerNames: readonly string[],
usersByName: ReadonlyMap<string, ActiveUser>,
fallbackUser: ActiveUser | null,
) {
const names = uniqueNames(ownerNames)
if (!node || !names.length) return null
const knownUsers = names
.map((name) => usersByName.get(normalizeName(name)))
.filter((user): user is ActiveUser => Boolean(user))
if (!knownUsers.length) return null
const boundUsers = knownUsers.filter(isDingtalkBound)
const unboundUsers = knownUsers.filter((user) => !isDingtalkBound(user))
if (unboundUsers.length && !fallbackUser) {
return {
node,
recipients: [] as string[],
routingFallbacks: [] as RoutingFallback[],
blockingReason: `${node.name}的确认人 ${unboundUsers.map((user) => user.name).join('、')} 未绑定钉钉,且兜底确认人不可用`,
}
}
const recipients = uniqueNames([
...boundUsers.map((user) => user.name),
...(unboundUsers.length && fallbackUser ? [fallbackUser.name] : []),
])
return {
node,
recipients,
routingFallbacks: unboundUsers.map((user) => ({
originalUserId: user.id,
originalUserName: user.name,
fallbackUserId: fallbackUser!.id,
fallbackUserName: fallbackUser!.name,
})),
blockingReason: '',
}
}
function firstEvaluated(
nodes: Array<ProductionStopConfirmationWorkflowNode | null>,
owners: string[][],
usersByName: ReadonlyMap<string, ActiveUser>,
fallbackUser: ActiveUser | null,
) {
for (let index = 0; index < nodes.length; index += 1) {
const evaluated = evaluateNode(nodes[index], owners[index] ?? [], usersByName, fallbackUser)
if (evaluated) return evaluated
}
return null
}
async function planReplay() {
const allowedBarcodes = new Set(
(argumentValue('barcodes') ?? '')
.split(',')
.map((value) => value.trim().toUpperCase())
.filter(Boolean),
)
const rows = await prisma.productionStopDemand.findMany({
where: {
confirmationStatus: 'PENDING',
confirmationStage: 0,
},
select: {
id: true,
demandNo: true,
submittedAt: true,
confirmationVotes: {
select: {
approverId: true,
approverName: true,
decision: true,
confirmationStage: true,
},
orderBy: [{ respondedAt: 'asc' }, { id: 'asc' }],
},
items: {
select: { barcode: true },
orderBy: { createdAt: 'asc' },
},
},
orderBy: [{ submittedAt: 'asc' }, { demandNo: 'asc' }],
})
const demands = allowedBarcodes.size
? rows.filter((row) => row.items.some((item) => (
allowedBarcodes.has(item.barcode.trim().toUpperCase())
)))
: rows
const barcodes = [...new Set(demands.flatMap((demand) => (
demand.items.map((item) => item.barcode.trim().toUpperCase()).filter(Boolean)
)))]
const [liveOwners, shopOwners, workflowNodes, workCalendar] = await Promise.all([
resolveProductionStopLiveRoutingOwnersByBarcodes(barcodes),
resolveSalesShopOwnersByBarcode(barcodes),
productionStopDemandRepository.listConfirmationWorkflowNodes(),
productionStopDemandRepository.listWorkCalendarDays(),
])
const activeNodes = workflowNodes.filter((node) => node.isActive)
const stageOneNode = activeNodes.find((node) => node.confirmerRole === 'OPS_DEPT_HEAD') ?? null
const stageTwoNode = activeNodes.find((node) => node.confirmerRole === 'OPS_DIRECTOR') ?? null
const stageThreeNode = activeNodes.find((node) => (
node.confirmerRole === 'OTHER_SHOP_BUSINESS_UNIT_HEADS'
)) ?? null
const fallbackNode = activeNodes.find((node) => node.confirmerRole === 'FIXED_APPROVER') ?? null
const allOwnerNames = [...new Set(demands.flatMap((demand) => {
const names: string[] = []
for (const item of demand.items) {
const barcode = item.barcode.trim().toUpperCase()
const live = liveOwners.get(barcode)
names.push(
...(live?.opsDeptHead ?? []),
...(live?.opsDirector ?? []),
...(shopOwners.get(barcode) ?? []),
)
}
if (fallbackNode?.fixedApproverName) names.push(fallbackNode.fixedApproverName)
return names
}))]
const users = await prisma.user.findMany({
where: {
name: { in: allOwnerNames },
status: 'ACTIVE',
},
select: {
id: true,
name: true,
dingtalkUserId: true,
dingtalkUnionId: true,
},
})
const usersByName = new Map(users.map((user) => [normalizeName(user.name), user]))
const fallbackNames = uniqueNames([fallbackNode?.fixedApproverName ?? ''])
const fallbackUser = fallbackNames
.map((name) => usersByName.get(normalizeName(name)))
.find((user): user is ActiveUser => Boolean(user) && isDingtalkBound(user)) ?? null
const plans: DemandPlan[] = []
for (const demand of demands) {
const ownerNames = {
opsDeptHead: [] as string[],
opsDirector: [] as string[],
shopBusinessUnitHead: [] as string[],
fallback: fallbackNames,
}
for (const item of demand.items) {
const barcode = item.barcode.trim().toUpperCase()
const live = liveOwners.get(barcode)
ownerNames.opsDeptHead.push(...(live?.opsDeptHead ?? []))
ownerNames.opsDirector.push(...(live?.opsDirector ?? []))
ownerNames.shopBusinessUnitHead.push(...(shopOwners.get(barcode) ?? []))
}
ownerNames.opsDeptHead = uniqueNames(ownerNames.opsDeptHead)
ownerNames.opsDirector = uniqueNames(ownerNames.opsDirector)
const directorSet = new Set(ownerNames.opsDirector.map(normalizeName))
ownerNames.shopBusinessUnitHead = uniqueNames(ownerNames.shopBusinessUnitHead)
.filter((name) => !directorSet.has(normalizeName(name)))
const votes = demand.confirmationVotes
const nonDirectorVotes = votes.filter((vote) => (
!directorSet.has(normalizeName(vote.approverName))
))
const routeBranch = votes.length === 0
? 'ZERO_VOTE' as const
: nonDirectorVotes.length > 0
? 'NON_DIRECTOR_VOTE' as const
: 'DIRECTOR_VOTE' as const
let selected: ReturnType<typeof firstEvaluated> = null
let reason = ''
let blockingReason = ''
if (routeBranch === 'ZERO_VOTE') {
selected = firstEvaluated(
[stageOneNode, stageTwoNode, stageThreeNode],
[ownerNames.opsDeptHead, ownerNames.opsDirector, ownerNames.shopBusinessUnitHead],
usersByName,
fallbackUser,
)
if (!selected) {
if (fallbackUser && stageThreeNode) {
selected = {
node: stageThreeNode,
recipients: [fallbackUser.name],
routingFallbacks: [],
blockingReason: '',
}
reason = '历史票为0,一至三级均无有效负责人,推送兜底确认人'
} else {
blockingReason = '历史票为0,但一至三级和兜底均无可用确认人'
}
} else {
reason = `历史票为0,按一级→二级→三级选择 ${selected.node.name}`
}
} else if (routeBranch === 'NON_DIRECTOR_VOTE') {
selected = firstEvaluated(
[stageOneNode, stageTwoNode, stageThreeNode],
[ownerNames.opsDeptHead, ownerNames.opsDirector, ownerNames.shopBusinessUnitHead],
usersByName,
fallbackUser,
)
if (selected) {
reason = `历史确认人包含非运营总负责人,按一级→二级→三级选择 ${selected.node.name}`
} else {
reason = '历史确认人包含非运营总负责人,一至三级均无有效确认人,直接进入已确认待走流程'
}
} else {
selected = evaluateNode(
stageThreeNode,
ownerNames.shopBusinessUnitHead,
usersByName,
fallbackUser,
)
if (selected) {
reason = '历史确认票均来自运营总负责人,直接进入三级需求确认'
} else {
reason = '历史确认票均来自运营总负责人,三级无有效有销量店铺负责人,直接进入已确认待走流程'
}
}
if (selected?.blockingReason) {
blockingReason = selected.blockingReason
selected = null
}
const targetNode = selected?.node ?? stageThreeNode
const targetStatus = selected ? 'PENDING' as const : 'AGREED' as const
const schedule = selected
? resolveProductionStopConfirmationDeadlineDetails(
new Date(),
[{ timeNode: selected.node.timeNode, delayDays: selected.node.delayDays }],
workCalendar,
)
: null
if (targetStatus === 'PENDING' && !selected?.recipients.length) {
blockingReason = blockingReason || `${selected?.node.name ?? '目标节点'}没有可推送确认人`
}
plans.push({
demandId: demand.id,
demandNo: demand.demandNo,
barcodes: demand.items.map((item) => item.barcode),
existingVotes: votes,
ownerNames,
routeBranch,
targetNode: selected?.node.name ?? targetNode?.name ?? '',
targetStage: targetNode?.sortOrder ?? 0,
recipients: selected?.recipients ?? [],
routingFallbacks: selected?.routingFallbacks ?? [],
targetStatus,
targetDemandStatus: targetStatus === 'AGREED'
? 'CONFIRMED_WAIT_FLOW'
: 'PENDING_CONFIRMATION',
targetDeadline: schedule?.deadline ? schedule.deadline.toISOString() : '',
targetDeadlineNote: schedule?.note ?? '',
reason,
blockingReason: targetStatus === 'PENDING' ? blockingReason : '',
})
}
return { plans, usersByName, fallbackUser }
}
async function writeBackup(plans: readonly DemandPlan[]) {
const demandIds = plans.map((plan) => plan.demandId)
const [demands, votes, warnings, assignments] = await Promise.all([
prisma.productionStopDemand.findMany({ where: { id: { in: demandIds } } }),
prisma.productionStopDemandConfirmationVote.findMany({
where: { demandId: { in: demandIds } },
}),
prisma.productionStopConfirmationWarning.findMany({
where: { demandId: { in: demandIds } },
}),
prisma.productionStopDemandConfirmationAssignment.findMany({
where: { demandId: { in: demandIds } },
}),
])
const backupPath = resolve(
argumentValue('backup')
?? `.master-data-audits/production-stop-stage0-confirmation-replay-backup-${Date.now()}.json`,
)
await mkdir(dirname(backupPath), { recursive: true })
await writeFile(backupPath, JSON.stringify({
generatedAt: new Date().toISOString(),
demandIds,
demands,
votes,
warnings,
assignments,
}, null, 2), 'utf8')
return backupPath
}
async function applyPlans(
plans: readonly DemandPlan[],
): Promise<ApplyResult> {
const applicablePlans = plans.filter((plan) => !plan.blockingReason)
const allNames = [...new Set(applicablePlans.flatMap((plan) => [
...plan.recipients,
...plan.routingFallbacks.flatMap((fallback) => [
fallback.originalUserName,
fallback.fallbackUserName,
]),
]))]
const ensuredApprovers = allNames.length
? await productionStopDemandRepository.ensureConfirmationApproversByUserNames(allNames)
: []
const approverByName = new Map(
ensuredApprovers.map((approver) => [normalizeName(approver.userName), approver]),
)
const now = new Date()
const result: ApplyResult = {
processed: 0,
pendingPushes: 0,
sent: 0,
failed: 0,
confirmedWaitFlow: 0,
failures: [],
}
const chunkSize = Math.max(1, Math.min(100, Number(argumentValue('batch-size') ?? 25)))
for (let index = 0; index < applicablePlans.length; index += chunkSize) {
const chunk = applicablePlans.slice(index, index + chunkSize)
await prisma.$transaction(async (tx) => {
for (const plan of chunk) {
const updated = await tx.productionStopDemand.updateMany({
where: {
id: plan.demandId,
confirmationStatus: 'PENDING',
confirmationStage: 0,
},
data: {
confirmationStage: plan.targetStage,
confirmationStatus: plan.targetStatus,
confirmationAt: plan.targetStatus === 'AGREED' ? now : null,
confirmationReasons: '',
confirmationStageEnteredAt: now,
confirmationDeadline: plan.targetDeadline ? new Date(plan.targetDeadline) : null,
confirmationDeadlineNote: plan.targetDeadlineNote,
confirmationOverdueAt: null,
confirmationPushedAt: null,
confirmationPushMessage: '',
demandStatus: plan.targetDemandStatus,
demandStatusAt: now,
demandStatusNote: plan.targetStatus === 'AGREED'
? '历史0级确认单按新规则完成确认,进入已确认待走流程'
: `历史0级确认单按新规则重路由至${plan.targetNode}`,
...(plan.targetStatus === 'AGREED' ? { rejectionAt: null } : {}),
},
})
if (updated.count !== 1) {
throw new Error(`需求 ${plan.demandNo} 已不在待确认 stage=0,停止本批次`)
}
await tx.productionStopDemandConfirmationVote.deleteMany({
where: { demandId: plan.demandId, confirmationStage: 0 },
})
await tx.productionStopConfirmationWarning.updateMany({
where: {
demandId: plan.demandId,
status: { in: ['PENDING', 'PROCESSING', 'FAILED'] },
},
data: {
status: 'CANCELLED',
lastError: '原0级确认逻辑已清除,改按当前确认规则重跑',
},
})
await tx.productionStopDemandConfirmationAssignment.deleteMany({
where: { demandId: plan.demandId },
})
for (const fallback of plan.routingFallbacks) {
const approver = approverByName.get(normalizeName(fallback.originalUserName))
const fallbackApprover = approverByName.get(normalizeName(fallback.fallbackUserName))
if (!approver || !fallbackApprover) {
throw new Error(
`需求 ${plan.demandNo} 缺少确认人映射:${fallback.originalUserName} → ${fallback.fallbackUserName}`,
)
}
await tx.productionStopDemandConfirmationAssignment.create({
data: {
demandId: plan.demandId,
approverId: approver.id,
approverUserId: approver.userId,
approverName: approver.userName,
proxyUserId: fallback.fallbackUserId,
proxyUserName: fallback.fallbackUserName,
source: 'ROUTING_FALLBACK',
},
})
}
}
}, {
maxWait: 15_000,
timeout: 120_000,
})
const pendingChunk = chunk.filter((plan) => plan.targetStatus === 'PENDING')
result.processed += chunk.length
result.confirmedWaitFlow += chunk.filter((plan) => plan.targetStatus === 'AGREED').length
result.pendingPushes += pendingChunk.length
if (pendingChunk.length) {
const notificationResult = await productionStopNotificationsService
.refreshDemandConfirmations(pendingChunk.map((plan) => plan.demandId))
result.sent += notificationResult.sent
result.failed += notificationResult.failed
const message = notificationResult.failed
? `新规则推送完成 ${notificationResult.sent} 人,失败 ${notificationResult.failed} 人`
: `已按新规则推送 ${notificationResult.sent} 人`
await prisma.productionStopDemand.updateMany({
where: { id: { in: pendingChunk.map((plan) => plan.demandId) } },
data: {
confirmationPushedAt: notificationResult.sent ? now : null,
confirmationPushMessage: message,
},
})
}
}
await operationLogService.record({
action: OperationLogAction.PRODUCTION_STOP_DEMAND_UPDATE,
status: OperationLogStatus.SUCCESS,
source: 'SYSTEM',
actorId: null,
actorName: '系统管理员',
workspaceCategory: '停产需求管理',
message: `历史0级待确认单按新规则重路由 ${result.processed} 条`,
details: {
mode: 'APPLY',
processed: result.processed,
pendingPushes: result.pendingPushes,
sent: result.sent,
failed: result.failed,
confirmedWaitFlow: result.confirmedWaitFlow,
},
})
return result
}
async function main() {
const apply = process.argv.includes('--apply')
if (apply && argumentValue('confirm') !== APPLY_CONFIRMATION) {
throw new Error(`正式执行必须追加 --confirm=${APPLY_CONFIRMATION};未写入任何数据`)
}
const { plans, usersByName, fallbackUser } = await planReplay()
const blocking = plans.filter((plan) => plan.blockingReason)
const summary = {
mode: apply ? 'APPLY' : 'DRY_RUN',
scanned: plans.length,
byRouteBranch: Object.fromEntries(
['ZERO_VOTE', 'NON_DIRECTOR_VOTE', 'DIRECTOR_VOTE'].map((branch) => [
branch,
plans.filter((plan) => plan.routeBranch === branch).length,
]),
),
byTargetNode: Object.fromEntries(
[...new Set(plans.map((plan) => plan.targetNode || 'NO_RECIPIENT'))].map((node) => [
node,
plans.filter((plan) => (plan.targetNode || 'NO_RECIPIENT') === node).length,
]),
),
pendingPushes: plans.filter((plan) => plan.targetStatus === 'PENDING').length,
confirmedWaitFlow: plans.filter((plan) => plan.targetStatus === 'AGREED').length,
routingFallbackAssignments:
plans.reduce((sum, plan) => sum + plan.routingFallbacks.length, 0),
totalTargetRecipients: plans.reduce((sum, plan) => sum + plan.recipients.length, 0),
maxRecipientsPerDemand: Math.max(0, ...plans.map((plan) => plan.recipients.length)),
missingSelectedDingtalk:
plans.flatMap((plan) => plan.recipients)
.map((name) => usersByName.get(normalizeName(name)))
.filter((user): user is ActiveUser => Boolean(user))
.filter((user) => !isDingtalkBound(user)).length,
fallbackRecipientAvailable: Boolean(fallbackUser && isDingtalkBound(fallbackUser)),
blocked: blocking.length,
}
const outputPath = resolve(
argumentValue('output')
?? (apply
? '.master-data-audits/production-stop-stage0-confirmation-replay-apply.json'
: '.master-data-audits/production-stop-stage0-confirmation-replay-dry-run.json'),
)
await mkdir(dirname(outputPath), { recursive: true })
if (apply) {
if (blocking.length) {
throw new Error(`有 ${blocking.length} 条需求存在阻断原因,未写入任何数据`)
}
if (!productionStopNotificationsService.isEnabled()) {
throw new Error('通知中心未启用,未写入任何数据')
}
const backupPath = await writeBackup(plans)
const applyResult = await applyPlans(plans)
await writeFile(outputPath, JSON.stringify({
summary: { ...summary, applyResult, backupPath },
plans,
}, null, 2), 'utf8')
console.log(JSON.stringify({
...summary,
applyResult,
backupPath,
outputPath,
}, null, 2))
return
}
await writeFile(outputPath, JSON.stringify({ summary, plans }, null, 2), 'utf8')
console.log(JSON.stringify({ ...summary, blockedSamples: blocking.slice(0, 20), outputPath }, null, 2))
}
main()
.catch((error) => {
console.error('[production-stop-stage0-replay] FAILED:', error)
process.exitCode = 1
})
.finally(async () => {
await prisma.$disconnect().catch(() => null)
await productionStopFlowRepository.close().catch(() => null)
await closeSupplyChainArchiveReadPool().catch(() => null)
})

View File

@ -889,12 +889,7 @@ class ProductStopDetailRepository {
SELECT *
FROM shop_rows
WHERE "sales30d" <> 0
OR "sales30dWithBig" <> 0
OR "dailyRealPerformance" <> 0
OR "grossMargin" <> 0
OR "feeRatio" <> 0
OR "afterSaleRatio" <> 0
OR "dailyOperatingProfit" <> 0
ORDER BY "barcode", "platform", "shopName"
`)
}

View File

@ -306,7 +306,7 @@ export type ProductionStopConfirmationAssignmentRecord = {
approverName: string
proxyUserId: string
proxyUserName: string
source: 'LEAVE' | 'WORK_CALENDAR'
source: 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK'
}
export type ProductionStopNewDemandNoticeRow = {
@ -2372,6 +2372,7 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit
const rows = await prisma.productionStopDemand.findMany({
where: {
confirmationStatus: 'PENDING',
confirmationStage: { gt: 0 },
...(targets === undefined ? {} : { id: { in: targets } }),
},
select: {
@ -2414,6 +2415,7 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit
return prisma.productionStopDemand.findMany({
where: {
confirmationStatus: 'PENDING',
confirmationStage: { gt: 0 },
confirmationOverdueAt: { not: null },
},
select: { id: true, demandNo: true },
@ -3758,7 +3760,7 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit
})
return rows.map((row) => ({
...row,
source: row.source as 'LEAVE' | 'WORK_CALENDAR',
source: row.source as 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK',
}))
}

View File

@ -69,7 +69,7 @@ function createHarness(initialPending: DemandRef[] = []) {
.filter((row) => !demandIds || demandIds.includes(row.id))
.map((row) => ({
barcodes: [],
confirmationStage: 0,
confirmationStage: 1,
confirmationStageEnteredAt: null,
confirmationDeadline: null,
opsDeptHead: [],
@ -210,7 +210,7 @@ function createHarness(initialPending: DemandRef[] = []) {
id: row.id,
demandNo: row.demandNo,
confirmationStatus: 'PENDING',
confirmationStage: row.confirmationStage ?? 0,
confirmationStage: row.confirmationStage ?? 1,
confirmationDeadline: row.confirmationDeadline ?? null,
}
: null
@ -316,9 +316,9 @@ describe('停产需求通知中心编排', () => {
{ id: 'd1', demandNo: 'TC20261020-001', barcodes: ['A1'] },
{ id: 'd2', demandNo: 'TC20261020-002', barcodes: ['A2'] },
])
harness.resolveDirectorNames.mockResolvedValue(new Map([
['A1', ['张三']],
['A2', ['张三']],
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
['A2', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
const first = await harness.service.refreshAll()
@ -350,9 +350,9 @@ describe('停产需求通知中心编排', () => {
{ id: 'a2', userId: 'u2', userName: '李四' },
{ id: 'a3', userId: 'u3', userName: '王五' },
])
harness.resolveDirectorNames.mockResolvedValue(new Map([
['A1', ['张三']],
['A2', ['李四']],
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
['A2', { opsDeptHead: ['李四'], opsDirector: [] }],
]))
const result = await harness.service.refreshAll()
@ -402,14 +402,15 @@ describe('停产需求通知中心编排', () => {
id: 'd1',
demandNo: 'TC20261020-001',
barcodes: ['A1'],
confirmationStage: 0,
confirmationStageEnteredAt: stageEnteredAt,
confirmationDeadline: deadline,
}])
harness.repository.listActiveApprovers.mockResolvedValue([
{ id: 'a1', userId: 'u1', userName: '张三' },
])
harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]]))
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
await harness.service.refreshAll()
@ -439,9 +440,9 @@ describe('停产需求通知中心编排', () => {
{ id: 'a2', userId: 'u2', userName: '李四' },
{ id: 'a3', userId: 'u3', userName: '王五' },
])
harness.resolveDirectorNames.mockResolvedValue(new Map([
['A1', ['张三']],
['A2', []],
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
['A2', { opsDeptHead: [], opsDirector: [] }],
]))
await harness.service.refreshAll()
@ -456,9 +457,9 @@ describe('停产需求通知中心编排', () => {
{ id: 'd1', demandNo: 'TC20261020-001', barcodes: ['A1'] },
{ id: 'd2', demandNo: 'TC20261020-002', barcodes: ['A2'] },
])
harness.resolveDirectorNames.mockResolvedValue(new Map([
['A1', ['张三']],
['A2', ['张三']],
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
['A2', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
const result = await harness.service.refreshDemandConfirmations(['d1'])
@ -475,11 +476,12 @@ describe('停产需求通知中心编排', () => {
.toBe(true)
})
it('旧流程没有店铺负责人时按产品档案运营总负责人精确推送', async () => {
it('三级没有有销量店铺负责人时不回退运营总负责人', async () => {
const harness = createHarness([{
id: 'd1',
demandNo: 'TC20261020-001',
barcodes: ['A1'],
confirmationStage: 3,
}])
harness.repository.listActiveApprovers.mockResolvedValue([
{ id: 'a1', userId: 'u1', userName: '张三' },
@ -494,7 +496,7 @@ describe('停产需求通知中心编排', () => {
await harness.service.refreshAll()
expect(harness.sends.map((send) => send.recipientAlias)).toEqual(['张三'])
expect(harness.sends).toEqual([])
})
it('一级和二级节点只推送当前节点实际负责人', async () => {
@ -539,7 +541,9 @@ describe('停产需求通知中心编排', () => {
demandNo: 'TC20261020-001',
barcodes: ['A1'],
}])
harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]]))
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
await harness.service.refreshAll()
harness.setPending([])
@ -620,7 +624,9 @@ describe('停产需求通知中心编排', () => {
createdAt: new Date(),
updatedAt: new Date(),
}])
harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]]))
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
await harness.service.refreshAll()
@ -771,7 +777,9 @@ describe('停产需求通知中心编排', () => {
{ id: 'a1', userId: 'u1', userName: '张三' },
])
harness.repository.findUserDingtalkIds.mockResolvedValue(new Map([['u1', 'ding-user-1']]))
harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]]))
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
await harness.service.refreshAll()
@ -785,7 +793,9 @@ describe('停产需求通知中心编排', () => {
demandNo: 'TC20261020-001',
barcodes: ['A1'],
}])
harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]]))
harness.resolveRoutingOwners.mockResolvedValue(new Map([
['A1', { opsDeptHead: ['张三'], opsDirector: [] }],
]))
harness.client.send.mockRejectedValueOnce(new Error('network down'))
const failed = await harness.service.refreshAll()
@ -810,7 +820,7 @@ describe('停产需求通知中心编排', () => {
id: 'warning-1',
demandId: 'd1',
demandNo: 'TC20261020-001',
confirmationStage: 0,
confirmationStage: 1,
stageEnteredAt: new Date(),
approverId: 'a1',
approverUserId: 'u1',
@ -828,7 +838,7 @@ describe('停产需求通知中心编排', () => {
id: 'd1',
demandNo: 'TC20261020-001',
confirmationStatus: 'PENDING',
confirmationStage: 0,
confirmationStage: 1,
confirmationDeadline: null,
})
@ -847,7 +857,7 @@ describe('停产需求通知中心编排', () => {
id: 'warning-2',
demandId: 'd1',
demandNo: 'TC20261020-001',
confirmationStage: 0,
confirmationStage: 1,
stageEnteredAt: new Date(),
approverId: 'a1',
approverUserId: 'u1',
@ -867,7 +877,7 @@ describe('停产需求通知中心编排', () => {
approverUserId: 'u1',
approverName: '张三',
decision: 'AGREED',
confirmationStage: 0,
confirmationStage: 1,
rejectionCategory: '',
reason: '',
source: 'USER',
@ -881,7 +891,7 @@ describe('停产需求通知中心编排', () => {
id: 'warning-3',
demandId: 'd1',
demandNo: 'TC20261020-001',
confirmationStage: 0,
confirmationStage: 1,
stageEnteredAt: new Date(),
approverId: 'a1',
approverUserId: 'u1',
@ -899,7 +909,7 @@ describe('停产需求通知中心编排', () => {
id: 'd1',
demandNo: 'TC20261020-001',
confirmationStatus: 'PENDING',
confirmationStage: 0,
confirmationStage: 1,
confirmationDeadline: new Date(),
confirmationOverdueAt: new Date(),
})

View File

@ -16,7 +16,6 @@ import {
type ProductionStopNewDemandRecipientType,
type ProductionStopPendingNotificationKind,
} from '@/lib/production-stop-notifications'
import { resolveProductionStopConfirmationApprovers } from '@/lib/production-stop-confirmation-routing'
import {
excludeConfirmedApproversFromFinalStage,
resolveProductionStopConfirmationNodeApprovers,
@ -234,7 +233,7 @@ export class ProductionStopNotificationsService {
const currentProxyByOriginalUser = new Map<string, {
proxyUserId: string
proxyUserName: string
source: 'LEAVE' | 'WORK_CALENDAR'
source: 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK'
}>()
if (kind === 'CONFIRM_PENDING') {
const calendarAssignments =
@ -342,7 +341,7 @@ export class ProductionStopNotificationsService {
approverName: string
proxyUserId: string
proxyUserName: string
source: 'LEAVE' | 'WORK_CALENDAR'
source: 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK'
}> = []
const warningUpserts: Promise<void>[] = []
for (const demand of pendingDemands) {
@ -353,15 +352,12 @@ export class ProductionStopNotificationsService {
const directorNames = (demand.barcodes ?? []).flatMap((barcode) => (
directorsByBarcode.get(barcode.trim().toUpperCase()) ?? []
))
const legacyDirectorNames = [
...directorNames,
...liveOwners.flatMap((owner) => owner.opsDirector),
]
const everyBarcodeMatched = (demand.barcodes?.length ?? 0) > 0
&& liveOwners.length === demand.barcodes.length
const node = demand.confirmationStage > 0
? workflowNodeByStage.get(demand.confirmationStage)
: null
if (!node) continue
const stageOwners = {
opsDeptHead: [...new Set([
...liveOwners.flatMap((owner) => owner.opsDeptHead),
@ -373,20 +369,17 @@ export class ProductionStopNotificationsService {
])],
shopBusinessUnitHead: directorNames,
}
const stageNames = node
? resolveProductionStopConfirmationRoutingNames(
node.confirmerRole,
stageOwners,
fixedApproverName,
)
: []
const stageNames = resolveProductionStopConfirmationRoutingNames(
node.confirmerRole,
stageOwners,
fixedApproverName,
)
const ensuredStageApprovers = stageNames.length
? await this.repository.ensureConfirmationApproversByUserNames(stageNames)
: []
for (const approver of ensuredStageApprovers) {
if (!recipientMap.has(approver.id)) recipientMap.set(approver.id, approver)
}
const baseRecipients = originalRecipients
const stageRecipients = [...new Map(
[...ensuredStageApprovers, ...originalRecipients].map((recipient) => [
recipient.id,
@ -403,26 +396,19 @@ export class ProductionStopNotificationsService {
routedStageOwners = { ...stageOwners, opsDeptHead: stageNames }
}
}
const routedRecipients = node
? resolveProductionStopConfirmationNodeApprovers(
stageRecipients,
node.confirmerRole,
routedStageOwners,
)
: resolveProductionStopConfirmationApprovers(
baseRecipients,
legacyDirectorNames,
)
const finalStageRecipients = node
? excludeConfirmedApproversFromFinalStage({
approvers: routedRecipients,
stage: node.sortOrder,
finalStage: finalConfirmationStage ?? node.sortOrder,
confirmerRole: node.confirmerRole,
votes: [...(agreedApproverIdsByDemand.get(demand.id) ?? [])]
.map((approverId) => ({ approverId, decision: 'AGREED' as const })),
})
: routedRecipients
const routedRecipients = resolveProductionStopConfirmationNodeApprovers(
stageRecipients,
node.confirmerRole,
routedStageOwners,
)
const finalStageRecipients = excludeConfirmedApproversFromFinalStage({
approvers: routedRecipients,
stage: node.sortOrder,
finalStage: finalConfirmationStage ?? node.sortOrder,
confirmerRole: node.confirmerRole,
votes: [...(agreedApproverIdsByDemand.get(demand.id) ?? [])]
.map((approverId) => ({ approverId, decision: 'AGREED' as const })),
})
for (const originalRecipient of finalStageRecipients) {
if (voteStageApproverKeys.has(
`${demand.id}:${demand.confirmationStage}:${originalRecipient.id}`,
@ -451,7 +437,7 @@ export class ProductionStopNotificationsService {
userName: proxyUserName,
}
: originalRecipient
const stageName = node?.name ?? `第${demand.confirmationStage}级需求确认`
const stageName = node.name
const deadlineText = demand.confirmationDeadline
? REMINDER_DEADLINE_FORMATTER.format(demand.confirmationDeadline)
: ''
@ -668,6 +654,11 @@ export class ProductionStopNotificationsService {
) {
const client = this.createClient()
if (!client) return { sent: 0, failed: 0, cancelled: 0 }
const activeStages = new Set(
(await this.repository.listConfirmationWorkflowNodes())
.filter((node) => node.isActive)
.map((node) => node.sortOrder),
)
const warnings = await this.repository.claimDueConfirmationWarnings(
now,
limit,
@ -681,6 +672,11 @@ export class ProductionStopNotificationsService {
let failed = 0
let cancelled = 0
for (const warning of warnings) {
if (warning.confirmationStage <= 0 || !activeStages.has(warning.confirmationStage)) {
await this.repository.cancelConfirmationWarning(warning.id)
cancelled += 1
continue
}
if (warning.warningType !== 'TIMEOUT') {
const demand = await this.repository.findDemandById(warning.demandId)
const votes = await this.repository.listConfirmationVotes(warning.demandId)