diff --git a/apps/backend/src/repositories/worker-platform/work-product-rule-repo.ts b/apps/backend/src/repositories/worker-platform/work-product-rule-repo.ts index 4f46e58f..b01c8f60 100644 --- a/apps/backend/src/repositories/worker-platform/work-product-rule-repo.ts +++ b/apps/backend/src/repositories/worker-platform/work-product-rule-repo.ts @@ -147,6 +147,53 @@ export async function listWorkOrdersForPriceSyncByProductRuleId( return result.rows } +/** + * 查询固定时间之后创建、仍处于「待完善」的工单。 + * + * 迁移 165 之后模板改价默认只刷新大厅 open 工单;只有手动「同步工单」显式要求 + * 待完善时才按这个时间窗取候选,避免一次性重写历史积压的待完善订单。 + * 用户付款金额有改价历史的工单单独计数并排除,避免覆盖人工核定的付款金额。 + */ +export async function listPendingMaterialWorkOrdersForPriceSyncByProductRuleId( + ruleId: number | string, + createdAfter: string, + client?: Pick, +): Promise<{ + orders: WorkOrderRow[] + paymentAmountAdjustedCount: number +}> { + const params = [Number(ruleId), createdAfter] + const baseWhere = `wo.product_rule_id = $1 + AND wo.status = 'pending_material' + AND wo.created_at > $2::timestamptz` + const paymentAdjustedFilter = `( + wo.user_payment_amount_updated_at IS NOT NULL + OR EXISTS ( + SELECT 1 + FROM work_order_payment_amount_history h + WHERE h.work_order_id = wo.id + ) + )` + const ordersSql = `${WORK_ORDER_SELECT} + WHERE ${baseWhere} + AND NOT ${paymentAdjustedFilter} + ORDER BY wo.id ASC` + const countSql = `SELECT COUNT(*)::int AS total + FROM work_orders wo + WHERE ${baseWhere} + AND ${paymentAdjustedFilter}` + const ordersResult = client + ? await client.query(ordersSql, params) + : await query(ordersSql, params) + const countResult = client + ? await client.query<{ total: number }>(countSql, params) + : await query<{ total: number }>(countSql, params) + return { + orders: ordersResult.rows, + paymentAmountAdjustedCount: Number(countResult.rows[0]?.total || 0), + } +} + export async function lockWorkProductRuleForPriceUpdate( client: Pick, ruleKey: string, diff --git a/apps/backend/src/services/cost-center/cost-center.test.ts b/apps/backend/src/services/cost-center/cost-center.test.ts index 59528226..797b88d5 100644 --- a/apps/backend/src/services/cost-center/cost-center.test.ts +++ b/apps/backend/src/services/cost-center/cost-center.test.ts @@ -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('改过用户付款金额的待完善工单会跳过')) +}) diff --git a/apps/backend/src/services/cost-center/product-catalog-service.ts b/apps/backend/src/services/cost-center/product-catalog-service.ts index 63f2a939..8fbe651b 100644 --- a/apps/backend/src/services/cost-center/product-catalog-service.ts +++ b/apps/backend/src/services/cost-center/product-catalog-service.ts @@ -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(',')}`, } } diff --git a/apps/backend/src/services/cost-center/work-order-hall-pricing.integration.test.ts b/apps/backend/src/services/cost-center/work-order-hall-pricing.integration.test.ts index 3cf1b7a1..c1e66501 100644 --- a/apps/backend/src/services/cost-center/work-order-hall-pricing.integration.test.ts +++ b/apps/backend/src/services/cost-center/work-order-hall-pricing.integration.test.ts @@ -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 diff --git a/apps/backend/src/services/worker-platform/admin-worker-catalog-service.ts b/apps/backend/src/services/worker-platform/admin-worker-catalog-service.ts index c4a434fe..0f68fc5b 100644 --- a/apps/backend/src/services/worker-platform/admin-worker-catalog-service.ts +++ b/apps/backend/src/services/worker-platform/admin-worker-catalog-service.ts @@ -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 { 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() diff --git a/apps/backend/src/services/worker-platform/work-order-hall-pricing-service.ts b/apps/backend/src/services/worker-platform/work-order-hall-pricing-service.ts index c15a0c2d..dfe23bd0 100644 --- a/apps/backend/src/services/worker-platform/work-order-hall-pricing-service.ts +++ b/apps/backend/src/services/worker-platform/work-order-hall-pricing-service.ts @@ -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 { 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( diff --git a/apps/frontend/src/pages/admin/cost-center/ProductCatalogPanel.tsx b/apps/frontend/src/pages/admin/cost-center/ProductCatalogPanel.tsx index 22f138bd..647cb3a3 100644 --- a/apps/frontend/src/pages/admin/cost-center/ProductCatalogPanel.tsx +++ b/apps/frontend/src/pages/admin/cost-center/ProductCatalogPanel.tsx @@ -412,10 +412,13 @@ export function ProductCatalogPanel() { : isAff ? '历史自动发货成本快照与销售事实' : '下游关联业务' + const pendingDesc = isTpl ? ',以及 2026-11-01 之后创建的待完善工单' : '' + const skipHint = isTpl ? '改过用户付款金额的待完善工单会跳过;' : '' modal.confirm({ title: '同步标准价格', - content: `确认将「${item.canonicalName}」的 ${currentPriceText} 同步至${targetDesc}?同步后将以新价格进行履约与结算。`, + width: 560, + content: `确认将「${item.canonicalName}」的 ${currentPriceText} 同步至${targetDesc}${pendingDesc}?${skipHint}同步后将以新价格进行履约与结算。`, okText: '确认同步', cancelText: '取消', onOk: async () => { @@ -683,7 +686,7 @@ export function ProductCatalogPanel() { size="small" icon={} style={{ paddingInline: 4, color: '#1677ff' }} - title="同步此模板在接单大厅的待抢单工单价格" + title="同步此模板的待抢单工单,以及 2026-11-01 后创建且未改过用户付款金额的待完善工单价格" loading={syncingProductId === row.id} onClick={() => handleSyncProductPrice(row)} > diff --git a/apps/frontend/src/services/admin/cost-center.ts b/apps/frontend/src/services/admin/cost-center.ts index a61b1ea5..bdff67b0 100644 --- a/apps/frontend/src/services/admin/cost-center.ts +++ b/apps/frontend/src/services/admin/cost-center.ts @@ -525,6 +525,12 @@ export function syncAdminProductPrice(productId: number) { updatedCount: number updatedNormalCount: number updatedPartialSharingCount: number + pendingMaterialCandidateCount?: number + pendingMaterialPaymentAmountAdjustedCount?: number + pendingMaterialUpdatedCount?: number + pendingMaterialUnchangedCount?: number + pendingMaterialSkippedCount?: number + pendingMaterialCreatedAfter?: string } message: string }>(`/api/v1/admin/cost-center/products/${productId}/sync-price`, {}) diff --git a/docs/统一订单履约与财务模型-权威版.md b/docs/统一订单履约与财务模型-权威版.md index 98d990a3..9a60e1ca 100644 --- a/docs/统一订单履约与财务模型-权威版.md +++ b/docs/统一订单履约与财务模型-权威版.md @@ -367,10 +367,15 @@ manual fulfillment 不是新的价格真源。 - 模板工单必须记录 `work_orders.hall_price_version_id`,指向本次价格物化使用的成本版本。 -- 模板改价只立即刷新已经在大厅中的 `open` 工单;`pending_material`、`unassigned` 不提前扫单。 +- 模板改价保存只立即刷新已经在大厅中的 `open` 工单;`pending_material`、`unassigned` 不提前扫单。 这些工单进入大厅时必须在同一发布事务内按最新生效成本版本物化价格。 -- 未发布工单不得因为模板改价被逐张补写价格或事件;改价失败时成本版本和已同步的大厅工单 - 必须全部回滚。 +- 手动「同步工单」可以额外把模板当前价补同步到 `pending_material` 工单,但必须同时满足: + ① 工单创建时间严格晚于 `2026-11-01 00:00:00 +08:00`; + ② 工单没有用户付款金额改价历史(`work_orders.user_payment_amount_updated_at` 为空,且 + `work_order_payment_amount_history` 无记录)。 + 创建时间更早、待分配、已指派、寄卖合同态或用户付款金额改过的工单不得被补写。 +- 除上述手动「同步工单」外,未发布工单不得因为模板改价被逐张补写价格或事件; + 改价失败时成本版本和已同步的大厅工单必须全部回滚。 - 普通工单按模板计价方式和订单原始规格数量计算。 - 拼单工单只刷新尚未加入的份额;已加入份额的 `unit_reward`、`share_reward` 是参与时的 合同快照,不得被后续模板改价重写。 @@ -1067,8 +1072,9 @@ docs/archive/ 该迁移不重写历史工单金额,寄卖合同态显式豁免。 迁移 `164` 增加接单模板到标准商品的显式关联,并同步商品渠道投影,保证新模板在无订单时也能 进入接单平台成本范围。 -迁移 `165` 删除覆盖未发布工单的改价候选索引,模板改价只刷新 `open` 工单;待完善和未分配 -工单在发布时物化最新价格,避免每次改价扫描数万行。 +迁移 `165` 删除覆盖未发布工单的改价候选索引,模板改价保存只刷新 `open` 工单;待完善和未分配 +工单在发布时物化最新价格,避免每次改价扫描数万行。手动「同步工单」例外:可补同步 +`2026-11-01 00:00:00 +08:00` 之后创建、且没有用户付款金额改价历史的待完善工单。 迁移 `166` 让接单平台路由支持动态模板匹配,清理历史伪造 key 和草稿商品,并拒绝对不存在模板 的非空 `workRuleKey` 写入。 迁移 `167` 清理待判定履约记录对历史假草稿商品的残留引用,并增加履约商品关联闸门。