- migration 114 将 sales_daily_facts.fulfillment_mode 重命名为 channel - DTO/查询参数/前端类型从 fulfillmentMode 统一为 channel - 成本中心类型 FulfillmentMode 更名为 FulfillmentChannel,并补齐卡券/待分类/归档取值 - 销售事实响应分组改为 byChannel
728 lines
25 KiB
TypeScript
728 lines
25 KiB
TypeScript
/**
|
||
* 成本定义 CRUD:成本项、成本版本、成本异常队列。
|
||
*
|
||
* 金额只在 cost_versions 改;异常队列只做登记与处理,不做成本计算。
|
||
* 成本解析与快照生成见 cost-resolution-service.ts。
|
||
*/
|
||
import { query } from '../../db/client.js'
|
||
import type { JsonObject } from '../../types/json.js'
|
||
import { createHttpError } from '../../utils/http.js'
|
||
import { nowIso } from '../../utils/time.js'
|
||
import type { AdminSession } from '../admin/admin-auth-service.js'
|
||
import {
|
||
COST_EXCEPTION_STATUSES,
|
||
COST_EXCEPTION_SUBJECT_TYPES,
|
||
COST_MODELS,
|
||
COST_MODEL_CODE_BASE,
|
||
COST_VERSION_SCOPES,
|
||
COST_VERSION_SOURCES,
|
||
COST_VERSION_STATUSES,
|
||
FULFILLMENT_CHANNELS,
|
||
PRICING_MODES,
|
||
PRODUCT_STATUSES,
|
||
assertKnownProvider,
|
||
assertOneOf,
|
||
costModelScopeSql,
|
||
mapCostException,
|
||
mapCostItem,
|
||
mapCostVersion,
|
||
normalizeId,
|
||
normalizeIsoDate,
|
||
normalizeNonNegativeInteger,
|
||
normalizeOptionalId,
|
||
normalizeOptionalText,
|
||
normalizePage,
|
||
normalizePageSize,
|
||
normalizeProviderKey,
|
||
normalizeRequiredText,
|
||
normalizeStatus,
|
||
requiredRow,
|
||
text,
|
||
toNumber,
|
||
} from './cost-center-shared.js'
|
||
import type { CostExceptionRow, CostItemRow, CostVersionRow } from './cost-center-shared.js'
|
||
import {
|
||
getCostItemRow,
|
||
getCostVersionById,
|
||
normalizeCostVersionScopeFields,
|
||
validateCostVersionScope,
|
||
} from './cost-resolution-service.js'
|
||
|
||
export async function listAdminCostItems(payload: JsonObject = {}) {
|
||
const page = normalizePage(payload.page)
|
||
const pageSize = normalizePageSize(payload.pageSize)
|
||
const offset = (page - 1) * pageSize
|
||
const params: unknown[] = []
|
||
const clauses: string[] = []
|
||
|
||
const keyword = text(payload.keyword)
|
||
if (keyword) {
|
||
params.push(`%${keyword}%`)
|
||
clauses.push(`(ci.code ILIKE $${params.length} OR ci.name ILIKE $${params.length})`)
|
||
}
|
||
const costModel = text(payload.costModel ?? payload.cost_model)
|
||
if (costModel) {
|
||
assertOneOf(costModel, COST_MODELS, '成本模型无效')
|
||
params.push(costModel)
|
||
clauses.push(`ci.cost_model = $${params.length}`)
|
||
}
|
||
const status = text(payload.status)
|
||
if (status) {
|
||
assertOneOf(status, PRODUCT_STATUSES, '成本项状态无效')
|
||
params.push(status)
|
||
clauses.push(`ci.status = $${params.length}`)
|
||
}
|
||
// 按履约方式筛选:只返回适用于该履约方式的成本模型。
|
||
const channel = text(payload.channel ?? payload.channel)
|
||
if (channel) {
|
||
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
|
||
params.push(channel)
|
||
clauses.push(costModelScopeSql(`$${params.length}`))
|
||
}
|
||
|
||
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''
|
||
const countResult = await query<{ total: number }>(
|
||
`SELECT COUNT(*)::int AS total FROM cost_items ci ${where}`,
|
||
params,
|
||
)
|
||
const listParams = [...params, pageSize, offset]
|
||
const result = await query<CostItemRow>(
|
||
`
|
||
SELECT
|
||
ci.*,
|
||
(SELECT COUNT(*)::int FROM cost_versions v WHERE v.cost_item_id = ci.id) AS version_count
|
||
FROM cost_items ci
|
||
${where}
|
||
ORDER BY ci.status ASC, ci.cost_model ASC, ci.name ASC, ci.id ASC
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}
|
||
`,
|
||
listParams,
|
||
)
|
||
|
||
return {
|
||
items: result.rows.map(mapCostItem),
|
||
pagination: { page, pageSize, total: toNumber(countResult.rows[0]?.total) },
|
||
}
|
||
}
|
||
|
||
export async function createAdminCostItem(payload: JsonObject, _session: AdminSession) {
|
||
const name = normalizeRequiredText(payload.name, '成本项名称', 120)
|
||
const costModel = normalizeStatus(
|
||
payload.costModel ?? payload.cost_model,
|
||
COST_MODELS,
|
||
null,
|
||
'成本模型无效',
|
||
)
|
||
const pricingMode = normalizeStatus(payload.pricingMode, PRICING_MODES, null, '计价方式无效')
|
||
// 编码由系统生成(按成本模型 + 冲突序号);显式传入时仍优先使用,兼容脚本导入。
|
||
const code = normalizeOptionalText(payload.code, 64) || (await generateCostItemCode(costModel))
|
||
const unitName = normalizeOptionalText(payload.unitName, 16) || '件'
|
||
const currency = normalizeOptionalText(payload.currency, 8) || 'CNY'
|
||
const status = normalizeStatus(payload.status, PRODUCT_STATUSES, 'active', '成本项状态无效')
|
||
const note = normalizeOptionalText(payload.note, 500)
|
||
const now = nowIso()
|
||
|
||
const result = await query<CostItemRow>(
|
||
`
|
||
INSERT INTO cost_items (
|
||
code, name, cost_model, pricing_mode, unit_name,
|
||
currency, status, note, created_at, updated_at
|
||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $9)
|
||
ON CONFLICT (code) DO NOTHING
|
||
RETURNING *
|
||
`,
|
||
[code, name, costModel, pricingMode, unitName, currency, status, note, now],
|
||
)
|
||
const inserted = result.rows[0]
|
||
if (!inserted) {
|
||
throw createHttpError('成本项编码已存在', {
|
||
statusCode: 409,
|
||
errorCode: 'cost_item_code_exists',
|
||
})
|
||
}
|
||
return { costItem: mapCostItem(inserted) }
|
||
}
|
||
|
||
async function generateCostItemCode(costModel: string) {
|
||
const base = COST_MODEL_CODE_BASE[costModel] || 'cost_item'
|
||
let candidate = base
|
||
let index = 2
|
||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||
const existing = await query<{ id: number }>(
|
||
'SELECT id FROM cost_items WHERE code = $1 LIMIT 1',
|
||
[candidate],
|
||
)
|
||
if (!existing.rows[0]) return candidate
|
||
candidate = `${base}_${index}`
|
||
index += 1
|
||
}
|
||
return `${base}_${Date.now()}`
|
||
}
|
||
|
||
export async function updateAdminCostItem(costItemId: number | string, payload: JsonObject) {
|
||
const id = normalizeId(costItemId, '成本项 ID')
|
||
const current = await getCostItemRow(id)
|
||
const name = normalizeRequiredText(payload.name ?? current.name, '成本项名称', 120)
|
||
const costModel = normalizeStatus(
|
||
payload.costModel ?? payload.cost_model,
|
||
COST_MODELS,
|
||
current.cost_model,
|
||
'成本模型无效',
|
||
)
|
||
const pricingMode = normalizeStatus(
|
||
payload.pricingMode,
|
||
PRICING_MODES,
|
||
current.pricing_mode,
|
||
'计价方式无效',
|
||
)
|
||
const unitName =
|
||
payload.unitName === undefined
|
||
? current.unit_name
|
||
: normalizeOptionalText(payload.unitName, 16) || '件'
|
||
const currency =
|
||
payload.currency === undefined
|
||
? current.currency
|
||
: normalizeOptionalText(payload.currency, 8) || 'CNY'
|
||
const status = normalizeStatus(payload.status, PRODUCT_STATUSES, current.status, '成本项状态无效')
|
||
const note = payload.note === undefined ? current.note : normalizeOptionalText(payload.note, 500)
|
||
|
||
const result = await query<CostItemRow>(
|
||
`
|
||
UPDATE cost_items
|
||
SET name = $1, cost_model = $2, pricing_mode = $3,
|
||
unit_name = $4, currency = $5, status = $6, note = $7, updated_at = $8
|
||
WHERE id = $9
|
||
RETURNING *
|
||
`,
|
||
[name, costModel, pricingMode, unitName, currency, status, note, nowIso(), id],
|
||
)
|
||
return { costItem: mapCostItem(requiredRow(result.rows[0], '成本项不存在')) }
|
||
}
|
||
|
||
/**
|
||
* 删除成本项:存在成本版本、成本快照或接单规则引用时拒绝删除。
|
||
*/
|
||
export async function deleteAdminCostItem(costItemId: number | string) {
|
||
const id = normalizeId(costItemId, '成本项 ID')
|
||
const current = await getCostItemRow(id)
|
||
const usageResult = await query<{
|
||
version_count: number
|
||
snapshot_count: number
|
||
rule_count: number
|
||
}>(
|
||
`
|
||
SELECT
|
||
(SELECT COUNT(*)::int FROM cost_versions WHERE cost_item_id = $1) AS version_count,
|
||
(SELECT COUNT(*)::int FROM cost_snapshots WHERE cost_item_id = $1) AS snapshot_count,
|
||
(SELECT COUNT(*)::int FROM work_product_rules WHERE cost_item_id = $1) AS rule_count
|
||
`,
|
||
[id],
|
||
)
|
||
const usage = usageResult.rows[0]
|
||
const blockers: string[] = []
|
||
if (toNumber(usage?.version_count) > 0)
|
||
blockers.push(`${toNumber(usage?.version_count)} 个成本版本`)
|
||
if (toNumber(usage?.snapshot_count) > 0)
|
||
blockers.push(`${toNumber(usage?.snapshot_count)} 条成本快照`)
|
||
if (toNumber(usage?.rule_count) > 0) blockers.push(`${toNumber(usage?.rule_count)} 个接单规则`)
|
||
if (blockers.length > 0) {
|
||
throw createHttpError(`成本项仍被引用(${blockers.join('、')}),不能删除;请改为归档`, {
|
||
statusCode: 409,
|
||
errorCode: 'cost_item_in_use',
|
||
})
|
||
}
|
||
await query('DELETE FROM cost_items WHERE id = $1', [id])
|
||
return { deleted: true, costItem: mapCostItem(current) }
|
||
}
|
||
|
||
export async function listAdminCostVersions(payload: JsonObject = {}) {
|
||
const page = normalizePage(payload.page)
|
||
const pageSize = normalizePageSize(payload.pageSize)
|
||
const offset = (page - 1) * pageSize
|
||
const params: unknown[] = []
|
||
const clauses: string[] = []
|
||
|
||
const costItemId = normalizeOptionalId(payload.costItemId)
|
||
if (costItemId) {
|
||
params.push(costItemId)
|
||
clauses.push(`v.cost_item_id = $${params.length}`)
|
||
}
|
||
const productId = normalizeOptionalId(payload.canonicalProductId)
|
||
if (productId) {
|
||
params.push(productId)
|
||
clauses.push(
|
||
`(
|
||
v.canonical_product_id = $${params.length}
|
||
OR (
|
||
v.scope_type = 'rule'
|
||
AND v.work_product_rule_id IN (
|
||
SELECT wpr.id
|
||
FROM work_product_rules wpr
|
||
JOIN product_catalog pp ON pp.canonical_sku = 'tpl:' || wpr.rule_key
|
||
WHERE pp.id = $${params.length}
|
||
)
|
||
)
|
||
)`,
|
||
)
|
||
}
|
||
const provider = text(payload.provider)
|
||
if (provider) {
|
||
params.push(normalizeProviderKey(provider))
|
||
clauses.push(`v.provider = $${params.length}`)
|
||
}
|
||
const status = text(payload.status)
|
||
if (status) {
|
||
assertOneOf(status, COST_VERSION_STATUSES, '成本版本状态无效')
|
||
params.push(status)
|
||
clauses.push(`v.status = $${params.length}`)
|
||
}
|
||
const costModel = text(payload.costModel ?? payload.cost_model)
|
||
if (costModel) {
|
||
assertOneOf(costModel, COST_MODELS, '成本模型无效')
|
||
params.push(costModel)
|
||
clauses.push(`ci.cost_model = $${params.length}`)
|
||
}
|
||
// 按履约方式筛选:只返回适用于该履约方式的成本模型。
|
||
const channel = text(payload.channel ?? payload.channel)
|
||
if (channel) {
|
||
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
|
||
params.push(channel)
|
||
clauses.push(costModelScopeSql(`$${params.length}`))
|
||
}
|
||
const keyword = text(payload.keyword)
|
||
if (keyword) {
|
||
params.push(`%${keyword}%`)
|
||
clauses.push(
|
||
`(ci.code ILIKE $${params.length} OR ci.name ILIKE $${params.length}
|
||
OR p.canonical_sku ILIKE $${params.length} OR p.canonical_name ILIKE $${params.length}
|
||
OR wpr.product_name ILIKE $${params.length} OR wpr.rule_key ILIKE $${params.length})`,
|
||
)
|
||
}
|
||
|
||
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''
|
||
const countResult = await query<{ total: number }>(
|
||
`
|
||
SELECT COUNT(*)::int AS total
|
||
FROM cost_versions v
|
||
JOIN cost_items ci ON ci.id = v.cost_item_id
|
||
LEFT JOIN product_catalog p ON p.id = v.canonical_product_id
|
||
LEFT JOIN work_product_rules wpr ON wpr.id = v.work_product_rule_id
|
||
${where}
|
||
`,
|
||
params,
|
||
)
|
||
const listParams = [...params, pageSize, offset]
|
||
const result = await query<CostVersionRow>(
|
||
`
|
||
SELECT
|
||
v.*,
|
||
ci.code AS cost_item_code,
|
||
ci.name AS cost_item_name,
|
||
ci.cost_model AS cost_item_cost_model,
|
||
ci.pricing_mode,
|
||
p.canonical_sku,
|
||
p.canonical_name,
|
||
wpr.product_name AS work_product_rule_name,
|
||
wpr.rule_key AS work_product_rule_key,
|
||
wpr.reward_amount AS rule_reward_amount,
|
||
wpr.unit_price_fen AS rule_unit_price_fen,
|
||
rev.revenue_item_count,
|
||
rev.revenue_fen,
|
||
rev.reward_avg_fen,
|
||
rev.reward_fen
|
||
FROM cost_versions v
|
||
JOIN cost_items ci ON ci.id = v.cost_item_id
|
||
LEFT JOIN product_catalog p ON p.id = v.canonical_product_id
|
||
LEFT JOIN work_product_rules wpr ON wpr.id = v.work_product_rule_id
|
||
LEFT JOIN (
|
||
SELECT
|
||
wo.product_rule_id,
|
||
COUNT(*)::int AS revenue_item_count,
|
||
SUM(COALESCE(oi.revenue_amount_fen, 0))::bigint AS revenue_fen,
|
||
ROUND(AVG(wo.reward_amount))::bigint AS reward_avg_fen,
|
||
SUM(wo.reward_amount)::bigint AS reward_fen
|
||
FROM work_orders wo
|
||
JOIN order_items oi ON oi.id = wo.order_item_id
|
||
JOIN orders o ON o.id = oi.order_id
|
||
WHERE o.pay_status IN ('paid', 'refunded')
|
||
GROUP BY wo.product_rule_id
|
||
) rev ON rev.product_rule_id = v.work_product_rule_id
|
||
${where}
|
||
ORDER BY
|
||
v.status ASC,
|
||
CASE
|
||
WHEN ci.code = 'sys_work_order_reward'
|
||
AND v.scope_type = 'global'
|
||
AND v.amount_fen = 0
|
||
THEN 1 ELSE 0
|
||
END ASC,
|
||
COALESCE(rev.revenue_item_count, 0) DESC,
|
||
v.effective_from DESC,
|
||
v.id DESC
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}
|
||
`,
|
||
listParams,
|
||
)
|
||
|
||
return {
|
||
items: result.rows.map(mapCostVersion),
|
||
pagination: { page, pageSize, total: toNumber(countResult.rows[0]?.total) },
|
||
}
|
||
}
|
||
|
||
export async function createAdminCostVersion(payload: JsonObject, session: AdminSession) {
|
||
const costItemId = normalizeId(payload.costItemId ?? payload.cost_item_id, '成本项 ID')
|
||
const costItem = await getCostItemRow(costItemId)
|
||
const scopeType = normalizeStatus(
|
||
payload.scopeType,
|
||
COST_VERSION_SCOPES,
|
||
'global',
|
||
'成本范围无效',
|
||
)
|
||
const rawProvider = normalizeProviderKey(normalizeOptionalText(payload.provider, 64))
|
||
if (rawProvider) {
|
||
assertKnownProvider(rawProvider)
|
||
}
|
||
const rawShopId = normalizeOptionalText(payload.shopId ?? payload.shop_id, 120)
|
||
const rawCanonicalProductId = normalizeOptionalId(
|
||
payload.canonicalProductId ?? payload.canonical_product_id,
|
||
)
|
||
const rawWorkProductRuleId = normalizeOptionalId(
|
||
payload.workProductRuleId ?? payload.work_product_rule_id,
|
||
)
|
||
const { provider, shopId, canonicalProductId, workProductRuleId } =
|
||
normalizeCostVersionScopeFields(scopeType, {
|
||
provider: rawProvider,
|
||
shopId: rawShopId,
|
||
canonicalProductId: rawCanonicalProductId,
|
||
workProductRuleId: rawWorkProductRuleId,
|
||
})
|
||
validateCostVersionScope(scopeType, {
|
||
provider,
|
||
shopId,
|
||
canonicalProductId,
|
||
workProductRuleId,
|
||
})
|
||
|
||
const amountFen = normalizeNonNegativeInteger(payload.amountFen ?? payload.amount_fen, 0)
|
||
const rateBps = normalizeNonNegativeInteger(payload.rateBps ?? payload.rate_bps, 0)
|
||
if (rateBps > 10000) {
|
||
throw createHttpError('比例不能超过 10000 个基点(100%)', {
|
||
statusCode: 400,
|
||
errorCode: 'cost_version_rate_invalid',
|
||
})
|
||
}
|
||
if (costItem.pricing_mode === 'percent_of_revenue' && rateBps <= 0) {
|
||
throw createHttpError('比例计价必须填写大于 0 的 rateBps', {
|
||
statusCode: 400,
|
||
errorCode: 'cost_version_rate_required',
|
||
})
|
||
}
|
||
if (costItem.pricing_mode !== 'percent_of_revenue' && amountFen <= 0) {
|
||
throw createHttpError('非比例计价必须填写大于 0 的金额', {
|
||
statusCode: 400,
|
||
errorCode: 'cost_version_amount_required',
|
||
})
|
||
}
|
||
|
||
const effectiveFrom = normalizeIsoDate(payload.effectiveFrom, '生效时间') || nowIso()
|
||
const effectiveTo = normalizeIsoDate(payload.effectiveTo, '失效时间', true)
|
||
if (effectiveTo && Date.parse(effectiveTo) <= Date.parse(effectiveFrom)) {
|
||
throw createHttpError('失效时间必须晚于生效时间', {
|
||
statusCode: 400,
|
||
errorCode: 'cost_version_period_invalid',
|
||
})
|
||
}
|
||
const source = normalizeStatus(payload.source, COST_VERSION_SOURCES, 'manual', '成本版本来源无效')
|
||
const status = normalizeStatus(
|
||
payload.status,
|
||
COST_VERSION_STATUSES,
|
||
'active',
|
||
'成本版本状态无效',
|
||
)
|
||
const changeReason = normalizeOptionalText(payload.changeReason ?? payload.change_reason, 500)
|
||
const now = nowIso()
|
||
|
||
const result = await query<CostVersionRow>(
|
||
`
|
||
INSERT INTO cost_versions (
|
||
cost_item_id, scope_type, provider, shop_id, canonical_product_id,
|
||
work_product_rule_id, amount_fen, rate_bps, effective_from, effective_to,
|
||
source, status, change_reason, created_by_admin_user_id,
|
||
approved_by_admin_user_id, created_at, updated_at
|
||
) VALUES (
|
||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
|
||
$11, $12, $13, $14, $14, $15, $15
|
||
)
|
||
ON CONFLICT DO NOTHING
|
||
RETURNING *
|
||
`,
|
||
[
|
||
costItemId,
|
||
scopeType,
|
||
provider,
|
||
shopId,
|
||
canonicalProductId,
|
||
workProductRuleId,
|
||
amountFen,
|
||
rateBps,
|
||
effectiveFrom,
|
||
effectiveTo,
|
||
source,
|
||
status,
|
||
changeReason,
|
||
session.userId,
|
||
now,
|
||
],
|
||
)
|
||
const inserted = result.rows[0]
|
||
if (!inserted) {
|
||
throw createHttpError('同一成本项 + 范围 + 生效时间已有版本', {
|
||
statusCode: 409,
|
||
errorCode: 'cost_version_exists',
|
||
})
|
||
}
|
||
return { version: await getCostVersionById(Number(inserted.id)) }
|
||
}
|
||
|
||
export async function retireAdminCostVersion(versionId: number | string, payload: JsonObject = {}) {
|
||
const id = normalizeId(versionId, '成本版本 ID')
|
||
const reason = normalizeRequiredText(
|
||
payload.changeReason ?? payload.change_reason ?? payload.reason,
|
||
'停用原因',
|
||
500,
|
||
)
|
||
const result = await query<{ id: number }>(
|
||
`
|
||
UPDATE cost_versions
|
||
SET status = 'retired', change_reason = $1, updated_at = $2
|
||
WHERE id = $3
|
||
RETURNING id
|
||
`,
|
||
[reason, nowIso(), id],
|
||
)
|
||
if (!result.rows[0]) {
|
||
throw createHttpError('成本版本不存在', {
|
||
statusCode: 404,
|
||
errorCode: 'cost_version_not_found',
|
||
})
|
||
}
|
||
return { version: await getCostVersionById(id) }
|
||
}
|
||
|
||
/**
|
||
* 删除成本版本:生效中的版本必须先停用;已被成本快照引用的版本不可删除。
|
||
*/
|
||
export async function deleteAdminCostVersion(versionId: number | string) {
|
||
const id = normalizeId(versionId, '成本版本 ID')
|
||
const current = await getCostVersionById(id)
|
||
if (current.status === 'active') {
|
||
throw createHttpError('生效中的成本版本不能删除,请先停用', {
|
||
statusCode: 409,
|
||
errorCode: 'cost_version_active',
|
||
})
|
||
}
|
||
const snapshotResult = await query<{ total: number }>(
|
||
'SELECT COUNT(*)::int AS total FROM cost_snapshots WHERE cost_version_id = $1',
|
||
[id],
|
||
)
|
||
const snapshotCount = toNumber(snapshotResult.rows[0]?.total)
|
||
if (snapshotCount > 0) {
|
||
throw createHttpError(`该成本版本已被 ${snapshotCount} 条成本快照引用,不能删除`, {
|
||
statusCode: 409,
|
||
errorCode: 'cost_version_in_use',
|
||
})
|
||
}
|
||
await query('DELETE FROM cost_versions WHERE id = $1', [id])
|
||
return { deleted: true, version: current }
|
||
}
|
||
|
||
export async function listAdminCostExceptions(payload: JsonObject = {}) {
|
||
const page = normalizePage(payload.page)
|
||
const pageSize = normalizePageSize(payload.pageSize)
|
||
const offset = (page - 1) * pageSize
|
||
const params: unknown[] = []
|
||
const clauses: string[] = []
|
||
|
||
const status = text(payload.status)
|
||
if (status) {
|
||
assertOneOf(status, COST_EXCEPTION_STATUSES, '异常状态无效')
|
||
params.push(status)
|
||
clauses.push(`ce.status = $${params.length}`)
|
||
}
|
||
const subjectType = text(payload.subjectType)
|
||
if (subjectType) {
|
||
assertOneOf(subjectType, COST_EXCEPTION_SUBJECT_TYPES, '异常主体无效')
|
||
params.push(subjectType)
|
||
clauses.push(`ce.subject_type = $${params.length}`)
|
||
}
|
||
const reason = text(payload.reason)
|
||
if (reason) {
|
||
params.push(reason)
|
||
clauses.push(`ce.reason = $${params.length}`)
|
||
}
|
||
// 时间范围:默认由前端传「近 N 天」,历史批量扫描产生的异常需要显式放开才能看到。
|
||
const since = normalizeIsoDate(payload.since, '异常起始时间', true)
|
||
if (since) {
|
||
params.push(since)
|
||
clauses.push(`ce.created_at >= $${params.length}::timestamptz`)
|
||
}
|
||
// 履约渠道筛选:异常表不存渠道,改为 join order_items 读 channel/status。
|
||
// 用 IN 半连接而不是 EXISTS:248k 异常 × 316k 订单项下,EXISTS 会逐行回表,
|
||
// 半连接能一次物化候选集合(实测 2.7s -> 0.4s)。
|
||
const channel = text(payload.channel ?? payload.channel)
|
||
if (channel) {
|
||
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
|
||
params.push(channel)
|
||
clauses.push(
|
||
`ce.order_item_id IN (
|
||
SELECT oi.id FROM order_items oi WHERE COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $${params.length}
|
||
)`,
|
||
)
|
||
}
|
||
|
||
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''
|
||
const countResult = await query<{ total: number }>(
|
||
`SELECT COUNT(*)::int AS total FROM cost_exceptions ce ${where}`,
|
||
params,
|
||
)
|
||
const listParams = [...params, pageSize, offset]
|
||
const result = await query<CostExceptionRow>(
|
||
`
|
||
SELECT
|
||
ce.*,
|
||
COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) AS channel
|
||
FROM cost_exceptions ce
|
||
LEFT JOIN order_items oi ON oi.id = ce.order_item_id
|
||
${where}
|
||
ORDER BY ce.status ASC, ce.created_at DESC, ce.id DESC
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}
|
||
`,
|
||
listParams,
|
||
)
|
||
|
||
return {
|
||
items: result.rows.map(mapCostException),
|
||
pagination: { page, pageSize, total: toNumber(countResult.rows[0]?.total) },
|
||
}
|
||
}
|
||
|
||
export type CostExceptionSummary = {
|
||
recentDays: number
|
||
openTotal: number
|
||
recentOpenTotal: number
|
||
historicalOpenTotal: number
|
||
reasons: Array<{ reason: string; openCount: number; recentOpenCount: number }>
|
||
}
|
||
|
||
/**
|
||
* 成本异常汇总:按原因聚合,并区分「近 N 天新增」与「历史批量」。
|
||
*
|
||
* 历史扫描会一次性写入十几万条开放异常,直接列全部没有可操作性;
|
||
* 页面先看近 N 天的量,再决定是否展开历史。
|
||
*/
|
||
export async function summarizeAdminCostExceptions(
|
||
payload: JsonObject = {},
|
||
): Promise<CostExceptionSummary> {
|
||
const rawDays = toNumber(payload.recentDays ?? payload.recent_days ?? 7)
|
||
const recentDays = Math.min(Math.max(Number.isFinite(rawDays) ? Math.round(rawDays) : 7, 1), 90)
|
||
const params: unknown[] = []
|
||
const clauses: string[] = []
|
||
|
||
const channel = text(payload.channel ?? payload.channel)
|
||
if (channel) {
|
||
assertOneOf(channel, FULFILLMENT_CHANNELS, '履约方式无效')
|
||
params.push(channel)
|
||
clauses.push(
|
||
`ce.order_item_id IN (
|
||
SELECT oi.id FROM order_items oi WHERE COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $${params.length}
|
||
)`,
|
||
)
|
||
}
|
||
|
||
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''
|
||
params.push(recentDays)
|
||
const recentInterval = `NOW() - make_interval(days => $${params.length}::int)`
|
||
|
||
const totals = await query<{ open_total: number; recent_open_total: number }>(
|
||
`
|
||
SELECT
|
||
COUNT(*) FILTER (WHERE ce.status = 'open')::int AS open_total,
|
||
COUNT(*) FILTER (
|
||
WHERE ce.status = 'open' AND ce.created_at >= ${recentInterval}
|
||
)::int AS recent_open_total
|
||
FROM cost_exceptions ce
|
||
${where}
|
||
`,
|
||
params,
|
||
)
|
||
const reasons = await query<{
|
||
reason: string
|
||
open_count: number
|
||
recent_open_count: number
|
||
}>(
|
||
`
|
||
SELECT
|
||
ce.reason,
|
||
COUNT(*) FILTER (WHERE ce.status = 'open')::int AS open_count,
|
||
COUNT(*) FILTER (
|
||
WHERE ce.status = 'open' AND ce.created_at >= ${recentInterval}
|
||
)::int AS recent_open_count
|
||
FROM cost_exceptions ce
|
||
${where}
|
||
GROUP BY ce.reason
|
||
ORDER BY open_count DESC, ce.reason ASC
|
||
`,
|
||
params,
|
||
)
|
||
|
||
const openTotal = toNumber(totals.rows[0]?.open_total)
|
||
const recentOpenTotal = toNumber(totals.rows[0]?.recent_open_total)
|
||
return {
|
||
recentDays,
|
||
openTotal,
|
||
recentOpenTotal,
|
||
historicalOpenTotal: Math.max(0, openTotal - recentOpenTotal),
|
||
reasons: reasons.rows.map((row) => ({
|
||
reason: row.reason,
|
||
openCount: toNumber(row.open_count),
|
||
recentOpenCount: toNumber(row.recent_open_count),
|
||
})),
|
||
}
|
||
}
|
||
|
||
export async function resolveAdminCostException(
|
||
exceptionId: number | string,
|
||
payload: JsonObject,
|
||
session: AdminSession,
|
||
) {
|
||
const id = normalizeId(exceptionId, '异常 ID')
|
||
const status = normalizeStatus(
|
||
payload.status,
|
||
COST_EXCEPTION_STATUSES,
|
||
'resolved',
|
||
'异常状态无效',
|
||
)
|
||
if (status === 'open') {
|
||
throw createHttpError('不能把异常重新置为 open', {
|
||
statusCode: 400,
|
||
errorCode: 'cost_exception_status_invalid',
|
||
})
|
||
}
|
||
const now = nowIso()
|
||
const note = text(payload.note ?? payload.resolutionNote ?? payload.resolution_note).slice(0, 300)
|
||
const result = await query<CostExceptionRow>(
|
||
`
|
||
UPDATE cost_exceptions
|
||
SET status = $1,
|
||
resolved_at = $2,
|
||
resolved_by_admin_user_id = $3,
|
||
resolution_note = $5
|
||
WHERE id = $4
|
||
RETURNING *
|
||
`,
|
||
[status, now, session.userId, id, note],
|
||
)
|
||
return { exception: mapCostException(requiredRow(result.rows[0], '成本异常不存在')) }
|
||
}
|