legacy-direct-sync.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // Called under the same tenant credit lock as scheduling and cancellation.
  2. async function directMatchingNativeBooking(db,co,common,old){
  3. if(Number(common.status)!==99||old.dszt!=='0'||old.teachingManaged||common.teachingManaged||
  4. old.bindingId||old.courseCategoryKey||old.creditHoldStatus||old.creditCostsSnapshot?.length||old.teacherPaySnapshot!=null||
  5. old.kssj||old.jssj||![old.szyh,old.pl,old.kcid].every(id=>/^[1-9]\d*$/.test(id))||
  6. (old.yykcid&&old.yykcid!==old.kcid))return null;
  7. // The operator identified member 252 in this tenant as a test account.
  8. if(co==='7pIbDBJmKx'&&old.szyh==='252')return null;
  9. const slot=/^(\d{4}-\d\d-\d\d) (?:[01]\d|2[0-3]):[0-5]\d(?::00)?$/.exec(old.yysj||'');
  10. if(!slot||(old.bxrq&&old.bxrq!==slot[1]))return null;
  11. return db.oneOrNone(`SELECT min(c."generalId") AS id
  12. FROM "CourseAppointment" n JOIN "CommonModel" c ON c.company=n.company AND c."modelId"=54 AND c."itemId"=n.id
  13. WHERE n.company=$1 AND n.szyh=$2 AND n.pl=$3 AND n.kcid=$4 AND n.dszt IN ('0','10','11','20','30','40') AND c.status=99
  14. AND n."sourceKey" LIKE 'schedule:%' AND c."sourceKey"=n."sourceKey"
  15. AND n.yysj IN ($5,$5||':00') AND COALESCE(NULLIF(n.bxrq,''),left(n.yysj,10))=left($5,10)
  16. AND COALESCE(NULLIF(n.yykcid,''),n.kcid)=n.kcid
  17. AND left($5,10)>=to_char(now() AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD')
  18. AND EXISTS(SELECT 1 FROM "_User" u WHERE u.company=$1 AND u."legacyUserId"=($2::text)::numeric
  19. AND u."legacyGroupId"=1 AND NOT COALESCE(u."isDeleted",false) AND NOT COALESCE(u."isDisabled",false))
  20. AND NOT EXISTS(SELECT 1 FROM "CourseCreditReservation" r WHERE r.company=$1 AND r."appointmentId"=$6)
  21. AND NOT EXISTS(SELECT 1 FROM "LessonRecord" l WHERE l.company=$1 AND l.yyds IN ($7,$8))
  22. HAVING count(*)=1`,[co,old.szyh,old.pl,old.kcid,old.yysj.slice(0,16),common.objectId,String(common.generalId),String(old.id)]);
  23. }
  24. async function handler(request,response){
  25. try{
  26. const u=request.user;if(!u)return response.status(401).json({success:false});await u.fetch({useMasterKey:true});if(u.get('isDisabled')||u.get('isDeleted')||u.get('adminRoleKey')!=='super-admin'||u.get('company')?.id!==__COMPANY_ID__)return response.status(403).json({success:false});
  27. const co=__COMPANY_ID__,p=request.body?.params||{},specs=__SPECS__,windows=__WINDOWS__,q=x=>'"'+x+'"',s=specs[p.modelId],m=Number(p.modelId);
  28. if(p.action==='status'){const result=await directControl(p,co,u);return response.json({success:true,data:{...result,appointmentDeletionVersion:'confirmed-ids-v1'}});}
  29. if(p.action==='review-income'||p.action==='finance-members'||p.action==='finance'||p.action==='status'||p.action==='claim'||p.action==='source'||p.action==='finish'||p.action==='conflicts'||p.action==='verify'||p.action==='supplement'||p.action==='evidence'||p.action==='reset-dataset')return response.json({success:true,data:await directControl(p,co,u)});
  30. await directLease(Psql,p,co);
  31. const legacy=r=>r&&typeof r.sourceKey==='string'&&(/\[\["(?:ID|GeneralID)",\d+\]\]/.test(r.sourceKey)||/^legacy:model:\d+:general:\d+$/.test(r.sourceKey));
  32. const unchanged=r=>legacy(r)&&!r.teachingManaged&&(r.createdAt===r.updatedAt||!r.updatedAt||Date.parse(r.updatedAt)<Date.parse('2026-08-01')||windows.some(([a,b])=>Date.parse(r.updatedAt)>=a&&Date.parse(r.updatedAt)<=b));
  33. const sameVersion=(a,b)=>a===b;
  34. if(p.action==='overview'){
  35. const data=[];for(const [id,spec] of Object.entries(specs)){const row=await Psql.one('SELECT (SELECT count(*)::int FROM "CommonModel" WHERE company=$1 AND "modelId"=$2) common,(SELECT count(*)::int FROM "'+spec.className+'" WHERE company=$1) addon,(SELECT count(*)::int FROM "CommonModel" c WHERE c.company=$1 AND c."modelId"=$2 AND NOT EXISTS(SELECT 1 FROM "'+spec.className+'" a WHERE a.company=c.company AND a.id=c."itemId")) missing_links',[co,Number(id)]);data.push({modelId:Number(id),...row});}return response.json({success:true,data});
  36. }
  37. if(!s)throw Error('Invalid model');
  38. const readSql='SELECT c."generalId",to_jsonb(c) AS common,to_jsonb(a) AS addon'+(m===60?',to_jsonb(r) AS reward':'')+' FROM "CommonModel" c LEFT JOIN "'+s.className+'" a ON a.company=c.company AND a.id=c."itemId"'+(m===60?' LEFT JOIN "ReviewReward" r ON r.company=a.company AND r."taskId"=a."objectId"':'')+' WHERE c.company=$1 AND c."modelId"=$2 AND c."generalId"=ANY($3::numeric[])';
  39. if(p.action==='read'){const ids=p.ids||[];if(ids.length>1000||ids.some(x=>!Number.isSafeInteger(x)||x<1))throw Error('Invalid IDs');return response.json({success:true,data:await Psql.query(readSql,[co,m,ids])});}
  40. if(!['append','patch'].includes(p.action)||!Array.isArray(p.rows)||p.rows.length>50)throw Error('Invalid mutation');
  41. const result=await Psql.tx(async t=>{
  42. await directLease(t,p,co);
  43. const fingerprint=(await t.one('SELECT md5($1) fingerprint',[JSON.stringify([p.action,m,p.rows])])).fingerprint;
  44. const receipt=await t.oneOrNone('SELECT fingerprint,result FROM "LegacyDirectBatch" WHERE company=$1 AND "runId"=$2 AND key=$3',[co,p.runId,p.batchKey]);if(receipt){if(receipt.fingerprint!==fingerprint)throw Error('batch_key_reused');return receipt.result;}
  45. await t.any("SELECT pg_advisory_xact_lock(hashtext('xs-credit:'||$1))",[co]);
  46. const out={modelId:m,createdCommon:0,createdAddon:0,updated:0,duplicates:0,rewardEvidence:0,conflicts:[],postimages:[]};
  47. async function insert(table,data,allowed){if(Object.keys(data).some(k=>!allowed.includes(k)))throw Error('Unexpected projected field');const cols=Object.keys(data).map(q).join(',');return t.one('INSERT INTO '+q(table)+' ('+cols+') SELECT '+Object.keys(data).map(k=>'v.'+q(k)).join(',')+' FROM jsonb_populate_record(NULL::'+q(table)+',$1::jsonb) v RETURNING *',[JSON.stringify(data)]);}
  48. for(const incoming of p.rows){
  49. const gid=Number(incoming.generalId);if(!Number.isSafeInteger(gid)||gid<1)throw Error('Invalid incoming ID');
  50. const cc=(await t.oneOrNone('SELECT to_jsonb(c) data FROM "CommonModel" c WHERE company=$1 AND "modelId"=$2 AND "generalId"=$3 FOR UPDATE',[co,m,gid]))?.data;
  51. if(p.action==='append'){
  52. // A repaired historical class already represents this appointment, even if the old source later gains a different generalId.
  53. if(m===59&&incoming.addon?.yyds&&String(incoming.addon.yyds)!=='0'){
  54. const repaired=await t.oneOrNone('SELECT "objectId",xymz FROM "LessonRecord" WHERE company=$1 AND yyds=$2 AND "sourceKey" LIKE \'repair:legacy-completed-appointment:%\' LIMIT 1 FOR UPDATE',[co,String(incoming.addon.yyds)]);
  55. if(repaired){out.conflicts.push({generalId:gid,reason:'同预约已有核实补录课次,保留补录并人工核对恢复的旧记录'});continue;}
  56. }
  57. if(cc&&(cc.teachingManaged||Number(cc.status)===-2||!legacy(cc))){out.conflicts.push({generalId:gid,reason:'新系统课次已受保护'});continue;}
  58. let item=cc?Number(cc.itemId):Number(incoming.addon?.id||gid);
  59. let aa=(await t.oneOrNone('SELECT to_jsonb(a) data FROM '+q(s.className)+' a WHERE company=$1 AND id=$2 FOR UPDATE',[co,item]))?.data;
  60. if(cc&&aa)continue;
  61. const sourceKey='legacy:model:'+m+':general:'+gid;
  62. if(!cc&&aa){item=900000000000+gid*100+m;aa=(await t.oneOrNone('SELECT to_jsonb(a) data FROM '+q(s.className)+' a WHERE company=$1 AND id=$2 FOR UPDATE',[co,item]))?.data;if(aa){out.conflicts.push({generalId:gid,reason:'附表编号冲突'});continue;}}
  63. const orphan=await t.oneOrNone('SELECT to_jsonb(a) data FROM '+q(s.className)+' a WHERE company=$1 AND "sourceKey"=$2 FOR UPDATE',[co,sourceKey]);
  64. if(orphan){out.conflicts.push({generalId:gid,reason:'已有同源孤立附表,保留待核对'});continue;}
  65. const now=new Date().toISOString(),common={...incoming.common,company:co,sourceKey,generalId:gid,itemId:item,modelId:m,createdAt:now,updatedAt:now},addon={...incoming.addon,company:co,sourceKey,id:item,createdAt:now,updatedAt:now};
  66. if(!common.objectId||!addon.objectId)throw Error('Missing object IDs');
  67. if(m===60){
  68. const key=(await t.one('SELECT xiaoshu_review_key($1,$2,$3) key',[String(addon.yhid),String(addon.xxjlid),String(addon.kywrq).slice(0,10)])).key;
  69. const duplicate=key&&await t.oneOrNone('SELECT "objectId" FROM "MemoryPracticeRecord" WHERE company=$1 AND "rewardTaskKey"=$2 LIMIT 1',[co,key]);
  70. addon.rewardTaskKey=duplicate?null:key;addon.rewardDuplicate=Boolean(duplicate);if(duplicate)out.duplicates++;
  71. // Same bounded historical-import semantics used on 2026-10-08. Only this transaction and this allowlisted table; restore triggers before recording historical zero-amount evidence.
  72. await t.none("SET LOCAL session_replication_role='replica'");
  73. await insert(s.className,addon,s.addonColumns);await t.none("SET LOCAL session_replication_role='origin'");
  74. if(String(addon.fxzt)==='1'){await t.any('SELECT xiaoshu_record_review_reward(m,true) FROM "MemoryPracticeRecord" m WHERE m.company=$1 AND m."objectId"=$2',[co,addon.objectId]);out.rewardEvidence++;}
  75. }else await insert(s.className,addon,s.addonColumns);
  76. out.createdAddon++;
  77. if(!cc){await insert('CommonModel',common,s.commonColumns);out.createdCommon++;}
  78. }else{
  79. if(!cc){out.conflicts.push({generalId:gid,reason:'主记录不存在'});continue;}
  80. const aa=(await t.oneOrNone('SELECT to_jsonb(a) data FROM '+q(s.className)+' a WHERE company=$1 AND id=$2 FOR UPDATE',[co,cc.itemId]))?.data;
  81. if(!aa||cc.objectId!==incoming.commonId||aa.objectId!==incoming.addonId||!sameVersion(cc.updatedAt,incoming.commonVersion)||!sameVersion(aa.updatedAt,incoming.addonVersion)||!(await directUnchanged(t,co,m,gid,cc,aa,unchanged))){
  82. out.conflicts.push({generalId:gid,reason:'新系统已有修改、版本变化或来源不可确认'});continue;
  83. }
  84. if(m===2||m===52||cc.teachingManaged||aa.teachingManaged||m===54&&(Number(cc.status)===-2||aa.bindingId||aa.creditHoldStatus||aa.courseCategoryKey)||m===58&&aa.enrollmentStatus==='active'){out.conflicts.push({generalId:gid,reason:'保留新系统课程内容或教学凭据'});continue;}
  85. const fields=Object.keys(incoming.values||{});if(!fields.length||fields.some(f=>!s.fields.includes(f)))throw Error('Invalid patch fields');
  86. if(m===60){
  87. const applied=(await t.one('SELECT xs_legacy_review_patch($1,$2,$3::jsonb,$4::jsonb) result',[co,aa.objectId,JSON.stringify(incoming.values),JSON.stringify(aa)])).result;
  88. if(!applied.applied){out.conflicts.push({generalId:gid,reason:applied.reason});continue;}
  89. }else await t.none('UPDATE '+q(s.className)+' a SET '+fields.map(f=>q(f)+'=v.'+q(f)).join(',')+',"updatedAt"=now() FROM jsonb_populate_record(NULL::'+q(s.className)+',$3::jsonb) v WHERE a.company=$1 AND a."objectId"=$2',[co,aa.objectId,JSON.stringify(incoming.values)]);
  90. out.updated++;
  91. }
  92. const after=await t.oneOrNone(readSql,[co,m,[gid]]);if(!after?.common||!after.addon)throw Error('Atomic projection verification failed');
  93. if(m===54){
  94. const kept=await directMatchingNativeBooking(t,co,after.common,after.addon);
  95. if(kept){
  96. // Keep both source IDs for reconciliation; only the native slot is bookable.
  97. after.common=(await t.one('UPDATE "CommonModel" c SET status=-2,"updatedAt"=now() WHERE company=$1 AND "objectId"=$2 RETURNING to_jsonb(c) AS data',[co,after.common.objectId])).data;
  98. out.duplicates++;
  99. out.conflicts.push({generalId:gid,reason:'与新系统预约 '+kept.id+' 重复,保留新系统时长'});
  100. }
  101. }
  102. if(m===60&&p.action==='append')await t.one('SELECT xs_legacy_review_track($1,$2)',[co,after.addon.objectId]);
  103. if(p.action==='patch'){const expected=(await t.one('SELECT to_jsonb(v) expected FROM jsonb_populate_record(NULL::'+q(s.className)+',$1::jsonb) v',[JSON.stringify(incoming.values)])).expected;if(Object.keys(incoming.values).some(f=>JSON.stringify(expected[f])!==JSON.stringify(after.addon[f])))throw Error('Post-write field verification failed');}
  104. if(m===60&&after.reward&&!(Number(after.reward.amount)===0&&['historical','exception'].includes(after.reward.status)))throw Error('Historical reward verification failed');
  105. await directBaseline(t,co,m,gid,after);
  106. out.postimages.push(after);
  107. }
  108. if(!/^[A-Za-z0-9:._-]{1,160}$/.test(p.batchKey||''))throw Error('Invalid batch key');
  109. await t.none('INSERT INTO "LegacyDirectBatch" (company,"runId",key,fingerprint,result) VALUES($1,$2,$3,$4,$5::jsonb)',[co,p.runId,p.batchKey,fingerprint,JSON.stringify(out)]);
  110. return out;
  111. });
  112. return response.json({success:true,data:result});
  113. }catch(e){return response.status(500).json({success:false,message:String(e.message||e)});}
  114. }