import {test,before,after} from 'node:test'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; import {mkdtemp,rm,readdir,mkdir,writeFile} from 'node:fs/promises'; import {tmpdir} from 'node:os'; import {join} from 'node:path'; import vm from 'node:vm'; import {PGlite} from '@electric-sql/pglite'; import {buildDirectBundle} from '../lib/legacy-direct-bundle.mjs'; import {specs} from '../lib/legacy-direct-specs.mjs'; import {legacyAddonFields} from '../lib/legacy-direct-projection.mjs'; import {runDirectSync,changesFor,scheduledBusinessDate,pruneCompletedCaches} from '../run-nightly-direct-sync.mjs'; const db=new PGlite();let context,runId;const owner='test-owner-0001'; const sql=async(s,p=[])=>(await db.query(s,p)).rows; const Psql={query:sql,any:sql,one:async(s,p)=>(await sql(s,p))[0],oneOrNone:async(s,p)=>(await sql(s,p))[0]||null,none:async(s,p)=>{await sql(s,p);}}; Psql.tx=async f=>{await db.exec('BEGIN');try{const r=await f(Psql);await db.exec('COMMIT');return r;}catch(e){await db.exec('ROLLBACK');throw e;}}; async function call(params,role='super-admin',company='co'){ let code=200,body;const response={status:n=>{code=n;return response;},json:j=>{body=j;return j;}}; await context.handler({user:{id:'operator',fetch:async()=>{},get:k=>({adminRoleKey:role,company:{id:company}}[k])},body:{params:{runId,owner,...params}}},response); return {code,...body}; } before(async()=>{ await db.exec(readFileSync(new URL('../sql/legacy-direct-sync.sql',import.meta.url),'utf8')); await db.exec(readFileSync(new URL('../sql/legacy-credit-balances.sql',import.meta.url),'utf8')); await db.exec('CREATE TABLE "CommonModel" ("objectId" text PRIMARY KEY,company text,"sourceKey" text,"generalId" numeric,"itemId" numeric,"modelId" numeric,"createdAt" timestamptz,"updatedAt" timestamptz,status numeric,"teachingManaged" boolean,title text,subtitle text)'); for(const [m,s] of Object.entries(specs)){ const fields=legacyAddonFields[m]||(m==='52'?['sy','yb','lj','yp']:['content','synopsis','mp4','ico','author','source']); await db.exec('CREATE TABLE "'+s.className+'" ("objectId" text PRIMARY KEY,company text,id numeric,"sourceKey" text,"createdAt" timestamptz,"updatedAt" timestamptz,"teachingManaged" boolean,'+fields.map(f=>'"'+f+'" text').join(',')+')'); } await db.exec('ALTER TABLE "MemoryPracticeRecord" ADD "rewardTaskKey" text, ADD "rewardDuplicate" boolean, ADD "assignmentVersion" numeric DEFAULT 0'); await db.exec(`ALTER TABLE "CourseAppointment" ADD "categoryEvidence" text, ADD "courseCategoryName" text, ADD "teachingRuleId" text, ADD "teacherPaySnapshot" numeric, ADD "creditCostsSnapshot" jsonb, ADD "creditHoldStatus" text, ADD "bindingId" text, ADD "courseCategoryKey" text, ADD "durationMinutes" numeric, ADD "deliveryMode" text; CREATE TABLE "TeachingCourseCategory"(company text,key text,active boolean); CREATE TABLE "TeachingCompensationRule"(company text,"objectId" text,"categoryKey" text,"durationMinutes" numeric,"deliveryMode" text,"effectiveFrom" text,active boolean,"teacherPay" numeric,"creditCosts" jsonb,revision integer,"createdAt" timestamptz DEFAULT now()); CREATE TABLE "LessonRecordFact"(company text,yyds text); CREATE TABLE "LessonCompletionReport"(company text,"appointmentId" text,"appointmentGeneralId" numeric); CREATE TABLE "WritingAudit"(target text,"before" jsonb,"after" jsonb); CREATE FUNCTION xs_payroll_audit(text,text,text,text,text,jsonb,jsonb) RETURNS void LANGUAGE sql AS $$ INSERT INTO "WritingAudit" VALUES($4,$6,$7) $$`); const rewardSource=readFileSync(new URL('../sql/review-rewards.sql',import.meta.url),'utf8');await db.exec(rewardSource.match(/CREATE OR REPLACE FUNCTION xiaoshu_review_key[\s\S]*?\$\$;/)[0]);await db.exec(rewardSource.match(/CREATE OR REPLACE FUNCTION xiaoshu_safe_shanghai_timestamp[\s\S]*?\$\$;/)[0]); await db.exec(`CREATE TABLE "ReviewReward" ("objectId" text,company text,"taskId" text,amount numeric,status text, "coachId" numeric,"studentId" numeric,"plannedDate" text,"completedAt" timestamptz,"completionRole" text,"completedBy" text); CREATE TABLE "PayrollLine" (company text,"reviewRewardId" text,excluded boolean);`); await db.exec('CREATE TABLE "LegacySyncConflict" ("objectId" text PRIMARY KEY,company text,"sourceKey" text,dataset text,"legacyKey" text,"conflictType" text,message text,resolved boolean,resolution text,"createdAt" timestamptz,"updatedAt" timestamptz)'); await db.exec('CREATE VIEW "ReviewRewardIncome" AS SELECT r.*,NULL::text AS "incomeMonth" FROM "ReviewReward" r'); await db.exec("CREATE FUNCTION xs_review_target(text,text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN RETURN; END $$"); const lessonSource=readFileSync(new URL('../sql/lesson-records.sql',import.meta.url),'utf8'); await db.exec(lessonSource.match(/CREATE OR REPLACE VIEW xs_review_task_link AS[\s\S]*?;/)[0]); await db.exec(readFileSync(new URL('../sql/legacy-review-sync.sql',import.meta.url),'utf8')); const columns=await sql("SELECT table_name,column_name FROM information_schema.columns WHERE table_schema='public'"); context={Psql,Parse:{User:function(){},Config:{get:async()=>({get:k=>({legacyScheduleApiUrl:'https://legacy.invalid/api',legacyScheduleApiId:'test',legacyScheduleApiKey:'test'}[k])})}},fetch:async()=>({ok:true,json:async()=>({retcode:0,result:[{GeneralID:101,kcid:'5',xxcs:1}],page:{itemCount:1,pageCount:1}})}),AbortSignal,Date,console}; vm.createContext(context);vm.runInContext(buildDirectBundle(columns,[],'co'),context); const r=await call({action:'claim',proposedRunId:'test-run-00001'});assert.equal(r.success,true,JSON.stringify(r));runId=r.data.runId; }); after(()=>db.close()); test('非超级管理员、其他帐套与另一执行者不能访问或写入',async()=>{ assert.equal((await call({action:'status'},'ops-manager')).code,403); assert.equal((await call({action:'status'},'super-admin','other')).code,403); assert.match((await call({action:'claim',owner:'another-owner-0001',proposedRunId:'another-run-00001'})).message,/another_sync_running/); assert.match((await call({action:'read',modelId:53,ids:[],owner:'wrong-owner-0001'})).message,/lease/); }); let original; test('主附表原子新增、批次重试复用结果,不允许同一批次编号换内容',async()=>{ const row={generalId:101,common:{objectId:'common101',status:99,title:'旧记录'},addon:{objectId:'addon101',id:101,kcid:'5',xxcs:'1'}}; const first=await call({action:'append',modelId:53,batchKey:'append-101',rows:[row]});assert.equal(first.success,true);assert.equal(first.data.createdCommon,1);original=first.data.postimages[0]; const again=await call({action:'append',modelId:53,batchKey:'append-101',rows:[row]});assert.deepEqual(JSON.parse(JSON.stringify(first.data)),JSON.parse(JSON.stringify(again.data))); assert.equal((await sql('SELECT count(*)::int n FROM "PracticeRecord"'))[0].n,1); assert.match((await call({action:'append',modelId:53,batchKey:'append-101',rows:[{...row,generalId:102}]})).message,/batch_key_reused/); const bad={generalId:102,common:{objectId:'common102',unknown:'bad'},addon:{objectId:'addon102',id:102,kcid:'5'}}; assert.equal((await call({action:'append',modelId:53,batchKey:'bad-102',rows:[bad]})).success,false); assert.equal((await sql('SELECT count(*)::int n FROM "PracticeRecord" WHERE id=102'))[0].n,0); }); test('已保存投影可刷新,修改后的记录保留;微秒级版本变化也拒绝覆盖',async()=>{ const patch=()=>({generalId:101,commonId:original.common.objectId,addonId:original.addon.objectId,commonVersion:original.common.updatedAt,addonVersion:original.addon.updatedAt,values:{xxcs:'2'}}); let r=await call({action:'patch',modelId:53,batchKey:'patch-101',rows:[patch()]});assert.equal(r.data.updated,1);original=r.data.postimages[0]; await sql('UPDATE "PracticeRecord" SET xxcs=\'新系统修改\' WHERE id=101'); r=await call({action:'patch',modelId:53,batchKey:'preserve-101',rows:[patch()]});assert.equal(r.data.updated,0);assert.equal(r.data.conflicts.length,1); await sql('UPDATE "PracticeRecord" SET xxcs=\'2\',"updatedAt"=\'2026-10-12T10:00:00.000002Z\' WHERE id=101'); const stale={...patch(),addonVersion:'2026-10-12T10:00:00.000001+00:00'}; r=await call({action:'patch',modelId:53,batchKey:'microsecond-101',rows:[stale]});assert.equal(r.data.updated,0); }); test('服务端捕获真实源编号并重新核对投影,缺主附表时不能生成对账凭据',async()=>{ assert.equal((await call({action:'source',modelId:53,page:1})).success,true); const evidence=await call({action:'evidence',modelId:53,conflicts:1});assert.equal(evidence.success,true);assert.equal(evidence.data.sourceChecksum,evidence.data.targetChecksum); await sql('DELETE FROM "PracticeRecord" WHERE id=101'); assert.match((await call({action:'evidence',modelId:53})).message,/projection_reconciliation_failed/); assert.match((await call({action:'finish',summary:{datasets:[]}})).message,/reconciliation_incomplete/); }); test('冲突记录重复保存不增加重复行',async()=>{ for(let i=0;i<2;i++)assert.equal((await call({action:'conflicts',rows:[{modelId:53,generalId:101,fields:['xxcs']}]})).success,true); assert.equal((await sql('SELECT count(*)::int n FROM "LegacySyncConflict"'))[0].n,1); }); test('字段差异按业务类型规范化,旧空评分不抹掉新评分',()=>{ assert.deepEqual(changesFor(53,{xxcs:'1'},{xxcs:1},['xxcs']),{}); assert.deepEqual(changesFor(59,{pf:''},{pf:5},['pf']),{}); assert.deepEqual(changesFor(60,{FXZT:'1'},{fxzt:'0'},['fxzt']),{fxzt:'1'}); }); test('每日运行入口只使用直接接口、按依赖顺序并写私有报告,未对账不报成功',async()=>{ const root=await mkdtemp(join(tmpdir(),'direct-sync-test-')),realFetch=globalThis.fetch,order=[]; try{ globalThis.fetch=async(url,options)=>{assert.ok(url.endsWith('/xiaoshu/sync/direct-v1'));const p=JSON.parse(options.body).params;let data; if(p.action==='status')data={source:'old-api/WXAPP',bridgeUsed:false}; else if(p.action==='claim')data={runId:'mock-run-000001',businessDate:'2026-10-12'}; else if(p.action==='supplement')data={accounts:{missing:0},nodes:{missing:0}}; else if(p.action==='source'){order.push(p.modelId);data={items:[],page:{itemCount:0,pageCount:1}};} else if(p.action==='finance-members')data=[]; else if(p.action==='read')data=[]; else if(p.action==='evidence')data={sourceChecksum:'d41d8cd98f00b204e9800998ecf8427e',targetChecksum:'d41d8cd98f00b204e9800998ecf8427e',reconciled:true}; else if(p.action==='finish')data=p.summary; return {ok:true,json:async()=>({success:true,data})}; }; const r=await runDirectSync({XIAOSHU_SYNC_REPORT_DIR:root,XIAOSHU_SYNC_OPERATOR_TOKEN:'test'});assert.equal(r.status,'completed');assert.ok(order.indexOf(56)f.endsWith('.json')));assert.ok(!(await readdir(root)).includes('direct-nightly.lock')); }finally{globalThis.fetch=realFetch;await rm(root,{recursive:true,force:true});} }); test('财务流水按最多四位会员并行,全部请求结束后才释放目录锁',async()=>{ const root=await mkdtemp(join(tmpdir(),'direct-finance-test-')),realFetch=globalThis.fetch; let active=0,peak=0,completed=0; try{ globalThis.fetch=async(url,options)=>{const p=JSON.parse(options.body).params;let data; if(p.action==='status')data={source:'old-api/WXAPP',bridgeUsed:false}; else if(p.action==='claim')data={runId:'mock-finance-run-001',businessDate:'2026-10-12'}; else if(p.action==='supplement')data={accounts:{missing:0},nodes:{missing:0}}; else if(p.action==='source')data={items:[],page:{itemCount:0,pageCount:1}}; else if(p.action==='read')data=[]; else if(p.action==='evidence')data={sourceChecksum:'d41d8cd98f00b204e9800998ecf8427e',targetChecksum:'d41d8cd98f00b204e9800998ecf8427e',reconciled:true}; else if(p.action==='finance-members')data=[1,2,3,4,5].map(id=>({id})); else if(p.action==='finance'){active++;peak=Math.max(peak,active);await new Promise(r=>setTimeout(r,15));active--;completed++;data={studentId:p.studentId,accounts:[],created:0};} else if(p.action==='finish')data=p.summary; return {ok:true,json:async()=>({success:true,data})}; }; const result=await runDirectSync({XIAOSHU_SYNC_REPORT_DIR:root,XIAOSHU_SYNC_OPERATOR_TOKEN:'test'}); assert.equal(result.status,'completed',result.reason);assert.equal(peak,4);assert.equal(completed,5); assert.equal(result.finance.members.length,5);assert.ok(!(await readdir(root)).includes('direct-nightly.lock')); }finally{globalThis.fetch=realFetch;await rm(root,{recursive:true,force:true});} }); test('有新系统计薪凭据的复习不回退、不重算工资',async()=>{ const row={generalId:301,common:{objectId:'memory-common',status:99},addon:{objectId:'memory-addon',id:301,yhid:'20',xxjlid:'33',plid:'30',kywrq:'2026-10-12',fxzt:'0'}}; const inserted=await call({action:'append',modelId:60,batchKey:'memory-301',rows:[row]});assert.equal(inserted.success,true,inserted.message);const t=inserted.data.postimages[0]; await sql('INSERT INTO "ReviewReward" VALUES(\'earned-reward\',\'co\',\'memory-addon\',1,\'earned\')'); const r=await call({action:'patch',modelId:60,batchKey:'memory-protected',rows:[{generalId:301,commonId:t.common.objectId,addonId:t.addon.objectId,commonVersion:t.common.updatedAt,addonVersion:t.addon.updatedAt,values:{fxzt:'1'}}]}); assert.equal(r.success,true,r.message);assert.equal(r.data.updated,0);assert.equal(r.data.conflicts.length,1); assert.equal((await sql('SELECT amount FROM "ReviewReward" WHERE "objectId"=\'earned-reward\''))[0].amount,'1'); assert.equal((await sql('SELECT fxzt FROM "MemoryPracticeRecord" WHERE id=301'))[0].fxzt,'0'); }); test('北京时间23点前补昨天、23点后执行今天,跨UTC日期仍正确',()=>{ assert.equal(scheduledBusinessDate(new Date('2026-10-12T14:59:00Z')),'2026-10-11'); assert.equal(scheduledBusinessDate(new Date('2026-10-12T15:00:00Z')),'2026-10-12'); assert.equal(scheduledBusinessDate(new Date('2026-10-12T16:01:00Z')),'2026-10-12'); }); test('新增账号与栏目幂等补齐,已有账户余额和目录名称保持不变',async()=>{ await db.exec('CREATE TABLE "_User" ("objectId" text PRIMARY KEY,company text,username text UNIQUE,"legacyUserId" numeric,"legacyUserData" jsonb);CREATE TABLE "Node" ("objectId" text PRIMARY KEY,company text,"sourceKey" text,"nodeId" numeric,"parentId" numeric,"nodeName" text,"createdAt" timestamptz,"updatedAt" timestamptz)'); await sql('INSERT INTO "_User" VALUES(\'existing-user\',\'co\',\'existing\',20,\'{"Purse":99}\')'); await sql('INSERT INTO "Node" ("objectId",company,"nodeId","nodeName") VALUES(\'existing-node\',\'co\',8,\'新系统目录\')'); await db.exec('ALTER TABLE "_User" ADD COLUMN "isDeleted" boolean, ADD COLUMN "sourceKey" text'); await db.exec('ALTER TABLE "_User" ADD COLUMN "createdAt" timestamptz DEFAULT now(),ADD COLUMN "_hashed_password" text;CREATE TABLE "_Session"("user" text)'); await db.exec(readFileSync(new URL('../sql/account-security.sql',import.meta.url),'utf8')); const previous=context.fetch;let passwords=0; context.Parse.Query=class{constructor(className){assert.equal(className,'Company');}async get(id){return{id,className:'Company'};}}; context.Parse.Object={createWithoutData:()=>{throw Error('Production SDK does not support two-argument createWithoutData');}}; context.Parse.User=class{constructor(){this.fields={};}set(k,v){this.fields[k]=v;}setUsername(v){this.fields.username=v;}setPassword(v){assert.equal(v,'12345678');passwords++;}async save(){this.id='new-user';const f=this.fields;assert.equal(f.identityType,'member');assert.equal(f.passwordResetRequired,false);assert.equal(f.adminRoleKey,undefined);assert.equal(f.password,undefined);await sql('INSERT INTO "_User" ("objectId",company,username,"legacyUserId","legacyUserData","_hashed_password") VALUES($1,$2,$3,$4,$5::jsonb,$6)',['new-user',f.company.id,f.username,f.legacyUserId,JSON.stringify(f.legacyUserData),'sdk-hashed-initial-password']);}}; context.fetch=async url=>{const action=new URL(url).searchParams.get('action');return {ok:true,json:async()=>({retcode:0,page:{pageCount:1},result:action==='user_list'?[{UserID:20,UserName:'existing',GroupID:1,Purse:1},{UserID:4000,UserName:'new-member',GroupID:1,Purse:10,Password:'ignored-hash'}]:[{NodeID:8,NodeName:'旧目录'},{NodeID:9,ParentID:8,NodeName:'新目录'}]})};}; try{let r=await call({action:'supplement'});assert.equal(r.success,true,r.message);assert.equal(r.data.accounts.created,1);assert.equal(r.data.nodes.created,1); assert.equal((await sql('SELECT "legacyPasswordMigrationAllowed" FROM "_User" WHERE "objectId"=\'new-user\''))[0].legacyPasswordMigrationAllowed,false); await sql('UPDATE "_User" SET "_hashed_password"=$1 WHERE "objectId"=\'new-user\'',['admin-reset-password']); r=await call({action:'supplement'});assert.equal(r.success,true,r.message);assert.equal(r.data.accounts.created,0);assert.equal(r.data.nodes.created,0);assert.equal(passwords,1); assert.equal((await sql('SELECT "_hashed_password" FROM "_User" WHERE "objectId"=\'new-user\''))[0]._hashed_password,'admin-reset-password'); assert.equal((await sql('SELECT "legacyUserData" FROM "_User" WHERE "legacyUserId"=20'))[0].legacyUserData.Purse,99); assert.equal((await sql('SELECT "nodeName" FROM "Node" WHERE "nodeId"=8'))[0].nodeName,'新系统目录'); }finally{context.fetch=previous;} }); test('新导入的老师和门店仍使用各自的一次性旧密码迁移,不设置学生初始密码',async()=>{ const previous=context.fetch;const passwords=new Map(); context.Parse.User=class{constructor(){this.fields={};}set(k,v){this.fields[k]=v;}setUsername(v){this.fields.username=v;}setPassword(v){this.password=v;}async save(){const f=this.fields;this.id='role-'+f.legacyUserId;passwords.set(f.legacyUserId,this.password);assert.ok(this.password.length>60);assert.equal(f.identityType,f.legacyGroupId===3?'coach':'store');await sql('INSERT INTO "_User" ("objectId",company,username,"legacyUserId","legacyUserData","_hashed_password") VALUES($1,$2,$3,$4,$5::jsonb,$6)',[this.id,f.company.id,f.username,f.legacyUserId,JSON.stringify(f.legacyUserData),'sdk-'+f.legacyUserId]);}}; context.fetch=async url=>({ok:true,json:async()=>({retcode:0,page:{pageCount:1},result:new URL(url).searchParams.get('action')==='user_list'?[{UserID:4001,UserName:'new-coach',GroupID:3},{UserID:4002,UserName:'new-store',GroupID:2}]:[]})}); try{const r=await call({action:'supplement'});assert.equal(r.success,true,r.message);assert.equal(r.data.accounts.created,2);assert.notEqual(passwords.get(4001),passwords.get(4002));assert.ok((await sql('SELECT "legacyPasswordMigrationAllowed" allowed FROM "_User" WHERE "legacyUserId" IN (4001,4002)')).every(r=>r.allowed===true));}finally{context.fetch=previous;} }); test('未取得服务器对账证据时不完成运行;已退出进程的目录锁可恢复',async()=>{ const root=await mkdtemp(join(tmpdir(),'direct-sync-negative-')),realFetch=globalThis.fetch;let finished=false; try{ await mkdir(join(root,'direct-nightly.lock')); await writeFile(join(root,'direct-nightly.lock/owner.json'),JSON.stringify({pid:2147483647})); globalThis.fetch=async(url,options)=>{const p=JSON.parse(options.body).params;let data; if(p.action==='status')data={source:'old-api/WXAPP',bridgeUsed:false}; else if(p.action==='claim')data={runId:'failed-run-000001',businessDate:'2026-10-12'}; else if(p.action==='supplement')data={accounts:{missing:0},nodes:{missing:0}}; else if(p.action==='source')data={items:[],page:{itemCount:0,pageCount:1}}; else if(p.action==='finance-members')data=[]; else if(p.action==='read')data=[]; else if(p.action==='evidence')data={sourceChecksum:'d41d8cd98f00b204e9800998ecf8427e',reconciled:false}; else if(p.action==='finish'){finished=true;data=p.summary;} return {ok:true,json:async()=>({success:true,data})}; }; const r=await runDirectSync({XIAOSHU_SYNC_REPORT_DIR:root,XIAOSHU_SYNC_OPERATOR_TOKEN:'test'}); assert.equal(r.status,'blocked');assert.match(r.reason,/checksum/);assert.equal(finished,false); assert.ok(!(await readdir(root)).includes('direct-nightly.lock')); }finally{globalThis.fetch=realFetch;await rm(root,{recursive:true,force:true});} }); test('删除标记禁止恢复,阅读数字编号冲突不会当作小树身份匹配', async()=>{ await sql('INSERT INTO "_User" ("objectId",company,username,"legacyUserId","legacyUserData","isDeleted","sourceKey") VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7)', ['deleted-user','co','deleted',55,'{"Purse":88,"SyncExcluded":true}',true,'legacy-sync:user:55']); await sql('INSERT INTO "_User" ("objectId",company,username,"legacyUserId","legacyUserData","isDeleted","sourceKey") VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7)', ['reading-user','co','reading',1855,'{"Purse":77}',false,'reading-unified:user:reading-user']); for(const name of ['UserExpDomP','UserSIcon','UserExpHis','UserUserPoint'])await db.exec('CREATE TABLE IF NOT EXISTS "'+name+'"(company text,"userId" numeric,"legacyFinanceId" text,"legacyFinanceHash" text)'); const previous=context.fetch; context.fetch=async url=>({ok:true,json:async()=>({retcode:0,page:{pageCount:1},result:new URL(url).searchParams.get('action')==='user_list'?[{UserID:55,UserName:'deleted',GroupID:3,State:1},{UserID:1855,UserName:'real-student',GroupID:1}]:[]})}); try { const r=await call({action:'supplement'});assert.equal(r.success,true,r.message); assert.equal(r.data.accounts.excluded,1);assert.equal(r.data.accounts.identityConflicts,1);assert.equal(r.data.accounts.matched,0);assert.equal(r.data.accounts.created,0); assert.equal((await sql('SELECT "isDeleted" FROM "_User" WHERE "objectId"=$1',['deleted-user']))[0].isDeleted,true); assert.equal((await sql('SELECT "legacyUserData" FROM "_User" WHERE "objectId"=$1',['reading-user']))[0].legacyUserData.Purse,77); assert.equal((await sql('SELECT count(*)::int n FROM "LegacySyncConflict" WHERE "conflictType"=$1',['reading-legacy-id-collision']))[0].n,1); } finally {context.fetch=previous;} }); test('只有全部数据集对账后才能完成,统计来自写入回执,完成重试幂等',async()=>{ await db.exec(`ALTER TABLE "_User" ADD COLUMN "identityType" text; CREATE TABLE "LegacyFinanceReceipt"(company text,"studentId" numeric,account text,"runId" text,ids jsonb,checksum text);`); await db.exec('CREATE TABLE "SysLog" ("objectId" text PRIMARY KEY,company text,"sourceKey" text,type1 text,type2 text,type3 text,detail text,"createdAt" timestamptz,"updatedAt" timestamptz)'); for(const name of ['UserExpDomP','UserSIcon','UserExpHis','UserUserPoint'])await db.exec('CREATE TABLE IF NOT EXISTS "'+name+'"(company text,"userId" numeric,"legacyFinanceId" text,"legacyFinanceHash" text)'); const previous=context.fetch; context.fetch=async()=>({ok:true,json:async()=>({retcode:0,result:[],page:{itemCount:0,pageCount:1}})}); try{ const datasets=[]; for(const modelId of [2,52,58,56,53,60,54,59,61]){ const source=await call({action:'source',modelId,page:1});assert.equal(source.success,true,source.message); const e=await call({action:'evidence',modelId});assert.equal(e.success,true,e.message); datasets.push({modelId,created:999,updated:999,failed:0,reconciled:true}); } const summary={status:'completed-with-preserved-conflicts',datasets,conflicts:1}; await db.exec(`INSERT INTO "_User"("objectId",company,"legacyUserId","identityType","sourceKey","legacyUserData") VALUES('finance-member','co',999,'member','legacy-sync:user:999','{}'),('new-only-member','co',1000,'member',NULL,'{"UserName":"new-only"}');`); assert.deepEqual(JSON.parse(JSON.stringify((await call({action:'finance-members'})).data)),[{id:'999'}]); assert.match((await call({action:'finish',summary})).message,/finance_reconciliation_incomplete/); for(const account of ['Purse','SilverCoin','UserExp','UserPoint'])await sql(`INSERT INTO "LegacyFinanceReceipt" VALUES('co',999,$1,$2,'[]',md5('[]'::jsonb::text))`,[account,runId]); await db.exec(`INSERT INTO "UserSIcon" VALUES('co',999,'source-1','checksum-1')`); await sql(`UPDATE "LegacyFinanceReceipt" SET ids='["source-1"]',checksum=md5('[{"id":"source-1","hash":"checksum-1"}]'::jsonb::text) WHERE account='SilverCoin'`); // Numeric source IDs are a server contract. await db.exec(`UPDATE "UserSIcon" SET "legacyFinanceId"='1';UPDATE "LegacyFinanceReceipt" SET ids='["1"]',checksum='tampered' WHERE account='SilverCoin';`); assert.match((await call({action:'finish',summary})).message,/finance_postimage_changed/); await sql(`UPDATE "LegacyFinanceReceipt" SET checksum=md5('[{"id":"1","hash":"checksum-1"}]'::jsonb::text) WHERE account='SilverCoin'`); assert.match((await call({action:'finish',summary})).message,/balance_reconciliation_incomplete/); await sql(`INSERT INTO "LegacyCreditBalanceReceipt"(company,"studentId","runId",result) VALUES('co',999,$1,'{"applied":2,"conflicts":1}')`,[runId]); const r=await call({action:'finish',summary});assert.equal(r.success,true,r.message);assert.equal(r.data.finance.rows,1);assert.equal(r.data.finance.members,1); assert.equal(r.data.finance.balances.applied,2);assert.equal(r.data.finance.balances.conflicts,1); assert.equal(r.data.createdBusinessRecords,2);assert.equal(r.data.refreshedBusinessRecords,1); assert.equal(r.data.bridgeUsed,false);assert.equal(r.data.settlementReady,false); const again=await call({action:'finish',summary});assert.deepEqual(JSON.parse(JSON.stringify(again.data)),JSON.parse(JSON.stringify(r.data))); assert.equal((await sql('SELECT count(*)::int n FROM "SysLog"'))[0].n,1); assert.equal((await call({action:'claim',proposedRunId:'next-run-0000001'})).data.alreadyCompleted,true); }finally{context.fetch=previous;} }); test('只清理七天前已完成运行的原始缓存,保留失败断点及报告',async()=>{ const root=await mkdtemp(join(tmpdir(),'direct-sync-retention-')); const ids=['11111111-1111-1111-1111-111111111111','22222222-2222-2222-2222-222222222222','33333333-3333-3333-3333-333333333333']; try{ for(let i=0;ix.endsWith('.json')).length,3); }finally{await rm(root,{recursive:true,force:true});} }); test('账号编号冲突时停止业务数据同步,保留阻塞报告',async()=>{ const root=await mkdtemp(join(tmpdir(),'direct-identity-block-')),realFetch=globalThis.fetch;let sourceCalls=0; try{ globalThis.fetch=async(url,options)=>{const p=JSON.parse(options.body).params;let data; if(p.action==='status')data={source:'old-api/WXAPP',bridgeUsed:false}; else if(p.action==='claim')data={runId:'identity-block-000001',businessDate:'2026-10-13'}; else if(p.action==='supplement')data={accounts:{identityConflicts:1}}; else {sourceCalls++;throw Error('business writes must not run');} return {ok:true,json:async()=>({success:true,data})}; }; const r=await runDirectSync({XIAOSHU_SYNC_REPORT_DIR:root,XIAOSHU_SYNC_OPERATOR_TOKEN:'test'}); assert.equal(r.status,'blocked');assert.equal(sourceCalls,0);assert.match(JSON.stringify(r),/legacy_account_identity_conflict/); }finally{globalThis.fetch=realFetch;await rm(root,{recursive:true,force:true});} }); test('旧来源未完成任务可跟进老师切换,后续完成不再因老师字段被拦截',async()=>{ await sql("UPDATE \"LegacyDirectRun\" SET status='running',\"leaseUntil\"=now()+interval '5 minutes' WHERE \"runId\"=$1",[runId]); const first=await call({action:'append',modelId:60,batchKey:'review-transfer-302',rows:[{generalId:302,common:{objectId:'review-common302',status:99},addon:{objectId:'review-addon302',id:302,yhid:'20',xxjlid:'34',plid:'30',kywrq:'2026-10-20',fxzt:'0',wcsj:''}}]}); assert.equal(first.success,true,first.message); const row=first.data.postimages[0]; const result=await call({action:'patch',modelId:60,batchKey:'review-transfer-302-patch',rows:[{generalId:302,commonId:row.common.objectId,addonId:row.addon.objectId,commonVersion:row.common.updatedAt,addonVersion:row.addon.updatedAt,values:{plid:'31'}}]}); assert.equal(result.success,true,result.message); assert.equal(result.data.updated,1,'可信旧来源的老师切换应同步'); assert.equal((await sql('SELECT plid FROM "MemoryPracticeRecord" WHERE id=302'))[0].plid,'31'); }); test('旧预约换编号或改到新系统时段,原子保留新课与时长;不相同时继续导入',async()=>{ await sql("UPDATE \"LegacyDirectRun\" SET status='running',\"leaseUntil\"=now()+interval '5 minutes' WHERE \"runId\"=$1",[runId]); await db.exec(`ALTER TABLE "_User" ADD COLUMN IF NOT EXISTS "legacyGroupId" numeric, ADD COLUMN IF NOT EXISTS "isDisabled" boolean; CREATE TABLE IF NOT EXISTS "CourseCreditReservation"(company text,"appointmentId" text); INSERT INTO "_User" ("objectId",company,username,"legacyUserId","legacyGroupId") VALUES('student-book','co','student-book',7801,1); INSERT INTO "CourseAppointment"("objectId",company,id,"sourceKey",szyh,pl,kcid,yykcid,yysj,bxrq,dszt,dslx) VALUES('native-a','co',8700,'schedule:native','7801','76','170','170','2099-12-01 21:00','2099-12-01','0','1'); INSERT INTO "CommonModel"("objectId",company,"modelId","itemId","generalId",status,"sourceKey") VALUES('native-c','co',54,8700,8700,99,'schedule:native')`); const append=(id,fields={})=>({action:'append',modelId:54,batchKey:'book-'+id,rows:[{generalId:id,common:{objectId:'c'+id,status:99},addon:{ objectId:'a'+id,id,szyh:'7801',pl:'76',kcid:'170',yykcid:'170',yysj:'2099-12-01 21:00:00',bxrq:'2099-12-01',dszt:'0',dslx:'2',...fields}}]}); const run=async req=>{const r=await call(req);assert.equal(r.success,true,r.message);return r.data}; const native=()=>sql(`SELECT to_jsonb(c) c,to_jsonb(a) a FROM "CommonModel" c JOIN "CourseAppointment" a ON c."itemId"=a.id WHERE c."objectId"='native-c'`); const before=await native();const added=await run(append(8711));assert.equal(added.postimages[0].common.status,-2);assert.equal(added.duplicates,1); assert.equal((await run(append(8711))).postimages[0].common.status,-2); assert.equal((await run(append(8712))).postimages[0].common.status,-2); for(const [i,change] of [{pl:'77'},{szyh:'7802'},{kcid:'180',yykcid:'180'},{yysj:'2099-12-01 21:30'},{dszt:'10'},{yykcid:'180'}].entries()){ assert.equal((await run(append(8720+i,change))).postimages[0].common.status,99); } const moved=(await run(append(8730,{yysj:'2099-12-01 19:00'}))).postimages[0]; const patch=(row,yysj,batchKey)=>({action:'patch',modelId:54,batchKey,rows:[{generalId:row.common.generalId,commonId:row.common.objectId, addonId:row.addon.objectId,commonVersion:row.common.updatedAt,addonVersion:row.addon.updatedAt,values:{yysj}}]}); const shifted=(await run(patch(moved,'2099-12-01 21:00','book-patch'))).postimages[0];assert.equal(shifted.common.status,-2); assert.equal((await run(patch(shifted,'2099-12-01 20:00','book-cancelled-patch'))).updated,0); await sql('INSERT INTO "CourseCreditReservation"(company,"appointmentId") VALUES($1,$2)',['co','c8740']); assert.equal((await run(append(8740))).postimages[0].common.status,99); await sql('INSERT INTO "LessonRecord"(company,"objectId",id,yyds) VALUES($1,$2,$3,$4)',['co','lesson-8741',9741,'8741']); assert.equal((await run(append(8741))).postimages[0].common.status,99); assert.deepEqual(await native(),before); }); test('new 398 appointments confirm and price on sync only with consistent confirmed same-year evidence',async()=>{ await sql("UPDATE \"LegacyDirectRun\" SET status='running',\"leaseUntil\"=now()+interval '5 minutes' WHERE \"runId\"=$1",[runId]); const now=Date.now(), day=offset=>new Date(now+offset*86400000).toLocaleDateString('sv-SE',{timeZone:'Asia/Shanghai'}); const yearOf=date=>{const [year,month]=date.split('-').map(Number);return month>=9?year:year-1;}; const schoolYear=yearOf(day(0)), incomingDay=yearOf(day(2))===schoolYear?day(2):day(0); await db.exec(`CREATE TABLE IF NOT EXISTS "_User" ("objectId" text PRIMARY KEY,company text,username text,"legacyUserId" numeric,"legacyGroupId" numeric,"legacyUserData" jsonb); CREATE TABLE IF NOT EXISTS "CourseCreditReservation"(company text,"appointmentId" text); ALTER TABLE "_User" ADD COLUMN IF NOT EXISTS nickname text, ADD COLUMN IF NOT EXISTS "isDeleted" boolean, ADD COLUMN IF NOT EXISTS "isDisabled" boolean; INSERT INTO "_User"("objectId",company,username,"legacyUserId","legacyGroupId",nickname) VALUES ('stage-early','co','stage-early',8801,1,'小明初二'), ('stage-conflict','co','stage-conflict',8802,1,'小明高一'), ('stage-profile-only','co','stage-profile-only',8803,1,'小明初三'), ('stage-expired','co','stage-expired',8804,1,'小明初三'); `); async function prior(id, student, date, evidence='人工核实初中'){ await sql('INSERT INTO "CourseAppointment"("objectId",company,id,kcid,szyh,yysj,"courseCategoryKey","categoryEvidence") VALUES($1,$2,$3,\'398\',$4,$5,\'middle_writing\',$6)',['history-'+id,'co',id,student,date,evidence]); await sql('INSERT INTO "CommonModel"("objectId",company,"modelId","itemId","generalId",status) VALUES($1,$2,54,$3,$3,99)',['history-common-'+id,'co',id]); } const oldMonth='09-03 18:00'; await prior(8801,'8801',schoolYear+'-'+oldMonth); await prior(8802,'8802',schoolYear+'-'+oldMonth); await prior(8803,'8803',schoolYear+'-'+oldMonth,'同步自动核对:初中'); await prior(8804,'8804',(schoolYear-1)+'-'+oldMonth); const append=(id,student,values={})=>({generalId:id,common:{objectId:'write-c'+id,status:99,subtitle:'阅读写作'},addon:{ objectId:'write-a'+id,id,szyh:String(student),pl:'76',kcid:'398',yykcid:'398',dslx:'2',dszt:'0',jffs:'线上', bxrq:incomingDay,yysj:incomingDay+' 21:00',...values}}); const run=async request=>{const r=await call(request);assert.equal(r.success,true,r.message);return r.data;}; const request={action:'append',modelId:54,batchKey:'sync-writing-stage-append',rows:[ append(8901,8801),append(8902,8802),append(8903,8803),append(8904,8804),append(8905,8801,{dszt:'30'}),append(8906,8801,{kcid:'399',yykcid:'399'}) ]}; const first=await run(request); const [ready,...waiting]=first.postimages.map(x=>x.addon); assert.equal(ready.courseCategoryKey,'middle_writing'); assert.match(ready.categoryEvidence,/^同步自动核对:/); assert.match(ready.teachingRuleId,/^seed:middle_writing:60:online:/); assert.equal(ready.durationMinutes,60); assert.equal(ready.deliveryMode,'online'); assert.equal(ready.teacherPaySnapshot,null); assert.equal(ready.creditCostsSnapshot,null); assert.equal(ready.creditHoldStatus,null); assert.ok(waiting.every(x=>!x.courseCategoryKey&&!x.teachingRuleId)); assert.deepEqual(JSON.parse(JSON.stringify(await run(request))),JSON.parse(JSON.stringify(first))); assert.equal((await sql('SELECT count(*)::int n FROM "WritingAudit"'))[0].n,1); assert.equal((await sql('SELECT count(*)::int n FROM "CourseCreditReservation" WHERE "appointmentId"=$1',['write-c8901']))[0].n,0); const patch=(row,changes,batchKey)=>({action:'patch',modelId:54,batchKey,rows:[{ generalId:row.generalId,commonId:row.common.objectId,addonId:row.addon.objectId,commonVersion:row.common.updatedAt, addonVersion:row.addon.updatedAt,values:changes}]}); const insertRule=`INSERT INTO "TeachingCompensationRule" (company,"objectId","categoryKey","durationMinutes","deliveryMode","effectiveFrom",active,"teacherPay","creditCosts",revision) VALUES`; await sql(insertRule+` ('co','middle-30-original','middle_writing',30,'offline',$1,true,31,'[{"account":"Purse","amount":1}]',1), ('co','middle-30-revised','middle_writing',30,'offline',$1,true,32,'[{"account":"Purse","amount":1}]',2)`,[incomingDay]); const moved=(await run(patch(first.postimages[0],{jffs:'线下',dslx:'1'},'sync-writing-stage-move'))).postimages[0]; assert.equal(moved.addon.teachingRuleId,'middle-30-revised'); assert.equal(moved.addon.courseCategoryKey,'middle_writing'); assert.equal(moved.addon.durationMinutes,30); assert.equal(moved.addon.deliveryMode,'offline'); assert.equal(moved.addon.teacherPaySnapshot,null); const reassigned=(await run(patch(moved,{szyh:'8802'},'sync-writing-stage-reassign'))).postimages[0]; assert.equal(reassigned.addon.courseCategoryKey,null); assert.equal(reassigned.addon.teachingRuleId,null); assert.equal(reassigned.addon.teacherPaySnapshot,null); assert.equal(reassigned.addon.creditCostsSnapshot,null); assert.equal(reassigned.addon.durationMinutes,null); assert.equal(reassigned.addon.deliveryMode,null); await sql(insertRule+` ('co','middle-30-disabled','middle_writing',30,'offline',$1,false,32,'[{"account":"Purse","amount":1}]',3)`,[incomingDay]); const noObsoleteRule=(await run({action:'append',modelId:54,batchKey:'sync-writing-retired-rule',rows:[ append(8911,8801,{dslx:'1',jffs:'线下'}) ]})).postimages[0]; assert.ok(!noObsoleteRule.addon.teachingRuleId||noObsoleteRule.addon.teachingRuleId.startsWith('seed:')); await db.exec(`INSERT INTO "LessonRecordFact" VALUES('co','8912')`); const fact=(await run({action:'append',modelId:54,batchKey:'sync-writing-fact',rows:[append(8912,8801)]})).postimages[0]; assert.equal(fact.addon.courseCategoryKey,null); assert.equal(fact.addon.teachingRuleId,null); const beforeReport=(await run({action:'append',modelId:54,batchKey:'sync-writing-before-report',rows:[append(8913,8801)]})).postimages[0]; await db.exec(`INSERT INTO "LessonCompletionReport" VALUES('co','write-c8913',8913)`); assert.equal((await run(patch(beforeReport,{dslx:'1'},'sync-writing-protect-report'))).updated,0); const duplicateCandidate=(await run({action:'append',modelId:54,batchKey:'sync-writing-coach-slot',rows:[append(8914,8801)]})).postimages[0]; await sql(`INSERT INTO "CourseAppointment"("objectId",company,id,"sourceKey",szyh,pl,kcid,yykcid,yysj,bxrq,dszt,dslx) VALUES('native-writing-a','co',8915,'schedule:native-writing','8801','77','398','398',$1,$2,'0','2')`,[incomingDay+' 21:00',incomingDay]); await db.exec(`INSERT INTO "CommonModel"("objectId",company,"modelId","itemId","generalId",status,"sourceKey") VALUES('native-writing-c','co',54,8915,8915,99,'schedule:native-writing')`); const duplicate=await run(patch(duplicateCandidate,{pl:'77'},'sync-writing-duplicate-coach')); assert.equal(duplicate.duplicates,1); assert.equal(duplicate.postimages[0].common.status,-2); const manual=(await run({action:'append',modelId:54,batchKey:'sync-writing-manual',rows:[ append(8907,8801,{courseCategoryKey:'high_writing',categoryEvidence:'人工核对高中',teacherPaySnapshot:65}) ]})).postimages[0]; const protectedResult=await run(patch(manual,{dslx:'1'},'sync-writing-protect-manual')); assert.equal(protectedResult.updated,0); assert.equal(protectedResult.conflicts.length,1); await sql('INSERT INTO "TeachingCourseCategory" VALUES ($1,$2,false)',['co','middle_writing']); const disabled=(await run({action:'append',modelId:54,batchKey:'sync-writing-disabled',rows:[append(8908,8801)]})).postimages[0]; assert.equal(disabled.addon.courseCategoryKey,null); assert.equal(disabled.addon.teachingRuleId,null); });