feat(limit-management): complete breach order audit workflow

This commit is contained in:
居居 2026-11-16 09:08:52 +08:00
parent 8cc0f8daab
commit 99b60989ee
18 changed files with 929 additions and 108 deletions

View File

@ -19,7 +19,7 @@
8. **老链接分界**:上架时间早于 2026-10-07 00:00 的链接(老链接)破价申诉通过;之后的按限价流程结束日期判定(上架时间需早于流程结束日期),并核对店铺款式编码 / 商品编码。
9. **负责人触发规则**:非运营发起的流程,前两个月全公司运营同价(不归属个人);两个月后按销量触发负责人(销量高者为负责人)。
10. **数据快照**:破价单在生成时保存金额快照;退款/售后状态单独记录,退款不等于免责(仍需判断是否已调价)。
11. **离职人员**:订单负责人已离职 → 自动标记「人员已离职」,不判定、不计乐捐。
11. **离职人员**:只按人员信息表 `SupplyChainManagementOwnerConfig` 关联员工目录的**当前**任职状态判断,不再直接使用员工目录的离职姓名历史。负责人当前离职 → 自动标记「人员已离职」,不判定、不计乐捐;此前由系统自动误标、但人员信息当前为在职或已无法匹配的订单 → 自动恢复为待申诉/待审核/已打回。首次修复执行 `npm run repair:supply-chain-breach-order-employment -- --apply`,日常生成任务会自动执行双向核对。
12. **是否有检测报告**:取素材平台「检测报告」接口(`/api/external/certificate-reports`,按 **SPU** 精确匹配,只认有报告文件的记录),进程内缓存 10 分钟;
接口未配置或读取失败时该列显示为空、筛选候选值为空。配置项:`MATERIAL_LIBRARY_CERTIFICATE_REPORT_API_BASE_URL/API_KEY`,
不填则复用素材平台 `MATERIAL_LIBRARY_WHITE_BACKGROUND_API_*`。
@ -40,7 +40,7 @@
2. **申诉范围**:链接时间 / 流程申请类支持**链接级一次性申诉**(默认勾选,覆盖该链接下全部破价订单,后续新单自动继承);优惠 / 活动类按订单申诉。
3. **审核要点仅审核人可见**;申诉人只看到凭证要求与示例图。
4. **凭证校验**:必填校验 + 识别提示(识别结果仅提示,人工一键打回);后续增加图片查重(hash / 相似度)与关键字段(订单号、链接 ID)一致性校验。
5. **乐捐**:驳回计 ¥10/单(离职不计);配套审计链(数据快照 + 申诉材料 + 审核记录),扣款执行交财务确认,保留异议通道。
5. **乐捐**:未通过审核的破价订单暂按 ¥10/单计入,未申诉、待审核、已打回、已驳回均计入;人员已离职不计,审核通过后自动从本月乐捐中扣减。同一线上订单只计一次;配套审计链(数据快照 + 申诉材料 + 审核记录),扣款执行交财务确认,保留异议通道。
6. **举证期限**:待与运营确认后设置(避免事后无法追溯凭证)。
## 三、权限(由管理员统一管理)
@ -57,7 +57,7 @@
- 没有「下载」权限时页面不展示导出入口,服务端导出接口同样鉴权(下载中心任务按「限价管理 · 下载」校验)。
- 没有「破价申诉」操作权限时:不显示申诉按钮,服务端拒绝提交申诉;运营角色默认获得该权限。
- 没有「经管审核」操作权限时:不显示审核按钮,服务端拒绝审核、生成和导入;经管角色默认获得该权限。
- 没有「经管审核」操作权限时:不显示审核按钮,服务端拒绝审核、生成和导入;「本月乐捐」金额、计费单数及乐捐明细导出也只对具备该权限的人员开放,普通运营接口不返回乐捐汇总。经管角色默认获得该权限。
- 普通运营只能看到负责人为本人姓名的数据;经管审核角色可以查看全部数据。
- 申诉与审核是两个独立权限,可以给同一人员同时配置,也可以只配置其中一个。
- 没有「规则配置」权限时,规则配置页签不显示、接口不可调用。
@ -66,12 +66,12 @@
1. **按天增量**:限价逻辑上线后,破价订单**按天增量生成**(每天只生成最新一天的破价单并入库),**历史数据不再重复回算**;破价订单审核页每天展示最新破价单。
**破价订单审核业务起点为 2026-11-01(北京时间)**:更早订单保留在数据库作为历史快照,但不进入当前列表、状态统计、筛选、导出或生成范围。
审核列表、状态统计和“本月乐捐”默认只查询北京时间**当前自然月**,且月份起点不早于 2026-11-01;12 月页面只展示付款时间在 12 月的订单。
审核列表、状态统计和“本月乐捐”默认只查询付款时间在北京时间**当前自然月**的订单,且月份起点不早于 2026-11-01;12 月页面只展示付款时间在 12 月的订单。“本月乐捐”按当前月破价订单暂计:审核通过和人员已离职通过状态排除自动扣减,同一线上订单只计一次,不受列表其他筛选条件影响。
页面数量按“订单商品明细行”统计,不按订单头去重;同一订单多个破价商品会形成多条明细。
首次回填执行 `npm run backfill:supply-chain-breach-orders:november`;之后每日任务默认只处理昨天单日。生产安装入口为 `npm run install:supply-chain-breach-order-systemd`,默认北京时间 10:00 执行,重复跑不会重复插入同一订单明细。
2. **数据来源**:聚水潭报表库(`jst_Orders` + `jst_OrderItem` / 天猫奇门 `jst_qmcust_orderlist` + `_item`),取 `seller_income_amount`、`buyer_paid_amount`、`qty`、`shop_i_id`、`shop_sku_id`、`pay_date`、退款状态,以及换货识别字段 `item_status`、`item_ext_data`(`item_source`、`sku_uuid`)。买家实付是破价判定金额,商家实收只用于平台承担快照。报表库查询较慢,逐日增量任务按天分片拉取。
- 上架时间:取每日链接快照 `JianSun_Old.JianSun.dbo.dm_jst_shop_goods_link_daily.created`,按 `shop_i_id` 匹配并取最早创建时间;该快照下游来自 `jst_skumap / jst_skumap_pdd / jst_skumap_qmcust_add`,避免直接扫描无索引大表导致每日任务超时。
- 链接负责人:优先 `op_TargetManagement` 最新记录(`shopproid → ider`),缺失时回退 `dim_ope_itemid_info_df`。
- 运营负责人:与停产下架同口径,按链接 `itemId`(破价单 `shopStyleCode`)优先读取 `op_TargetManagement` 最新记录(`shopproid → ider`),缺失时回退 `dim_ope_itemid_info_df`;部门负责人和利润中心再按该负责人的姓名关联本地人员信息。
- 订单商品负责人:优先产品档案 `opsHead`,缺失时按条码回退 `dim_ope_itemid_info_df`。
3. **限价来源**:钉钉流程(仅取**已完结**),共 4 个模板,同步脚本 `scripts/sync-limit-workflows.mjs`:
- 「新品限价及限价调整」→ 货号取「货号(非商品编码)」,限价取「期望日常限价」;
@ -127,11 +127,12 @@
- 期初数据更新:把新的 `限价期初数据*.xlsx` 放进 `shared/limit-workflow-sync/期初数据/` 即可,下次同步自动取最新。
- `SupplyChainBreachRuleConfig` 不需要灌数:接口读取时用代码内置默认值,首次在「规则配置」保存时落库。
6. **店铺链接限价为空的兼容与修复**:新单不再依赖 `SupplyChainLinkLimitPrice` 提供负责人、上架时间或流程结束日期。任务重跑时,已有破价单的 `ownerName / listedAt / flowEndDate` 只补空值;若某批候选的三项都为空,任务会在写库前失败,避免继续产生普通负责人不可见的脏数据。
6. **店铺链接限价为空的兼容与修复**:新单不再依赖 `SupplyChainLinkLimitPrice` 提供负责人、上架时间或流程结束日期。任务重跑时,已解析出的最新 `ownerName / deptOwner / profitCenter` 会修正旧值,`listedAt / flowEndDate` 只补空值;若某批候选的运营负责人、上架时间、流程结束日期都为空,任务会在写库前失败,避免继续产生普通负责人不可见的脏数据。
7. **统一条码限价明细**:`SupplyChainLimitPriceDetailService` 是限价页面与破价审核共用的 `barcode → effective limit detail` 读取入口。返回条码、货号、SPU、负责人限价、非负责人限价、生效时间、流程号和流程结束日期;调用方不再各自拼装货号限价。页面无 `asOf` 时取当前版本,破价审核传订单付款时间取历史版本。
8. **已有破价单刷新**:按付款时点重新生成时,已有单会刷新数量、买家实付、商家实收、平台承担、限价、差额、订单/退款状态及空白元数据,以修正旧算法快照;`status / appeal / review` 等人工流程字段保持不变。
8. **已有破价单刷新**:按付款时点重新生成时,已有单会刷新数量、买家实付、商家实收、平台承担、限价、差额、订单/退款状态,并按链接负责人和人员信息修正运营负责人、部门负责人、利润中心;`status / appeal / review` 等人工流程字段保持不变。
9. **链接身份字段**:破价单只保存一个「运营负责人」,取链接 `itemId` 对应的负责人(与停产下架一致);「部门负责人」和「利润中心」按运营负责人姓名关联人员信息。新增字段上线后先执行 `npm run backfill:supply-chain-breach-order-identity -- --dry-run` 核对范围,再执行 `npm run backfill:supply-chain-breach-order-identity` 修正历史身份字段;回填不改金额、申诉、审核和乐捐状态。
### 每日聚水潭物流规则快照

View File

@ -43,6 +43,8 @@
"install:limit-price-snapshot-systemd": "bash scripts/install-limit-price-snapshot-systemd-timer.sh",
"sync:supply-chain-breach-orders": "tsx scripts/sync-supply-chain-breach-orders.ts",
"backfill:supply-chain-breach-orders:november": "tsx scripts/sync-supply-chain-breach-orders.ts --from=2026-11-01 --to=2026-11-11",
"backfill:supply-chain-breach-order-identity": "tsx scripts/backfill-supply-chain-breach-order-identity.ts",
"repair:supply-chain-breach-order-employment": "tsx scripts/sync-supply-chain-breach-order-employment.ts",
"install:supply-chain-breach-order-systemd": "bash scripts/install-supply-chain-breach-order-timer.sh",
"import:province-shipment-share": "node scripts/import-province-shipment-share.mjs",
"init:logistics-reference": "tsx scripts/init-logistics-reference.ts",

View File

@ -0,0 +1,2 @@
ALTER TABLE "SupplyChainBreachOrder"
ADD COLUMN "deptOwner" TEXT NOT NULL DEFAULT '';

View File

@ -5408,7 +5408,11 @@ model SupplyChainBreachOrder {
limitUnitPrice Decimal? @db.Decimal(18, 4)
limitTotal Decimal? @db.Decimal(18, 4)
gapAmount Decimal? @db.Decimal(18, 4)
/// 店铺链接运营负责人(与停产下架同口径):参与权限归属,并与订单商品负责人比对判定限价。
ownerName String @default("")
/// 部门负责人(按运营负责人从人员信息关联)。
deptOwner String @default("")
/// 利润中心(按运营负责人从人员信息关联)。
profitCenter String @default("")
orderStatus String @default("")
refundStatus String @default("")

View File

@ -0,0 +1,81 @@
import { loadEnvConfig } from '@next/env'
import { BREACH_ORDER_MONITOR_START_DATE } from '../src/lib/supply-chain-breach-order'
const DATE_KEY_PATTERN = /^\d{4}-\d{2}-\d{2}$/
function argument(name: string) {
const prefix = `--${name}=`
return process.argv.find((value) => value.startsWith(prefix))?.slice(prefix.length).trim() ?? null
}
function dateArgument(name: string, fallback: string) {
const value = argument(name) ?? fallback
if (!DATE_KEY_PATTERN.test(value)) throw new Error(`--${name} 必须是 YYYY-MM-DD`)
return value
}
function shanghaiDateKey(value: Date) {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).formatToParts(value)
const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((item) => item.type === type)?.value ?? ''
return `${part('year')}-${part('month')}-${part('day')}`
}
function printUsage() {
console.log(`破价单链接身份字段回填
默认从 2026-11-01 回填到北京时间今天:
npm run backfill:supply-chain-breach-order-identity
指定区间:
npm run backfill:supply-chain-breach-order-identity -- --from=2026-11-01 --to=2026-11-13
只预览不写库:
npm run backfill:supply-chain-breach-order-identity -- --dry-run
`)
}
async function main() {
if (process.argv.includes('--help')) {
printUsage()
return
}
const dateFrom = dateArgument('from', BREACH_ORDER_MONITOR_START_DATE)
const dateTo = dateArgument('to', shanghaiDateKey(new Date()))
const batchSize = Number(argument('batch-size') ?? 5_000)
const dryRun = process.argv.includes('--dry-run')
const plan = { event: 'start', dateFrom, dateTo, batchSize, dryRun }
console.log(JSON.stringify(plan))
loadEnvConfig(process.cwd())
const [
{ supplyChainBreachOrderService },
{ jstBreachOrderSourceRepository },
{ prisma },
] = await Promise.all([
import('../src/server/services/supply-chain-breach-order.service'),
import('../src/server/repositories/jst-breach-order-source.repository'),
import('../src/lib/prisma'),
])
try {
const result = await supplyChainBreachOrderService.backfillLinkIdentityMetadata({
dateFrom,
dateTo,
batchSize,
dryRun,
})
console.log(JSON.stringify({ event: 'finish', ...result }))
} finally {
await jstBreachOrderSourceRepository.close().catch(() => undefined)
await prisma.$disconnect().catch(() => undefined)
}
}
void main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
})

View File

@ -0,0 +1,39 @@
import { loadEnvConfig } from '@next/env'
function printUsage() {
console.log(`破价订单负责人在职状态双向核对
预览(默认,不写库):
npm run repair:supply-chain-breach-order-employment
执行修复:
npm run repair:supply-chain-breach-order-employment -- --apply
`)
}
async function main() {
if (process.argv.includes('--help')) {
printUsage()
return
}
const dryRun = !process.argv.includes('--apply')
loadEnvConfig(process.cwd())
const [
{ supplyChainBreachOrderService },
{ prisma },
] = await Promise.all([
import('../src/server/services/supply-chain-breach-order.service'),
import('../src/lib/prisma'),
])
try {
const result = await supplyChainBreachOrderService.markLeftEmployees({ dryRun })
console.log(JSON.stringify({ event: 'finish', ...result }))
} finally {
await prisma.$disconnect().catch(() => undefined)
}
}
void main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
})

View File

@ -0,0 +1,77 @@
import { render, screen } from '@testing-library/react'
import { BreachOrderTab } from './BreachOrderTab'
describe('BreachOrderTab field layout', () => {
beforeEach(() => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({
success: true,
data: {
rows: [{
id: 'breach-1',
platform: '京东',
shopName: '店铺甲',
soId: 'SO-1',
oId: 'O-1',
payDate: '2026-11-12T02:00:00.000Z',
itemCode: 'BARCODE-1',
shopItemCode: 'SHOP-SKU-1',
shopStyleCode: 'LINK-1',
qty: 1,
buyerPaidAmount: 80,
platformBearAmount: 20,
sellerIncomeAmount: 100,
limitUnitPrice: 120,
limitTotal: 120,
gapAmount: -20,
ownerName: '运营负责人甲',
deptOwner: '部门负责人丙',
profitCenter: '利润中心丁',
orderStatus: 'Sent',
refundStatus: '',
status: 'PENDING_APPEAL',
statusLabel: '待申诉',
appealType: '',
appealScope: 'ORDER',
processNo: '',
appealRound: 1,
previousAppeal: null,
appealDesc: '',
appealImages: [],
appliedFromLink: false,
autoSuggested: '',
autoSuggestedNote: '',
reviewedBy: '',
reviewedAt: null,
reviewReason: '',
reviewNote: '',
fineAmount: 0,
listedAt: '2026-09-01T00:00:00.000Z',
flowEndDate: '2026-10-31T00:00:00.000Z',
}],
pageInfo: { page: 1, total: 1, totalPages: 1 },
stats: { total: 1, byStatus: { PENDING_APPEAL: 1 }, fineTotal: 0, finedOrderCount: 0, finePerOrder: 10 },
canAppeal: false,
canReview: false,
},
}),
} as Response)
})
it('renders platform, shop, product and each personnel field in independent columns', async () => {
render(<BreachOrderTab canExport />)
expect(await screen.findByText('SO-1')).toBeInTheDocument()
for (const header of ['平台', '店铺', '商品编码', '运营负责人', '部门负责人', '利润中心']) {
expect(screen.getByRole('columnheader', {
name: new RegExp(`^${header}(?:\\s|$)`),
})).toBeInTheDocument()
}
for (const value of ['京东', '店铺甲', 'BARCODE-1', '运营负责人甲', '部门负责人丙', '利润中心丁']) {
expect(screen.getByText(value)).toBeInTheDocument()
}
expect(screen.queryByText(/本月乐捐/)).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '导出乐捐明细' })).not.toBeInTheDocument()
})
})

View File

@ -32,6 +32,10 @@ type BreachOrder = {
limitTotal: number | null
gapAmount: number | null
ownerName: string
deptOwner: string
profitCenter: string
orderStatus: string
refundStatus: string
status: string
statusLabel: string
appealType: string
@ -58,7 +62,13 @@ type Detail = { order: BreachOrder; linkOrders: LinkOrder[]; canAppeal: boolean;
type ListPayload = {
rows: BreachOrder[]
pageInfo: { page: number; total: number; totalPages: number }
stats: { total: number; byStatus: Record<string, number>; fineTotal: number; finedOrderCount: number; finePerOrder: number }
stats: {
total: number
byStatus: Record<string, number>
fineTotal?: number
finedOrderCount?: number
finePerOrder?: number
}
canAppeal: boolean
canReview: boolean
viewerName?: string
@ -84,6 +94,40 @@ const STATUS_TABS: Array<{ key: string; label: string }> = [
const money = (value: number | null | undefined) => (value === null || value === undefined ? '—' : `¥${Number(value).toFixed(2)}`)
const day = (value: string | null) => (value ? new Date(value).toISOString().slice(0, 10) : '—')
const text = (value: string | null | undefined) => value?.trim() || '—'
type BreachTableColumn = {
field: string
label: string
width: number
filterKey?: 'platform' | 'shopName' | 'ownerName' | 'appealType' | 'status' | 'itemCode' | 'shopStyleCode' | 'shopItemCode' | 'soId' | 'payDate'
}
const TABLE_COLUMNS: readonly BreachTableColumn[] = [
{ field: 'payDate', label: '付款日期', width: 96, filterKey: 'payDate' },
{ field: 'platform', label: '平台', width: 104, filterKey: 'platform' },
{ field: 'shopName', label: '店铺', width: 190, filterKey: 'shopName' },
{ field: 'soId', label: '线上订单号', width: 170, filterKey: 'soId' },
{ field: 'oId', label: '内部订单号', width: 120 },
{ field: 'itemCode', label: '商品编码', width: 160, filterKey: 'itemCode' },
{ field: 'shopStyleCode', label: '店铺款式编码', width: 145, filterKey: 'shopStyleCode' },
{ field: 'shopItemCode', label: '店铺商品编码', width: 145, filterKey: 'shopItemCode' },
{ field: 'qty', label: '数量', width: 74 },
{ field: 'buyerPaidAmount', label: '买家实付', width: 108 },
{ field: 'platformBearAmount', label: '平台承担', width: 108 },
{ field: 'sellerIncomeAmount', label: '商家实收', width: 108 },
{ field: 'limitUnitPrice', label: '限价单价', width: 104 },
{ field: 'limitTotal', label: '限价×数量', width: 112 },
{ field: 'gapAmount', label: '价差', width: 96 },
{ field: 'ownerName', label: '运营负责人', width: 132, filterKey: 'ownerName' },
{ field: 'deptOwner', label: '部门负责人', width: 136 },
{ field: 'profitCenter', label: '利润中心', width: 120 },
{ field: 'orderStatus', label: '订单状态', width: 104 },
{ field: 'refundStatus', label: '退款状态', width: 104 },
{ field: 'listedAt', label: '上架时间', width: 104 },
{ field: 'flowEndDate', label: '流程结束日期', width: 116 },
{ field: 'status', label: '审核状态', width: 96, filterKey: 'status' },
]
/** 可批量、可下拉、输入即查询的筛选框(值以标签展示,支持粘贴多个值)。 */
function MultiFilterChip({
@ -226,7 +270,7 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
return () => controller.abort()
}, [openHeaderFilter, headerOptions])
// 列宽可人工拖拽调整(默认按初始像素宽)
const DEFAULT_COL_WIDTHS = [92, 180, 150, 140, 150, 180, 110, 118, 150, 88]
const DEFAULT_COL_WIDTHS = TABLE_COLUMNS.map((column) => column.width)
const [colWidths, setColWidths] = useState<number[]>(DEFAULT_COL_WIDTHS)
const startColumnResize = (index: number, event: React.MouseEvent) => {
event.preventDefault()
@ -467,13 +511,13 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
const body = await response.json()
const rows: BreachOrder[] = body?.data?.rows ?? []
const header = kind === 'fine'
? ['线上订单号', '内部订单号', '平台', '店铺', '商品编码', '运营负责人', '商家实收', '限价', '价差', '驳回原因', '审核人', '乐捐金额']
: ['付款日期', '平台', '店铺', '线上订单号', '内部订单号', '商品编码', '店铺款式编码', '店铺商品编码', '数量', '商家实收', '限价×数量', '价差', '运营负责人', '状态', '申诉类型', '流程号']
? ['线上订单号', '内部订单号', '平台', '店铺', '商品编码', '运营负责人', '部门负责人', '利润中心', '商家实收', '限价', '价差', '驳回原因', '审核人', '乐捐金额']
: ['付款日期', '平台', '店铺', '线上订单号', '内部订单号', '商品编码', '店铺款式编码', '店铺商品编码', '数量', '买家实付', '平台承担', '商家实收', '限价单价', '限价×数量', '价差', '运营负责人', '部门负责人', '利润中心', '订单状态', '退款状态', '上架时间', '流程结束日期', '审核状态', '申诉类型', '流程号']
const lines = [header.join(',')]
for (const row of rows) {
const cells = kind === 'fine'
? [row.soId, row.oId, row.platform, row.shopName, row.itemCode, row.ownerName, row.sellerIncomeAmount, row.limitTotal, row.gapAmount, row.reviewReason, row.reviewedBy, row.fineAmount]
: [day(row.payDate), row.platform, row.shopName, row.soId, row.oId, row.itemCode, row.shopStyleCode, row.shopItemCode, row.qty, row.sellerIncomeAmount, row.limitTotal, row.gapAmount, row.ownerName, row.statusLabel, row.appealType, row.processNo]
? [row.soId, row.oId, row.platform, row.shopName, row.itemCode, row.ownerName, row.deptOwner, row.profitCenter, row.sellerIncomeAmount, row.limitTotal, row.gapAmount, row.reviewReason, row.reviewedBy, row.fineAmount]
: [day(row.payDate), row.platform, row.shopName, row.soId, row.oId, row.itemCode, row.shopStyleCode, row.shopItemCode, row.qty, row.buyerPaidAmount, row.platformBearAmount, row.sellerIncomeAmount, row.limitUnitPrice, row.limitTotal, row.gapAmount, row.ownerName, row.deptOwner, row.profitCenter, row.orderStatus, row.refundStatus, day(row.listedAt), day(row.flowEndDate), row.statusLabel, row.appealType, row.processNo]
lines.push(cells.map((value) => `"${String(value ?? '').replaceAll('"', '""')}"`).join(','))
}
const blob = new Blob(['\ufeff' + lines.join('\n')], { type: 'text/csv;charset=utf-8' })
@ -589,10 +633,12 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
))}
</div>
<span className={styles.chip}>共 <b>{stats?.total ?? 0}</b> 条破价明细</span>
<span className={`${styles.chip} ${styles.chipWarn}`}>
本月乐捐 <b>{money(stats?.fineTotal ?? 0)}</b>
(已计 {stats?.finedOrderCount ?? 0} 单,¥{stats?.finePerOrder ?? 10}/单)
</span>
{canReview && (
<span className={`${styles.chip} ${styles.chipWarn}`} title="本月破价订单暂按 ¥10/单计;审核通过或人员已离职自动扣减,同一线上订单只计一次">
本月乐捐 <b>{money(stats?.fineTotal ?? 0)}</b>
(已计 {stats?.finedOrderCount ?? 0} 单,¥{stats?.finePerOrder ?? 10}/单)
</span>
)}
<span className={styles.chip}>
付款日期
<input
@ -609,7 +655,7 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
<MultiFilterChip label="店铺款式编码" placeholder="款式编码" field="shopStyleCode" values={styleCodeFilters} onChange={setStyleCodeFilters} width={110} />
<MultiFilterChip label="店铺商品编码" placeholder="店铺商品编码" field="shopItemCode" values={shopItemCodeFilters} onChange={setShopItemCodeFilters} width={110} />
<MultiFilterChip label="订单号" placeholder="搜索/粘贴多个订单号" field="orderNo" values={orderNoFilters} onChange={setOrderNoFilters} width={140} />
<MultiFilterChip label="负责人" placeholder="选择/搜索负责人" field="owner" values={ownerFilters} onChange={setOwnerFilters} width={100} />
<MultiFilterChip label="运营负责人" placeholder="选择/搜索负责人" field="owner" values={ownerFilters} onChange={setOwnerFilters} width={100} />
<MultiFilterChip label="申诉原因" placeholder="选择申诉类型" field="appealType" values={appealTypeFilters} onChange={setAppealTypeFilters} width={110} />
<MultiFilterChip label="平台" placeholder="选择平台" field="platform" values={platformFilters} onChange={setPlatformFilters} width={90} />
<MultiFilterChip label="店铺" placeholder="选择店铺" field="shopName" values={shopFilters} onChange={setShopFilters} width={120} />
@ -619,7 +665,9 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
{canExport && (
<>
<button type="button" className={styles.btn} onClick={() => void exportRows('list')}>导出当前筛选</button>
<button type="button" className={styles.btn} onClick={() => void exportRows('fine')}>导出乐捐明细</button>
{canReview && (
<button type="button" className={styles.btn} onClick={() => void exportRows('fine')}>导出乐捐明细</button>
)}
</>
)}
{hasActiveFilters && (
@ -634,37 +682,42 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
</colgroup>
<thead>
<tr>
{sortTh('payDate', '付款日期', 0, 'payDate')}
{sortTh('platform', '平台 / 店铺', 1, 'platform')}
{sortTh('itemCode', '商品编码', 2, 'itemCode')}
{sortTh('shopStyleCode', '店铺款式编码', 3, 'shopStyleCode')}
{sortTh('shopItemCode', '店铺商品编码', 4, 'shopItemCode')}
{sortTh('soId', '订单号', 5, 'soId')}
{sortTh('listedAt', '上架时间', 6)}
{sortTh('flowEndDate', '流程结束日期', 7)}
{sortTh('sellerIncomeAmount', '商家实收 / 限价', 8)}
{sortTh('status', '状态', 9, 'status')}
{TABLE_COLUMNS.map((column, index) => sortTh(
column.field,
column.label,
index,
column.filterKey,
))}
</tr>
</thead>
<tbody>
{loading && <tr><td colSpan={10} className={styles.state}>加载中…</td></tr>}
{!loading && error && <tr><td colSpan={10} className={`${styles.state} ${styles.error}`}>{error}</td></tr>}
{!loading && !error && orders.length === 0 && <tr><td colSpan={10} className={styles.state}>暂无破价订单</td></tr>}
{loading && <tr><td colSpan={TABLE_COLUMNS.length} className={styles.state}>加载中…</td></tr>}
{!loading && error && <tr><td colSpan={TABLE_COLUMNS.length} className={`${styles.state} ${styles.error}`}>{error}</td></tr>}
{!loading && !error && orders.length === 0 && <tr><td colSpan={TABLE_COLUMNS.length} className={styles.state}>暂无破价订单</td></tr>}
{orders.map((row) => (
<tr key={row.id} className={activeId === row.id ? styles.on : undefined} onClick={() => setActiveId(row.id)}>
<td className={styles.num}>{day(row.payDate)}</td>
<td>{row.platform}<span className={styles.sub}>{row.shopName}</span></td>
<td className={styles.num}>{row.itemCode}<span className={styles.sub}>{row.ownerName || '(未匹配)'}</span></td>
<td className={styles.num}>{row.shopStyleCode || '—'}</td>
<td className={styles.num}>{row.shopItemCode || '—'}</td>
<td className={styles.num}>{row.soId || '—'}<span className={styles.sub}>内部 {row.oId || '—'}</span></td>
<td>{text(row.platform)}</td>
<td title={row.shopName}>{text(row.shopName)}</td>
<td className={styles.num}>{text(row.soId)}</td>
<td className={styles.num}>{text(row.oId)}</td>
<td className={styles.num}>{text(row.itemCode)}</td>
<td className={styles.num}>{text(row.shopStyleCode)}</td>
<td className={styles.num}>{text(row.shopItemCode)}</td>
<td className={styles.num}>{row.qty}</td>
<td className={styles.num}>{money(row.buyerPaidAmount)}</td>
<td className={styles.num}>{money(row.platformBearAmount)}</td>
<td className={styles.num}>{money(row.sellerIncomeAmount)}</td>
<td className={styles.num}>{money(row.limitUnitPrice)}</td>
<td className={styles.num}>{money(row.limitTotal)}</td>
<td className={`${styles.num} ${styles.gap}`}>{money(row.gapAmount)}</td>
<td>{text(row.ownerName)}</td>
<td>{text(row.deptOwner)}</td>
<td>{text(row.profitCenter)}</td>
<td>{text(row.orderStatus)}</td>
<td>{text(row.refundStatus)}</td>
<td className={styles.num}>{day(row.listedAt)}</td>
<td className={styles.num}>{day(row.flowEndDate)}</td>
<td className={styles.num}>
{money(row.sellerIncomeAmount)}
<b className={styles.gap}> {row.gapAmount !== null ? row.gapAmount.toFixed(2) : ''}</b>
<span className={styles.sub}>限价 {money(row.limitTotal)}({money(row.limitUnitPrice)}×{row.qty})</span>
</td>
<td><span className={`${styles.tag} ${STATUS_CLASS[row.status] ?? ''}`}>{row.statusLabel}</span></td>
</tr>
))}
@ -696,17 +749,28 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
<h3>订单与破价数据</h3>
<div className={styles.in}>
<div className={styles.price}>
<div><span>买家实付</span><b>{money(order.buyerPaidAmount)}</b></div>
<div><span>平台承担</span><b>{money(order.platformBearAmount)}</b></div>
<div><span>商家实收</span><b className={(order.gapAmount ?? 0) < 0 ? styles.bad : undefined}>{money(order.sellerIncomeAmount)}</b></div>
<div><span>限价单价</span><b>{money(order.limitUnitPrice)}</b></div>
<div><span>限价×数量</span><b>{money(order.limitTotal)}</b></div>
<div><span>价差</span><b className={(order.gapAmount ?? 0) < 0 ? styles.bad : undefined}>{order.gapAmount !== null ? order.gapAmount.toFixed(2) : '—'}</b></div>
</div>
<div className={styles.facts}>
<div><span>付款日期</span><b>{day(order.payDate)}</b></div>
<div><span>平台 / 店铺</span><b>{order.platform} · {order.shopName}</b></div>
<div><span>商品编码</span><b>{order.itemCode}</b></div>
<div><span>运营负责人</span><b>{order.ownerName || '—'}</b></div>
<div><span>店铺款式编码</span><b>{order.shopStyleCode || '—'}</b></div>
<div><span>店铺商品编码</span><b>{order.shopItemCode || '—'}</b></div>
<div><span>平台</span><b>{text(order.platform)}</b></div>
<div><span>店铺</span><b>{text(order.shopName)}</b></div>
<div><span>线上订单号</span><b>{text(order.soId)}</b></div>
<div><span>内部订单号</span><b>{text(order.oId)}</b></div>
<div><span>商品编码</span><b>{text(order.itemCode)}</b></div>
<div><span>店铺款式编码</span><b>{text(order.shopStyleCode)}</b></div>
<div><span>店铺商品编码</span><b>{text(order.shopItemCode)}</b></div>
<div><span>数量</span><b>{order.qty}</b></div>
<div><span>运营负责人</span><b>{text(order.ownerName)}</b></div>
<div><span>部门负责人</span><b>{text(order.deptOwner)}</b></div>
<div><span>利润中心</span><b>{text(order.profitCenter)}</b></div>
<div><span>订单状态</span><b>{text(order.orderStatus)}</b></div>
<div><span>退款状态</span><b>{text(order.refundStatus)}</b></div>
<div><span>上架时间</span><b>{day(order.listedAt)}</b></div>
<div><span>限价流程结束日期</span><b>{day(order.flowEndDate)}</b></div>
</div>

View File

@ -64,6 +64,11 @@ export type BreachGenerationAuth = {
adjustedLimitPrice: number | null
}
export type BreachGenerationOwnerPersonnel = {
departmentOwner: string
profitCenter: string
}
/** 破价判定豁免所需的流程数据(货号维度)。 */
export type BreachGenerationAuthContext = {
/** 内部条码(商品编码)→ 货号 */
@ -78,6 +83,8 @@ export type BreachGenerationAuthContext = {
limitTimelineByBarcode?: Map<string, LimitPriceTimeline>
/** 货号 → 价格授权列表 */
authsByStyle: Map<string, BreachGenerationAuth[]>
/** 运营负责人(标准化姓名)→ 人员信息中的部门负责人/利润中心 */
personnelByOwner?: Map<string, BreachGenerationOwnerPersonnel>
}
export type BreachGenerationCandidate = {
@ -98,6 +105,8 @@ export type BreachGenerationCandidate = {
limitTotal: number
gapAmount: number
ownerName: string
deptOwner: string
profitCenter: string
orderStatus: string
refundStatus: string
listedAt: Date | null
@ -272,6 +281,7 @@ export function buildBreachOrderCandidates(
current.buyerPaidAmount = Number(current.buyerPaidAmount || 0) + Number(line.buyerPaidAmount || 0)
current.sellerIncomeAmount = Number(current.sellerIncomeAmount || 0) + Number(line.sellerIncomeAmount || 0)
current.fromManualSwap = Boolean(current.fromManualSwap || line.fromManualSwap)
current.linkOwnerName = current.linkOwnerName || line.linkOwnerName
} else {
aggregated.set(key, { ...line })
}
@ -372,7 +382,8 @@ export function buildBreachOrderCandidates(
?? (limitTimeline ? null : (styleCode ? authContext?.flowEndDateByStyle.get(styleCode) : null))
?? linkLimit?.flowEndDate
?? null
const candidateOwnerName = orderOwnerName || linkOwnerName || cleanOwnerName(linkLimit?.ownerName)
const candidateOwnerName = linkOwnerName || orderOwnerName || cleanOwnerName(linkLimit?.ownerName)
const personnel = authContext?.personnelByOwner?.get(normalizeOwnerName(candidateOwnerName))
if (!candidateOwnerName) stats.missingOwnerName += 1
if (!listedAt) stats.missingListedAt += 1
if (!flowEndDate) stats.missingFlowEndDate += 1
@ -399,6 +410,8 @@ export function buildBreachOrderCandidates(
limitTotal,
gapAmount: Number((buyerPaid - limitTotal).toFixed(4)),
ownerName: candidateOwnerName,
deptOwner: cleanOwnerName(personnel?.departmentOwner),
profitCenter: cleanOwnerName(personnel?.profitCenter),
orderStatus: row.orderStatus || '',
refundStatus: row.refundStatus || '',
listedAt,

View File

@ -10,6 +10,8 @@ export type BreachOrderMetadataCandidate = {
limitTotal: number
gapAmount: number
ownerName: string
deptOwner: string
profitCenter: string
orderStatus: string
refundStatus: string
listedAt: Date | null
@ -29,6 +31,8 @@ export type StoredBreachOrderMetadata = {
limitTotal: unknown
gapAmount: unknown
ownerName: string
deptOwner: string
profitCenter: string
orderStatus: string
refundStatus: string
listedAt: Date | null
@ -46,6 +50,8 @@ export type BreachOrderSnapshotRefresh = {
limitTotal: number
gapAmount: number
ownerName: string | null
deptOwner: string
profitCenter: string
orderStatus: string
refundStatus: string
listedAt: Date | null
@ -62,6 +68,10 @@ function sameDate(left: Date | null, right: Date | null) {
return (left?.getTime() ?? null) === (right?.getTime() ?? null)
}
function preferCandidate(candidate: string | null | undefined, stored: string | null | undefined) {
return String(candidate ?? '').trim() || String(stored ?? '')
}
/**
* 刷新破价计算快照,并补齐元数据空值。
* 不包含 status / appeal / review 等人工流程字段。
@ -71,9 +81,9 @@ export function planBreachOrderSnapshotRefresh(
stored: StoredBreachOrderMetadata | undefined,
): BreachOrderSnapshotRefresh | null {
if (!stored) return null
const ownerName = !stored.ownerName.trim() && candidate.ownerName.trim()
? candidate.ownerName.trim()
: stored.ownerName
const ownerName = preferCandidate(candidate.ownerName, stored.ownerName)
const deptOwner = preferCandidate(candidate.deptOwner, stored.deptOwner)
const profitCenter = preferCandidate(candidate.profitCenter, stored.profitCenter)
const listedAt = stored.listedAt ?? candidate.listedAt
const flowEndDate = stored.flowEndDate ?? candidate.flowEndDate
const changed = !sameDate(stored.payDate, candidate.payDate)
@ -85,6 +95,8 @@ export function planBreachOrderSnapshotRefresh(
|| !sameNumber(stored.limitTotal, candidate.limitTotal)
|| !sameNumber(stored.gapAmount, candidate.gapAmount)
|| stored.ownerName !== ownerName
|| stored.deptOwner !== deptOwner
|| stored.profitCenter !== profitCenter
|| stored.orderStatus !== candidate.orderStatus
|| stored.refundStatus !== candidate.refundStatus
|| !sameDate(stored.listedAt, listedAt)
@ -101,6 +113,8 @@ export function planBreachOrderSnapshotRefresh(
limitTotal: candidate.limitTotal,
gapAmount: candidate.gapAmount,
ownerName,
deptOwner,
profitCenter,
orderStatus: candidate.orderStatus,
refundStatus: candidate.refundStatus,
listedAt,

View File

@ -140,7 +140,7 @@ export const BREACH_REJECT_REASONS = [
'申诉原因与破价无关',
] as const
/** 乐捐:驳回按 ¥10/单计;人员已离职不计。 */
/** 乐捐:未通过审核的破价订单暂按 ¥10/单计;审核通过或人员已离职不计。 */
export const BREACH_FINE_AMOUNT = 10
/** 优惠出资方字典(用于核对实付款与商家实收的差额由谁承担)。 */

View File

@ -59,6 +59,9 @@ describe('jst-breach-order-source repository', () => {
await expect(repository.listLinkOwners(['10025303494470'])).resolves.toEqual(
new Map([['10025303494470', '负责人甲']]),
)
const sqlText = String(request.query.mock.calls[0]?.[0] ?? '')
expect(sqlText).toContain('shopproid AS itemId')
expect(sqlText).toContain('ider AS ownerName')
expect(repository.listItemOwners).toHaveBeenCalledWith(['10025303494470'])
})

View File

@ -283,7 +283,7 @@ class JstBreachOrderSourceRepository {
return listedAtByKey
}
/** 按店铺款式编码读取链接维度负责人(op_TargetManagement 最新记录)。 */
/** 按店铺款式编码读取运营负责人(与停产下架同口径:链接 itemId → 负责人)。 */
async listLinkOwners(itemIds: readonly string[]): Promise<Map<string, string>> {
const ids = [...new Set(itemIds.map((value) => String(value ?? '').trim()).filter(Boolean))]
const ownerByItemId = new Map<string, string>()

View File

@ -17,6 +17,11 @@ const mockPrisma = {
supplyChainBreachOrder: {
findMany: jest.fn(),
createMany: jest.fn(),
count: jest.fn(),
updateMany: jest.fn(),
},
supplyChainBreachOrderLog: {
findMany: jest.fn(),
},
$executeRaw: jest.fn(),
}
@ -27,6 +32,10 @@ const mockRepository = {
listLinkOwners: jest.fn(),
listItemOwners: jest.fn(),
}
const mockOwnerConfigRepository = {
listOwnerOptions: jest.fn(),
listOwnerEmployment: jest.fn(),
}
const mockLimitPriceDetailService = {
listStyleCodesWithAnyLimitVersion: jest.fn(),
listTimelinesByBarcodes: jest.fn(),
@ -48,6 +57,11 @@ jest.mock('@/lib/prisma', () => ({ prisma: {
supplyChainBreachOrder: {
findMany: (...args: unknown[]) => mockPrisma.supplyChainBreachOrder.findMany(...args),
createMany: (...args: unknown[]) => mockPrisma.supplyChainBreachOrder.createMany(...args),
count: (...args: unknown[]) => mockPrisma.supplyChainBreachOrder.count(...args),
updateMany: (...args: unknown[]) => mockPrisma.supplyChainBreachOrder.updateMany(...args),
},
supplyChainBreachOrderLog: {
findMany: (...args: unknown[]) => mockPrisma.supplyChainBreachOrderLog.findMany(...args),
},
$executeRaw: (...args: unknown[]) => mockPrisma.$executeRaw(...args),
} }))
@ -62,6 +76,12 @@ jest.mock('@/server/repositories/jst-breach-order-source.repository', () => ({
listItemOwners: (...args: unknown[]) => mockRepository.listItemOwners(...args),
},
}))
jest.mock('@/server/repositories/supply-chain-management-owner-config.repository', () => ({
supplyChainManagementOwnerConfigRepository: {
listOwnerOptions: (...args: unknown[]) => mockOwnerConfigRepository.listOwnerOptions(...args),
listOwnerEmployment: (...args: unknown[]) => mockOwnerConfigRepository.listOwnerEmployment(...args),
},
}))
jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({
supplyChainPermissionSettingsService: {},
}))
@ -101,6 +121,9 @@ describe('SupplyChainBreachOrderService generate', () => {
mockPrisma.supplyChainLinkLimitPrice.findMany.mockResolvedValue([])
mockPrisma.supplyChainBreachOrder.findMany.mockResolvedValue([])
mockPrisma.supplyChainBreachOrder.createMany.mockResolvedValue({ count: 1 })
mockPrisma.supplyChainBreachOrder.count.mockResolvedValue(1)
mockPrisma.supplyChainBreachOrder.updateMany.mockResolvedValue({ count: 1 })
mockPrisma.supplyChainBreachOrderLog.findMany.mockResolvedValue([])
mockPrisma.$executeRaw.mockResolvedValue(1)
mockRepository.listOrderItems.mockResolvedValue([{
oId: 'ORDER-1',
@ -127,6 +150,23 @@ describe('SupplyChainBreachOrderService generate', () => {
['LINK-1::SHOP-SKU-1::BARCODE-1', new Date('2026-09-01T00:00:00Z')],
]))
mockRepository.listLinkOwners.mockResolvedValue(new Map([['LINK-1', '负责人甲']]))
mockOwnerConfigRepository.listOwnerOptions.mockResolvedValue([{
operationOwner: '负责人甲',
departmentOwner: '部门负责人乙',
generalOwner: '总负责人丁',
profitCenter: '利润中心丙',
}])
mockOwnerConfigRepository.listOwnerEmployment.mockResolvedValue([{
name: '负责人甲',
sourceStatus: 'EMPLOYED',
departmentOwner: '部门负责人乙',
generalOwner: '总负责人丁',
}, {
name: '离职负责人乙',
sourceStatus: 'DIMISSIONED',
departmentOwner: '部门负责人丙',
generalOwner: '总负责人戊',
}])
mockRepository.listItemOwners.mockResolvedValue(new Map())
mockLimitPriceDetailService.listStyleCodesWithAnyLimitVersion.mockResolvedValue(new Set(['STYLE-1']))
mockLimitPriceDetailService.listTimelinesByBarcodes.mockResolvedValue(new Map([[
@ -189,6 +229,8 @@ describe('SupplyChainBreachOrderService generate', () => {
const created = mockPrisma.supplyChainBreachOrder.createMany.mock.calls[0][0].data[0]
expect(created).toMatchObject({
ownerName: '负责人甲',
deptOwner: '部门负责人乙',
profitCenter: '利润中心丙',
listedAt: new Date('2026-09-01T00:00:00Z'),
flowEndDate: new Date('2026-08-01T00:00:00Z'),
})
@ -262,6 +304,8 @@ describe('SupplyChainBreachOrderService generate', () => {
limitTotal: 100,
gapAmount: -20,
ownerName: '',
deptOwner: '',
profitCenter: '',
orderStatus: 'Sent',
refundStatus: '',
listedAt: null,
@ -293,10 +337,93 @@ describe('SupplyChainBreachOrderService generate', () => {
limitTotal: 90,
gapAmount: -10,
ownerName: '负责人甲',
deptOwner: '部门负责人乙',
profitCenter: '利润中心丙',
orderStatus: 'Sent',
refundStatus: '',
listedAt: '2026-09-01T00:00:00.000Z',
flowEndDate: '2026-08-01T00:00:00.000Z',
}])
})
it('按人员配置双向核对离职状态,并恢复在职人员的自动离职误标', async () => {
mockPrisma.supplyChainBreachOrder.findMany.mockResolvedValue([{
id: 'BREACH-ACTIVE',
ownerName: '负责人甲',
status: 'LEFT_EMPLOYEE',
reviewedBy: '系统自动排查',
reviewReason: '负责人已离职(系统自动标记)',
appealType: '',
appealDesc: '',
appealImages: [],
processNo: '',
appliedFromLink: false,
}, {
id: 'BREACH-LEFT',
ownerName: '离职负责人乙',
status: 'PENDING_APPEAL',
reviewedBy: '',
reviewReason: '',
appealType: '',
appealDesc: '',
appealImages: [],
processNo: '',
appliedFromLink: false,
}, {
id: 'BREACH-UNKNOWN',
ownerName: '未匹配负责人',
status: 'LEFT_EMPLOYEE',
reviewedBy: '系统自动排查',
reviewReason: '负责人已离职(系统自动标记)',
appealType: '',
appealDesc: '',
appealImages: [],
processNo: '',
appliedFromLink: false,
}])
const result = await service.markLeftEmployees({ dryRun: true })
expect(result).toMatchObject({
marked: 1,
restored: 2,
dryRun: true,
resignedNames: ['离职负责人乙'],
})
expect(mockPrisma.supplyChainBreachOrder.updateMany).not.toHaveBeenCalled()
expect(mockPrisma.$executeRaw).not.toHaveBeenCalled()
})
it('可预览链接身份字段回填,只处理能匹配链接负责人表的记录', async () => {
mockPrisma.supplyChainBreachOrder.findMany
.mockResolvedValueOnce([{
id: 'BREACH-1',
shopStyleCode: 'LINK-1',
ownerName: '',
deptOwner: '',
profitCenter: '',
}, {
id: 'BREACH-2',
shopStyleCode: 'MISSING-LINK',
ownerName: '',
deptOwner: '',
profitCenter: '',
}])
.mockResolvedValueOnce([])
mockRepository.listLinkOwners.mockResolvedValue(new Map([['LINK-1', '负责人甲']]))
const result = await service.backfillLinkIdentityMetadata({
dateFrom: '2026-11-01',
dateTo: '2026-11-13',
dryRun: true,
})
expect(result).toMatchObject({
dryRun: true,
scanned: 2,
updated: 1,
unresolved: 1,
})
expect(mockPrisma.$executeRaw).not.toHaveBeenCalled()
})
})

View File

@ -35,6 +35,12 @@ jest.mock('@/server/services/supply-chain-breach-evidence.service', () => ({
buildBreachEvidenceVerdict: (...args: unknown[]) => mockVerdict(...args),
}))
jest.mock('@/server/services/supply-chain-breach-rule-config.service', () => ({ supplyChainBreachRuleConfigService: {} }))
jest.mock('@/server/repositories/supply-chain-management-owner-config.repository', () => ({
supplyChainManagementOwnerConfigRepository: {
listOwnerEmployment: jest.fn().mockResolvedValue([]),
listOwnerOptions: jest.fn().mockResolvedValue([]),
},
}))
const viewer = { id: 'reviewer', name: 'reviewer', canAppeal: true, canReview: true }
const current = {
@ -113,7 +119,7 @@ describe('破价订单历史隔离', () => {
await service.listPage({ page: 1, pageSize: 50, filters: {}, viewer })
const listArgs = mockFindMany.mock.calls.at(-1)?.[0]
const listArgs = mockFindMany.mock.calls[0]?.[0]
const statsArgs = mockGroupBy.mock.calls.at(-1)?.[0]
expect(listArgs.where.payDate).toEqual({
gte: new Date('2026-11-30T16:00:00.000Z'),
@ -123,14 +129,19 @@ describe('破价订单历史隔离', () => {
expect(mockCount).toHaveBeenCalledWith({ where: listArgs.where })
})
it('本月乐捐按已计费订单汇总,并返回计费单数', async () => {
mockFindMany.mockResolvedValue([])
it('本月乐捐暂计所有未通过且非离职订单,并按线上订单去重', async () => {
mockFindMany
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
{ id: 'fine-line-1', soId: 'order-1' },
{ id: 'fine-line-2', soId: 'order-1' },
])
mockGroupBy.mockResolvedValue([{
status: 'REJECTED',
_count: { _all: 2 },
_sum: { fineAmount: 10 },
}])
mockCount.mockResolvedValueOnce(2).mockResolvedValueOnce(1)
mockCount.mockResolvedValueOnce(2)
const result = await service.listPage({ page: 1, pageSize: 50, filters: {}, viewer })
@ -139,6 +150,32 @@ describe('破价订单历史隔离', () => {
finedOrderCount: 1,
finePerOrder: 10,
})
const fineQuery = mockFindMany.mock.calls[1]?.[0]
expect(fineQuery.where).toMatchObject({
payDate: expect.objectContaining({
gte: expect.any(Date),
lt: expect.any(Date),
}),
status: {
in: ['PENDING_APPEAL', 'PENDING_REVIEW', 'RETURNED', 'REJECTED'],
},
})
})
it('普通运营不查询且不返回本月乐捐汇总', async () => {
mockFindMany.mockResolvedValue([])
const result = await service.listPage({
page: 1,
pageSize: 50,
filters: {},
viewer: { ...viewer, canReview: false },
})
expect(mockFindMany).toHaveBeenCalledTimes(1)
expect(result.stats).not.toHaveProperty('fineTotal')
expect(result.stats).not.toHaveProperty('finedOrderCount')
expect(result.stats).not.toHaveProperty('finePerOrder')
})
it('历史订单详情不可进入当前审核', async () => {

View File

@ -33,7 +33,9 @@ import {
buildBreachOrderCandidates,
type BreachGenerationAuth,
type BreachGenerationAuthContext,
type BreachGenerationOwnerPersonnel,
} from '@/lib/breach-order-generation'
import { supplyChainManagementOwnerConfigRepository } from '@/server/repositories/supply-chain-management-owner-config.repository'
export type BreachOrderListFilters = {
status?: string[]
@ -61,7 +63,9 @@ export type BreachOrderListFilters = {
const BREACH_SORT_FIELDS: ReadonlySet<string> = new Set([
'payDate', 'platform', 'shopName', 'itemCode', 'shopStyleCode', 'shopItemCode',
'soId', 'oId', 'listedAt', 'flowEndDate', 'sellerIncomeAmount', 'limitTotal', 'gapAmount', 'status',
'soId', 'oId', 'listedAt', 'flowEndDate', 'qty', 'buyerPaidAmount', 'platformBearAmount',
'sellerIncomeAmount', 'limitUnitPrice', 'limitTotal', 'gapAmount',
'ownerName', 'deptOwner', 'profitCenter', 'orderStatus', 'refundStatus', 'status',
])
type Viewer = { id: string; name: string; canAppeal: boolean; canReview: boolean }
@ -76,9 +80,17 @@ const SYSTEM_AUTO_VIEWER: Viewer = {
/** 老链接申诉类型(自动审核适用)。 */
const LEGACY_LINK_APPEAL_TYPE = '老链接,上架时间早于限价流程'
const AUTO_LEFT_REVIEWER = '系统自动排查'
const AUTO_LEFT_REASON = '负责人已离职(系统自动标记)'
const decimalToNumber = (value: Prisma.Decimal | null | undefined) => (value === null || value === undefined ? null : Number(value))
function normalizedOwnerKey(value: string | null | undefined) {
return String(value ?? '')
.normalize('NFKC')
.replace(/[\s\u200B-\u200D\uFEFF]/g, '')
}
/** 生成 dateFrom ~ dateTo(含首尾)的日期列表;日期非法或倒序时返回空数组。 */
function eachDay(dateFrom: string, dateTo: string) {
const days: string[] = []
@ -106,33 +118,174 @@ class SupplyChainBreachOrderService {
}
}
private async buildOwnerEmploymentMap() {
const entries = await supplyChainManagementOwnerConfigRepository.listOwnerEmployment()
const statusByOwner = new Map<string, 'EMPLOYED' | 'DIMISSIONED'>()
for (const entry of entries) {
const key = normalizedOwnerKey(entry.name)
if (key) statusByOwner.set(key, entry.sourceStatus)
}
return statusByOwner
}
/**
* 自动排查离职负责人:人员信息里已离职(INACTIVE)的负责人,其破价单自动标记「人员已离职」,
* 不判定、不计乐捐(覆盖待申诉/待审核/已打回状态)。
* 负责人离职状态双向核对:
* - 人员配置中当前为离职 → 待申诉/待审核/已打回自动转「人员已离职」;
* - 曾被系统自动标为离职、但人员配置当前为在职或已无法匹配 → 恢复原审核阶段。
* 不复用员工目录的离职姓名集合,避免同名/历史离职记录误伤当前在职负责人。
*/
async markLeftEmployees() {
const resigned = await prisma.employeeDirectory.findMany({
where: { sourceStatus: 'DIMISSIONED' },
select: { name: true },
})
const names = [...new Set(resigned.map((item) => item.name.trim()).filter(Boolean))]
if (!names.length) return { marked: 0, names: [] }
const result = await prisma.supplyChainBreachOrder.updateMany({
async markLeftEmployees(options: { dryRun?: boolean } = {}) {
const statusByOwner = await this.buildOwnerEmploymentMap()
const rows = await prisma.supplyChainBreachOrder.findMany({
where: {
ownerName: { in: names },
status: { in: [BREACH_ORDER_STATUS.PENDING_APPEAL, BREACH_ORDER_STATUS.PENDING_REVIEW, BREACH_ORDER_STATUS.RETURNED] },
payDate: { gte: breachMonitorStartAt() },
status: {
in: [
BREACH_ORDER_STATUS.PENDING_APPEAL,
BREACH_ORDER_STATUS.PENDING_REVIEW,
BREACH_ORDER_STATUS.RETURNED,
BREACH_ORDER_STATUS.LEFT_EMPLOYEE,
],
},
},
data: {
status: BREACH_ORDER_STATUS.LEFT_EMPLOYEE,
fineAmount: 0,
reviewDecision: 'LEFT',
reviewReason: '负责人已离职(系统自动标记)',
reviewedBy: '系统自动排查',
reviewedAt: new Date(),
select: {
id: true,
ownerName: true,
status: true,
reviewedBy: true,
reviewReason: true,
appealType: true,
appealDesc: true,
appealImages: true,
processNo: true,
appliedFromLink: true,
},
})
return { marked: result.count, names }
const markRows = rows.filter((row) =>
(
row.status === BREACH_ORDER_STATUS.PENDING_APPEAL
|| row.status === BREACH_ORDER_STATUS.PENDING_REVIEW
|| row.status === BREACH_ORDER_STATUS.RETURNED
)
&& statusByOwner.get(normalizedOwnerKey(row.ownerName)) === 'DIMISSIONED')
const restoreRows = rows.filter((row) =>
row.status === BREACH_ORDER_STATUS.LEFT_EMPLOYEE
&& row.reviewedBy === AUTO_LEFT_REVIEWER
&& row.reviewReason === AUTO_LEFT_REASON
&& statusByOwner.get(normalizedOwnerKey(row.ownerName)) !== 'DIMISSIONED')
const restoreIds = restoreRows.map((row) => row.id)
const logs = restoreIds.length
? await prisma.supplyChainBreachOrderLog.findMany({
where: {
orderId: { in: restoreIds },
action: { not: 'AUTO_LEFT_EMPLOYEE' },
},
orderBy: { createdAt: 'desc' },
select: {
orderId: true,
action: true,
operatorName: true,
detail: true,
createdAt: true,
},
})
: []
const latestLogByOrder = new Map<string, (typeof logs)[number]>()
for (const log of logs) {
if (!latestLogByOrder.has(log.orderId)) latestLogByOrder.set(log.orderId, log)
}
const restorePlans = restoreRows.map((row) => {
const latestLog = latestLogByOrder.get(row.id)
const hasAppeal = Boolean(
row.appealType
|| row.appealDesc
|| row.processNo
|| row.appliedFromLink
|| (Array.isArray(row.appealImages) && row.appealImages.length),
)
const isReturned = latestLog?.action === 'REVIEW_RETURN'
const isPendingReview = !isReturned && (
hasAppeal
|| latestLog?.action === 'APPEAL_ORDER'
|| latestLog?.action === 'APPEAL_LINK'
)
const status = isReturned
? BREACH_ORDER_STATUS.RETURNED
: isPendingReview
? BREACH_ORDER_STATUS.PENDING_REVIEW
: BREACH_ORDER_STATUS.PENDING_APPEAL
const detail = latestLog?.detail && typeof latestLog.detail === 'object' && !Array.isArray(latestLog.detail)
? latestLog.detail as Record<string, unknown>
: {}
return {
id: row.id,
status,
reviewDecision: isReturned ? 'RETURN' : '',
reviewReason: isReturned ? String(detail.reason ?? '') : '',
reviewNote: isReturned ? String(detail.note ?? '') : '',
reviewedBy: isReturned ? latestLog?.operatorName ?? '' : '',
reviewedAt: isReturned ? latestLog?.createdAt?.toISOString() ?? null : null,
}
})
const resignedNames = [...new Set(markRows.map((row) => row.ownerName.trim()).filter(Boolean))]
if (options.dryRun) {
return {
marked: markRows.length,
restored: restorePlans.length,
resignedNames,
dryRun: true,
}
}
let marked = 0
for (let offset = 0; offset < markRows.length; offset += 1_000) {
const result = await prisma.supplyChainBreachOrder.updateMany({
where: { id: { in: markRows.slice(offset, offset + 1_000).map((row) => row.id) } },
data: {
status: BREACH_ORDER_STATUS.LEFT_EMPLOYEE,
fineAmount: 0,
reviewDecision: 'LEFT',
reviewReason: AUTO_LEFT_REASON,
reviewNote: '',
reviewedBy: AUTO_LEFT_REVIEWER,
reviewedAt: new Date(),
},
})
marked += result.count
}
let restored = 0
for (let offset = 0; offset < restorePlans.length; offset += 1_000) {
restored += await prisma.$executeRaw`
UPDATE "SupplyChainBreachOrder" AS breached
SET
"status" = candidate."status",
"fineAmount" = 0,
"reviewDecision" = candidate."reviewDecision",
"reviewReason" = candidate."reviewReason",
"reviewNote" = candidate."reviewNote",
"reviewedBy" = candidate."reviewedBy",
"reviewedAt" = (NULLIF(candidate."reviewedAt", '')::timestamptz AT TIME ZONE 'UTC'),
"updatedAt" = CURRENT_TIMESTAMP
FROM jsonb_to_recordset(${JSON.stringify(restorePlans.slice(offset, offset + 1_000))}::jsonb) AS candidate(
id text,
"status" text,
"reviewDecision" text,
"reviewReason" text,
"reviewNote" text,
"reviewedBy" text,
"reviewedAt" text
)
WHERE breached.id = candidate.id
AND breached."status" = 'LEFT_EMPLOYEE'
AND breached."reviewedBy" = ${AUTO_LEFT_REVIEWER}
AND breached."reviewReason" = ${AUTO_LEFT_REASON}
`
}
return {
marked,
restored,
resignedNames,
dryRun: false,
}
}
async listPage(input: {
@ -235,7 +388,7 @@ class SupplyChainBreachOrderService {
where.ownerName = { in: [input.viewer.name] }
}
const [rows, total, statusGroups, finedOrderCount] = await Promise.all([
const [rows, total, statusGroups, fineRows] = await Promise.all([
prisma.supplyChainBreachOrder.findMany({
where,
orderBy: [{ [sortField]: sortDirection } as Prisma.SupplyChainBreachOrderOrderByWithRelationInput, { createdAt: 'desc' }],
@ -250,23 +403,39 @@ class SupplyChainBreachOrderService {
...(input.viewer.canReview ? {} : { ownerName: { in: [input.viewer.name] } }),
},
_count: { _all: true },
_sum: { fineAmount: true },
}),
prisma.supplyChainBreachOrder.count({
where: {
payDate: payDateRange,
fineAmount: { gt: 0 },
...(input.viewer.canReview ? {} : { ownerName: { in: [input.viewer.name] } }),
},
}),
input.viewer.canReview
? prisma.supplyChainBreachOrder.findMany({
where: {
payDate: {
gte: monthBounds.startAt,
lt: monthBounds.endAtExclusive,
},
status: {
in: [
BREACH_ORDER_STATUS.PENDING_APPEAL,
BREACH_ORDER_STATUS.PENDING_REVIEW,
BREACH_ORDER_STATUS.RETURNED,
BREACH_ORDER_STATUS.REJECTED,
],
},
},
select: { id: true, soId: true },
})
: Promise.resolve([]),
])
const stats: Record<string, number> = {}
let fineTotal = 0
for (const group of statusGroups) {
stats[group.status] = group._count._all
fineTotal += Number(group._sum.fineAmount ?? 0)
}
const fineByOrder = new Map<string, number>()
for (const row of fineRows) {
const key = row.soId.trim() || row.id
if (!fineByOrder.has(key)) fineByOrder.set(key, BREACH_FINE_AMOUNT)
}
const finedOrderCount = fineByOrder.size
const fineTotal = [...fineByOrder.values()].reduce((sum, value) => sum + value, 0)
return {
rows: rows.map((row) => this.toDto(row)),
@ -279,9 +448,11 @@ class SupplyChainBreachOrderService {
stats: {
total: Object.values(stats).reduce((sum, value) => sum + value, 0),
byStatus: stats,
fineTotal,
finedOrderCount,
finePerOrder: BREACH_FINE_AMOUNT,
...(input.viewer.canReview ? {
fineTotal,
finedOrderCount,
finePerOrder: BREACH_FINE_AMOUNT,
} : {}),
},
}
}
@ -627,22 +798,19 @@ class SupplyChainBreachOrderService {
if (!order) throw new Error('破价订单不存在')
if (!isBreachOrderMonitored(order.payDate)) throw new Error(`破价订单审核从 ${BREACH_ORDER_MONITOR_START_DATE} 开始,历史订单不可审核`)
// 审核前自动排查负责人是否离职:已离职的单直接转「人员已离职」,不判定、不计乐捐。
// 审核前按人员配置的当前任职状态排查;不读取员工目录的离职历史,避免同名/旧记录误判。
if (order.ownerName) {
const resigned = await prisma.employeeDirectory.findFirst({
where: { name: order.ownerName.trim(), sourceStatus: 'DIMISSIONED' },
select: { id: true },
})
if (resigned) {
const statusByOwner = await this.buildOwnerEmploymentMap()
if (statusByOwner.get(normalizedOwnerKey(order.ownerName)) === 'DIMISSIONED') {
await prisma.supplyChainBreachOrder.update({
where: { id: order.id },
data: {
status: BREACH_ORDER_STATUS.LEFT_EMPLOYEE,
fineAmount: 0,
reviewDecision: 'LEFT',
reviewReason: '负责人已离职(系统自动标记)',
reviewReason: AUTO_LEFT_REASON,
reviewNote: input.note?.trim() || '',
reviewedBy: '系统自动排查',
reviewedBy: AUTO_LEFT_REVIEWER,
reviewedAt: new Date(),
},
})
@ -710,12 +878,28 @@ class SupplyChainBreachOrderService {
return { status, fineAmount: isSecondRoundPass ? 0 : fineAmount, covered: rowsWithPrimary.length }
}
/** 加载破价判定数据:条码→货号/商品负责人、货号→负责人限价/流程结束日期、货号→价格授权。 */
/** 运营负责人 → 人员信息中的部门负责人/利润中心,按姓名标准化后关联。 */
private async buildOwnerPersonnelMap() {
const ownerOptions = await supplyChainManagementOwnerConfigRepository.listOwnerOptions()
const personnelByOwner = new Map<string, BreachGenerationOwnerPersonnel>()
for (const owner of ownerOptions) {
const key = normalizedOwnerKey(owner.operationOwner)
if (!key) continue
personnelByOwner.set(key, {
departmentOwner: owner.departmentOwner.trim(),
profitCenter: owner.profitCenter.trim(),
})
}
return personnelByOwner
}
/** 加载破价判定数据:条码→货号/订单商品负责人、货号→负责人限价/流程结束日期、货号→价格授权、运营负责人→人员信息。 */
private async buildAuthContext(): Promise<BreachGenerationAuthContext> {
const [archives, styleLimits, auths] = await Promise.all([
const [archives, styleLimits, auths, personnelByOwner] = await Promise.all([
prisma.supplyChainProductArchive.findMany({ select: { barcode: true, sku: true, opsHead: true } }),
prisma.supplyChainStyleLimitPrice.findMany(),
prisma.supplyChainLimitFlowAuth.findMany(),
this.buildOwnerPersonnelMap(),
])
const barcodeToStyle = new Map<string, string>()
const orderOwnerByBarcode = new Map<string, string>()
@ -751,7 +935,113 @@ class SupplyChainBreachOrderService {
})
authsByStyle.set(styleCode, list)
}
return { barcodeToStyle, ownerLimitByStyle, orderOwnerByBarcode, flowEndDateByStyle, authsByStyle }
return {
barcodeToStyle,
ownerLimitByStyle,
orderOwnerByBarcode,
flowEndDateByStyle,
authsByStyle,
personnelByOwner,
}
}
/**
* 按停产下架同口径回填:链接 itemId → 运营负责人,再按人员信息关联部门负责人和利润中心。
* 只更新三个身份字段,不重新计算金额,也不修改申诉、审核和乐捐状态。
*/
async backfillLinkIdentityMetadata(input: {
dateFrom: string
dateTo: string
batchSize?: number
dryRun?: boolean
}) {
const dateFrom = breachMonitorStartAt(input.dateFrom)
const dateTo = new Date(`${input.dateTo}T23:59:59.999+08:00`)
if (dateTo < dateFrom) throw new Error('回填结束日期不能早于开始日期')
const requestedBatchSize = Number.isFinite(input.batchSize) ? Math.trunc(input.batchSize as number) : 5_000
const batchSize = Math.min(10_000, Math.max(500, requestedBatchSize))
const payDate = { gte: dateFrom, lte: dateTo }
const coverage = async () => {
const [total, ownerName, deptOwner, profitCenter] = await Promise.all([
prisma.supplyChainBreachOrder.count({ where: { payDate } }),
prisma.supplyChainBreachOrder.count({ where: { payDate, ownerName: { not: '' } } }),
prisma.supplyChainBreachOrder.count({ where: { payDate, deptOwner: { not: '' } } }),
prisma.supplyChainBreachOrder.count({ where: { payDate, profitCenter: { not: '' } } }),
])
return { total, ownerName, deptOwner, profitCenter }
}
const coverageBefore = await coverage()
const personnelByOwner = await this.buildOwnerPersonnelMap()
const rows = await prisma.supplyChainBreachOrder.findMany({
where: { payDate },
orderBy: { id: 'asc' },
select: {
id: true,
shopStyleCode: true,
ownerName: true,
deptOwner: true,
profitCenter: true,
},
})
const scanned = rows.length
let updated = 0
let unresolved = 0
const linkOwnerByItemId = await jstBreachOrderSourceRepository.listLinkOwners(
[...new Set(rows.map((row) => row.shopStyleCode.trim()).filter(Boolean))],
)
const patches = rows.flatMap((row) => {
const linkOwnerName = linkOwnerByItemId.get(row.shopStyleCode.trim()) ?? ''
if (!linkOwnerName && !row.ownerName) {
unresolved += 1
return []
}
const ownerName = linkOwnerName || row.ownerName.trim()
const personnel = personnelByOwner.get(normalizedOwnerKey(ownerName))
const next = {
id: row.id,
ownerName,
deptOwner: personnel?.departmentOwner || row.deptOwner.trim(),
profitCenter: personnel?.profitCenter || row.profitCenter.trim(),
}
if (
next.ownerName === row.ownerName
&& next.deptOwner === row.deptOwner
&& next.profitCenter === row.profitCenter
) return []
return [next]
})
if (input.dryRun) {
updated = patches.length
} else {
for (let offset = 0; offset < patches.length; offset += batchSize) {
const batch = patches.slice(offset, offset + batchSize)
updated += await prisma.$executeRaw`
UPDATE "SupplyChainBreachOrder" AS breached
SET
"ownerName" = COALESCE(NULLIF(btrim(candidate."ownerName"), ''), breached."ownerName"),
"deptOwner" = COALESCE(NULLIF(btrim(candidate."deptOwner"), ''), breached."deptOwner"),
"profitCenter" = COALESCE(NULLIF(btrim(candidate."profitCenter"), ''), breached."profitCenter"),
"updatedAt" = CURRENT_TIMESTAMP
FROM jsonb_to_recordset(${JSON.stringify(batch)}::jsonb) AS candidate(
id text,
"ownerName" text,
"deptOwner" text,
"profitCenter" text
)
WHERE breached.id = candidate.id
`
}
}
return {
dateFrom: input.dateFrom,
dateTo: input.dateTo,
dryRun: Boolean(input.dryRun),
scanned,
updated,
unresolved,
coverageBefore,
coverageAfter: input.dryRun ? coverageBefore : await coverage(),
}
}
/** 从聚水潭订单明细买家实付 + 流程限价生成/刷新破价单。 */
@ -861,6 +1151,8 @@ class SupplyChainBreachOrderService {
limitTotal: true,
gapAmount: true,
ownerName: true,
deptOwner: true,
profitCenter: true,
orderStatus: true,
refundStatus: true,
listedAt: true,
@ -906,6 +1198,8 @@ class SupplyChainBreachOrderService {
limitTotal: number
gapAmount: number
ownerName: string | null
deptOwner: string
profitCenter: string
orderStatus: string
refundStatus: string
listedAt: Date | null
@ -923,6 +1217,8 @@ class SupplyChainBreachOrderService {
limitTotal: row.limitTotal,
gapAmount: row.gapAmount,
ownerName: row.ownerName,
deptOwner: row.deptOwner,
profitCenter: row.profitCenter,
orderStatus: row.orderStatus,
refundStatus: row.refundStatus,
listedAt: row.listedAt?.toISOString() ?? null,
@ -941,11 +1237,9 @@ class SupplyChainBreachOrderService {
"limitUnitPrice" = candidate."limitUnitPrice"::numeric,
"limitTotal" = candidate."limitTotal"::numeric,
"gapAmount" = candidate."gapAmount"::numeric,
"ownerName" = CASE
WHEN btrim(breached."ownerName") = '' AND NULLIF(btrim(candidate."ownerName"), '') IS NOT NULL
THEN candidate."ownerName"
ELSE breached."ownerName"
END,
"ownerName" = COALESCE(NULLIF(btrim(candidate."ownerName"), ''), breached."ownerName"),
"deptOwner" = COALESCE(NULLIF(btrim(candidate."deptOwner"), ''), breached."deptOwner"),
"profitCenter" = COALESCE(NULLIF(btrim(candidate."profitCenter"), ''), breached."profitCenter"),
"orderStatus" = candidate."orderStatus",
"refundStatus" = candidate."refundStatus",
"listedAt" = COALESCE(
@ -968,6 +1262,8 @@ class SupplyChainBreachOrderService {
"limitTotal" numeric,
"gapAmount" numeric,
"ownerName" text,
"deptOwner" text,
"profitCenter" text,
"orderStatus" text,
"refundStatus" text,
"listedAt" text,
@ -1058,6 +1354,7 @@ class SupplyChainBreachOrderService {
limitTotal: decimalToNumber(row.limitTotal),
gapAmount: decimalToNumber(row.gapAmount),
ownerName: row.ownerName,
deptOwner: row.deptOwner,
profitCenter: row.profitCenter,
orderStatus: row.orderStatus,
refundStatus: row.refundStatus,

View File

@ -454,6 +454,28 @@ describe('破价判定流程豁免(同价申请 / 活动限价)', () => {
})
})
it('运营负责人取链接负责人,并按该负责人关联部门负责人和利润中心', () => {
const context = authContext([])
context.orderOwnerByBarcode = new Map([['AUTH-BARCODE-1', '订单负责人甲']])
context.personnelByOwner = new Map([['链接负责人乙', {
departmentOwner: '部门负责人丙',
profitCenter: '利润中心丁',
}]])
const { candidates } = buildBreachOrderCandidates(
[authLine({ buyerPaidAmount: 80, linkOwnerName: '链接负责人乙' })],
[],
context,
)
expect(candidates).toHaveLength(1)
expect(candidates[0]).toMatchObject({
ownerName: '链接负责人乙',
deptOwner: '部门负责人丙',
profitCenter: '利润中心丁',
})
})
it('订单商品负责人与链接负责人一致时按负责人限价判定', () => {
const context = authContext([])
context.orderOwnerByBarcode = new Map([['AUTH-BARCODE-1', '负责人甲']])

View File

@ -16,6 +16,8 @@ describe('planBreachOrderSnapshotRefresh', () => {
limitTotal: 90,
gapAmount: -10,
ownerName: '负责人甲',
deptOwner: '部门负责人乙',
profitCenter: '利润中心丙',
orderStatus: 'Sent',
refundStatus: '',
listedAt,
@ -34,6 +36,8 @@ describe('planBreachOrderSnapshotRefresh', () => {
limitTotal: 100,
gapAmount: -20,
ownerName: '',
deptOwner: '',
profitCenter: '',
orderStatus: 'Sent',
refundStatus: '',
listedAt: null,
@ -52,6 +56,8 @@ describe('planBreachOrderSnapshotRefresh', () => {
limitTotal: 90,
gapAmount: -10,
ownerName: '负责人甲',
deptOwner: '部门负责人乙',
profitCenter: '利润中心丙',
orderStatus: 'Sent',
refundStatus: '',
listedAt,
@ -66,6 +72,8 @@ describe('planBreachOrderSnapshotRefresh', () => {
limitTotal: 90,
gapAmount: -10,
ownerName: '负责人甲',
deptOwner: '部门负责人乙',
profitCenter: '利润中心丙',
listedAt,
flowEndDate,
})).toBeNull()
@ -75,19 +83,49 @@ describe('planBreachOrderSnapshotRefresh', () => {
const refresh = planBreachOrderSnapshotRefresh({
...candidate,
ownerName: '',
deptOwner: '',
profitCenter: '',
listedAt: null,
flowEndDate: null,
}, {
...stored,
ownerName: '原负责人',
deptOwner: '原部门负责人',
profitCenter: '原利润中心',
listedAt: new Date('2026-08-01T00:00:00Z'),
flowEndDate: new Date('2026-10-01T00:00:00Z'),
})
expect(refresh).toMatchObject({
ownerName: '原负责人',
deptOwner: '原部门负责人',
profitCenter: '原利润中心',
listedAt: new Date('2026-08-01T00:00:00Z'),
flowEndDate: new Date('2026-10-01T00:00:00Z'),
limitUnitPrice: 90,
})
})
it('候选已解析的运营负责人和人员信息会修正已有值', () => {
const refresh = planBreachOrderSnapshotRefresh({
...candidate,
ownerName: '链接负责人甲',
deptOwner: '新部门负责人乙',
profitCenter: '新利润中心丙',
}, {
...stored,
limitUnitPrice: 90,
limitTotal: 90,
gapAmount: -10,
ownerName: '旧负责人',
deptOwner: '旧部门负责人',
profitCenter: '旧利润中心',
listedAt,
flowEndDate,
})
expect(refresh).toMatchObject({
ownerName: '链接负责人甲',
deptOwner: '新部门负责人乙',
profitCenter: '新利润中心丙',
})
})
})