/** @jest-environment node */ import { AUTO_LISTING_DELIVERY_STATUS, AUTO_LISTING_EVENT_TYPE, backfillXiaoyiDeliveriesForTarget, createExternalNotificationTarget, listExternalNotificationDeliveries, listExternalNotificationTargets, queueTaskDetailBarcodeImagesUpdatedNotification, queueTaskDetailFullSetNotification, processExternalNotificationDelivery, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE, XIAOYI_AUTO_LISTING_EVENT_TYPE, retryExternalNotificationDelivery, setExternalNotificationTargetActive, testExternalNotificationTarget, updateExternalNotificationTarget, } from '@/lib/external-auto-listing' import { prisma } from '@/lib/prisma' import { postAutoListingCallback } from '@/lib/external-auto-listing-callback' import { decryptCallbackSecret, encryptCallbackSecret } from '@/lib/external-auto-listing-crypto' jest.mock('@/lib/external-auto-listing-callback', () => ({ ...jest.requireActual('@/lib/external-auto-listing-callback'), postAutoListingCallback: jest.fn(), validateAutoListingCallbackUrl: jest.fn(async (url: string) => new URL(url).href), })) jest.mock('@/lib/prisma', () => ({ prisma: { $executeRawUnsafe: jest.fn(), $queryRawUnsafe: jest.fn(), $queryRaw: jest.fn(), $transaction: jest.fn(), material: { findFirst: jest.fn(), }, materialAssetBarcode: { findMany: jest.fn(), }, }, })) jest.mock('@/lib/public-app-url', () => ({ getPublicAppOrigin: jest.fn(() => 'https://sc.jiansun.vip'), })) describe('external auto listing', () => { const encryptionKey = process.env.API_KEY_ENCRYPTION_KEY beforeAll(() => { process.env.API_KEY_ENCRYPTION_KEY = 'external-auto-listing-test-key-for-fixtures' }) afterAll(() => { if (encryptionKey === undefined) delete process.env.API_KEY_ENCRYPTION_KEY else process.env.API_KEY_ENCRYPTION_KEY = encryptionKey }) beforeEach(() => { jest.clearAllMocks() jest.useFakeTimers() ;(prisma.$executeRawUnsafe as jest.Mock).mockResolvedValue(undefined) ;(prisma.$queryRawUnsafe as jest.Mock).mockResolvedValue([]) jest.mocked(prisma.$queryRaw).mockResolvedValue([{ ready: true }]) ;(prisma.$transaction as jest.Mock).mockImplementation(async (callback: any) => callback({ $executeRawUnsafe: jest.fn().mockResolvedValue(undefined), $queryRawUnsafe: jest.fn().mockResolvedValue([]), }), ) ;(prisma.materialAssetBarcode.findMany as jest.Mock).mockResolvedValue([]) }) afterEach(() => { jest.useRealTimers() }) test('应能创建并更新自动上架通知目标', async () => { ;(prisma.$queryRawUnsafe as jest.Mock) .mockResolvedValueOnce([ { id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', isActive: true, authType: 'bearer', authConfig: { token: 'secret-token' }, eventTypes: [AUTO_LISTING_EVENT_TYPE, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: new Date('2026-03-25T10:00:00.000Z'), updatedAt: new Date('2026-03-25T10:00:00.000Z'), }, ]) .mockResolvedValueOnce([ { id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', isActive: true, authType: 'bearer', authConfig: { token: 'secret-token' }, eventTypes: [AUTO_LISTING_EVENT_TYPE, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: new Date('2026-03-25T10:00:00.000Z'), updatedAt: new Date('2026-03-25T10:00:00.000Z'), }, ]) .mockResolvedValueOnce([ { id: 'target-1', name: '自动上架平台-新版', callbackUrl: 'https://auto.example.com/callback', isActive: false, authType: 'header', authConfig: { headerName: 'X-Signature', headerValue: 'abc123' }, eventTypes: [AUTO_LISTING_EVENT_TYPE, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: new Date('2026-03-25T10:00:00.000Z'), updatedAt: new Date('2026-03-25T10:30:00.000Z'), }, ]) .mockResolvedValueOnce([ { id: 'target-1', name: '自动上架平台-新版', callbackUrl: 'https://auto.example.com/callback', isActive: false, authType: 'header', authConfig: { headerName: 'X-Signature', headerValue: 'abc123' }, eventTypes: [AUTO_LISTING_EVENT_TYPE, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: new Date('2026-03-25T10:00:00.000Z'), updatedAt: new Date('2026-03-25T10:30:00.000Z'), }, ]) const created = await createExternalNotificationTarget({ name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', authType: 'bearer', authConfig: { token: 'secret-token' }, }) const insert = jest.mocked(prisma.$executeRawUnsafe).mock.calls.find(([sql]) => sql.includes('INSERT INTO "external_notification_targets"')) const savedConfig = JSON.parse(String(insert?.[6])) expect(savedConfig).not.toHaveProperty('token') expect(JSON.stringify(savedConfig)).not.toContain('secret-token') expect(decryptCallbackSecret(savedConfig)).toBe('secret-token') expect(created).toEqual({ id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', isActive: true, authType: 'bearer', authConfig: { token: 'secret-token' }, eventTypes: [AUTO_LISTING_EVENT_TYPE, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: '2026-03-25T10:00:00.000Z', updatedAt: '2026-03-25T10:00:00.000Z', }) const listed = await listExternalNotificationTargets() expect(listed).toHaveLength(1) const updated = await updateExternalNotificationTarget('target-1', { name: '自动上架平台-新版', callbackUrl: 'https://auto.example.com/callback', isActive: false, authType: 'header', authConfig: { headerName: 'X-Signature', headerValue: 'abc123', }, }) expect(updated).toEqual({ id: 'target-1', name: '自动上架平台-新版', callbackUrl: 'https://auto.example.com/callback', isActive: false, authType: 'header', authConfig: { headerName: 'X-Signature', headerValue: 'abc123' }, eventTypes: [AUTO_LISTING_EVENT_TYPE, TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: '2026-03-25T10:00:00.000Z', updatedAt: '2026-03-25T10:30:00.000Z', }) }) test('保留已加密的凭据,改回调地址时要求填写新凭据', async () => { const target = { id: 'target-1', name: '上架系统', callbackUrl: 'https://receiver.example.com/callback', authType: 'header', authConfig: { headerName: 'X-Key', ...encryptCallbackSecret('fixture-secret') }, isActive: false, eventTypes: [AUTO_LISTING_EVENT_TYPE], } jest.mocked(prisma.$queryRawUnsafe).mockResolvedValue([target]) await updateExternalNotificationTarget(target.id, { name: '改名' }) const update = jest.mocked(prisma.$executeRawUnsafe).mock.calls.find(([sql]) => sql.includes('UPDATE "external_notification_targets"')) expect(update?.[4]).toBeNull() expect(JSON.parse(String(update?.[6]))).toEqual(target.authConfig) await expect(updateExternalNotificationTarget(target.id, { callbackUrl: 'https://different.example.com/callback', })).rejects.toThrow('重新填写') await expect(updateExternalNotificationTarget(target.id, { authConfig: { headerName: 'X-New-Key' }, })).rejects.toThrow('重新填写') }) test('启停只修改状态,不重写凭据或地址', async () => { jest.mocked(prisma.$executeRawUnsafe).mockResolvedValueOnce(1) jest.mocked(prisma.$queryRawUnsafe).mockResolvedValueOnce([{ id: 'target-1', isActive: false }]) await expect(setExternalNotificationTargetActive('target-1', false)).resolves.toMatchObject({ isActive: false }) expect(prisma.$executeRawUnsafe).toHaveBeenCalledWith( expect.stringContaining('SET is_active = $2, updated_at = NOW()'), 'target-1', false, ) }) test('测试使用已保存凭据,停用目标也只发一次无素材的探针', async () => { const callbackUrl = 'https://receiver.example.com/callback' jest.mocked(prisma.$queryRawUnsafe).mockResolvedValueOnce([{ id: 'target-1', callbackUrl, authType: 'bearer', authConfig: encryptCallbackSecret('fixture-token'), isActive: false, eventTypes: [AUTO_LISTING_EVENT_TYPE], }]) jest.mocked(postAutoListingCallback).mockResolvedValueOnce(204) await expect(testExternalNotificationTarget('target-1')).resolves.toEqual({ statusCode: 204, error: null }) expect(postAutoListingCallback).toHaveBeenCalledTimes(1) expect(postAutoListingCallback).toHaveBeenCalledWith(callbackUrl, { 'Content-Type': 'application/json', Authorization: 'Bearer fixture-token', }, { eventId: expect.any(String), eventType: 'auto-listing.callback.test', test: true, occurredAt: expect.any(String), }) expect(prisma.$executeRawUnsafe).not.toHaveBeenCalled() }) function mockClaim(attemptCount = 1, writeCount = 1) { const query = jest.fn() .mockResolvedValueOnce([{ id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', authType: 'none', authConfig: {}, eventTypes: [AUTO_LISTING_EVENT_TYPE], createdAt: new Date(), }]) .mockResolvedValueOnce([{ materialId: 'material-1', attemptCount, maxAttempts: 5, payload: { eventId: 'evt-1' } }]) .mockResolvedValue([]) const write = jest.fn().mockResolvedValue(writeCount) jest.mocked(prisma.$transaction).mockImplementation(async action => action({ $queryRaw: query, $executeRaw: write } as any)) jest.mocked(prisma.material.findFirst).mockResolvedValue({ id: 'material-1' } as any) return { query, write } } test('认领时计次,完成写回绑定同一个未过期租约', async () => { const { query, write } = mockClaim() jest.mocked(postAutoListingCallback).mockResolvedValueOnce(200) await expect(processExternalNotificationDelivery('delivery-1')).resolves.toEqual({ success: true, status: AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED, }) expect(query.mock.calls[0][0].join('')).toContain('SKIP LOCKED') expect(query.mock.calls[1][0].join('')).toContain('attempt_count=LEAST') expect(write.mock.calls[0][0].join('')).toContain('lease_expires_at > NOW()') expect(write.mock.calls[0].at(-1)).toBe(query.mock.calls[1][1]) const [sql, resetError, circuitError] = write.mock.calls[1] expect(sql.join('')).toContain('IS NULL THEN 0') expect(sql.join('')).toContain("INTERVAL '1 millisecond') ELSE NULL END") expect([resetError, circuitError]).toEqual([null, null]) }) test('过期持有者无法更新目标熔断计数或覆盖投递结果', async () => { const { write } = mockClaim(1, 0) jest.mocked(postAutoListingCallback).mockResolvedValueOnce(500) await expect(processExternalNotificationDelivery('expired-job')).resolves.toBeNull() expect(write).toHaveBeenCalledTimes(1) }) test('创建通知任务时应把预览图和拉取地址写入 payload', async () => { ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ id: 'material-1', taskNo: null, productModel: 'XG025503', categoryName: '旗舰店', sceneName: '客厅', materialType: '任务-详情', previewUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/cover.webp', isFullSet: true, createdAt: new Date('2026-03-25T08:00:00.000Z'), assets: [ { id: 'asset-main-1', assetType: 'main-preview', fileUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/main/1.webp', fileName: 'main-1.webp', sortOrder: 0, }, { id: 'asset-sku-1', assetType: 'sku-preview', fileUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/sku/1.webp', fileName: 'sku-1.webp', sortOrder: 1, }, { id: 'asset-detail-1', assetType: 'detail-preview', fileUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/detail/1.webp', fileName: 'detail-1.webp', sortOrder: 2, }, ], }) ;(prisma.$queryRawUnsafe as jest.Mock) .mockResolvedValueOnce([ { id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', isActive: true, authType: 'none', authConfig: {}, eventTypes: [AUTO_LISTING_EVENT_TYPE], createdAt: new Date('2026-03-25T10:00:00.000Z'), updatedAt: new Date('2026-03-25T10:00:00.000Z'), }, ]) .mockResolvedValueOnce([{ id: 'delivery-1' }]) const createdIds = await queueTaskDetailFullSetNotification('material-1') const insertCall = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[1] const payload = JSON.parse(insertCall[9]) expect(createdIds).toEqual(['delivery-1']) expect(payload.pullUrl).toBe( 'https://sc.jiansun.vip/api/external/product-assets?materialId=material-1', ) expect(payload.coverPreviewUrl).toBe( 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/cover.webp', ) expect(payload.previewAssets).toEqual({ main: [ { id: 'asset-main-1', url: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/main/1.webp', fileName: 'main-1.webp', sortOrder: 0, }, ], sku: [ { id: 'asset-sku-1', url: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/sku/1.webp', fileName: 'sku-1.webp', sortOrder: 1, }, ], detail: [ { id: 'asset-detail-1', url: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/detail/1.webp', fileName: 'detail-1.webp', sortOrder: 2, }, ], }) }) test('手工重放重置投递预算和目标熔断,保留成功记录及生效中的租约', async () => { const query = jest.fn().mockResolvedValue([{ id: 'target-1', enabled: true }]) const write = jest.fn().mockResolvedValueOnce(1).mockResolvedValueOnce(1).mockResolvedValueOnce(0) jest.mocked(prisma.$transaction).mockImplementation(async action => action({ $queryRaw: query, $executeRaw: write } as any)) await expect(retryExternalNotificationDelivery('delivery-2', 'admin')).resolves.toBe('queued') await expect(retryExternalNotificationDelivery('delivery-2', 'admin')).resolves.toBe('conflict') const [sql, actor, id] = write.mock.calls[0] expect(sql.join('')).toContain("status<>'succeeded'") expect(sql.join('')).toContain("status<>'processing' OR COALESCE(lease_expires_at,updated_at + INTERVAL '10 minutes') <= NOW()") expect(sql.join('')).toContain('attempt_count=0') expect(sql.join('')).toContain('next_retry_at=NOW()') expect([actor, id]).toEqual(['admin', 'delivery-2']) const [resetSql, targetId] = write.mock.calls[1] expect(resetSql.join('')).toContain('consecutive_failures=0, circuit_open_until=NULL') expect(targetId).toBe('target-1') expect(write).toHaveBeenCalledTimes(3) }) test('精确匹配素材、任务、项目和事件编号,在截取最近记录前执行筛选', async () => { ;(prisma.$queryRawUnsafe as jest.Mock).mockResolvedValue([]) await listExternalNotificationDeliveries({ status: 'retrying', targetId: 'target-1', query: ' project-abc ', limit: 50, }) const [sql, ...params] = jest.mocked(prisma.$queryRawUnsafe).mock.calls.at(-1)! expect(sql).toContain('d.status = $1') expect(sql).toContain('d.target_id = $2') expect(sql).toContain('d.material_id = $3 OR d.task_no = UPPER($3)') expect(sql).toContain("d.payload->>'projectId' = $3 OR d.payload->>'eventId' = $3") expect(sql).toContain('ORDER BY d.created_at DESC') expect(sql).toContain('LIMIT $4') expect(params).toEqual(['retrying', 'target-1', 'project-abc', 50]) }) test('条码图片更新通知应展开成一条码一记录并附带 lookupUrl', async () => { ;(prisma.material.findFirst as jest.Mock).mockResolvedValue({ id: 'material-1', taskNo: 'TASK202604220001', productModel: 'XG025503', categoryName: '旗舰店', sceneName: '客厅', materialType: '任务-详情', authorName: '旧作者', createdAt: new Date('2026-04-22T09:00:00.000Z'), user: { realName: '张三', username: 'zhangsan', }, assets: [ { id: 'asset-sku-1', fileUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/sku/1.webp', fileName: 'sku-1.webp', sortOrder: 0, skuCode: 'SKU-001', createdAt: new Date('2026-04-22T09:00:00.000Z'), updatedAt: new Date('2026-04-22T09:05:00.000Z'), barcodes: [{ barcode: '690000000001' }, { barcode: '690000000002' }], }, ], }) ;(prisma.materialAssetBarcode.findMany as jest.Mock).mockResolvedValue([ { barcode: '690000000001', assetId: 'asset-sku-1', asset: { createdAt: new Date('2026-04-22T09:00:00.000Z'), sortOrder: 0, }, }, { barcode: '690000000002', assetId: 'asset-sku-1', asset: { createdAt: new Date('2026-04-22T09:00:00.000Z'), sortOrder: 0, }, }, ]) ;(prisma.$queryRawUnsafe as jest.Mock) .mockResolvedValueOnce([ { id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback', isActive: true, authType: 'none', authConfig: {}, eventTypes: [TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE], createdAt: new Date('2026-04-22T10:00:00.000Z'), updatedAt: new Date('2026-04-22T10:00:00.000Z'), }, ]) .mockResolvedValueOnce([{ id: 'delivery-barcode-1' }]) const createdIds = await queueTaskDetailBarcodeImagesUpdatedNotification('material-1', ['asset-sku-1']) const insertCall = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[1] const payload = JSON.parse(insertCall[9]) expect(createdIds).toEqual(['delivery-barcode-1']) expect(insertCall[3]).toBe(TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE) expect(typeof insertCall[7]).toBe('string') expect(insertCall[7]).toBe(payload.eventId) expect(payload.items).toEqual([ { materialId: 'material-1', assetId: 'asset-sku-1', skuCode: 'SKU-001', barcode: '690000000001', previewUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/sku/1.webp', fileName: 'sku-1.webp', sortOrder: 0, uploadedAt: '2026-04-22T09:00:00.000Z', updatedAt: '2026-04-22T09:05:00.000Z', uploaderName: '张三', isLatest: true, lookupUrl: 'https://sc.jiansun.vip/api/external/product-barcode-images?barcode=690000000001', }, { materialId: 'material-1', assetId: 'asset-sku-1', skuCode: 'SKU-001', barcode: '690000000002', previewUrl: 'https://s3.jiansun.vip/gongxiangpan/public-display/task-detail/material-1/sku/1.webp', fileName: 'sku-1.webp', sortOrder: 0, uploadedAt: '2026-04-22T09:00:00.000Z', updatedAt: '2026-04-22T09:05:00.000Z', uploaderName: '张三', isLatest: true, lookupUrl: 'https://sc.jiansun.vip/api/external/product-barcode-images?barcode=690000000002', }, ]) }) test('重试退避使用数据库时间,并将回调失败计入目标熔断', async () => { const { write } = mockClaim(2) jest.mocked(postAutoListingCallback).mockResolvedValueOnce(502) await expect(processExternalNotificationDelivery('delivery-tz-1')).resolves.toEqual({ success: false, status: AUTO_LISTING_DELIVERY_STATUS.RETRYING, }) const [statement, , , , delay] = write.mock.calls[0] expect(statement.join('')).toContain("INTERVAL '1 millisecond'") expect(delay).toBeGreaterThanOrEqual(5 * 60 * 1000) expect(delay).toBeLessThan(6 * 60 * 1000) const [circuitSql, , , limit, cooldown] = write.mock.calls[1] expect(circuitSql.join('')).toContain('consecutive_failures+1 >=') expect(limit).toBe(10) expect(cooldown).toBe(120_000) }) test('新启用目标可幂等补投已展开的历史小壹交付事件,且不干扰停用或未订阅目标', async () => { const createMany = jest.fn().mockResolvedValue({ count: 2 }) ;(prisma as any).externalNotificationDelivery = { createMany } ;(prisma.$queryRawUnsafe as jest.Mock) .mockResolvedValueOnce([{ id: 'target-new', name: '新上架目标', callbackUrl: 'https://new.example.com/callback', isActive: true, authType: 'none', authConfig: {}, eventTypes: [XIAOYI_AUTO_LISTING_EVENT_TYPE], createdAt: new Date('2026-12-05T00:00:00.000Z'), updatedAt: new Date('2026-12-05T00:00:00.000Z'), }]) .mockResolvedValueOnce([ { eventId: 'evt-outbox-1', materialId: 'mat-1', revisionId: 'rev-1', materialType: '自动上架-详情', outcomeKind: 'detail', projectId: 'proj-1', createdAt: new Date('2026-12-01T00:00:00.000Z'), }, { eventId: 'evt-outbox-2', materialId: 'mat-2', revisionId: 'rev-2', materialType: '自动上架-视频', outcomeKind: 'video', projectId: 'proj-2', createdAt: new Date('2026-12-02T00:00:00.000Z'), }, ]) .mockResolvedValueOnce([]) const res = await backfillXiaoyiDeliveriesForTarget('target-new') expect(res).toEqual({ enqueued: 2 }) expect(createMany).toHaveBeenCalledWith({ skipDuplicates: true, data: expect.arrayContaining([ expect.objectContaining({ targetId: 'target-new', dedupeKey: 'evt-outbox-1', materialId: 'mat-1' }), expect.objectContaining({ targetId: 'target-new', dedupeKey: 'evt-outbox-2', materialId: 'mat-2' }), ]), }) ;(prisma.$queryRawUnsafe as jest.Mock).mockResolvedValueOnce([{ id: 'target-off', name: '停用目标', callbackUrl: 'https://off.example.com/callback', isActive: false, authType: 'none', authConfig: {}, eventTypes: [XIAOYI_AUTO_LISTING_EVENT_TYPE], createdAt: new Date('2026-12-05T00:00:00.000Z'), updatedAt: new Date('2026-12-05T00:00:00.000Z'), }]) await expect(backfillXiaoyiDeliveriesForTarget('target-off')).resolves.toEqual({ enqueued: 0 }) }) })