fix(fulfillment): 修复自动发货任务上下文并发覆盖

This commit is contained in:
yml2213
2026-11-03 13:14:07 +08:00
parent b3fb330ad9
commit b842d00fc3
4 changed files with 132 additions and 19 deletions
@@ -10,6 +10,7 @@ import type {
TaskUpdatePatch,
} from '../types/repository/inputs.js'
import type { TaskListQueryResult, TaskRow } from '../types/repository/rows.js'
import type { JsonObject } from '../types/json.js'
type TaskQueryExecutor = (text: string, params?: unknown[]) => Promise<{ rows: unknown[] }>
const AFFILIATE_DASH_EXECUTOR_KEY = 'affiliate_dash'
@@ -255,6 +256,31 @@ export async function updateTask(
})
}
/**
* 原子合并任务上下文,避免调用方拿旧 TaskRow 整段覆盖并发写入的其它字段。
* 只合并顶层 key;调用方应传入完整的子对象 patch。
*/
export async function mergeTaskContext(
taskId: number | string,
patch: JsonObject,
updatedAt?: string | undefined,
): Promise<TaskRow | null> {
return withTransaction(async (client) => {
const result = await client.query<{ id: number }>(
`
UPDATE fulfillment_tasks
SET context_json = COALESCE(context_json, '{}'::jsonb) || $2::jsonb,
updated_at = COALESCE($3, updated_at)
WHERE id = $1
RETURNING id
`,
[Number(taskId), JSON.stringify(patch), updatedAt || null],
)
if (!result.rows[0]) return null
return getTaskByIdWithExecutor(client.query.bind(client) as TaskQueryExecutor, taskId)
})
}
export async function updateTaskStatusIfCurrent(
taskId: number | string,
currentStatus: string,