331 lines
11 KiB
TypeScript
331 lines
11 KiB
TypeScript
import type { PoolClient } from 'pg'
|
|
|
|
import { query, withTransaction } from '../../db/client.js'
|
|
import type { FulfillmentChannel } from './channel-types.js'
|
|
import { canonicalizeInternalSku, compareFulfillmentChannel } from './internal-sku-resolver.js'
|
|
|
|
export type InternalSkuChannelRow = {
|
|
id: number
|
|
internal_sku: string
|
|
channel: FulfillmentChannel
|
|
priority: number
|
|
is_fallback: boolean
|
|
enabled: boolean
|
|
canonical_product_id: number | null
|
|
config_json: Record<string, unknown>
|
|
source: string
|
|
note: string
|
|
created_by_admin_user_id: number | null
|
|
}
|
|
|
|
export type InternalSkuChannelPlan = {
|
|
primary: InternalSkuChannelRow | null
|
|
fallbacks: InternalSkuChannelRow[]
|
|
attempts: InternalSkuChannelRow[]
|
|
conflicts: InternalSkuChannelRow[]
|
|
}
|
|
|
|
export async function listInternalSkuChannels(
|
|
internalSku: string,
|
|
): Promise<InternalSkuChannelRow[]> {
|
|
const key = canonicalizeInternalSku(internalSku)
|
|
if (!key) return []
|
|
const result = await query<InternalSkuChannelRow>(
|
|
`
|
|
SELECT route.id,
|
|
sku.internal_sku_key AS internal_sku,
|
|
route.channel,
|
|
route.priority,
|
|
(route.route_role = 'fallback') AS is_fallback,
|
|
route.enabled,
|
|
route.canonical_product_id,
|
|
route.carrier_config_json AS config_json,
|
|
route.source,
|
|
route.note,
|
|
route.created_by_admin_user_id
|
|
FROM sku_channel_routes route
|
|
JOIN internal_skus sku ON sku.id = route.internal_sku_id
|
|
WHERE sku.internal_sku_key = $1 AND route.enabled = TRUE
|
|
ORDER BY
|
|
route.priority ASC,
|
|
route.channel ASC
|
|
`,
|
|
[key],
|
|
)
|
|
return result.rows
|
|
}
|
|
|
|
/** 批量读取内部 SKU 渠道计划,供下单入口与发单入口共用。 */
|
|
export async function loadInternalSkuChannelPlans(
|
|
internalSkus: string[],
|
|
): Promise<Map<string, InternalSkuChannelPlan>> {
|
|
const keys = [...new Set(internalSkus.map(canonicalizeInternalSku).filter(Boolean))]
|
|
const result = new Map<string, InternalSkuChannelPlan>()
|
|
if (keys.length === 0) return result
|
|
|
|
const rows = await query<InternalSkuChannelRow>(
|
|
`
|
|
SELECT route.id,
|
|
sku.internal_sku_key AS internal_sku,
|
|
route.channel,
|
|
route.priority,
|
|
(route.route_role = 'fallback') AS is_fallback,
|
|
route.enabled,
|
|
route.canonical_product_id,
|
|
route.carrier_config_json AS config_json,
|
|
route.source,
|
|
route.note,
|
|
route.created_by_admin_user_id
|
|
FROM sku_channel_routes route
|
|
JOIN internal_skus sku ON sku.id = route.internal_sku_id
|
|
WHERE route.enabled = TRUE AND sku.internal_sku_key = ANY($1::text[])
|
|
ORDER BY sku.internal_sku_key, route.priority, route.channel, route.id
|
|
`,
|
|
[keys],
|
|
)
|
|
const grouped = new Map<string, InternalSkuChannelRow[]>()
|
|
for (const row of rows.rows) {
|
|
const key = canonicalizeInternalSku(row.internal_sku)
|
|
const channels = grouped.get(key) || []
|
|
channels.push(row)
|
|
grouped.set(key, channels)
|
|
}
|
|
for (const [key, channels] of grouped) result.set(key, planInternalSkuChannels(channels))
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* 渠道计划:同一时间只允许一个主渠道;同级多渠道视为配置冲突。
|
|
* is_fallback 渠道只在主渠道不可用或失败后按 priority 顺序尝试。
|
|
*/
|
|
export function planInternalSkuChannels(input: InternalSkuChannelRow[]): InternalSkuChannelPlan {
|
|
// 历史数据可能因空格/全半角差异残留同一渠道的多行。按规范化 SKU 读取后,
|
|
// 同一渠道只保留优先级最高的一行,避免把同一能力误判成冲突。
|
|
const byChannel = new Map<FulfillmentChannel, InternalSkuChannelRow>()
|
|
for (const row of input.filter((item) => item.enabled)) {
|
|
const current = byChannel.get(row.channel)
|
|
if (
|
|
!current ||
|
|
Number(row.is_fallback) < Number(current.is_fallback) ||
|
|
(row.is_fallback === current.is_fallback && row.priority < current.priority) ||
|
|
(row.is_fallback === current.is_fallback &&
|
|
row.priority === current.priority &&
|
|
row.id < current.id)
|
|
) {
|
|
byChannel.set(row.channel, row)
|
|
}
|
|
}
|
|
const channels = [...byChannel.values()]
|
|
.filter((row) => row.enabled)
|
|
.sort(
|
|
(a, b) =>
|
|
a.priority - b.priority ||
|
|
Number(a.is_fallback) - Number(b.is_fallback) ||
|
|
compareFulfillmentChannel(a.channel, b.channel),
|
|
)
|
|
|
|
const explicitPrimary = channels.filter((row) => !row.is_fallback)
|
|
const primaryPool = explicitPrimary
|
|
if (primaryPool.length === 0) {
|
|
return { primary: null, fallbacks: [], attempts: [], conflicts: [] }
|
|
}
|
|
|
|
const topPriority = Math.min(...primaryPool.map((row) => row.priority))
|
|
const top = primaryPool.filter((row) => row.priority === topPriority)
|
|
const distinctTop = top.filter(
|
|
(row, index) => top.findIndex((candidate) => candidate.channel === row.channel) === index,
|
|
)
|
|
if (distinctTop.length > 1) {
|
|
return { primary: null, fallbacks: [], attempts: [], conflicts: distinctTop }
|
|
}
|
|
|
|
const primary = distinctTop[0] || null
|
|
const fallbacks = channels.filter((row) => row.channel !== primary?.channel && row.is_fallback)
|
|
return {
|
|
primary,
|
|
fallbacks,
|
|
attempts: primary ? [primary, ...fallbacks] : [],
|
|
conflicts: [],
|
|
}
|
|
}
|
|
|
|
type InternalSkuChannelUpsertInput = {
|
|
internalSku: string
|
|
channel: FulfillmentChannel
|
|
priority?: number
|
|
isFallback?: boolean
|
|
enabled?: boolean
|
|
canonicalProductId?: number | null
|
|
configJson?: Record<string, unknown> | undefined
|
|
source?: string
|
|
note?: string | undefined
|
|
adminUserId?: number | null | undefined
|
|
replacePriority?: boolean
|
|
clearCanonicalProduct?: boolean
|
|
replaceConfig?: boolean
|
|
}
|
|
|
|
async function upsertInternalSkuChannelWithExecutor(
|
|
client: Pick<PoolClient, 'query'>,
|
|
input: InternalSkuChannelUpsertInput,
|
|
): Promise<number> {
|
|
const internalSku = canonicalizeInternalSku(input.internalSku)
|
|
if (!internalSku) return 0
|
|
const skuResult = await client.query<{ id: string }>(
|
|
'SELECT ensure_canonical_internal_sku($1) AS id',
|
|
[internalSku],
|
|
)
|
|
const internalSkuId = Number(skuResult.rows[0]?.id || 0)
|
|
if (!internalSkuId) return 0
|
|
if (input.enabled !== false && input.isFallback !== true) {
|
|
await client.query(
|
|
`UPDATE sku_channel_routes
|
|
SET route_role = 'fallback',
|
|
priority = GREATEST(priority, 90),
|
|
updated_at = NOW()
|
|
WHERE internal_sku_id = $1
|
|
AND channel <> $2
|
|
AND enabled = TRUE
|
|
AND route_role = 'primary'`,
|
|
[internalSkuId, input.channel],
|
|
)
|
|
}
|
|
const result = await client.query<{ id: number }>(
|
|
`
|
|
INSERT INTO sku_channel_routes (
|
|
internal_sku_id, channel, route_role, priority, enabled,
|
|
canonical_product_id, carrier_config_json, source, note, created_by_admin_user_id,
|
|
created_at, updated_at
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9, $10, NOW(), NOW())
|
|
ON CONFLICT (internal_sku_id, channel) DO UPDATE SET
|
|
priority = CASE
|
|
WHEN $11::boolean THEN EXCLUDED.priority
|
|
ELSE LEAST(sku_channel_routes.priority, EXCLUDED.priority)
|
|
END,
|
|
route_role = EXCLUDED.route_role,
|
|
enabled = EXCLUDED.enabled,
|
|
canonical_product_id = CASE
|
|
WHEN $12::boolean THEN NULL
|
|
ELSE COALESCE(EXCLUDED.canonical_product_id, sku_channel_routes.canonical_product_id)
|
|
END,
|
|
carrier_config_json = CASE
|
|
WHEN $13::boolean THEN EXCLUDED.carrier_config_json
|
|
ELSE sku_channel_routes.carrier_config_json || EXCLUDED.carrier_config_json
|
|
END,
|
|
source = EXCLUDED.source,
|
|
note = CASE WHEN EXCLUDED.note <> '' THEN EXCLUDED.note ELSE sku_channel_routes.note END,
|
|
created_by_admin_user_id = COALESCE(EXCLUDED.created_by_admin_user_id, sku_channel_routes.created_by_admin_user_id),
|
|
updated_at = NOW()
|
|
RETURNING id
|
|
`,
|
|
[
|
|
internalSkuId,
|
|
input.channel,
|
|
input.isFallback === true ? 'fallback' : 'primary',
|
|
Number.isFinite(Number(input.priority)) ? Number(input.priority) : 100,
|
|
input.enabled !== false,
|
|
input.canonicalProductId ?? null,
|
|
JSON.stringify(input.configJson || {}),
|
|
String(input.source || 'auto').trim() || 'auto',
|
|
String(input.note || '').slice(0, 300),
|
|
input.adminUserId ?? null,
|
|
input.replacePriority === true,
|
|
input.clearCanonicalProduct === true,
|
|
input.replaceConfig === true,
|
|
],
|
|
)
|
|
return Number(result.rows[0]?.id || 0)
|
|
}
|
|
|
|
export async function upsertInternalSkuChannelWithClient(
|
|
client: PoolClient,
|
|
input: InternalSkuChannelUpsertInput,
|
|
): Promise<number> {
|
|
return upsertInternalSkuChannelWithExecutor(client, input)
|
|
}
|
|
|
|
export async function upsertInternalSkuChannel(
|
|
input: InternalSkuChannelUpsertInput,
|
|
): Promise<number> {
|
|
return withTransaction((client) => upsertInternalSkuChannelWithExecutor(client, input))
|
|
}
|
|
|
|
/**
|
|
* 运营指定一个主渠道。其他渠道保留为显式兜底,避免下一次又被同级优先级抢占。
|
|
*/
|
|
export async function setInternalSkuPrimaryChannel(input: {
|
|
internalSku: string
|
|
channel: FulfillmentChannel
|
|
canonicalProductId?: number | null
|
|
source?: string
|
|
configJson?: Record<string, unknown> | undefined
|
|
note?: string | undefined
|
|
adminUserId?: number | null
|
|
clearCanonicalProduct?: boolean
|
|
replaceConfig?: boolean
|
|
}): Promise<void> {
|
|
const internalSku = canonicalizeInternalSku(input.internalSku)
|
|
if (!internalSku) return
|
|
|
|
await upsertInternalSkuChannel({
|
|
internalSku,
|
|
channel: input.channel,
|
|
priority: 10,
|
|
isFallback: false,
|
|
enabled: true,
|
|
canonicalProductId: input.canonicalProductId ?? null,
|
|
configJson: input.configJson,
|
|
source: input.source || 'operator',
|
|
note: input.note,
|
|
adminUserId: input.adminUserId,
|
|
replacePriority: true,
|
|
...(input.clearCanonicalProduct === undefined
|
|
? {}
|
|
: { clearCanonicalProduct: input.clearCanonicalProduct }),
|
|
...(input.replaceConfig === undefined ? {} : { replaceConfig: input.replaceConfig }),
|
|
})
|
|
}
|
|
|
|
export async function disableInternalSkuChannel(input: {
|
|
internalSku: string
|
|
channel: FulfillmentChannel
|
|
}): Promise<number> {
|
|
const result = await query(
|
|
`
|
|
UPDATE sku_channel_routes route
|
|
SET enabled = FALSE, updated_at = NOW()
|
|
FROM internal_skus sku
|
|
WHERE sku.id = route.internal_sku_id
|
|
AND sku.internal_sku_key = $1
|
|
AND route.channel = $2
|
|
`,
|
|
[canonicalizeInternalSku(input.internalSku), input.channel],
|
|
)
|
|
return result.rowCount || 0
|
|
}
|
|
|
|
export async function deleteInternalSkuChannelById(channelId: number): Promise<boolean> {
|
|
const id = Math.trunc(Number(channelId) || 0)
|
|
if (id <= 0) return false
|
|
const result = await query(`DELETE FROM sku_channel_routes WHERE id = $1`, [id])
|
|
return (result.rowCount || 0) > 0
|
|
}
|
|
|
|
export async function deleteInternalSkuChannelsByIds(idsInput: number[]): Promise<{
|
|
deletedIds: number[]
|
|
missingIds: number[]
|
|
}> {
|
|
const ids = [...new Set(idsInput.map(Number).filter((id) => Number.isInteger(id) && id > 0))]
|
|
if (ids.length === 0) return { deletedIds: [], missingIds: [] }
|
|
const result = await query<{ id: number }>(
|
|
`DELETE FROM sku_channel_routes WHERE id = ANY($1::bigint[]) RETURNING id`,
|
|
[ids],
|
|
)
|
|
const deletedIds = result.rows.map((row) => Number(row.id))
|
|
const deleted = new Set(deletedIds)
|
|
return {
|
|
deletedIds,
|
|
missingIds: ids.filter((id) => !deleted.has(id)),
|
|
}
|
|
}
|