feat(cost-center): 同步工单补同步待完善价格,跳过改过用户付款金额的工单
This commit is contained in:
@@ -442,3 +442,47 @@ test('第三方卡券商品禁止绕过卡券 SKU 配置手工创建', async ()
|
||||
/卡券 SKU 配置自动创建/,
|
||||
)
|
||||
})
|
||||
|
||||
test('同步工单补同步待完善价格,跳过有用户付款金额改价历史的工单', async () => {
|
||||
const [repoSource, syncSource, catalogSource, panelSource] = await Promise.all([
|
||||
readFile(
|
||||
new URL('../../repositories/worker-platform/work-product-rule-repo.ts', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
readFile(
|
||||
new URL('../../services/worker-platform/admin-worker-catalog-service.ts', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
readFile(new URL('./product-catalog-service.ts', import.meta.url), 'utf8'),
|
||||
readFile(
|
||||
new URL(
|
||||
'../../../../frontend/src/pages/admin/cost-center/ProductCatalogPanel.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
])
|
||||
|
||||
// 待完善候选:固定时间窗 + 用户付款金额改价历史排除。
|
||||
assert.ok(repoSource.includes("AND wo.status = 'pending_material'"))
|
||||
assert.ok(repoSource.includes('AND wo.created_at > $2::timestamptz'))
|
||||
assert.ok(repoSource.includes('work_order_payment_amount_history'))
|
||||
assert.ok(repoSource.includes('user_payment_amount_updated_at'))
|
||||
assert.ok(repoSource.includes('paymentAmountAdjustedCount'))
|
||||
|
||||
// 固定时间严格大于北京时间 2026-11-01 00:00:00。
|
||||
assert.ok(
|
||||
syncSource.includes("PENDING_MATERIAL_PRICE_SYNC_CREATED_AFTER = '2026-11-01T00:00:00+08:00'"),
|
||||
)
|
||||
assert.ok(syncSource.includes('includePendingMaterial'))
|
||||
assert.ok(syncSource.includes('expectedStatus: WORK_ORDER_STATUS.PENDING_MATERIAL'))
|
||||
assert.ok(syncSource.includes('pendingMaterialPaymentAmountAdjustedCount'))
|
||||
|
||||
// 只有「同步工单」入口带待完善;改价保存仍保持只同步 open。
|
||||
assert.ok(catalogSource.includes('includePendingMaterial: true'))
|
||||
assert.ok(catalogSource.includes('用户付款金额改过跳过'))
|
||||
|
||||
// 前端确认文案说明同步范围与跳过口径。
|
||||
assert.ok(panelSource.includes('2026-11-01 之后创建的待完善工单'))
|
||||
assert.ok(panelSource.includes('改过用户付款金额的待完善工单会跳过'))
|
||||
})
|
||||
|
||||
@@ -1968,13 +1968,40 @@ export async function syncAdminProductPrice(productIdInput: unknown, session: Ad
|
||||
if (!rule) {
|
||||
throw createHttpError('未找到关联的接单模板', { statusCode: 404 })
|
||||
}
|
||||
const synced = await syncAdminWorkProductRulePrice(rule.id, session.username)
|
||||
const synced = await syncAdminWorkProductRulePrice(rule.id, session.username, {
|
||||
includePendingMaterial: true,
|
||||
})
|
||||
const pendingParts: string[] = []
|
||||
if (
|
||||
synced.pendingMaterialCandidateCount > 0 ||
|
||||
synced.pendingMaterialPaymentAmountAdjustedCount > 0
|
||||
) {
|
||||
pendingParts.push(
|
||||
`待完善 ${synced.pendingMaterialUpdatedCount} 单(${synced.pendingMaterialCreatedAfter.slice(0, 10)} 后创建)`,
|
||||
)
|
||||
if (synced.pendingMaterialUnchangedCount > 0) {
|
||||
pendingParts.push(`待完善无需变更 ${synced.pendingMaterialUnchangedCount} 单`)
|
||||
}
|
||||
if (synced.pendingMaterialPaymentAmountAdjustedCount > 0) {
|
||||
pendingParts.push(
|
||||
`用户付款金额改过跳过 ${synced.pendingMaterialPaymentAmountAdjustedCount} 单`,
|
||||
)
|
||||
}
|
||||
if (synced.pendingMaterialSkippedCount > 0) {
|
||||
pendingParts.push(`其他原因跳过 ${synced.pendingMaterialSkippedCount} 单`)
|
||||
}
|
||||
}
|
||||
const messageParts = [
|
||||
`待抢单 ${synced.updatedNormalCount} 单`,
|
||||
`部分拼单 ${synced.updatedPartialSharingCount} 单`,
|
||||
...pendingParts,
|
||||
]
|
||||
return {
|
||||
success: true,
|
||||
type: 'work_order_price_synced',
|
||||
product,
|
||||
synced,
|
||||
message: `已同步 ${synced.updatedCount} 单:待抢单 ${synced.updatedNormalCount} 单,部分拼单 ${synced.updatedPartialSharingCount} 单`,
|
||||
message: `已同步 ${synced.updatedCount + synced.pendingMaterialUpdatedCount} 单:${messageParts.join(',')}`,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ test(
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const { saveAdminWorkProductRule } =
|
||||
const { saveAdminWorkProductRule, syncAdminWorkProductRulePrice } =
|
||||
await import('../worker-platform/admin-worker-catalog-service.js')
|
||||
const { setAdminProductPrice } = await import('./product-catalog-service.js')
|
||||
const { materializeWorkOrderHallPriceWithClient } =
|
||||
@@ -232,6 +232,57 @@ test(
|
||||
],
|
||||
)
|
||||
|
||||
// 手动「同步工单」补同步待完善:固定时间前创建、有用户付款金额改价历史的都不动。
|
||||
const oldPendingId = await insertWorkOrder({
|
||||
label: 'old-pending',
|
||||
status: 'pending_material',
|
||||
rewardAmount: 2640,
|
||||
})
|
||||
await query(`UPDATE work_orders SET created_at = '2026-10-31T23:59:59+08:00' WHERE id = $1`, [
|
||||
oldPendingId,
|
||||
])
|
||||
const paymentAdjustedPendingId = await insertWorkOrder({
|
||||
label: 'payment-adjusted-pending',
|
||||
status: 'pending_material',
|
||||
rewardAmount: 2640,
|
||||
})
|
||||
await query(
|
||||
`INSERT INTO work_order_payment_amount_history (
|
||||
work_order_id, previous_amount_fen, amount_fen, reason, changed_by, changed_at
|
||||
) VALUES ($1, 1300, 1410, 'integration-test', 'integration-test', NOW())`,
|
||||
[paymentAdjustedPendingId],
|
||||
)
|
||||
const manualSync = await syncAdminWorkProductRulePrice(ruleId, 'integration-test', {
|
||||
includePendingMaterial: true,
|
||||
})
|
||||
assert.equal(manualSync.pendingMaterialCandidateCount, 1)
|
||||
assert.equal(manualSync.pendingMaterialPaymentAmountAdjustedCount, 1)
|
||||
assert.equal(manualSync.pendingMaterialUpdatedCount, 1)
|
||||
const pendingAfterManualSync = await query<{
|
||||
id: number
|
||||
reward_amount: number
|
||||
hall_price_version_id: number | null
|
||||
}>(
|
||||
`SELECT id, reward_amount, hall_price_version_id
|
||||
FROM work_orders
|
||||
WHERE id = ANY($1::bigint[])
|
||||
ORDER BY id`,
|
||||
[[pendingId, unassignedId, oldPendingId, paymentAdjustedPendingId]],
|
||||
)
|
||||
assert.deepEqual(
|
||||
pendingAfterManualSync.rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
reward: Number(row.reward_amount),
|
||||
version: Number(row.hall_price_version_id),
|
||||
})),
|
||||
[
|
||||
{ id: pendingId, reward: 2670, version: secondVersionId },
|
||||
{ id: unassignedId, reward: 2640, version: 0 },
|
||||
{ id: oldPendingId, reward: 2640, version: 0 },
|
||||
{ id: paymentAdjustedPendingId, reward: 2640, version: 0 },
|
||||
],
|
||||
)
|
||||
|
||||
const sharingRow = await query<{
|
||||
reward_amount: number
|
||||
sharing_unit_reward: number
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
deleteWorkProductRule,
|
||||
detachWorkProductRuleCostVersions,
|
||||
getWorkProductRuleById,
|
||||
listPendingMaterialWorkOrdersForPriceSyncByProductRuleId,
|
||||
listWorkOrdersForPriceSyncByProductRuleId,
|
||||
listWorkProductRulesPage,
|
||||
upsertWorkProductRule,
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
normalizeWorkOrderGiftCooldownMinutes,
|
||||
WORK_ORDER_ACCEPTANCE_MODE,
|
||||
} from '../../domain/work-order-acceptance-mode.js'
|
||||
import { WORK_ORDER_STATUS } from '../../domain/work-order-status.js'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { randomId } from '../../utils/random.js'
|
||||
@@ -629,13 +631,42 @@ export type WorkProductRulePriceSyncResult = {
|
||||
skippedInvalidPricingCount: number
|
||||
skippedUnchangedCount: number
|
||||
skippedUnavailableCount: number
|
||||
/** 待完善候选数:只有显式要求补同步且晚于固定起点时才会大于 0。 */
|
||||
pendingMaterialCandidateCount: number
|
||||
/** 因用户付款金额存在改价历史而跳过的待完善单数。 */
|
||||
pendingMaterialPaymentAmountAdjustedCount: number
|
||||
pendingMaterialUpdatedCount: number
|
||||
/** 已经是当前模板价、无需变更的待完善单数。 */
|
||||
pendingMaterialUnchangedCount: number
|
||||
pendingMaterialSkippedCount: number
|
||||
/** 待完善同步使用的固定创建时间下限,供提示文案复用。 */
|
||||
pendingMaterialCreatedAfter: string
|
||||
}
|
||||
|
||||
export type WorkProductRulePriceSyncOptions = {
|
||||
/**
|
||||
* 是否把模板价补同步到「待完善」工单。
|
||||
*
|
||||
* 只处理固定起点之后创建的工单;模板改价保存默认不带这个选项,保持只刷新 open 工单。
|
||||
*/
|
||||
includePendingMaterial?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 待完善工单价格同步的固定起点(北京时间 2026-11-01 00:00:00)。
|
||||
*
|
||||
* 迁移 165 之后模板改价默认只刷新大厅 open 工单;待完善积压量大,
|
||||
* 只有手动「同步工单」显式要求时才回写,且严格晚于该时间才处理。
|
||||
*/
|
||||
export const PENDING_MATERIAL_PRICE_SYNC_CREATED_AFTER = '2026-11-01T00:00:00+08:00'
|
||||
|
||||
/**
|
||||
* 在调用方事务内同步模板价格。
|
||||
*
|
||||
* 只刷新已经进入大厅的 open 工单。pending_material / unassigned 在发布前不展示价格,
|
||||
* 默认只刷新已经进入大厅的 open 工单。pending_material / unassigned 在发布前不展示价格,
|
||||
* 发布入口会在同一事务内按最新成本版本物化,避免改价时扫描数万张未发布工单。
|
||||
* 手动「同步工单」可以额外带上待完善工单,但只处理固定起点之后创建的,且遇到个别
|
||||
* 无法定价的待完善单只跳过,不中止整批。
|
||||
* 这里不发布实时事件;只有事务提交后才可以刷新大厅缓存和广播。
|
||||
*/
|
||||
export async function syncAdminWorkProductRulePriceWithClient(
|
||||
@@ -643,8 +674,17 @@ export async function syncAdminWorkProductRulePriceWithClient(
|
||||
ruleId: number,
|
||||
actorName: string,
|
||||
now: string,
|
||||
options: WorkProductRulePriceSyncOptions = {},
|
||||
): Promise<WorkProductRulePriceSyncResult> {
|
||||
const candidates = await listWorkOrdersForPriceSyncByProductRuleId(ruleId, client)
|
||||
const pendingResult = options.includePendingMaterial
|
||||
? await listPendingMaterialWorkOrdersForPriceSyncByProductRuleId(
|
||||
ruleId,
|
||||
PENDING_MATERIAL_PRICE_SYNC_CREATED_AFTER,
|
||||
client,
|
||||
)
|
||||
: { orders: [], paymentAmountAdjustedCount: 0 }
|
||||
const pendingCandidates = pendingResult.orders
|
||||
const result: WorkProductRulePriceSyncResult = {
|
||||
candidateCount: candidates.length,
|
||||
updatedCount: 0,
|
||||
@@ -653,12 +693,18 @@ export async function syncAdminWorkProductRulePriceWithClient(
|
||||
skippedInvalidPricingCount: 0,
|
||||
skippedUnchangedCount: 0,
|
||||
skippedUnavailableCount: 0,
|
||||
pendingMaterialCandidateCount: pendingCandidates.length,
|
||||
pendingMaterialPaymentAmountAdjustedCount: pendingResult.paymentAmountAdjustedCount,
|
||||
pendingMaterialUpdatedCount: 0,
|
||||
pendingMaterialUnchangedCount: 0,
|
||||
pendingMaterialSkippedCount: 0,
|
||||
pendingMaterialCreatedAfter: PENDING_MATERIAL_PRICE_SYNC_CREATED_AFTER,
|
||||
}
|
||||
if (candidates.length === 0) return result
|
||||
if (candidates.length === 0 && pendingCandidates.length === 0) return result
|
||||
const rule = await getActiveWorkProductRuleWithClient(client, ruleId)
|
||||
const hallPriceVersionId = await getEffectiveCostVersionIdWithClient(client, ruleId, now)
|
||||
if (!rule || !hallPriceVersionId) {
|
||||
throw createHttpError('模板价格无法物化到现有大厅工单,已中止整批改价', {
|
||||
throw createHttpError('模板价格无法物化到现有工单,已中止整批改价', {
|
||||
statusCode: 409,
|
||||
errorCode: 'work_order_hall_price_invalid',
|
||||
})
|
||||
@@ -697,11 +743,47 @@ export async function syncAdminWorkProductRulePriceWithClient(
|
||||
}
|
||||
}
|
||||
|
||||
for (const workOrder of pendingCandidates) {
|
||||
if (workOrder.assigned_worker_id) {
|
||||
result.pendingMaterialSkippedCount += 1
|
||||
continue
|
||||
}
|
||||
const materialized = await materializeWorkOrderHallPriceWithClient(client, workOrder.id, {
|
||||
now,
|
||||
actorName,
|
||||
rule,
|
||||
hallPriceVersionId,
|
||||
expectedStatus: WORK_ORDER_STATUS.PENDING_MATERIAL,
|
||||
})
|
||||
if (materialized.reason === 'invalid_pricing') {
|
||||
// 待完善单来自历史模板配置时可能算不出价格;跳过个别单,不阻断大厅改价。
|
||||
result.pendingMaterialSkippedCount += 1
|
||||
continue
|
||||
}
|
||||
if (
|
||||
materialized.reason === 'no_template' ||
|
||||
materialized.reason === 'preserved_consignment' ||
|
||||
materialized.reason === 'status_changed'
|
||||
) {
|
||||
result.pendingMaterialSkippedCount += 1
|
||||
continue
|
||||
}
|
||||
if (!materialized.updated) {
|
||||
result.pendingMaterialUnchangedCount += 1
|
||||
continue
|
||||
}
|
||||
result.pendingMaterialUpdatedCount += 1
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/** 将指定模板的当前价格同步到已经进入接单大厅的 open 工单。 */
|
||||
export async function syncAdminWorkProductRulePrice(ruleId: number | string, actorName = '') {
|
||||
/** 将指定模板的当前价格同步到 open 工单;调用方可以额外要求补同步待完善工单。 */
|
||||
export async function syncAdminWorkProductRulePrice(
|
||||
ruleId: number | string,
|
||||
actorName = '',
|
||||
options: WorkProductRulePriceSyncOptions = {},
|
||||
) {
|
||||
const normalizedRuleId = normalizeOptionalId(ruleId)
|
||||
const rule = normalizedRuleId ? await getWorkProductRuleById(normalizedRuleId) : null
|
||||
if (!rule) {
|
||||
@@ -713,7 +795,7 @@ export async function syncAdminWorkProductRulePrice(ruleId: number | string, act
|
||||
const now = nowIso()
|
||||
const result = await withTransaction(async (client) => {
|
||||
await client.query(`SELECT id FROM work_product_rules WHERE id = $1 FOR SHARE`, [rule.id])
|
||||
return syncAdminWorkProductRulePriceWithClient(client, Number(rule.id), actorName, now)
|
||||
return syncAdminWorkProductRulePriceWithClient(client, Number(rule.id), actorName, now, options)
|
||||
})
|
||||
invalidateAllWorkerHallListCache()
|
||||
publishWorkerHallRealtimeRefresh()
|
||||
|
||||
@@ -18,6 +18,7 @@ export type HallPriceMaterializationReason =
|
||||
| 'sharing_filled'
|
||||
| 'no_template'
|
||||
| 'preserved_consignment'
|
||||
| 'status_changed'
|
||||
| 'invalid_pricing'
|
||||
|
||||
export type HallPriceMaterializationResult = {
|
||||
@@ -152,6 +153,8 @@ export async function materializeWorkOrderHallPriceWithClient(
|
||||
eventType?: string
|
||||
rule?: WorkProductRuleRow
|
||||
hallPriceVersionId?: number | null
|
||||
/** 只允许在该状态物化;用于补同步待完善时避免覆盖已发布 / 已接走的工单。 */
|
||||
expectedStatus?: string
|
||||
},
|
||||
): Promise<HallPriceMaterializationResult> {
|
||||
const workOrder = await lockWorkOrder(client, workOrderId)
|
||||
@@ -162,6 +165,21 @@ export async function materializeWorkOrderHallPriceWithClient(
|
||||
})
|
||||
}
|
||||
|
||||
if (options.expectedStatus && workOrder.status !== options.expectedStatus) {
|
||||
return {
|
||||
workOrderId: Number(workOrder.id),
|
||||
reason: 'status_changed',
|
||||
updated: false,
|
||||
rewardAmount: Number(workOrder.reward_amount || 0),
|
||||
sharingUnitReward: Number(workOrder.sharing_unit_reward || 0),
|
||||
hallPriceVersionId: Number(workOrder.hall_price_version_id || 0) || null,
|
||||
joinedQuantity: 0,
|
||||
lockedShareReward: 0,
|
||||
sharingPartial: false,
|
||||
workerIds: [],
|
||||
}
|
||||
}
|
||||
|
||||
const activeShares =
|
||||
workOrder.sharing_enabled === true ? await lockActiveShares(client, workOrder.id) : []
|
||||
const joinedQuantity = activeShares.reduce(
|
||||
|
||||
Reference in New Issue
Block a user