66 lines
2.4 KiB
TypeScript
66 lines
2.4 KiB
TypeScript
import { createHash } from 'node:crypto'
|
|
import { acquireTaskMaterialUploadSessionLocks } from '@/lib/material-upload-cross-process-lock'
|
|
import type { Prisma } from '@prisma/client'
|
|
import { prisma } from '@/lib/prisma'
|
|
import type { XiaoyiDeliveryKind, XiaoyiDeliveryMetadata } from '@/lib/xiaoyi-delivery-material'
|
|
|
|
export type DeliveryReference = { materialId: string; revisionId: string | null }
|
|
|
|
export type DeliverySnapshot = {
|
|
authorName: string
|
|
productModel: string
|
|
categoryName: string
|
|
productCategoryName: string
|
|
brandName: string
|
|
productName: string
|
|
metadata: XiaoyiDeliveryMetadata | null
|
|
related: Partial<Record<XiaoyiDeliveryKind, DeliveryReference>>
|
|
legacy?: true
|
|
eventId?: string
|
|
}
|
|
|
|
type RevisionAssetInput = Prisma.RevisionAssetCreateManyRevisionInput
|
|
|
|
export function saveDeliveryRevision(
|
|
tx: Prisma.TransactionClient,
|
|
revision: { materialId: string; ownerId: string; projectId: string; kind: XiaoyiDeliveryKind; requestId: string; fingerprint: string; parentId: string | null },
|
|
snapshot: DeliverySnapshot,
|
|
assets: RevisionAssetInput[],
|
|
) {
|
|
return tx.deliveryRevision.create({
|
|
data: { ...revision, snapshot, assets: { createMany: { data: assets } } },
|
|
select: { id: true },
|
|
})
|
|
}
|
|
|
|
export async function getDeliveryRevision(materialId: string, revisionId: string) {
|
|
const revision = await prisma.deliveryRevision.findFirst({
|
|
where: { id: revisionId, materialId },
|
|
include: { assets: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }] } },
|
|
})
|
|
if (!revision) return null
|
|
return {
|
|
...revision,
|
|
snapshot: revision.snapshot as DeliverySnapshot,
|
|
assets: revision.assets.map(asset => ({ ...asset, barcodes: asset.barcodes.map(barcode => ({ barcode })) })),
|
|
}
|
|
}
|
|
|
|
export function getLegacyDeliveryRevisionId(materialId: string) {
|
|
return prisma.deliveryRevision.findFirst({
|
|
where: { materialId, snapshot: { path: ['legacy'], equals: true } },
|
|
select: { id: true },
|
|
})
|
|
}
|
|
|
|
export function getHistoricalDeliveryAsset(materialId: string, assetId: string) {
|
|
return prisma.revisionAsset.findFirst({
|
|
where: { id: assetId, revision: { materialId } },
|
|
})
|
|
}
|
|
|
|
export function acquireDeliveryAttemptLock(owner: string, project: string, attempt: string, timeoutMs?: number) {
|
|
const key = createHash('sha256').update(`${owner}/${project}/${attempt}`).digest('hex')
|
|
return acquireTaskMaterialUploadSessionLocks([`delivery-${key}`], { timeoutMs })
|
|
}
|