286 lines
9.9 KiB
TypeScript
286 lines
9.9 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 id, internal_sku, channel, priority, is_fallback, enabled, canonical_product_id,
|
|
config_json, source, note, created_by_admin_user_id
|
|
FROM internal_sku_channels
|
|
WHERE canonicalize_internal_sku(internal_sku) = $1 AND enabled = TRUE
|
|
ORDER BY
|
|
priority ASC,
|
|
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 id, internal_sku, channel, priority, is_fallback, enabled,
|
|
canonical_product_id, config_json, source, note, created_by_admin_user_id
|
|
FROM internal_sku_channels
|
|
WHERE enabled = TRUE AND canonicalize_internal_sku(internal_sku) = ANY($1::text[])
|
|
ORDER BY canonicalize_internal_sku(internal_sku), priority, channel, 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.length > 0 ? explicitPrimary : channels
|
|
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
|
|
}
|
|
|
|
async function upsertInternalSkuChannelWithExecutor(
|
|
client: Pick<PoolClient, 'query'>,
|
|
input: InternalSkuChannelUpsertInput,
|
|
): Promise<number> {
|
|
const internalSku = canonicalizeInternalSku(input.internalSku)
|
|
if (!internalSku) return 0
|
|
if (input.enabled !== false && input.isFallback !== true) {
|
|
await client.query(
|
|
`UPDATE internal_sku_channels
|
|
SET is_fallback = TRUE,
|
|
priority = GREATEST(priority, 90),
|
|
updated_at = NOW()
|
|
WHERE canonicalize_internal_sku(internal_sku) = $1
|
|
AND channel <> $2
|
|
AND enabled = TRUE
|
|
AND is_fallback = FALSE`,
|
|
[internalSku, input.channel],
|
|
)
|
|
}
|
|
const result = await client.query<{ id: number }>(
|
|
`
|
|
INSERT INTO internal_sku_channels (
|
|
internal_sku, channel, priority, is_fallback, enabled,
|
|
canonical_product_id, 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, channel) DO UPDATE SET
|
|
priority = CASE
|
|
WHEN $11::boolean THEN EXCLUDED.priority
|
|
ELSE LEAST(internal_sku_channels.priority, EXCLUDED.priority)
|
|
END,
|
|
is_fallback = EXCLUDED.is_fallback,
|
|
enabled = EXCLUDED.enabled,
|
|
canonical_product_id = COALESCE(EXCLUDED.canonical_product_id, internal_sku_channels.canonical_product_id),
|
|
config_json = internal_sku_channels.config_json || EXCLUDED.config_json,
|
|
source = EXCLUDED.source,
|
|
note = CASE WHEN EXCLUDED.note <> '' THEN EXCLUDED.note ELSE internal_sku_channels.note END,
|
|
created_by_admin_user_id = COALESCE(EXCLUDED.created_by_admin_user_id, internal_sku_channels.created_by_admin_user_id),
|
|
updated_at = NOW()
|
|
RETURNING id
|
|
`,
|
|
[
|
|
internalSku,
|
|
input.channel,
|
|
Number.isFinite(Number(input.priority)) ? Number(input.priority) : 100,
|
|
input.isFallback === true,
|
|
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,
|
|
],
|
|
)
|
|
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
|
|
}): 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,
|
|
})
|
|
}
|
|
|
|
export async function disableInternalSkuChannel(input: {
|
|
internalSku: string
|
|
channel: FulfillmentChannel
|
|
}): Promise<number> {
|
|
const result = await query(
|
|
`
|
|
UPDATE internal_sku_channels
|
|
SET enabled = FALSE, updated_at = NOW()
|
|
WHERE canonicalize_internal_sku(internal_sku) = $1 AND 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 internal_sku_channels 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 internal_sku_channels 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)),
|
|
}
|
|
}
|