'use strict'; const test = require('node:test'), assert = require('node:assert/strict'); const { Ledger } = require('../core/ledger'); const { FeishuSync, FIELDS, TABLE_NAME } = require('../core/sync'); test('同步写后超时保留待办;重试先查稳定键,不再新建记录', async () => { const l = new Ledger(':memory:'); l.enqueue('inventory'); const records = []; let creates = 0, throwAfterWrite = true; const fake = async (url, opt) => { let d; const body = opt.body ? JSON.parse(opt.body) : {}; if (url.includes('/auth/')) return { ok: true, json: async () => ({ code: 0, tenant_access_token: 'fake', expire: 7200 }) }; if (url.includes('/tables?')) d = { items: [{ table_id: 'tbl-new', name: TABLE_NAME }], has_more: false }; else if (url.includes('/fields?')) d = { items: FIELDS.map(([field_name, type]) => ({ field_name, type })), has_more: false }; else if (url.includes('/records/search')) d = { items: records, has_more: false }; else if (opt.method === 'POST') { creates++; records.push({ record_id: 'rec-new', fields: body.fields }); if (throwAfterWrite) { throwAfterWrite = false; throw new Error('模拟写已完成但网络超时'); } d = { record: records[0] }; } else if (opt.method === 'PUT') { records[0].fields = body.fields; d = { record: records[0] }; } else d = { record: records[0] }; return { ok: true, json: async () => ({ code: 0, data: d }) }; }; const sync = new FeishuSync( l, { enabled: true, appId: 'fake', appSecret: 'fake', baseToken: 'fake', tableId: 'tbl-new' }, fake, ); await sync.tick(); assert.equal(sync.status().failed, 1); assert.equal(sync.status().pending, 1); await sync.tick(); assert.equal(creates, 1); assert.equal(sync.status().pending, 0); assert.equal(sync.status().failed, 0); l.close(); }); test('未配置不调用网络;配置旧表名时禁止写入', async () => { const l = new Ledger(':memory:'); let calls = 0; await new FeishuSync(l, null, () => { calls++; }).tick(); assert.equal(calls, 0); const fake = async url => ({ ok: true, json: async () => url.includes('/auth/') ? { code: 0, tenant_access_token: 'fake' } : { code: 0, data: { items: [{ table_id: 'old', name: '10月_销售单据' }], has_more: false } }, }); const sync = new FeishuSync(l, { enabled: true, appId: 'x', appSecret: 'x', baseToken: 'x', tableId: 'old' }, fake); await sync.tick(); assert.match(sync.status().error, /只允许同步到专用表/); l.close(); });