Merge remote-tracking branch 'origin/codex/xuxiake-mainline' into codex/wuyongjie-main-stage0-replay-release-20261125
This commit is contained in:
commit
4ba18cd615
@ -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",
|
||||
|
||||
@ -0,0 +1,28 @@
|
||||
-- 商品品牌升级监控(普通大货 → 自有品牌,连续不达标回退)
|
||||
CREATE TABLE "SupplyChainBrandUpgradeMonitor" (
|
||||
"id" TEXT NOT NULL,
|
||||
"spu" VARCHAR(64) NOT NULL,
|
||||
"periodKey" VARCHAR(7) NOT NULL,
|
||||
"suggestedBrand" VARCHAR(64) NOT NULL,
|
||||
"storeName" VARCHAR(128) NOT NULL DEFAULT '',
|
||||
"storePerformance" DECIMAL(20,4) NOT NULL DEFAULT 0,
|
||||
"threeStorePerformance" DECIMAL(20,4) NOT NULL DEFAULT 0,
|
||||
"shareRatio" DECIMAL(10,6) NOT NULL DEFAULT 0,
|
||||
"status" VARCHAR(32) NOT NULL DEFAULT 'NOTIFIED',
|
||||
"notifiedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"brandChangedAt" TIMESTAMP(3),
|
||||
"failedMonths" INTEGER NOT NULL DEFAULT 0,
|
||||
"lastEvaluatedPeriod" VARCHAR(7),
|
||||
"revertNotifiedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "SupplyChainBrandUpgradeMonitor_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "SupplyChainBrandUpgradeMonitor_spu_periodKey_suggestedBrand_key"
|
||||
ON "SupplyChainBrandUpgradeMonitor"("spu", "periodKey", "suggestedBrand");
|
||||
CREATE INDEX "SupplyChainBrandUpgradeMonitor_status_idx"
|
||||
ON "SupplyChainBrandUpgradeMonitor"("status");
|
||||
CREATE INDEX "SupplyChainBrandUpgradeMonitor_spu_idx"
|
||||
ON "SupplyChainBrandUpgradeMonitor"("spu");
|
||||
@ -6870,3 +6870,27 @@ model ReferenceEstimateRecord {
|
||||
|
||||
@@index([ownerId, updatedAt])
|
||||
}
|
||||
|
||||
/// 商品品牌升级监控:普通大货 → 自有品牌(亿家达/卓禾/欧意朗),连续不达标回退
|
||||
model SupplyChainBrandUpgradeMonitor {
|
||||
id String @id @default(cuid())
|
||||
spu String @db.VarChar(64)
|
||||
periodKey String @db.VarChar(7)
|
||||
suggestedBrand String @db.VarChar(64)
|
||||
storeName String @default("") @db.VarChar(128)
|
||||
storePerformance Decimal @default(0) @db.Decimal(20, 4)
|
||||
threeStorePerformance Decimal @default(0) @db.Decimal(20, 4)
|
||||
shareRatio Decimal @default(0) @db.Decimal(10, 6)
|
||||
status String @default("NOTIFIED") @db.VarChar(32)
|
||||
notifiedAt DateTime @default(now())
|
||||
brandChangedAt DateTime?
|
||||
failedMonths Int @default(0)
|
||||
lastEvaluatedPeriod String? @db.VarChar(7)
|
||||
revertNotifiedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([spu, periodKey, suggestedBrand])
|
||||
@@index([status])
|
||||
@@index([spu])
|
||||
}
|
||||
|
||||
@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env bash
|
||||
# 安装/更新「商品品牌升级监控」月度任务(Linux systemd)。
|
||||
# 默认每月 3 日 04:00(Asia/Shanghai)执行,统计上一个自然月:
|
||||
# 1) 普通大货 → 自有品牌 升级推送
|
||||
# 2) 已升级且连续约 60 天不达标 → 回退推送
|
||||
set -euo pipefail
|
||||
|
||||
BASE="${FURNITURE_PROD_BASE:-/opt/furniture-3d-system-prod}"
|
||||
SERVICE_NAME="${BRAND_UPGRADE_MONITOR_SERVICE_NAME:-furniture-brand-upgrade-monitor}"
|
||||
APP_ROOT="$BASE/current/furniture-3d-system"
|
||||
SHARED="$BASE/shared"
|
||||
APP_ENV="$SHARED/.env"
|
||||
SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service"
|
||||
TIMER_FILE="/etc/systemd/system/$SERVICE_NAME.timer"
|
||||
SCHEDULE="${BRAND_UPGRADE_MONITOR_SCHEDULE:-*-*-03 04:00:00 Asia/Shanghai}"
|
||||
RANDOMIZED_DELAY_SEC="${BRAND_UPGRADE_MONITOR_RANDOMIZED_DELAY_SEC:-10min}"
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "This installer must run as root." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -d "$APP_ROOT" ]; then
|
||||
echo "Missing app root: $APP_ROOT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$APP_ENV" ]; then
|
||||
echo "Missing app env: $APP_ENV" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cat >"$SERVICE_FILE" <<EOF
|
||||
[Unit]
|
||||
Description=Publish product brand upgrade / revert reminders from last month's SABC and Tmall sales
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=$APP_ROOT
|
||||
Environment=NODE_ENV=production
|
||||
EnvironmentFile=$APP_ENV
|
||||
ExecStart=/bin/bash -lc 'set -euo pipefail; period=\$(date -d "\$(date +%%Y-%%m-01) -1 day" +%%Y-%%m); cd "$APP_ROOT"; ./node_modules/.bin/tsx scripts/run-brand-upgrade-monitor.ts --apply --period=\$period'
|
||||
TimeoutStartSec=2h
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
EOF
|
||||
|
||||
cat >"$TIMER_FILE" <<EOF
|
||||
[Unit]
|
||||
Description=Publish product brand upgrade reminders on the third day of each month
|
||||
|
||||
[Timer]
|
||||
OnCalendar=$SCHEDULE
|
||||
Persistent=true
|
||||
RandomizedDelaySec=$RANDOMIZED_DELAY_SEC
|
||||
Unit=$SERVICE_NAME.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now "$SERVICE_NAME.timer"
|
||||
systemctl list-timers --all "$SERVICE_NAME.timer" --no-pager
|
||||
|
||||
echo "已安装 $SERVICE_NAME.timer($SCHEDULE)"
|
||||
echo "推送接收人默认「海棠」,可用 SUPPLY_CHAIN_BRAND_UPGRADE_RECIPIENT 覆盖。"
|
||||
echo "内部接口密钥:BRAND_UPGRADE_MONITOR_SECRET(POST /api/internal/brand-upgrade-monitor/run)"
|
||||
@ -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)
|
||||
})
|
||||
30
furniture-3d-system/scripts/run-brand-upgrade-monitor.ts
Normal file
30
furniture-3d-system/scripts/run-brand-upgrade-monitor.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { loadEnvConfig } from '@next/env'
|
||||
|
||||
loadEnvConfig(process.cwd())
|
||||
|
||||
function arg(name: string) {
|
||||
const prefix = `--${name}=`
|
||||
return process.argv.slice(2).find((value) => value.startsWith(prefix))?.slice(prefix.length) ?? ''
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// 默认只算不推;正式推送必须显式 --apply
|
||||
const dryRun = !process.argv.includes('--apply')
|
||||
const periodKey = arg('period') || undefined
|
||||
const [{ prisma }, { supplyChainBrandUpgradeMonitorService }] = await Promise.all([
|
||||
import('../src/lib/prisma'),
|
||||
import('../src/server/services/supply-chain-brand-upgrade-monitor.service'),
|
||||
])
|
||||
try {
|
||||
const summary = await supplyChainBrandUpgradeMonitorService.run({ periodKey, dryRun })
|
||||
console.log(JSON.stringify(summary, null, 2))
|
||||
if (summary.errors.length > 0) process.exitCode = 1
|
||||
} finally {
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.stack || error.message : String(error))
|
||||
process.exitCode = 1
|
||||
})
|
||||
@ -0,0 +1,27 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainBrandUpgradeMonitorService } from '@/server/services/supply-chain-brand-upgrade-monitor.service'
|
||||
|
||||
function hasCronSecret(request: NextRequest) {
|
||||
const expected = process.env.BRAND_UPGRADE_MONITOR_SECRET?.trim()
|
||||
const received = request.headers.get('x-brand-upgrade-monitor-secret')?.trim()
|
||||
return Boolean(expected && received && expected === received)
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
if (!hasCronSecret(request)) {
|
||||
return jsonError(
|
||||
ErrorCode.AUTH_INVALID_TOKEN,
|
||||
'品牌升级监控执行密钥无效',
|
||||
401,
|
||||
ctx.requestId,
|
||||
)
|
||||
}
|
||||
const period = request.nextUrl.searchParams.get('period')?.trim() || undefined
|
||||
const dryRun = request.nextUrl.searchParams.get('dryRun') === 'true'
|
||||
const summary = await supplyChainBrandUpgradeMonitorService.run({ periodKey: period, dryRun })
|
||||
return jsonSuccess(summary, 200, ctx.requestId)
|
||||
}, { requireAuth: false })
|
||||
}
|
||||
@ -0,0 +1,86 @@
|
||||
import sql from 'mssql'
|
||||
|
||||
/** 参与「品牌升级」判断的三家天猫店(聚水潭 shop_name 实际写法)。 */
|
||||
export const BRAND_UPGRADE_TMALL_STORES = [
|
||||
'天猫_亿家达旗舰店',
|
||||
'天猫_卓禾家具旗舰店',
|
||||
'天猫_欧意朗旗舰店',
|
||||
] as const
|
||||
|
||||
export type TmallStoreSalesRow = {
|
||||
shopName: string
|
||||
barcode: string
|
||||
realPerformance: number
|
||||
}
|
||||
|
||||
let pool: sql.ConnectionPool | null = null
|
||||
|
||||
function requiredEnv(name: string) {
|
||||
const value = process.env[name]?.trim()
|
||||
if (!value) throw new Error(`Missing required environment variable: ${name}`)
|
||||
return value
|
||||
}
|
||||
|
||||
function booleanEnv(name: string, fallback: boolean) {
|
||||
const value = process.env[name]?.trim().toLowerCase()
|
||||
if (!value) return fallback
|
||||
return value === 'true' || value === '1'
|
||||
}
|
||||
|
||||
async function getPool() {
|
||||
if (pool?.connected) return pool
|
||||
pool = await 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: booleanEnv('JST_REPORT_DB_ENCRYPT', true),
|
||||
trustServerCertificate: booleanEnv('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE', true),
|
||||
},
|
||||
requestTimeout: Number(process.env.JST_REPORT_DB_REQUEST_TIMEOUT_MS?.trim() || '600000'),
|
||||
pool: { max: 2, min: 0, idleTimeoutMillis: 60_000 },
|
||||
}).connect()
|
||||
return pool
|
||||
}
|
||||
|
||||
/**
|
||||
* 按「店铺 + 商品编码」汇总指定月份的真实业绩(只查三家天猫店)。
|
||||
* 日期参数使用 YYYY-MM-DD(含首尾)。
|
||||
*/
|
||||
export async function listTmallStoreSales(input: {
|
||||
periodStart: string
|
||||
periodEnd: string
|
||||
stores?: readonly string[]
|
||||
}): Promise<TmallStoreSalesRow[]> {
|
||||
const stores = input.stores ?? BRAND_UPGRADE_TMALL_STORES
|
||||
if (!stores.length) return []
|
||||
const request = (await getPool()).request()
|
||||
request.input('periodStart', sql.Date, input.periodStart)
|
||||
request.input('periodEnd', sql.Date, input.periodEnd)
|
||||
const storeParams = stores.map((store, index) => {
|
||||
const name = `store${index}`
|
||||
request.input(name, sql.NVarChar(200), store)
|
||||
return `@${name}`
|
||||
})
|
||||
const result = await request.query<{
|
||||
shopName: string
|
||||
barcode: string
|
||||
realPerformance: string
|
||||
}>(`
|
||||
SELECT LTRIM(RTRIM(shop_name)) AS shopName,
|
||||
UPPER(LTRIM(RTRIM(CAST(skuoid AS nvarchar(100))))) AS barcode,
|
||||
SUM(CAST(COALESCE(real_performance, 0) AS decimal(38, 4))) AS realPerformance
|
||||
FROM [rpt].[dws_sn_sales_full_info_di]
|
||||
WHERE stat_date >= @periodStart
|
||||
AND stat_date <= @periodEnd
|
||||
AND LTRIM(RTRIM(shop_name)) IN (${storeParams.join(', ')})
|
||||
GROUP BY LTRIM(RTRIM(shop_name)), UPPER(LTRIM(RTRIM(CAST(skuoid AS nvarchar(100)))))
|
||||
`)
|
||||
return result.recordset.map((row) => ({
|
||||
shopName: String(row.shopName ?? '').trim(),
|
||||
barcode: String(row.barcode ?? '').trim().toUpperCase(),
|
||||
realPerformance: Number(row.realPerformance || 0),
|
||||
}))
|
||||
}
|
||||
@ -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"
|
||||
`)
|
||||
}
|
||||
|
||||
@ -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',
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@ -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(),
|
||||
})
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -0,0 +1,445 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { dingtalkWorkNotificationService } from '@/server/integrations/dingtalk/dingtalk-work-notification.service'
|
||||
import {
|
||||
BRAND_UPGRADE_TMALL_STORES,
|
||||
listTmallStoreSales,
|
||||
} from '@/server/repositories/jst-tmall-store-sales.repository'
|
||||
|
||||
/** 升级前品牌 */
|
||||
export const BRAND_UPGRADE_SOURCE_BRAND = '其他品牌-普通大货'
|
||||
|
||||
/** 三家天猫店 → 对应自有品牌(按达标店铺决定建议品牌) */
|
||||
export const BRAND_UPGRADE_STORE_BRAND_MAP: Record<string, string> = {
|
||||
'天猫_亿家达旗舰店': '自有品牌-亿家达',
|
||||
'天猫_卓禾家具旗舰店': '自有品牌-卓禾',
|
||||
'天猫_欧意朗旗舰店': '自有品牌-欧意朗',
|
||||
}
|
||||
|
||||
export const BRAND_UPGRADE_OWN_BRANDS = new Set(Object.values(BRAND_UPGRADE_STORE_BRAND_MAP))
|
||||
|
||||
/** 单店真实业绩门槛 */
|
||||
export const BRAND_UPGRADE_MIN_STORE_PERFORMANCE = 60_000
|
||||
/** 单店在「三大天猫店合计」中的占比门槛 */
|
||||
export const BRAND_UPGRADE_MIN_SHARE = 0.6
|
||||
/** 品牌变更后连续多少个自然月不达标才回退(≈60 天,可用环境变量覆盖) */
|
||||
export const BRAND_UPGRADE_REVERT_FAILED_MONTHS = Math.max(
|
||||
1,
|
||||
Number(process.env.SUPPLY_CHAIN_BRAND_UPGRADE_REVERT_MONTHS?.trim() || '2') || 2,
|
||||
)
|
||||
export const DEFAULT_BRAND_UPGRADE_RECIPIENT = '海棠'
|
||||
|
||||
export type BrandUpgradePeriod = {
|
||||
periodKey: string
|
||||
start: Date
|
||||
end: Date
|
||||
startText: string
|
||||
endText: string
|
||||
}
|
||||
|
||||
export type BrandUpgradeHit = {
|
||||
storeName: string
|
||||
suggestedBrand: string
|
||||
storePerformance: number
|
||||
threeStorePerformance: number
|
||||
shareRatio: number
|
||||
}
|
||||
|
||||
export type BrandUpgradeEvaluation = {
|
||||
threeStorePerformance: number
|
||||
hits: BrandUpgradeHit[]
|
||||
}
|
||||
|
||||
function round2(value: number) {
|
||||
return Math.round(value * 100) / 100
|
||||
}
|
||||
|
||||
function shanghaiYearMonth(now: Date) {
|
||||
const shifted = new Date(now.getTime() + 8 * 60 * 60 * 1000)
|
||||
return { year: shifted.getUTCFullYear(), month: shifted.getUTCMonth() + 1 }
|
||||
}
|
||||
|
||||
/** 当前月份(上海时区),如 2026-11 */
|
||||
export function shanghaiPeriodKey(now = new Date()) {
|
||||
const { year, month } = shanghaiYearMonth(now)
|
||||
return `${year}-${String(month).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
/** 上一个自然月,如 2026-10 */
|
||||
export function previousPeriodKey(now = new Date()) {
|
||||
const { year, month } = shanghaiYearMonth(now)
|
||||
const previousYear = month === 1 ? year - 1 : year
|
||||
const previousMonth = month === 1 ? 12 : month - 1
|
||||
return `${previousYear}-${String(previousMonth).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function periodDateRange(periodKey: string): BrandUpgradePeriod {
|
||||
const match = /^(\d{4})-(\d{2})$/.exec(periodKey.trim())
|
||||
if (!match) throw new Error(`核算月份格式不正确:${periodKey}`)
|
||||
const year = Number(match[1])
|
||||
const month = Number(match[2])
|
||||
if (month < 1 || month > 12) throw new Error(`核算月份格式不正确:${periodKey}`)
|
||||
const start = new Date(Date.UTC(year, month - 1, 1))
|
||||
const end = new Date(Date.UTC(year, month, 0))
|
||||
return {
|
||||
periodKey: `${year}-${String(month).padStart(2, '0')}`,
|
||||
start,
|
||||
end,
|
||||
startText: start.toISOString().slice(0, 10),
|
||||
endText: end.toISOString().slice(0, 10),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一个 SPU 是否达到「品牌升级」条件:
|
||||
* 单店真实业绩 ≥ 60,000,且该店在「三大天猫店合计」中的占比 ≥ 60%。
|
||||
* 占比分母固定为三家天猫店合计(不是全渠道)。
|
||||
*/
|
||||
export function evaluateBrandUpgrade(storeSales: Record<string, number>): BrandUpgradeEvaluation {
|
||||
const values = BRAND_UPGRADE_TMALL_STORES.map((store) => ({
|
||||
store,
|
||||
value: Math.max(0, Number(storeSales[store] ?? 0)),
|
||||
}))
|
||||
const threeStorePerformance = values.reduce((sum, item) => sum + item.value, 0)
|
||||
const hits = values.flatMap(({ store, value }) => {
|
||||
if (value < BRAND_UPGRADE_MIN_STORE_PERFORMANCE) return []
|
||||
const shareRatio = threeStorePerformance > 0 ? value / threeStorePerformance : 0
|
||||
if (shareRatio < BRAND_UPGRADE_MIN_SHARE) return []
|
||||
return [{
|
||||
storeName: store,
|
||||
suggestedBrand: BRAND_UPGRADE_STORE_BRAND_MAP[store],
|
||||
storePerformance: round2(value),
|
||||
threeStorePerformance: round2(threeStorePerformance),
|
||||
shareRatio,
|
||||
}]
|
||||
})
|
||||
return { threeStorePerformance: round2(threeStorePerformance), hits }
|
||||
}
|
||||
|
||||
function periodLabel(periodKey: string) {
|
||||
const match = /^(\d{4})-(\d{2})$/.exec(periodKey)
|
||||
return match ? `${match[1]}年${Number(match[2])}月` : periodKey
|
||||
}
|
||||
|
||||
function formatMoney(value: number) {
|
||||
return Number(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||
}
|
||||
|
||||
function isSameMonth(value: Date | null | undefined, periodKey: string) {
|
||||
if (!value) return false
|
||||
const yearMonth = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
}).format(value)
|
||||
return yearMonth === periodKey
|
||||
}
|
||||
|
||||
export function buildBrandUpgradeMessage(input: {
|
||||
spu: string
|
||||
periodKey: string
|
||||
hit: BrandUpgradeHit
|
||||
saCodes: Array<{ barcode: string; rating: string }>
|
||||
}) {
|
||||
const codes = input.saCodes.length
|
||||
? input.saCodes.map((item) => `${item.barcode}(${item.rating})`).join('、')
|
||||
: '—'
|
||||
return [
|
||||
'【聚水潭-商品资料修改品牌】',
|
||||
`SPU:${input.spu}`,
|
||||
`当前品牌:${BRAND_UPGRADE_SOURCE_BRAND} → 建议改为:${input.hit.suggestedBrand}`,
|
||||
`达标店铺:${input.hit.storeName}`,
|
||||
`店铺真实业绩:¥${formatMoney(input.hit.storePerformance)}(≥60,000)`,
|
||||
`三大天猫店合计:¥${formatMoney(input.hit.threeStorePerformance)}`,
|
||||
`该店占比:${(input.hit.shareRatio * 100).toFixed(2)}%(≥60%)`,
|
||||
`含 S/A 编码:${codes}`,
|
||||
`统计月份:${periodLabel(input.periodKey)}`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function buildBrandRevertMessage(input: {
|
||||
spu: string
|
||||
periodKey: string
|
||||
currentBrand: string
|
||||
failedMonths: number
|
||||
}) {
|
||||
return [
|
||||
'【聚水潭-商品资料修改品牌】',
|
||||
`SPU:${input.spu}`,
|
||||
`当前品牌:${input.currentBrand}`,
|
||||
`已连续 ${input.failedMonths} 个自然月不达标(约 60 天)`,
|
||||
`建议改回:${BRAND_UPGRADE_SOURCE_BRAND}`,
|
||||
`统计月份:${periodLabel(input.periodKey)}`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
async function resolveRecipient() {
|
||||
const name = process.env.SUPPLY_CHAIN_BRAND_UPGRADE_RECIPIENT?.trim()
|
||||
|| DEFAULT_BRAND_UPGRADE_RECIPIENT
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { name },
|
||||
select: { name: true, dingtalkUserId: true },
|
||||
})
|
||||
if (user?.dingtalkUserId) return { name: user.name, userId: user.dingtalkUserId }
|
||||
const employee = await prisma.employeeDirectory.findFirst({
|
||||
where: { name },
|
||||
select: { name: true, dingtalkUserId: true },
|
||||
})
|
||||
if (employee?.dingtalkUserId) return { name: employee.name, userId: employee.dingtalkUserId }
|
||||
throw new Error(`未找到钉钉接收人「${name}」(缺少 dingtalkUserId)`)
|
||||
}
|
||||
|
||||
export type BrandUpgradeMonitorSummary = {
|
||||
periodKey: string
|
||||
dryRun: boolean
|
||||
recipient: string
|
||||
saCodes: number
|
||||
candidateSpus: number
|
||||
hits: number
|
||||
notified: number
|
||||
skipped: number
|
||||
brandChanged: number
|
||||
revertNotified: number
|
||||
details: Array<{
|
||||
spu: string
|
||||
storeName: string
|
||||
storePerformance: number
|
||||
threeStorePerformance: number
|
||||
shareRatio: number
|
||||
suggestedBrand: string
|
||||
saCodes: string[]
|
||||
alreadyNotified: boolean
|
||||
}>
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
export class SupplyChainBrandUpgradeMonitorService {
|
||||
async run(input: { periodKey?: string; dryRun?: boolean } = {}): Promise<BrandUpgradeMonitorSummary> {
|
||||
const period = periodDateRange(input.periodKey?.trim() || previousPeriodKey())
|
||||
const dryRun = input.dryRun === true
|
||||
const now = new Date()
|
||||
const summary: BrandUpgradeMonitorSummary = {
|
||||
periodKey: period.periodKey,
|
||||
dryRun,
|
||||
recipient: '',
|
||||
saCodes: 0,
|
||||
candidateSpus: 0,
|
||||
hits: 0,
|
||||
notified: 0,
|
||||
skipped: 0,
|
||||
brandChanged: 0,
|
||||
revertNotified: 0,
|
||||
details: [],
|
||||
errors: [],
|
||||
}
|
||||
|
||||
// 1) 上一个自然月 S/A 编码(SABC 结果表按 date 存 periodStart/periodEnd)
|
||||
const saRows = await prisma.supplyChainProductArchiveSabcResult.findMany({
|
||||
where: {
|
||||
periodStart: period.start,
|
||||
periodEnd: period.end,
|
||||
sabcRating: { in: ['S', 'A'] },
|
||||
},
|
||||
select: { barcode: true, sabcRating: true },
|
||||
})
|
||||
summary.saCodes = saRows.length
|
||||
if (saRows.length === 0) {
|
||||
summary.errors.push(`${periodLabel(period.periodKey)}还没有 SABC 结果(S/A 编码为空),请先生成该月 SABC`)
|
||||
return summary
|
||||
}
|
||||
|
||||
const saRatings = new Map<string, string>()
|
||||
for (const row of saRows) {
|
||||
const code = String(row.barcode ?? '').trim().toUpperCase()
|
||||
if (code) saRatings.set(code, String(row.sabcRating ?? '').trim())
|
||||
}
|
||||
|
||||
const saArchives = await prisma.supplyChainProductArchive.findMany({
|
||||
where: { barcode: { in: [...saRatings.keys()] } },
|
||||
select: { barcode: true, spu: true, brand: true },
|
||||
})
|
||||
|
||||
const candidateSpus = new Set<string>()
|
||||
const saCodesBySpu = new Map<string, Array<{ barcode: string; rating: string }>>()
|
||||
for (const row of saArchives) {
|
||||
const spu = String(row.spu ?? '').trim()
|
||||
if (!spu) continue
|
||||
if (String(row.brand ?? '').trim() !== BRAND_UPGRADE_SOURCE_BRAND) continue
|
||||
candidateSpus.add(spu)
|
||||
const barcode = String(row.barcode ?? '').trim()
|
||||
const rating = saRatings.get(barcode.toUpperCase()) ?? ''
|
||||
const list = saCodesBySpu.get(spu) ?? []
|
||||
list.push({ barcode, rating })
|
||||
saCodesBySpu.set(spu, list)
|
||||
}
|
||||
summary.candidateSpus = candidateSpus.size
|
||||
|
||||
// 2) 需要监控的 SPU:本月候选 + 已升级待回退
|
||||
const records = await prisma.supplyChainBrandUpgradeMonitor.findMany({
|
||||
where: { status: { in: ['NOTIFIED', 'BRAND_CHANGED'] } },
|
||||
})
|
||||
const monitoredSpus = new Set(records.map((record) => record.spu))
|
||||
const interestSpus = [...new Set([...candidateSpus, ...monitoredSpus])]
|
||||
if (interestSpus.length === 0) return summary
|
||||
|
||||
const archiveRows = await prisma.supplyChainProductArchive.findMany({
|
||||
where: { spu: { in: interestSpus } },
|
||||
select: { barcode: true, spu: true, brand: true },
|
||||
})
|
||||
const barcodeToSpu = new Map<string, string>()
|
||||
const spuCurrentBrand = new Map<string, string>()
|
||||
for (const row of archiveRows) {
|
||||
const spu = String(row.spu ?? '').trim()
|
||||
const barcode = String(row.barcode ?? '').trim().toUpperCase()
|
||||
if (!spu) continue
|
||||
if (barcode) barcodeToSpu.set(barcode, spu)
|
||||
if (!spuCurrentBrand.has(spu)) spuCurrentBrand.set(spu, String(row.brand ?? '').trim())
|
||||
}
|
||||
|
||||
// 3) 三家天猫店按 SPU 汇总真实业绩
|
||||
const storeRows = await listTmallStoreSales({
|
||||
periodStart: period.startText,
|
||||
periodEnd: period.endText,
|
||||
})
|
||||
const spuStoreSales = new Map<string, Record<string, number>>()
|
||||
for (const row of storeRows) {
|
||||
const spu = barcodeToSpu.get(row.barcode)
|
||||
if (!spu) continue
|
||||
const bucket = spuStoreSales.get(spu) ?? {}
|
||||
bucket[row.shopName] = (bucket[row.shopName] ?? 0) + row.realPerformance
|
||||
spuStoreSales.set(spu, bucket)
|
||||
}
|
||||
|
||||
const recipient = await resolveRecipient()
|
||||
summary.recipient = recipient.name
|
||||
|
||||
// 4) 升级推送(每个 SPU + 目标品牌 + 月份只推一次)
|
||||
for (const spu of candidateSpus) {
|
||||
const evaluation = evaluateBrandUpgrade(spuStoreSales.get(spu) ?? {})
|
||||
for (const hit of evaluation.hits) {
|
||||
summary.hits += 1
|
||||
const existing = await prisma.supplyChainBrandUpgradeMonitor.findUnique({
|
||||
where: { spu_periodKey_suggestedBrand: { spu, periodKey: period.periodKey, suggestedBrand: hit.suggestedBrand } },
|
||||
})
|
||||
summary.details.push({
|
||||
spu,
|
||||
storeName: hit.storeName,
|
||||
storePerformance: hit.storePerformance,
|
||||
threeStorePerformance: hit.threeStorePerformance,
|
||||
shareRatio: hit.shareRatio,
|
||||
suggestedBrand: hit.suggestedBrand,
|
||||
saCodes: (saCodesBySpu.get(spu) ?? []).map((item) => `${item.barcode}(${item.rating})`),
|
||||
alreadyNotified: Boolean(existing),
|
||||
})
|
||||
if (existing) {
|
||||
summary.skipped += 1
|
||||
continue
|
||||
}
|
||||
const content = buildBrandUpgradeMessage({
|
||||
spu,
|
||||
periodKey: period.periodKey,
|
||||
hit,
|
||||
saCodes: saCodesBySpu.get(spu) ?? [],
|
||||
})
|
||||
if (dryRun) {
|
||||
summary.notified += 1
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await dingtalkWorkNotificationService.sendText({ userIds: [recipient.userId], content })
|
||||
await prisma.supplyChainBrandUpgradeMonitor.create({
|
||||
data: {
|
||||
spu,
|
||||
periodKey: period.periodKey,
|
||||
suggestedBrand: hit.suggestedBrand,
|
||||
storeName: hit.storeName,
|
||||
storePerformance: hit.storePerformance,
|
||||
threeStorePerformance: hit.threeStorePerformance,
|
||||
shareRatio: hit.shareRatio,
|
||||
status: 'NOTIFIED',
|
||||
notifiedAt: now,
|
||||
},
|
||||
})
|
||||
summary.notified += 1
|
||||
} catch (error) {
|
||||
summary.errors.push(`SPU ${spu} 升级推送失败:${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5) 品牌变更检测 + 连续不达标回退
|
||||
for (const record of records) {
|
||||
const currentBrand = spuCurrentBrand.get(record.spu) ?? ''
|
||||
if (record.status === 'NOTIFIED') {
|
||||
if (currentBrand && BRAND_UPGRADE_OWN_BRANDS.has(currentBrand)) {
|
||||
summary.brandChanged += 1
|
||||
if (!dryRun) {
|
||||
await prisma.supplyChainBrandUpgradeMonitor.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'BRAND_CHANGED', brandChangedAt: now },
|
||||
})
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// BRAND_CHANGED:品牌已不是自有品牌 → 关闭监控
|
||||
if (!currentBrand || !BRAND_UPGRADE_OWN_BRANDS.has(currentBrand)) {
|
||||
if (!dryRun) {
|
||||
await prisma.supplyChainBrandUpgradeMonitor.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'CLOSED' },
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const evaluation = evaluateBrandUpgrade(spuStoreSales.get(record.spu) ?? {})
|
||||
if (evaluation.hits.length > 0) {
|
||||
if (!dryRun) {
|
||||
await prisma.supplyChainBrandUpgradeMonitor.update({
|
||||
where: { id: record.id },
|
||||
data: { failedMonths: 0, lastEvaluatedPeriod: period.periodKey },
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (record.lastEvaluatedPeriod === period.periodKey) continue
|
||||
|
||||
const failedMonths = record.failedMonths + 1
|
||||
if (!dryRun) {
|
||||
await prisma.supplyChainBrandUpgradeMonitor.update({
|
||||
where: { id: record.id },
|
||||
data: { failedMonths, lastEvaluatedPeriod: period.periodKey },
|
||||
})
|
||||
}
|
||||
if (failedMonths < BRAND_UPGRADE_REVERT_FAILED_MONTHS) continue
|
||||
// 每个月最多提醒一次(未处理则下个月继续提醒)
|
||||
if (isSameMonth(record.revertNotifiedAt, period.periodKey)) continue
|
||||
|
||||
const content = buildBrandRevertMessage({
|
||||
spu: record.spu,
|
||||
periodKey: period.periodKey,
|
||||
currentBrand,
|
||||
failedMonths,
|
||||
})
|
||||
if (dryRun) {
|
||||
summary.revertNotified += 1
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await dingtalkWorkNotificationService.sendText({ userIds: [recipient.userId], content })
|
||||
await prisma.supplyChainBrandUpgradeMonitor.update({
|
||||
where: { id: record.id },
|
||||
data: { revertNotifiedAt: now },
|
||||
})
|
||||
summary.revertNotified += 1
|
||||
} catch (error) {
|
||||
summary.errors.push(`SPU ${record.spu} 回退推送失败:${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
return summary
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainBrandUpgradeMonitorService = new SupplyChainBrandUpgradeMonitorService()
|
||||
@ -0,0 +1,183 @@
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
supplyChainProductArchiveSabcResult: { findMany: jest.fn() },
|
||||
supplyChainProductArchive: { findMany: jest.fn() },
|
||||
supplyChainBrandUpgradeMonitor: {
|
||||
findMany: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
user: { findFirst: jest.fn() },
|
||||
employeeDirectory: { findFirst: jest.fn() },
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('@/server/repositories/jst-tmall-store-sales.repository', () => ({
|
||||
BRAND_UPGRADE_TMALL_STORES: ['天猫_亿家达旗舰店', '天猫_卓禾家具旗舰店', '天猫_欧意朗旗舰店'],
|
||||
listTmallStoreSales: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('@/server/integrations/dingtalk/dingtalk-work-notification.service', () => ({
|
||||
dingtalkWorkNotificationService: { sendText: jest.fn() },
|
||||
}))
|
||||
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { listTmallStoreSales } from '@/server/repositories/jst-tmall-store-sales.repository'
|
||||
import { dingtalkWorkNotificationService } from '@/server/integrations/dingtalk/dingtalk-work-notification.service'
|
||||
import {
|
||||
evaluateBrandUpgrade,
|
||||
previousPeriodKey,
|
||||
periodDateRange,
|
||||
supplyChainBrandUpgradeMonitorService,
|
||||
} from './supply-chain-brand-upgrade-monitor.service'
|
||||
|
||||
const sabcFindMany = prisma.supplyChainProductArchiveSabcResult.findMany as jest.Mock
|
||||
const archiveFindMany = prisma.supplyChainProductArchive.findMany as jest.Mock
|
||||
const monitorFindMany = prisma.supplyChainBrandUpgradeMonitor.findMany as jest.Mock
|
||||
const monitorFindUnique = prisma.supplyChainBrandUpgradeMonitor.findUnique as jest.Mock
|
||||
const monitorCreate = prisma.supplyChainBrandUpgradeMonitor.create as jest.Mock
|
||||
const monitorUpdate = prisma.supplyChainBrandUpgradeMonitor.update as jest.Mock
|
||||
const userFindFirst = prisma.user.findFirst as jest.Mock
|
||||
const employeeFindFirst = prisma.employeeDirectory.findFirst as jest.Mock
|
||||
const storeSales = listTmallStoreSales as jest.Mock
|
||||
const sendText = dingtalkWorkNotificationService.sendText as jest.Mock
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks()
|
||||
monitorFindMany.mockResolvedValue([])
|
||||
monitorFindUnique.mockResolvedValue(null)
|
||||
monitorCreate.mockResolvedValue({})
|
||||
monitorUpdate.mockResolvedValue({})
|
||||
userFindFirst.mockResolvedValue({ name: '海棠', dingtalkUserId: 'dingtalk-haitang' })
|
||||
employeeFindFirst.mockResolvedValue(null)
|
||||
sendText.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('商品品牌升级监控规则', () => {
|
||||
it('单店业绩≥6万且占三家天猫店≥60%才命中', () => {
|
||||
const hit = evaluateBrandUpgrade({
|
||||
'天猫_亿家达旗舰店': 30000,
|
||||
'天猫_卓禾家具旗舰店': 30000,
|
||||
'天猫_欧意朗旗舰店': 120000,
|
||||
})
|
||||
expect(hit.hits.map((item) => item.suggestedBrand)).toEqual(['自有品牌-欧意朗'])
|
||||
expect(hit.hits[0].shareRatio).toBeCloseTo(120000 / 180000, 6)
|
||||
expect(hit.threeStorePerformance).toBe(180000)
|
||||
|
||||
// 业绩够但占比不足 60%
|
||||
const shareMiss = evaluateBrandUpgrade({
|
||||
'天猫_亿家达旗舰店': 100000,
|
||||
'天猫_卓禾家具旗舰店': 0,
|
||||
'天猫_欧意朗旗舰店': 70000,
|
||||
})
|
||||
expect(shareMiss.hits).toEqual([])
|
||||
|
||||
// 占比够但单店不足 6 万
|
||||
const amountMiss = evaluateBrandUpgrade({
|
||||
'天猫_亿家达旗舰店': 50000,
|
||||
'天猫_卓禾家具旗舰店': 1000,
|
||||
'天猫_欧意朗旗舰店': 0,
|
||||
})
|
||||
expect(amountMiss.hits).toEqual([])
|
||||
})
|
||||
|
||||
it('多家店都超过6万时逐店算占比,仅推送同时满足两项的店', () => {
|
||||
const result = evaluateBrandUpgrade({
|
||||
'天猫_亿家达旗舰店': 90000,
|
||||
'天猫_卓禾家具旗舰店': 80000,
|
||||
'天猫_欧意朗旗舰店': 10000,
|
||||
})
|
||||
// 两家都≥6万,但占比分别 50%、44.4%,都不足 60%
|
||||
expect(result.hits).toEqual([])
|
||||
})
|
||||
|
||||
it('按上海时区计算上一个自然月', () => {
|
||||
expect(previousPeriodKey(new Date('2026-11-25T02:00:00Z'))).toBe('2026-10')
|
||||
expect(previousPeriodKey(new Date('2026-01-15T02:00:00Z'))).toBe('2025-12')
|
||||
expect(periodDateRange('2026-10')).toMatchObject({
|
||||
startText: '2026-10-01',
|
||||
endText: '2026-10-31',
|
||||
})
|
||||
})
|
||||
|
||||
it('命中后推送钉钉给海棠,并记录当月通知', async () => {
|
||||
sabcFindMany.mockResolvedValue([{ barcode: 'CODE1', sabcRating: 'S' }])
|
||||
archiveFindMany
|
||||
.mockResolvedValueOnce([{ barcode: 'CODE1', spu: 'SPU1', brand: '其他品牌-普通大货' }])
|
||||
.mockResolvedValueOnce([
|
||||
{ barcode: 'CODE1', spu: 'SPU1', brand: '其他品牌-普通大货' },
|
||||
{ barcode: 'CODE2', spu: 'SPU1', brand: '其他品牌-普通大货' },
|
||||
])
|
||||
storeSales.mockResolvedValue([
|
||||
{ shopName: '天猫_欧意朗旗舰店', barcode: 'CODE1', realPerformance: 120000 },
|
||||
{ shopName: '天猫_亿家达旗舰店', barcode: 'CODE2', realPerformance: 30000 },
|
||||
])
|
||||
|
||||
const summary = await supplyChainBrandUpgradeMonitorService.run({ periodKey: '2026-10' })
|
||||
|
||||
expect(summary.notified).toBe(1)
|
||||
expect(sendText).toHaveBeenCalledWith(expect.objectContaining({
|
||||
userIds: ['dingtalk-haitang'],
|
||||
content: expect.stringContaining('聚水潭-商品资料修改品牌'),
|
||||
}))
|
||||
expect(monitorCreate).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
spu: 'SPU1',
|
||||
periodKey: '2026-10',
|
||||
suggestedBrand: '自有品牌-欧意朗',
|
||||
status: 'NOTIFIED',
|
||||
}),
|
||||
}))
|
||||
})
|
||||
|
||||
it('同一个月同一 SPU 不重复推送', async () => {
|
||||
sabcFindMany.mockResolvedValue([{ barcode: 'CODE1', sabcRating: 'A' }])
|
||||
archiveFindMany
|
||||
.mockResolvedValueOnce([{ barcode: 'CODE1', spu: 'SPU1', brand: '其他品牌-普通大货' }])
|
||||
.mockResolvedValueOnce([{ barcode: 'CODE1', spu: 'SPU1', brand: '其他品牌-普通大货' }])
|
||||
storeSales.mockResolvedValue([
|
||||
{ shopName: '天猫_欧意朗旗舰店', barcode: 'CODE1', realPerformance: 120000 },
|
||||
])
|
||||
monitorFindUnique.mockResolvedValue({ id: 'existing' })
|
||||
|
||||
const summary = await supplyChainBrandUpgradeMonitorService.run({ periodKey: '2026-10' })
|
||||
|
||||
expect(summary.notified).toBe(0)
|
||||
expect(summary.skipped).toBe(1)
|
||||
expect(sendText).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('已升级品牌连续2个自然月不达标时推送回退', async () => {
|
||||
sabcFindMany.mockResolvedValue([{ barcode: 'CODE1', sabcRating: 'S' }])
|
||||
archiveFindMany
|
||||
.mockResolvedValueOnce([{ barcode: 'CODE1', spu: 'SPU1', brand: '自有品牌-欧意朗' }])
|
||||
.mockResolvedValueOnce([{ barcode: 'CODE1', spu: 'SPU1', brand: '自有品牌-欧意朗' }])
|
||||
storeSales.mockResolvedValue([
|
||||
{ shopName: '天猫_亿家达旗舰店', barcode: 'CODE1', realPerformance: 10000 },
|
||||
])
|
||||
monitorFindMany.mockResolvedValue([{
|
||||
id: 'rec-1',
|
||||
spu: 'SPU1',
|
||||
periodKey: '2026-01',
|
||||
suggestedBrand: '自有品牌-欧意朗',
|
||||
status: 'BRAND_CHANGED',
|
||||
brandChangedAt: new Date('2026-02-01T00:00:00Z'),
|
||||
failedMonths: 1,
|
||||
lastEvaluatedPeriod: '2026-08',
|
||||
revertNotifiedAt: null,
|
||||
}])
|
||||
|
||||
const summary = await supplyChainBrandUpgradeMonitorService.run({ periodKey: '2026-09' })
|
||||
|
||||
expect(summary.revertNotified).toBe(1)
|
||||
expect(sendText).toHaveBeenCalledWith(expect.objectContaining({
|
||||
userIds: ['dingtalk-haitang'],
|
||||
content: expect.stringContaining('建议改回:其他品牌-普通大货'),
|
||||
}))
|
||||
expect(monitorUpdate).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { id: 'rec-1' },
|
||||
data: expect.objectContaining({ revertNotifiedAt: expect.any(Date) }),
|
||||
}))
|
||||
})
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user