fix(worker-platform): 修正寄卖超时押金扣除与拼单份额归属

- 超时扣除类策略在解绑前没收寄卖发布押金,兼容 material 历史回退

- 拼单份额按库存归属没收,避免误扣其他卖家

- 履约押金核销排除 consignment_publish 流水

- 补充 7 场景隔离库集成测试
This commit is contained in:
2026-11-10 12:09:14 +08:00
parent 05d3675f55
commit 87658a59b1
6 changed files with 727 additions and 43 deletions
@@ -423,9 +423,64 @@ export async function forfeitConsignmentPublishDepositBySubmissionWithClient(
return forfeitAmount
}
/** 从工单物料解析本次/最近一次寄售占用的库存:优先当前 consignment,解绑后回退 consignmentHistory。 */
export function resolveConsignmentInventoryIdFromMaterial(material: unknown): number {
const parseRecord = (value: unknown): Record<string, unknown> => {
if (typeof value === 'string') {
try {
const parsed = JSON.parse(value)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: {}
} catch {
return {}
}
}
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {}
}
const root = parseRecord(material)
const currentId = Number(parseRecord(root.consignment).inventoryId || 0)
if (currentId > 0) return currentId
const history = Array.isArray(root.consignmentHistory) ? root.consignmentHistory : []
for (let index = history.length - 1; index >= 0; index -= 1) {
const id = Number(parseRecord(history[index]).inventoryId || 0)
if (id > 0) return id
}
return 0
}
/** 按库存没收寄卖发布押金:份额超时必须按份额自己的库存归属,避免没收错卖家。 */
export async function forfeitConsignmentPublishDepositByInventoryWithClient(
client: PoolClient,
input: {
inventoryId: number | string
workOrderId?: number | null
note: string
now: string
},
): Promise<number> {
const res = await client.query<{ source_submission_id: number | null }>(
'SELECT source_submission_id FROM consignment_inventories WHERE id = $1',
[input.inventoryId],
)
const submissionId = res.rows[0]?.source_submission_id
if (!submissionId) return 0
return forfeitConsignmentPublishDepositBySubmissionWithClient(client, {
submissionId,
workOrderId: input.workOrderId ?? null,
note: input.note,
now: input.now,
})
}
/**
* 工单侧入口:按工单 material_json 里的寄卖现货找到卖家的提报单,没收其发布押金。
* 工单侧入口:按工单物料里的寄卖现货找到卖家的提报单,没收其发布押金。
* 不是寄卖履约单、或押金已释放/已没收时返回 0(幂等)。
*
* 兼容解绑顺序:若 material.consignment 已被移入 consignmentHistory,
* 回退取最近一条历史库存,避免「先解绑再没收」时静默失效。
*/
export async function forfeitConsignmentPublishDepositByWorkOrderWithClient(
client: PoolClient,
@@ -435,24 +490,14 @@ export async function forfeitConsignmentPublishDepositByWorkOrderWithClient(
now: string
},
): Promise<number> {
const res = await client.query<{ submission_id: number | null }>(
`
SELECT inv.source_submission_id AS submission_id
FROM work_orders wo
JOIN consignment_inventories inv
ON inv.id = CASE
WHEN (wo.material_json->'consignment'->>'inventoryId') ~ '^[0-9]+$'
THEN (wo.material_json->'consignment'->>'inventoryId')::int
END
WHERE wo.id = $1
`,
const res = await client.query<{ material_json: unknown }>(
'SELECT material_json FROM work_orders WHERE id = $1',
[input.workOrderId],
)
const submissionId = res.rows[0]?.submission_id
if (!submissionId) return 0
return forfeitConsignmentPublishDepositBySubmissionWithClient(client, {
submissionId,
const inventoryId = resolveConsignmentInventoryIdFromMaterial(res.rows[0]?.material_json)
if (!inventoryId) return 0
return forfeitConsignmentPublishDepositByInventoryWithClient(client, {
inventoryId,
workOrderId: Number(input.workOrderId),
note: input.note,
now: input.now,
@@ -39,6 +39,9 @@ export async function getOutstandingDepositAmountWithClient(
COALESCE(SUM(CASE WHEN ledger_type = 'deposit_deduction' THEN ABS(amount) ELSE 0 END), 0)::int AS deducted_amount
FROM worker_wallet_ledgers
WHERE worker_id = $1 AND related_work_order_id = $2
-- 寄卖发布押金是独立保证金,不能计入该工单的履约押金核销,
-- 否则「先没收发布押金、再结算履约押金」会把履约押金少退/少扣。
AND COALESCE(payload_json->>'kind', '') <> 'consignment_publish'
`,
[workerId, workOrderId],
)
@@ -604,15 +604,6 @@ export async function settleOverdueWorkOrder(input: {
// 赠送单已确认加好友后不再退押金:释放类处置转为扣除,事件类型按实际资金动作记录。
const forfeitGiftDeposit = isWorkOrderGiftDepositForfeitable(workOrder)
// 确认加好友之后该单押金不退:打手履约押金按上面的 forfeitGiftDeposit 处理,
// 寄卖卖家的发布押金同口径一并没收(写 deposit_deduction 流水,之后不可能再退)。
if (forfeitGiftDeposit) {
await forfeitConsignmentPublishDepositByWorkOrderWithClient(client, {
workOrderId: Number(workOrder.id),
note: '已确认加好友,取消/脱离工单没收寄卖发布押金',
now: input.now,
})
}
const releasePolicies = ['reopen', 'cancel_release', 'rematch_release']
const isRematch = input.policy === 'rematch_release' || input.policy === 'rematch_deduct'
const shouldReleaseDeposit = releasePolicies.includes(input.policy) && !forfeitGiftDeposit
@@ -622,6 +613,10 @@ export async function settleOverdueWorkOrder(input: {
(releasePolicies.includes(input.policy) && forfeitGiftDeposit)
const effectivePolicy =
releasePolicies.includes(input.policy) && forfeitGiftDeposit ? 'cancel_deduct' : input.policy
// 寄卖发布押金口径:赠送单确认加好友一律没收;普通超时只有「扣除押金」类策略没收,
// 释放类策略(reopen / cancel_release / rematch_release)保留冻结,随商品在库继续担保。
const shouldForfeitPublishDeposit =
forfeitGiftDeposit || input.policy === 'cancel_deduct' || input.policy === 'rematch_deduct'
const workerId = Number(workOrder.assigned_worker_id || 0)
let resolvedDepositAmount = 0
@@ -706,6 +701,18 @@ export async function settleOverdueWorkOrder(input: {
[targetStatus, input.now, input.workOrderId],
)
// 寄卖发布押金必须在解绑前处理:解绑会把 material.consignment 移入 consignmentHistory,
// 之后再按工单反查库存会落空(历史缺陷)。赠送单确认加好友时一律没收;普通超时仅扣除类策略没收。
if (shouldForfeitPublishDeposit) {
await forfeitConsignmentPublishDepositByWorkOrderWithClient(client, {
workOrderId: input.workOrderId,
note: forfeitGiftDeposit
? '已确认加好友,取消/脱离工单没收寄卖发布押金'
: `寄卖履约超时,扣除寄卖保证金(${effectivePolicy})`,
now: input.now,
})
}
// 超时处置(重开/取消):被本工单占用的寄卖现货必须先放回在库池。
// 内部现货履约单在赠送冷静期内同样带 deadline_at,若不解绑,现货会永久停留在 consumed:
// 既不再参与匹配,发货押金也没有释放入口。
@@ -713,13 +720,8 @@ export async function settleOverdueWorkOrder(input: {
now: input.now,
reason: `超时处置(${effectivePolicy})`,
})
// 新版寄卖分配(支持数量/拼单):回补剩余数量,并按平台规则没收寄卖保证金。
// 新版寄卖分配(支持数量/拼单):回补剩余数量。
await releaseConsignmentAllocationsForWorkOrderWithClient(client, input.workOrderId, input.now)
await forfeitConsignmentPublishDepositByWorkOrderWithClient(client, {
workOrderId: input.workOrderId,
note: `寄卖履约超时,扣除寄卖保证金(${effectivePolicy})`,
now: input.now,
})
await createWorkOrderEventWithClient(client, {
workOrderId: input.workOrderId,
@@ -25,7 +25,7 @@ import {
import { maybeUpgradeWorkerLevel } from './worker-ranking-repo.js'
import type { WorkOrderRow, WorkOrderShareRow } from './types.js'
import {
forfeitConsignmentPublishDepositByWorkOrderWithClient,
forfeitConsignmentPublishDepositByInventoryWithClient,
releaseConsignmentPublishDepositBySubmissionWithClient,
settleConsignmentSupplierPayoutByWorkOrderWithClient,
} from './consignment-deposit-repo.js'
@@ -1144,15 +1144,21 @@ export async function settleOverdueWorkOrderShare(input: {
}
}
// 寄卖份额超时:库存回池 + 按平台规则扣除该供货打手的寄卖保证金。
await releaseConsignmentAllocationForShareWithClient(client, Number(share.id), input.now)
if (share.consignment_inventory_id) {
await forfeitConsignmentPublishDepositByWorkOrderWithClient(client, {
// 寄卖份额超时:库存回池 + 按平台规则没收该份额供货打手的寄卖保证金。
// 必须按份额自己的库存归属:母单 material 只指向第一件库存,多卖家拼单会没收错人。
const shouldForfeitPublishDeposit =
input.policy === 'cancel_deduct' ||
input.policy === 'rematch_deduct' ||
Boolean(share.friend_added_at)
if (shouldForfeitPublishDeposit && share.consignment_inventory_id) {
await forfeitConsignmentPublishDepositByInventoryWithClient(client, {
inventoryId: share.consignment_inventory_id,
workOrderId: input.workOrderId,
note: '寄卖拼单超时,扣除寄卖保证金',
now: input.now,
}).catch(() => 0)
})
}
await releaseConsignmentAllocationForShareWithClient(client, Number(share.id), input.now)
await client.query(
`UPDATE work_order_shares