优化缺货订单候选读取并保留最新版本筛选
This commit is contained in:
parent
a1320767da
commit
545acb8d93
28
furniture-3d-system/docs/排障记录/2026-11-12-缺货订单读取优化.md
Normal file
28
furniture-3d-system/docs/排障记录/2026-11-12-缺货订单读取优化.md
Normal file
@ -0,0 +1,28 @@
|
||||
# 缺货订单读取优化
|
||||
|
||||
## 问题与调整
|
||||
|
||||
订单明细原来先读取两个订单源的Id上下界,再查询约69个历史Id分段。每次重读都重复访问历史订单,最近出现多次30秒查询超时,无法发布完整结果。
|
||||
|
||||
保持原四个只读视图和数据库连接地址。候选查询每个平台仅按绑定的`status=Question`读取订单号、异常类型,在应用中保留缺货、真实缺货、预售。实测在当前视图中叠加异常类型IN、类型或标签筛选会显著变慢,因此这些条件在最新记录读取后执行。未能获取底层索引或执行计划权限,本次依据真实查询结果与耗时选择读取方式,未修改外部视图、表或索引。
|
||||
|
||||
每批100个bigint订单号读取候选订单的全部版本,按修改时间、源Id取最新,再检查Question、三种异常类型、刷单标签和补发类型。这样最新版本改为Sent、其他异常类型或补发后,不会退回旧的缺货记录。商品明细继续分批读取并取最新源Id;任一来源失败不发布部分结果。没有新增日期、订单数或最终行数限制。
|
||||
|
||||
两个读取工作槽、单次30秒预算、商品明细超时拆批、60秒完整快照缓存及并发请求合并保持原有规则。组合装拆分、换货和替换款、JSReportReplica库存来源及云仓扣减、分类、Z/AE/AY汇总和每日报表存档仍由原有服务处理。
|
||||
|
||||
## 实际验证
|
||||
|
||||
- 2026-11-12 16:37:42(北京时间),直接使用实际Repository完整读取1183条原始明细:OTHER 409条、TAOBAO 774条,耗时59.842秒。候选查询2次,最新订单版本查询11次,商品明细查询11次,全部成功。两个源候选集合分别为2869、3167条Question记录,最终只取符合指定异常类型及排除规则的订单明细。
|
||||
- 2026-11-12 16:40:51,本地localhost:3000真实登录后强制重读,接口完成1227条组合拆分后明细及全部资料、库存、换货字段匹配,用时26.200秒;缓存内再次读取1.008秒,时间戳和行数相同。页面读取并展示3.695秒。以上是本次开发环境观测值,上游数据库和网络负载变化会影响耗时。
|
||||
- 使用真实页面与接口,未拦截或替换响应。1227条记录逐条满足Question、三类异常、无刷单标签及补发;行ID无重复。9项库存DTO字段均为空或有限数值。
|
||||
- Excel导出1227条,与接口一致。逐条核对Z为完整明细同货号M件数合计、AE为线上订单号和货号的行数、AY按缺货分类取M数量或0。当前导出的9个库存列无负数和横杠占位,数值0和空值均保留。
|
||||
- 浏览器1920和982宽度截图正常,无页面运行错误或横向溢出。查询和导出继续使用现有页面组件。
|
||||
- 10组缺货相关测试125项通过;类型检查和实现文件ESLint通过。回归覆盖双来源、bigint精度、最新状态/异常/补发/刷单不回退、1201候选跨批完整读取、明细去重、空集合及来源失败。
|
||||
|
||||
证据保存于本地忽略目录`.codex-runtime`及`.codex-logs`,包括真实完整接口快照、查询耗时、Excel导出和截图,不提交订单原始数据或连接密钥。
|
||||
|
||||
## 交接与审查
|
||||
|
||||
继续使用用户指定的“如懿”分支。本次已fetch远端,未合并共享开发主线的251个独有提交;本地运行目录仅同步当前任务对应的Repository与测试,保留其他并行开发改动。未发布生产,未写入外部数据源,未重建每日缺货报表。
|
||||
|
||||
规范审查:passed。架构保持Route → Service → Repository;页面沿用现有视觉;修复重复历史查询及慢筛选的读取方式,并以真实完整接口与导出验证。**这是自审,不是独立复审**。
|
||||
@ -26,8 +26,8 @@
|
||||
## 用户已确认的修正
|
||||
|
||||
- 2026-11-11 从全部明细视图、列设置与导出中移除“状态”“退款状态”;旧浏览器偏好中的这两个字段在恢复时自动过滤。下方原文件映射保留来源说明。
|
||||
- 2026-11-11 数据源地址保持不变,读取 `rpt.jst_Orders` / `rpt.jst_OrderItem` 和 `rpt.jst_qmcust_orderlist` / `rpt.jst_qmcust_orderlist_item`,通过内部订单号关联。先读取订单源 Id 上下界,按完整范围每段 100,000 个 Id 筛选异常订单,再按每批 100 个内部订单号读取商品明细。移除 SQL 中的全量窗口排序,改为服务端按来源、内部订单号、明细号及源修改时间/行 Id 去重;缺少明细号时使用源行 Id。两个平台共用两个读取工作槽。单次查询预算 30 秒;超时的大分段继续二分(最小约 1,000 个 Id,明细最小单订单),无日期或额外订单状态限制,不截断最终结果。不可恢复的失败会终止任务,不发布部分明细。
|
||||
- 明细接口 `GET /api/supply-chain/management/shortage-order-details`;`refresh=1` 启动重读。页面和接口均受 `shortageOrderDetails` 查看权限控制。接口快速返回 `loading`(HTTP 202,含订单/商品明细/档案匹配进度)、`ready`(HTTP 200,含完整快照)或 `error`(HTTP 200,含可重试提示);页面每 2 秒查询状态,只有初次手动刷新请求携带 `refresh=1`,离开页面后停止轮询。完整成功结果缓存 60 秒,并发请求共用一次读取;后台失败后轮询不重复触发读取,需点击刷新重试。页面显示读取百分比、失败、空结果或最近成功读取时间,导出在读取中或失败时禁用。扫描不再依赖一条浏览器 HTTP 请求持续等待。当前任务和缓存保存在常驻 Node 进程内,重启后需重新读取;上游全量读取可能持续数分钟,完成前仅返回进度。
|
||||
- 2026-11-12 优化订单读取,数据源地址及四个订单/明细视图保持不变。每个平台只按 `status=Question` 读取内部订单号和异常类型,在服务端保留缺货、真实缺货、预售候选;按每批100个 bigint 内部订单号读取候选订单的全部版本,按修改时间、源Id去重后再检查最终状态、异常类型、刷单标签和补发类型。之后分批读取商品明细并按来源、订单号、明细号及源Id去重;缺少明细号时使用源行Id。不再读取历史Id上下界和约69个历史分段,不在候选SQL中叠加异常类型IN、标签或类型条件,以避免当前源视图选择慢查询。两个平台共用两个读取工作槽,单次查询预算仍为30秒,明细超时可二分至单订单。无日期限制、候选数量上限或最终明细截断;失败不发布部分数据。
|
||||
- 明细接口 `GET /api/supply-chain/management/shortage-order-details`;`refresh=1` 启动重读。页面和接口均受 `shortageOrderDetails` 查看权限控制。接口快速返回 `loading`(HTTP 202,含订单/商品明细/档案匹配进度)、`ready`(HTTP 200,含完整快照)或 `error`(HTTP 200,含可重试提示);页面每 2 秒查询状态,只有初次手动刷新请求携带 `refresh=1`,离开页面后停止轮询。完整成功结果缓存 60 秒,并发请求共用一次读取;后台失败后轮询不重复触发读取,需点击刷新重试。页面显示读取百分比、失败、空结果或最近成功读取时间,导出在读取中或失败时禁用。读取不再依赖一条浏览器 HTTP 请求持续等待。当前任务和缓存保存在常驻 Node 进程内,重启后需重新读取;实际耗时受上游数据库和网络影响,完成前仅返回进度。
|
||||
- 当前直接映射 N 异常类型=`question_type`、T 标签=`labels`。独立缺货报表仍待每日快照接入;明细补齐来源不代表已生成每日归档。
|
||||
- 2026-11-11 AE 按原文件 AE10“表格内线上订单号&货号在此表内的计数”实现:在完整缺货明细内按“线上订单号 + 货号”统计明细行数,先计算再筛选、分页;与 Z 的 M 数量件数合计分别处理。线上订单号或货号缺失时留空,不把未知记录归为一组。
|
||||
- 2026-11-11 用户确认 AG 从 `rpt.jst_sku_replace_rule` 获取。原商品编码在去除首尾空格、统一大小写后精确匹配 `sku_id`,保留编码前导零;同编码多条有效规则取修改时间(缺失时取创建时间)较新者,时间相同时取较大源行 Id。`data` 中多个候选按源顺序去重展示,不按库存擅自挑选。档案读取同时包含原编码和全部换货候选;AG 用逗号连接编码,AF/AH 分别去重显示对应货号和标签。无有效规则时三项留空;有编码但目标档案缺失时保留 AG,缺失的 AF/AH 留空。换货规则读取失败会使整次读取失败,不发布缺失换货字段的部分快照。
|
||||
|
||||
@ -19,164 +19,142 @@ describe('缺货订单只读来源', () => {
|
||||
})
|
||||
})
|
||||
|
||||
function mockPool(failTaobao = false, maxId = 1, timeoutLargeRange = false, timeoutLargeItems = false, headerRows?: (fromId: number) => Record<string, unknown>[]) {
|
||||
function mockPool(options: { failSource?: string; failLatest?: boolean; empty?: boolean; timeoutItems?: boolean; headers?: Record<string, unknown>[] } = {}) {
|
||||
const calls: Array<{ query: string; inputs: Record<string, unknown> }> = []
|
||||
const pool = {
|
||||
connect: jest.fn(), close: jest.fn().mockResolvedValue(undefined),
|
||||
request: () => {
|
||||
const inputs: Record<string, unknown> = {}
|
||||
const request = {
|
||||
input: (key: string, _type: unknown, value: unknown) => { inputs[key] = value; return request },
|
||||
query: jest.fn(async (query: string) => {
|
||||
calls.push({ query, inputs })
|
||||
if (failTaobao && query.includes('[jst_qmcust_orderlist]')) throw new Error('source unavailable')
|
||||
if (query.includes('MIN(Id)')) return { recordset: [{ minId: 1, maxId }] }
|
||||
if (timeoutLargeRange && Number(inputs.throughId) - Number(inputs.fromId) >= 99999) {
|
||||
throw Object.assign(new Error('query timeout'), { code: 'ETIMEOUT' })
|
||||
}
|
||||
if (query.includes('o.question_type') && headerRows) return { recordset: headerRows(Number(inputs.fromId)) }
|
||||
if (query.includes('o.question_type')) return { recordset: [{
|
||||
internalOrderId: '9007199254740993', exceptionType: '缺货', orderStatus: 'Question',
|
||||
sourceRowId: inputs.fromId, sourceModifiedAt: inputs.fromId === 100001 ? '2026-11-11 01:00:00' : '2026-11-10 01:00:00',
|
||||
shopName: `shop-${inputs.fromId}`,
|
||||
}, ...(timeoutLargeItems ? [{ internalOrderId: '9007199254740994', exceptionType: '预售', orderStatus: 'Question', sourceRowId: inputs.fromId, sourceModifiedAt: null }] : [])] }
|
||||
if (timeoutLargeItems && Object.keys(inputs).length > 1) {
|
||||
throw Object.assign(new Error('item query timeout'), { code: 'ETIMEOUT' })
|
||||
}
|
||||
return { recordset: Object.values(inputs).flatMap(internalOrderId => [
|
||||
{ internalOrderId, itemId: '001', barcode: '0001', quantity: 1, sourceRowId: 1 },
|
||||
{ internalOrderId, itemId: '001', barcode: '0001', quantity: 2, sourceRowId: 2 },
|
||||
]) }
|
||||
}),
|
||||
}
|
||||
return request
|
||||
},
|
||||
}
|
||||
const headers = options.headers ?? [{ internalOrderId: '9007199254740993', exceptionType: '缺货', orderStatus: 'Question', sourceRowId: 1, sourceModifiedAt: null },
|
||||
...(options.timeoutItems ? [{ internalOrderId: '9007199254740994', exceptionType: '预售', orderStatus: 'Question', sourceRowId: 1, sourceModifiedAt: null }] : [])]
|
||||
const pool = { connect: jest.fn(), close: jest.fn().mockResolvedValue(undefined), request: () => {
|
||||
const inputs: Record<string, unknown> = {}
|
||||
const request = {
|
||||
input: (key: string, _type: unknown, value: unknown) => { inputs[key] = value; return request },
|
||||
query: jest.fn(async (query: string) => {
|
||||
calls.push({ query, inputs })
|
||||
if (options.failSource && query.includes(options.failSource)) throw new Error('source unavailable')
|
||||
if (query.includes('@orderStatus')) return { recordset: options.empty ? [] : headers.map(row => ({ internalOrderId: row.internalOrderId, exceptionType: row.exceptionType })) }
|
||||
if (query.includes('WHERE o.o_id IN')) {
|
||||
if (options.failLatest) throw new Error('latest unavailable')
|
||||
return { recordset: headers.filter(row => Object.values(inputs).includes(row.internalOrderId)) }
|
||||
}
|
||||
if (options.timeoutItems && Object.keys(inputs).length > 1) throw Object.assign(new Error('item query timeout'), { code: 'ETIMEOUT' })
|
||||
return { recordset: Object.values(inputs).flatMap(internalOrderId => [
|
||||
{ internalOrderId, itemId: '001', barcode: '0001', quantity: 1, sourceRowId: 1 },
|
||||
{ internalOrderId, itemId: '001', barcode: '0001', quantity: 2, sourceRowId: 2 },
|
||||
]) }
|
||||
}),
|
||||
}
|
||||
return request
|
||||
} }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
return { pool, calls }
|
||||
}
|
||||
|
||||
it('binds the exact three types on both platforms and looks up items by bigint without date limits', async () => {
|
||||
it('reads each complete candidate set once and preserves bigint IDs through latest-version and item lookups', async () => {
|
||||
const { calls } = mockPool()
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
const progress = jest.fn()
|
||||
const rows = await repository.listOrderItems(progress)
|
||||
expect(SHORTAGE_QUESTION_TYPES).toEqual(['缺货', '真实缺货', '预售'])
|
||||
const headers = calls.filter(call => call.query.includes('o.question_type'))
|
||||
expect(headers).toHaveLength(2)
|
||||
for (const call of headers) {
|
||||
expect(call.inputs).toEqual({ question0: '缺货', question1: '真实缺货', question2: '预售', fromId: 1, throughId: 1 })
|
||||
expect(call.query).toContain('o.question_type IN (@question0, @question1, @question2)')
|
||||
expect(call.query).toContain("o.type NOT LIKE N'%补发%'")
|
||||
expect(call.query).not.toMatch(/TOP\s*\(|pay_date\s*[><=]|status\s+IN|labels\s+LIKE/i)
|
||||
expect(call.query).not.toMatch(/ROW_NUMBER|ORDER BY/i)
|
||||
const candidates = calls.filter(call => call.query.includes('@orderStatus'))
|
||||
expect(candidates).toHaveLength(2)
|
||||
expect(candidates.map(call => call.query)).toEqual(expect.arrayContaining([expect.stringContaining('[jst_Orders]'), expect.stringContaining('[jst_qmcust_orderlist]')]))
|
||||
for (const call of candidates) {
|
||||
expect(call.inputs).toEqual({ orderStatus: 'Question' })
|
||||
expect(call.query).toContain('o.question_type AS exceptionType')
|
||||
expect(call.query).toContain('o.status = @orderStatus')
|
||||
expect(call.query).not.toMatch(/DISTINCT|o.labels|o.type/)
|
||||
expect(call.query).not.toMatch(/TOP\s*\(|pay_date\s*[><=]|@fromId|@throughId|ROW_NUMBER/i)
|
||||
}
|
||||
const items = calls.filter(call => call.query.includes('WHERE i.o_id IN'))
|
||||
expect(items).toHaveLength(2)
|
||||
expect(items[0].inputs).toEqual({ order0: '9007199254740993' })
|
||||
for (const call of calls.filter(call => call.query.includes('WHERE o.o_id IN'))) {
|
||||
expect(call.inputs).toEqual({ order0: '9007199254740993' })
|
||||
expect(call.query.split('WHERE')[1]).not.toMatch(/status|question_type|labels|\.type/)
|
||||
}
|
||||
expect(calls.filter(call => call.query.includes('WHERE i.o_id IN'))[0].inputs).toEqual({ order0: '9007199254740993' })
|
||||
expect(rows.map(row => row.id)).toEqual(['OTHER:9007199254740993:001', 'TAOBAO:9007199254740993:001'])
|
||||
expect(rows[0]).toMatchObject({ barcode: '0001', quantity: 2 })
|
||||
expect(rows[0]).not.toHaveProperty('sourceRowId')
|
||||
expect(rows[0]).not.toHaveProperty('sourceModifiedAt')
|
||||
expect(jest.mocked(sql.ConnectionPool).mock.calls[0][0]).toMatchObject({ options: { readOnlyIntent: true } })
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('keeps only Question orders and excludes brush-order labels on both platforms before reading items', async () => {
|
||||
const examples = [
|
||||
{ internalOrderId: '1', orderStatus: 'Sent', labels: null },
|
||||
{ internalOrderId: '2', orderStatus: 'Question', labels: '普通,刷单待处理,其他' },
|
||||
{ internalOrderId: '3', orderStatus: 'Sent', labels: '刷单' },
|
||||
{ internalOrderId: '4', orderStatus: ' sent ', labels: '' },
|
||||
{ internalOrderId: '5', orderStatus: 'Question', labels: '已完成刷单' },
|
||||
{ internalOrderId: '6', orderStatus: 'Question', labels: '普通订单' },
|
||||
{ internalOrderId: '7', orderStatus: null, labels: null },
|
||||
{ internalOrderId: '8', orderStatus: 'Question', labels: null },
|
||||
{ internalOrderId: '9', orderStatus: 'Question', labels: '' },
|
||||
{ internalOrderId: '10', orderStatus: 'WaitConfirm', labels: '' },
|
||||
{ internalOrderId: '11', orderStatus: 'Cancelled', labels: '' },
|
||||
{ internalOrderId: '12', orderStatus: 'Sent', labels: '' },
|
||||
]
|
||||
const { calls } = mockPool(false, 1, false, false, () => examples.map((row, index) => ({ ...row, exceptionType: '缺货', sourceRowId: index + 1, sourceModifiedAt: null })))
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows.map(row => row.id)).toEqual(['OTHER:6:001', 'OTHER:8:001', 'OTHER:9:001', 'TAOBAO:6:001', 'TAOBAO:8:001', 'TAOBAO:9:001'])
|
||||
for (const call of calls.filter(call => call.query.includes('WHERE i.o_id IN'))) expect(Object.values(call.inputs)).toEqual(['6', '8', '9'])
|
||||
expect(progress).toHaveBeenLastCalledWith({ stage: 'items', completed: 2, total: 2 })
|
||||
expect(calls).toHaveLength(6)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ orderStatus: 'Sent', labels: null },
|
||||
{ orderStatus: 'Question', labels: '刷单待处理' },
|
||||
{ orderStatus: 'Cancelled', labels: null },
|
||||
])('never restores an older eligible order when the latest record is excluded: %j', async excluded => {
|
||||
const { calls } = mockPool(false, 100001, false, false, fromId => [{
|
||||
internalOrderId: '9007199254740993', exceptionType: '缺货', sourceRowId: fromId,
|
||||
sourceModifiedAt: fromId === 1 ? '2026-11-11 10:00:00' : '2026-11-12 10:00:00',
|
||||
...(fromId === 1 ? { orderStatus: 'Question', labels: null } : excluded),
|
||||
}])
|
||||
{ orderStatus: 'Sent' }, { orderStatus: 'Cancelled' }, { orderStatus: 'WaitConfirm' }, { orderStatus: null },
|
||||
{ labels: '普通,刷单待处理,其他' }, { labels: '已完成刷单' }, { exceptionType: '其他' }, { exceptionType: null }, { orderType: '售后补发' },
|
||||
])('never restores an older eligible order when its latest record is excluded on either source: %j', async excluded => {
|
||||
const base = { internalOrderId: '9007199254740993', orderStatus: 'Question', exceptionType: '缺货' }
|
||||
const { calls } = mockPool({ headers: [
|
||||
{ ...base, sourceRowId: 2, sourceModifiedAt: '2026-11-12 10:00:00', ...excluded },
|
||||
{ ...base, sourceRowId: 1, sourceModifiedAt: '2026-11-11 10:00:00' },
|
||||
] })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
expect(await repository.listOrderItems()).toEqual([])
|
||||
expect(calls.filter(call => call.query.includes('WHERE i.o_id IN'))).toHaveLength(0)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('rejects the entire result when one platform fails', async () => {
|
||||
mockPool(true)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).rejects.toThrow('source unavailable')
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('covers every source Id range without gaps and deduplicates across ranges by modification time', async () => {
|
||||
const { calls } = mockPool(false, 200001)
|
||||
it('deduplicates by modification time and then source ID regardless of row order, retaining eligible labels', async () => {
|
||||
const base = { internalOrderId: '1', exceptionType: '缺货', orderStatus: 'Question', labels: '普通订单' }
|
||||
mockPool({ headers: [
|
||||
{ ...base, sourceRowId: 20, sourceModifiedAt: '2026-11-11 00:00:00', shopName: 'older' },
|
||||
{ ...base, sourceRowId: 3, sourceModifiedAt: '2026-11-12 00:00:00', shopName: 'newest' },
|
||||
{ ...base, sourceRowId: 2, sourceModifiedAt: '2026-11-12 00:00:00', shopName: 'tie-loser' },
|
||||
{ ...base, sourceRowId: 30, sourceModifiedAt: null, shopName: 'undated' },
|
||||
] })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
const ranges = calls.filter(call => call.query.includes('[jst_Orders] o')).map(call => [call.inputs.fromId, call.inputs.throughId])
|
||||
expect(ranges).toEqual([[1, 100000], [100001, 200000], [200001, 200001]])
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows[0]).toMatchObject({ shopName: 'shop-100001', quantity: 2 })
|
||||
expect(rows.every(row => row.shopName === 'newest' && row.quantity === 2)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('subdivides a timed-out range without dropping or overlapping any source Ids', async () => {
|
||||
const { calls } = mockPool(false, 100000, true)
|
||||
it('retains all candidates and final rows across item batches without a date or order cap', async () => {
|
||||
const { calls } = mockPool({ headers: Array.from({ length: 1201 }, (_, index) => ({
|
||||
internalOrderId: String(index + 1), exceptionType: '缺货', orderStatus: 'Question', sourceRowId: index + 1, sourceModifiedAt: null,
|
||||
})) })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const progress = jest.fn()
|
||||
const rows = await repository.listOrderItems(progress)
|
||||
const ranges = calls.filter(call => call.query.includes('[jst_Orders] o')).map(call => [call.inputs.fromId, call.inputs.throughId])
|
||||
expect(ranges).toEqual([[1, 100000], [1, 50000], [50001, 100000]])
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(progress).toHaveBeenLastCalledWith({ stage: 'items', completed: 2, total: 2 })
|
||||
const rows = await repository.listOrderItems()
|
||||
expect(rows).toHaveLength(2402)
|
||||
expect(new Set(rows.map(row => row.id)).size).toBe(2402)
|
||||
const latestCalls = calls.filter(call => call.query.includes('WHERE o.o_id IN'))
|
||||
expect(latestCalls).toHaveLength(26)
|
||||
expect(latestCalls.every(call => Object.keys(call.inputs).length <= 100)).toBe(true)
|
||||
const itemCalls = calls.filter(call => call.query.includes('WHERE i.o_id IN'))
|
||||
expect(itemCalls).toHaveLength(26)
|
||||
expect(itemCalls.every(call => Object.keys(call.inputs).length <= 100)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('skips item reads for an empty platform result', async () => {
|
||||
const request = { input: jest.fn(), query: jest.fn().mockResolvedValue({ recordset: [{ minId: null, maxId: null }] }) }
|
||||
request.input.mockReturnValue(request)
|
||||
const pool = { connect: jest.fn(), request: () => request, close: jest.fn() }
|
||||
pool.connect.mockResolvedValue(pool)
|
||||
jest.mocked(sql.ConnectionPool).mockImplementation(() => pool as unknown as sql.ConnectionPool)
|
||||
it.each([{ failSource: '[jst_qmcust_orderlist]' }, { failLatest: true }])('rejects incomplete source or latest-version reads: %j', async options => {
|
||||
mockPool(options)
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).rejects.toThrow('unavailable')
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('skips latest-version and item reads for empty candidate sets', async () => {
|
||||
const { calls } = mockPool({ empty: true })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
await expect(repository.listOrderItems()).resolves.toEqual([])
|
||||
expect(request.query).toHaveBeenCalledTimes(2)
|
||||
expect(calls).toHaveLength(2)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
it('subdivides timed-out item batches and retains every order with unique latest item rows', async () => {
|
||||
const { calls } = mockPool(false, 1, false, true)
|
||||
it('subdivides timed-out item batches without losing orders or retaining duplicate item versions', async () => {
|
||||
const { calls } = mockPool({ timeoutItems: true })
|
||||
const repository = new SupplyChainShortageOrderRepository()
|
||||
const rows = await repository.listOrderItems()
|
||||
const batches = calls.filter(call => call.query.includes('[jst_OrderItem] i')).map(call => Object.values(call.inputs))
|
||||
expect(batches).toEqual([
|
||||
['9007199254740993', '9007199254740994'], ['9007199254740993'], ['9007199254740994'],
|
||||
])
|
||||
expect(batches).toEqual([['9007199254740993', '9007199254740994'], ['9007199254740993'], ['9007199254740994']])
|
||||
expect(rows).toHaveLength(4)
|
||||
expect(new Set(rows.map(row => row.id)).size).toBe(4)
|
||||
expect(rows.every(row => row.quantity === 2)).toBe(true)
|
||||
await repository.close()
|
||||
})
|
||||
|
||||
|
||||
it('rejects invalid SQL identifiers before connecting', () => {
|
||||
expect(() => shortageHeaderSql('rpt]; DROP VIEW x;--', 'OTHER')).toThrow('Invalid report schema')
|
||||
})
|
||||
|
||||
@ -48,7 +48,7 @@ function requiredEnv(name: string) {
|
||||
return value
|
||||
}
|
||||
|
||||
/** 所有分段共用两个工作槽,任一失败后停止分配新任务并等在途请求结束。 */
|
||||
/** 所有批量读取共用两个工作槽,任一失败后停止分配新任务并等在途请求结束。 */
|
||||
async function readBatches<T>(batches: readonly T[], read: (batch: T) => Promise<void>) {
|
||||
let next = 0
|
||||
let failed = false
|
||||
@ -66,8 +66,9 @@ function timedOut(error: unknown) {
|
||||
}
|
||||
|
||||
/** 标识符只能来自经过校验的本地配置;业务条件全部绑定参数。 */
|
||||
export function shortageHeaderSql(schema: string, source: Source) {
|
||||
export function shortageHeaderSql(schema: string, source: Source, orderCount = 1) {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) throw new Error('Invalid report schema')
|
||||
if (!Number.isInteger(orderCount) || orderCount < 1 || orderCount > 100) throw new Error('Invalid order batch size')
|
||||
const table = source === 'OTHER' ? 'jst_Orders' : 'jst_qmcust_orderlist'
|
||||
return `SELECT CAST(o.o_id AS varchar(50)) AS internalOrderId,
|
||||
o.so_id AS onlineOrderId, o.type AS orderType,
|
||||
@ -76,9 +77,17 @@ export function shortageHeaderSql(schema: string, source: Source) {
|
||||
CONVERT(varchar(19), o.pay_date, 120) AS paidAt,
|
||||
o.Id AS sourceRowId, CONVERT(varchar(23), o.modified, 121) AS sourceModifiedAt
|
||||
FROM [${schema}].[${table}] o
|
||||
WHERE o.Id >= @fromId AND o.Id <= @throughId
|
||||
AND o.question_type IN (@question0, @question1, @question2)
|
||||
AND (o.type IS NULL OR o.type NOT LIKE N'%补发%')
|
||||
WHERE o.o_id IN (${Array.from({ length: orderCount }, (_, index) => `@order${index}`).join(',')})
|
||||
OPTION (RECOMPILE)`
|
||||
}
|
||||
|
||||
/** 只扫一次候选集合;之后读取候选订单的所有版本,再决定最新版本是否仍符合条件。 */
|
||||
export function shortageCandidateSql(schema: string, source: Source) {
|
||||
shortageHeaderSql(schema, source)
|
||||
const table = source === 'OTHER' ? 'jst_Orders' : 'jst_qmcust_orderlist'
|
||||
return `SELECT CAST(o.o_id AS varchar(50)) AS internalOrderId, o.question_type AS exceptionType
|
||||
FROM [${schema}].[${table}] o
|
||||
WHERE o.status = @orderStatus
|
||||
OPTION (RECOMPILE)`
|
||||
}
|
||||
|
||||
@ -119,26 +128,19 @@ export class SupplyChainShortageOrderRepository {
|
||||
const sources: Source[] = ['OTHER', 'TAOBAO']
|
||||
const headers = { OTHER: new Map<string, HeaderRecord>(), TAOBAO: new Map<string, HeaderRecord>() }
|
||||
const items = { OTHER: new Map<string, ItemRecord>(), TAOBAO: new Map<string, ItemRecord>() }
|
||||
const ranges: Array<{ source: Source; fromId: number; throughId: number }> = []
|
||||
onProgress?.({ stage: 'orders', completed: 0, total: 0 })
|
||||
let completed = 0
|
||||
onProgress?.({ stage: 'orders', completed, total: sources.length })
|
||||
await readBatches(sources, async source => {
|
||||
const orderTable = source === 'OTHER' ? 'jst_Orders' : 'jst_qmcust_orderlist'
|
||||
const bounds = (await pool.request().query<{ minId: number | null; maxId: number | null }>(`
|
||||
SELECT MIN(Id) AS minId, MAX(Id) AS maxId FROM [${schema}].[${orderTable}]
|
||||
`)).recordset[0]
|
||||
if (bounds.minId === null || bounds.maxId === null) return
|
||||
// 覆盖开始读取时的完整源 Id 范围,不增加日期限制,也不限制最终明细数。
|
||||
for (let fromId = bounds.minId; fromId <= bounds.maxId; fromId += 100_000) {
|
||||
ranges.push({ source, fromId, throughId: Math.min(fromId + 99_999, bounds.maxId) })
|
||||
}
|
||||
})
|
||||
const readRange = async ({ source, fromId, throughId }: typeof ranges[number]): Promise<void> => {
|
||||
try {
|
||||
const candidates = pool.request().input('orderStatus', sql.NVarChar(255), 'Question')
|
||||
// 仅按状态读取小集合,避免异常类型 IN 组合在源视图上触发历史表扫描。
|
||||
const ids = [...new Set((await candidates.query<{ internalOrderId: string; exceptionType: string }>(shortageCandidateSql(schema, source)))
|
||||
.recordset.filter(row => SHORTAGE_QUESTION_TYPES.includes(row.exceptionType as typeof SHORTAGE_QUESTION_TYPES[number]))
|
||||
.map(row => row.internalOrderId))]
|
||||
for (let offset = 0; offset < ids.length; offset += 100) {
|
||||
const orderIds = ids.slice(offset, offset + 100)
|
||||
const request = pool.request()
|
||||
.input('fromId', sql.Int, fromId)
|
||||
.input('throughId', sql.Int, throughId)
|
||||
SHORTAGE_QUESTION_TYPES.forEach((type, index) => request.input(`question${index}`, sql.NVarChar(255), type))
|
||||
const batch = (await request.query<HeaderRecord>(shortageHeaderSql(schema, source))).recordset
|
||||
orderIds.forEach((id, index) => request.input(`order${index}`, sql.BigInt, id))
|
||||
const batch = (await request.query<HeaderRecord>(shortageHeaderSql(schema, source, orderIds.length))).recordset
|
||||
for (const header of batch) {
|
||||
const previous = headers[source].get(header.internalOrderId)
|
||||
if (!previous || (header.sourceModifiedAt ?? '') > (previous.sourceModifiedAt ?? '') ||
|
||||
@ -146,27 +148,18 @@ export class SupplyChainShortageOrderRepository {
|
||||
headers[source].set(header.internalOrderId, header)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 只对确实超时的大分段继续细分,子范围不重叠,不吞掉失败或返回部分结果。
|
||||
if (!timedOut(error) || throughId - fromId < 1_000) throw error
|
||||
const middle = Math.floor((fromId + throughId) / 2)
|
||||
await readRange({ source, fromId, throughId: middle })
|
||||
await readRange({ source, fromId: middle + 1, throughId })
|
||||
}
|
||||
}
|
||||
let completed = 0
|
||||
onProgress?.({ stage: 'orders', completed, total: ranges.length })
|
||||
await readBatches(ranges, async range => {
|
||||
await readRange(range)
|
||||
onProgress?.({ stage: 'orders', completed: ++completed, total: ranges.length })
|
||||
onProgress?.({ stage: 'orders', completed: ++completed, total: sources.length })
|
||||
})
|
||||
|
||||
const itemBatches: Array<{ source: Source; orders: HeaderRecord[] }> = []
|
||||
for (const source of sources) {
|
||||
// 先跨分段取同一订单的最新记录再筛选,避免排除最新状态后退回旧的异常订单。
|
||||
// 先取候选订单的所有版本并去重,避免排除最新状态后退回旧的异常订单。
|
||||
// 两个平台共用此条件,且在明细读取、货号需求汇总和缺货分类之前执行。
|
||||
const orders = [...headers[source].values()].filter(order =>
|
||||
order.orderStatus?.trim() === 'Question' && !order.labels?.includes('刷单'))
|
||||
order.orderStatus?.trim() === 'Question' && !order.labels?.includes('刷单') &&
|
||||
SHORTAGE_QUESTION_TYPES.includes(order.exceptionType as typeof SHORTAGE_QUESTION_TYPES[number]) &&
|
||||
!order.orderType?.includes('补发'))
|
||||
for (let offset = 0; offset < orders.length; offset += 100) {
|
||||
itemBatches.push({ source, orders: orders.slice(offset, offset + 100) })
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user