import { prisma } from '@/lib/prisma' type ListingUpdate = { eventId: string sequence: number state: 'listing' | 'listed' | 'failed' listingId: string | null message: string | null } export type ListingStatus = ListingUpdate & { updatedAt: string } export const pendingListingStatus = { state: 'pending', sequence: 0 } as const export function parseListingUpdate(body: unknown): ListingUpdate | null { if (!body || typeof body !== 'object') return null const { eventId, sequence, state, listingId, message } = body as Record if (typeof eventId !== 'string' || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(eventId) || typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 1 || (state !== 'listing' && state !== 'listed' && state !== 'failed')) return null if (listingId != null && (typeof listingId !== 'string' || !listingId.trim() || listingId.length > 160)) return null if (message != null && (typeof message !== 'string' || !message.trim() || message.length > 500)) return null return { eventId, sequence, state, listingId: listingId?.trim() ?? null, message: message?.trim() ?? null } } // Existing consumers share the automatic-listing channel and have no store identifier. const AUTOMATIC_LISTING_CHANNEL = 'auto-listing' export function applyListingReceipt(current: ListingStatus | undefined, update: ListingUpdate, now: string) { if (current && update.sequence <= current.sequence) { if (update.sequence === current.sequence && (update.state !== current.state || update.listingId !== current.listingId || update.message !== current.message)) { return { status: 409, code: 'SEQUENCE_CONFLICT', message: '同一状态序号的内容必须一致' } as const } return { status: 200, applied: false, listingStatus: current } as const } if (current?.state === 'listed' && update.state !== 'listed') { return { status: 409, code: 'ALREADY_LISTED', message: '上架成功后不能改回上架中或失败' } as const } return { status: 200, applied: true, listingStatus: { ...update, updatedAt: now } } as const } export async function recordListingStatus(materialId: string, update: ListingUpdate) { return prisma.$transaction(async (tx) => { const [row] = await tx.$queryRaw>` SELECT COALESCE(o.id, e.id) AS "eventId", e.id AS "legacyEventId", m."deletedAt", d.listing_status AS "listingStatus" FROM desktop_material_deliveries d JOIN materials m ON m.id = d.material_id LEFT JOIN xiaoyi_auto_listing_outbox o ON o.revision_id = m.current_revision_id LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = m.id WHERE d.material_id = ${materialId} AND m.access_scope = 'general' AND NOT m.task_detail_private AND NOT m.is_incomplete_shell FOR UPDATE OF d, m ` if (!row) return { status: 404, code: 'MATERIAL_NOT_FOUND', message: '小壹交付素材不存在' } as const if (row.deletedAt) return { status: 410, code: 'MATERIAL_DELETED', message: '素材已撤回' } as const if (row.eventId !== update.eventId && row.legacyEventId !== update.eventId && !await tx.xiaoyiAutoListingOutbox.findFirst({ where: { id: update.eventId, materialId }, select: { id: true } })) { return { status: 409, code: 'EVENT_MISMATCH', message: '事件 ID 与素材不匹配' } as const } const identity = { materialId, channel: AUTOMATIC_LISTING_CHANNEL, store: '' } const key = { materialId_channel_store: identity } const channel = await tx.channelListing.findUnique({ where: key }) const receipts = (channel?.receipts ?? {}) as Record const legacy = row.listingStatus if (legacy && (receipts[legacy.eventId]?.sequence ?? 0) < legacy.sequence) receipts[legacy.eventId] = legacy const result = applyListingReceipt(receipts[update.eventId], update, new Date().toISOString()) if (result.status !== 200 || !result.applied) return result receipts[update.eventId] = result.listingStatus const current = row.eventId === update.eventId const listed = channel?.state === 'listed' || legacy?.state === 'listed' const state = listed || update.state === 'listed' ? 'listed' : current ? update.state : channel?.state ?? legacy?.state ?? 'pending' const previousListingId = channel?.listingId ?? legacy?.listingId ?? null const listingId = current ? update.listingId ?? previousListingId : previousListingId ?? (update.state === 'listed' ? update.listingId : null) await tx.channelListing.upsert({ where: key, create: { ...identity, listingId, state, receipts }, update: { listingId, state, receipts }, }) if (current && (!listed || update.state === 'listed')) { await tx.$executeRaw` UPDATE desktop_material_deliveries SET listing_status = ${JSON.stringify(result.listingStatus)}::jsonb WHERE material_id = ${materialId} ` } return result }) }