Forráskód Böngészése

Match course 398 writing stage and rules during legacy sync

彭峰 1 órája
szülő
commit
aca2f0e37e

+ 5 - 2
scripts/cloud/legacy-appointment-deletions.js

@@ -70,14 +70,17 @@ async function handler(request,response) {
     const c=(await db.oneOrNone('SELECT to_jsonb(c) AS data FROM "CommonModel" c WHERE company=$1 AND "objectId"=$2 FOR UPDATE',[co,row.common.objectId]))?.data;
     if(!c||Number(c.status)===-2)continue;
     const a=(await db.oneOrNone('SELECT to_jsonb(a) AS data FROM "CourseAppointment" a WHERE company=$1 AND id=$2 FOR UPDATE',[co,c.itemId]))?.data;
+    const syncWriting=hasSyncWritingPlan(a);
     let reason='';
     if(!a||!appointmentDeletionImported(c)||!appointmentDeletionImported(a))reason='来源或主附表不完整';
     else if(JSON.stringify(c)!==JSON.stringify(row.common)||JSON.stringify(a)!==JSON.stringify(row.addon))reason='核对期间新系统已有修改';
-    else if(c.teachingManaged||a.teachingManaged||a.bindingId||a.creditHoldStatus||a.courseCategoryKey||a.payStatus||Number(a.dszt||0)!==0)reason='保留新系统排课、课时预留、上课或计薪凭据';
+    else if(c.teachingManaged||a.teachingManaged||a.bindingId||a.creditHoldStatus||a.courseCategoryKey&&!syncWriting||a.payStatus||Number(a.dszt||0)!==0||
+        (syncWriting&&(a.creditCostsSnapshot?.length||a.teacherPaySnapshot!=null||
+          await syncWritingHasTeachingEvidence(db,co,c,a))))reason='保留新系统排课、课时预留、上课或计薪凭据';
     else if(await db.oneOrNone('SELECT "objectId" FROM "LessonRecord" WHERE company=$1 AND yyds::text=ANY($2::text[]) LIMIT 1',[co,[String(gid),String(a.id)]]))reason='已有上课记录';
     else {
      const baseline=await db.oneOrNone('SELECT fingerprint=md5($4::jsonb::text) AS matches FROM "LegacyDirectBaseline" WHERE company=$1 AND model=$2 AND gid=$3',[co,54,gid,JSON.stringify([c,a])]);
-     if(baseline?!baseline.matches:!appointmentDeletionUnmodified(c)||!appointmentDeletionUnmodified(a))reason='保留新系统已修改的课次';
+     if(baseline?!baseline.matches:syncWriting||!appointmentDeletionUnmodified(c)||!appointmentDeletionUnmodified(a))reason='保留新系统已修改的课次';
     }
     if(reason){if(!p.dryRun)await appointmentDeletionConflict(db,co,gid,reason);out.conflicts++;continue;}
     if(p.dryRun){out.wouldCancel++;continue;}

+ 2 - 1
scripts/cloud/legacy-appointment.js

@@ -61,7 +61,8 @@ async function confirmLegacyWritingStage(db,order,current) {
     FROM "CommonModel" c JOIN "CourseAppointment" a ON a.company=c.company AND a.id=c."itemId"
     WHERE c.company=$1 AND c."modelId"=54 AND c.status=99 AND a.szyh::text=$2
     AND a."courseCategoryKey" IN ('primary_writing','middle_writing','high_writing')
-    AND length(trim(COALESCE(a."categoryEvidence",'')))>=2 AND a."categoryEvidence" NOT LIKE '开课自动核对:%'`,[co,String(row.studentId)]);
+    AND length(trim(COALESCE(a."categoryEvidence",'')))>=2
+    AND a."categoryEvidence" NOT LIKE '开课自动核对:%' AND a."categoryEvidence" NOT LIKE '同步自动核对:%'`,[co,String(row.studentId)]);
   const today=appOverviewToday();
   const trusted=legacyWritingStageAssessment({studentId:row.studentId,startsAt:row.startsAt},prior,today);
   if(!trusted.canAutoConfirm)throw Error('缺少一致的本学年已确认写作课记录,请由管理员核对学段');

+ 23 - 6
scripts/cloud/legacy-direct-sync.js

@@ -1,7 +1,7 @@
 // Called under the same tenant credit lock as scheduling and cancellation.
-async function directMatchingNativeBooking(db,co,common,old){
+async function directMatchingNativeBooking(db,co,common,old,syncWriting=false){
  if(Number(common.status)!==99||old.dszt!=='0'||old.teachingManaged||common.teachingManaged||
-    old.bindingId||old.courseCategoryKey||old.creditHoldStatus||old.creditCostsSnapshot?.length||old.teacherPaySnapshot!=null||
+    old.bindingId||old.creditHoldStatus||(!syncWriting&&old.courseCategoryKey)||old.creditCostsSnapshot?.length||old.teacherPaySnapshot!=null||
     old.kssj||old.jssj||![old.szyh,old.pl,old.kcid].every(id=>/^[1-9]\d*$/.test(id))||
     (old.yykcid&&old.yykcid!==old.kcid))return null;
  // The operator identified member 252 in this tenant as a test account.
@@ -48,6 +48,7 @@ try{
   for(const incoming of p.rows){
    const gid=Number(incoming.generalId);if(!Number.isSafeInteger(gid)||gid<1)throw Error('Invalid incoming ID');
    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;
+   let syncWriting=false,replaceWritingPlan=false;
    if(p.action==='append'){
     // A repaired historical class already represents this appointment, even if the old source later gains a different generalId.
     if(m===59&&incoming.addon?.yyds&&String(incoming.addon.yyds)!=='0'){
@@ -78,11 +79,19 @@ try{
    }else{
     if(!cc){out.conflicts.push({generalId:gid,reason:'主记录不存在'});continue;}
     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;
-    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))){
+    syncWriting=m===54&&hasSyncWritingPlan(aa);
+    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,syncWriting?()=>false:unchanged))){
      out.conflicts.push({generalId:gid,reason:'新系统已有修改、版本变化或来源不可确认'});continue;
     }
-    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;}
-    const fields=Object.keys(incoming.values||{});if(!fields.length||fields.some(f=>!s.fields.includes(f)))throw Error('Invalid patch fields');
+    const fields=Object.keys(incoming.values||{});
+    replaceWritingPlan=syncWriting&&fields.some(field=>syncWritingScheduleFields.includes(field));
+    const protectedAppointment=m===54&&(Number(cc.status)===-2||aa.bindingId||aa.creditHoldStatus||
+      (aa.courseCategoryKey&&!syncWriting)||(syncWriting&&(aa.payStatus||aa.creditCostsSnapshot?.length||aa.teacherPaySnapshot!=null||
+        (replaceWritingPlan&&aa.dszt!=='0')||await syncWritingHasTeachingEvidence(t,co,cc,aa))));
+    if(m===2||m===52||cc.teachingManaged||aa.teachingManaged||protectedAppointment||m===58&&aa.enrollmentStatus==='active'){
+     out.conflicts.push({generalId:gid,reason:'保留新系统课程内容或教学凭据'});continue;
+    }
+    if(!fields.length||fields.some(f=>!s.fields.includes(f)))throw Error('Invalid patch fields');
     if(m===60){
      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;
      if(!applied.applied){out.conflicts.push({generalId:gid,reason:applied.reason});continue;}
@@ -91,13 +100,21 @@ try{
    }
    const after=await t.oneOrNone(readSql,[co,m,[gid]]);if(!after?.common||!after.addon)throw Error('Atomic projection verification failed');
    if(m===54){
-    const kept=await directMatchingNativeBooking(t,co,after.common,after.addon);
+    const kept=await directMatchingNativeBooking(t,co,after.common,after.addon,syncWriting);
     if(kept){
      // Keep both source IDs for reconciliation; only the native slot is bookable.
      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;
      out.duplicates++;
      out.conflicts.push({generalId:gid,reason:'与新系统预约 '+kept.id+' 重复,保留新系统时长'});
     }
+    const appointment=after.addon;
+    const newWriting=p.action==='append'&&!cc&&appointment.kcid==='398'&&appointment.dszt==='0'&&!appointment.courseCategoryKey&&
+     !appointment.categoryEvidence&&!appointment.bindingId&&!appointment.creditHoldStatus&&!appointment.payStatus&&
+     !appointment.teachingRuleId&&!appointment.durationMinutes&&!appointment.deliveryMode&&
+     appointment.teacherPaySnapshot==null&&!appointment.creditCostsSnapshot?.length;
+    if(!kept&&(replaceWritingPlan||newWriting&&!await syncWritingHasTeachingEvidence(t,co,after.common,appointment))){
+     await updateSyncedWritingPlan(t,co,u.id,after,replaceWritingPlan);
+    }
    }
    if(m===60&&p.action==='append')await t.one('SELECT xs_legacy_review_track($1,$2)',[co,after.addon.objectId]);
    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');}

+ 22 - 0
scripts/cloud/legacy-writing-sync-ownership.js

@@ -0,0 +1,22 @@
+const syncWritingEvidencePrefix = '同步自动核对:';
+
+function hasSyncWritingPlan(appointment) {
+  return appointment?.kcid === '398' &&
+    ['primary_writing', 'middle_writing', 'high_writing'].includes(appointment.courseCategoryKey) &&
+    String(appointment.categoryEvidence || '').startsWith(syncWritingEvidencePrefix);
+}
+
+async function syncWritingHasTeachingEvidence(db, companyId, common, appointment) {
+  return Boolean(await db.oneOrNone(`
+    SELECT 1 WHERE EXISTS (
+      SELECT 1 FROM "CourseCreditReservation" WHERE company=$1 AND "appointmentId"=$2
+    ) OR EXISTS (
+      SELECT 1 FROM "LessonRecord" WHERE company=$1 AND yyds::text=ANY($3::text[])
+    ) OR EXISTS (
+      SELECT 1 FROM "LessonRecordFact" WHERE company=$1 AND yyds::text=ANY($3::text[])
+    ) OR EXISTS (
+      SELECT 1 FROM "LessonCompletionReport" WHERE company=$1
+        AND ("appointmentId"=$2 OR "appointmentGeneralId"::text=ANY($3::text[]))
+    )
+  `, [companyId, common.objectId, [String(common.generalId), String(appointment.id)]]));
+}

+ 102 - 0
scripts/cloud/legacy-writing-sync.js

@@ -0,0 +1,102 @@
+const syncWritingScheduleFields = ['szyh', 'kcid', 'yykcid', 'dslx', 'jffs', 'bxrq', 'yysj', 'sdsd'];
+
+async function planSyncedWriting(db, companyId, common, appointment) {
+  const today = new Date().toLocaleDateString('sv-SE', {timeZone: 'Asia/Shanghai'});
+  const startsAt = String(appointment.yysj || '').trim();
+  const date = startsAt.slice(0, 10);
+  if (Number(common.status) !== 99 || appointment.kcid !== '398' || appointment.yykcid !== '398' ||
+      appointment.dszt !== '0' || appointment.kssj || appointment.jssj || date < today ||
+      (appointment.bxrq && appointment.bxrq !== date) ||
+      !/^[1-9]\d*$/.test(appointment.szyh) || !['1', '2'].includes(appointment.dslx)) return null;
+
+  const profiles = await db.any(`
+    SELECT to_jsonb(u)->>'grade' AS grade, u."legacyUserData"->>'Position' AS position,
+      u."legacyUserData"->'UserBase'->>'Position' AS "basePosition",
+      u."legacyUserData"->>'HoneyName' AS "oldName", u."legacyUserData"->>'UserName' AS "oldUsername",
+      to_jsonb(u)->>'realName' AS "realName", to_jsonb(u)->>'nickname' AS nickname, u.username
+    FROM "_User" u
+    WHERE u.company=$1 AND u."legacyUserId"=$2::numeric AND u."legacyGroupId"=1
+      AND NOT COALESCE(u."isDeleted",false) AND NOT COALESCE(u."isDisabled",false)
+    LIMIT 2 FOR SHARE OF u
+  `, [companyId, appointment.szyh]);
+  if (profiles.length !== 1) return null;
+
+  const confirmed = await db.any(`
+    SELECT c."generalId" AS "appointmentGeneralId", a.szyh AS "studentId", a.yysj AS "startsAt",
+      a."courseCategoryKey" AS category, a."categoryEvidence" AS evidence
+    FROM "CourseAppointment" a
+    JOIN "CommonModel" c ON c.company=a.company AND c."modelId"=54 AND c."itemId"=a.id
+    WHERE a.company=$1 AND a.szyh=$2 AND c.status=99 AND c."objectId"<>$3
+      AND a."courseCategoryKey" IN ('primary_writing','middle_writing','high_writing')
+      AND length(trim(COALESCE(a."categoryEvidence",'')))>=2
+      AND a."categoryEvidence" NOT LIKE '开课自动核对:%' AND a."categoryEvidence" NOT LIKE $4
+    ORDER BY a.yysj DESC,c."generalId" DESC
+  `, [companyId, appointment.szyh, common.objectId, syncWritingEvidencePrefix + '%']);
+  const identity = {studentId: appointment.szyh, startsAt};
+  const trusted = legacyWritingStageAssessment(identity, confirmed, today);
+  const stage = legacyWritingStageAssessment({...profiles[0], ...identity, studentName: common.title}, confirmed, today);
+  if (!trusted.canAutoConfirm || !stage.canAutoConfirm) return null;
+
+  const category = stage.suggestedCategoryKey;
+  const duration = appointment.dslx === '1' ? 30 : 60;
+  const mode = /offline|线下|到店|面授/.test(appointment.jffs || '') ? 'offline' : 'online';
+  // As in the payroll rules, only the latest revision of each effective date can apply.
+  const rule = await db.oneOrNone(`
+    WITH stored AS (
+      SELECT DISTINCT ON (r."effectiveFrom") r.*
+      FROM "TeachingCompensationRule" r WHERE r.company=$1 AND r."categoryKey"=$2
+        AND r."durationMinutes"=$3 AND r."deliveryMode"=$4 AND r."effectiveFrom"<=$5
+      ORDER BY r."effectiveFrom",r.revision DESC,r."createdAt" DESC,r."objectId"
+    ), candidates AS (
+      SELECT to_jsonb(r)||jsonb_build_object('isDefault',false) AS rule
+      FROM stored r
+      UNION ALL
+      SELECT seed FROM jsonb_array_elements($6::jsonb) seed
+      WHERE seed->>'categoryKey'=$2 AND (seed->>'durationMinutes')::numeric=$3
+        AND seed->>'deliveryMode'=$4 AND seed->>'effectiveFrom'<=$5
+        AND NOT EXISTS (SELECT 1 FROM stored r WHERE r."effectiveFrom"=seed->>'effectiveFrom')
+    )
+    SELECT rule FROM candidates
+    WHERE COALESCE((rule->>'active')::boolean,true)
+      AND NOT EXISTS (SELECT 1 FROM "TeachingCourseCategory" tc WHERE tc.company=$1 AND tc.key=$2 AND tc.active=false)
+    ORDER BY rule->>'effectiveFrom' DESC
+    LIMIT 1
+  `, [companyId, category, duration, mode, date, JSON.stringify(legacyAppointmentSeedRules())]);
+  const price = rule?.rule;
+  const costs = price?.creditCosts;
+  if (price?.teacherPay == null || !Number.isFinite(Number(price.teacherPay)) || Number(price.teacherPay) < 0 ||
+      !price.objectId || !Array.isArray(costs) || !costs.length) return null;
+  if (costs.some(cost => !['Purse', 'SilverCoin', 'UserExp', 'UserPoint'].includes(cost?.account) ||
+      !Number.isFinite(Number(cost.amount)) || Number(cost.amount) <= 0) ||
+      new Set(costs.map(cost => cost.account)).size !== costs.length) return null;
+  return {
+    courseCategoryKey: category,
+    courseCategoryName: {
+      primary_writing: '小学语法写作课', middle_writing: '中学语法写作课', high_writing: '高中语法写作课'
+    }[category],
+    categoryEvidence: syncWritingEvidencePrefix + stage.evidence,
+    teachingRuleId: price.objectId,
+    durationMinutes: duration,
+    deliveryMode: mode
+  };
+}
+
+async function updateSyncedWritingPlan(db, companyId, actorId, row, replacesPriorPlan) {
+  const plan = await planSyncedWriting(db, companyId, row.common, row.addon);
+  if (!plan && !replacesPriorPlan) return;
+  const previous = row.addon;
+  row.addon = (await db.one(`
+    UPDATE "CourseAppointment" a SET
+      "courseCategoryKey"=v."courseCategoryKey", "courseCategoryName"=v."courseCategoryName",
+      "categoryEvidence"=v."categoryEvidence", "teachingRuleId"=v."teachingRuleId",
+      "durationMinutes"=v."durationMinutes", "deliveryMode"=v."deliveryMode",
+      "updatedAt"=GREATEST(a."createdAt",a."updatedAt",clock_timestamp())
+    FROM jsonb_populate_record(NULL::"CourseAppointment",$3::jsonb) v
+    WHERE a.company=$1 AND a."objectId"=$2 RETURNING to_jsonb(a) AS data
+  `, [companyId, previous.objectId, JSON.stringify(plan || {})])).data;
+  await db.one('SELECT xs_payroll_audit($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb)', [
+    companyId, actorId, 'sync-writing-appointment-plan', row.common.objectId,
+    plan ? '按同学年已确认记录核对写作学段和计费规则' : '旧预约变化后重新核对写作学段和计费规则',
+    JSON.stringify(previous), JSON.stringify(row.addon)
+  ]);
+}

+ 1 - 1
scripts/cloud/payroll-integrity.js

@@ -181,7 +181,7 @@ function writingStageAssessment(row,confirmed,asOf=businessDate()){
  const stage=stages[0],evidence=[...new Set(sources.map(s=>s.evidence))].slice(0,3).join(';');
  return{canAutoConfirm:true,suggestedCategoryKey:stage+'_writing',evidence,assessmentReason:'系统证据一致:'+labels[stage]};
 }
-async function writingMappingPage(context,input){const co=payrollTenant(context,input),month=text(input.month);if(month&&!/^\d{4}-(0[1-9]|1[0-2])$/.test(month))fail(400,'工资月份无效');const rows=await Psql.query(`SELECT c."objectId" AS "appointmentId",c."generalId" AS "appointmentGeneralId",c."title" AS "studentName",c."subtitle" AS "courseName",a."szyh" AS "studentId",a."yysj" AS "startsAt",a."updatedAt",a."courseCategoryKey" AS "categoryKey",a."categoryEvidence" AS evidence,to_jsonb(u)->>'grade' AS grade,u."legacyUserData"->>'Position' AS position,u."legacyUserData"->'UserBase'->>'Position' AS "basePosition",u."legacyUserData"->>'HoneyName' AS "oldName",u."legacyUserData"->>'UserName' AS "oldUsername",u."realName",u."nickname",u."username" FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company"=c."company" AND a."id"::text=c."itemId"::text LEFT JOIN "_User" u ON u."company"=c."company" AND u."legacyUserId"::text=a."szyh"::text WHERE c."company"=$1 AND c."modelId"=54 AND c."status"<>-2 AND c."subtitle" ~ '阅读|写作|语法|作文|强化' AND (a."dszt" IN ('0','10') OR ($2<>'' AND c."generalId"::text IN (SELECT source->>'yyds' FROM xs_payroll_sources($1) source WHERE to_char(xs_payroll_time(source->>'lessonAt') AT TIME ZONE 'Asia/Shanghai','YYYY-MM')=$2))) AND NOT (COALESCE(a."courseCategoryKey",'') IN ('primary_writing','middle_writing','high_writing') AND length(trim(COALESCE(a."categoryEvidence",'')))>=2) ORDER BY a."yysj",c."objectId"`,[co,month]);
+async function writingMappingPage(context,input){const co=payrollTenant(context,input),month=text(input.month);if(month&&!/^\d{4}-(0[1-9]|1[0-2])$/.test(month))fail(400,'工资月份无效');const rows=await Psql.query(`SELECT c."objectId" AS "appointmentId",c."generalId" AS "appointmentGeneralId",c."title" AS "studentName",c."subtitle" AS "courseName",a."szyh" AS "studentId",a."yysj" AS "startsAt",a."updatedAt",a."courseCategoryKey" AS "categoryKey",a."categoryEvidence" AS evidence,to_jsonb(u)->>'grade' AS grade,u."legacyUserData"->>'Position' AS position,u."legacyUserData"->'UserBase'->>'Position' AS "basePosition",u."legacyUserData"->>'HoneyName' AS "oldName",u."legacyUserData"->>'UserName' AS "oldUsername",u."realName",u."nickname",u."username" FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company"=c."company" AND a."id"::text=c."itemId"::text LEFT JOIN "_User" u ON u."company"=c."company" AND u."legacyUserId"::text=a."szyh"::text WHERE c."company"=$1 AND c."modelId"=54 AND c."status"<>-2 AND (a."kcid"::text='398' OR c."subtitle" ~ '阅读|写作|语法|作文|强化') AND (a."dszt" IN ('0','10') OR ($2<>'' AND c."generalId"::text IN (SELECT source->>'yyds' FROM xs_payroll_sources($1) source WHERE to_char(xs_payroll_time(source->>'lessonAt') AT TIME ZONE 'Asia/Shanghai','YYYY-MM')=$2))) AND NOT (COALESCE(a."courseCategoryKey",'') IN ('primary_writing','middle_writing','high_writing') AND length(trim(COALESCE(a."categoryEvidence",'')))>=2) ORDER BY a."yysj",c."objectId"`,[co,month]);
  const ids=[...new Set(rows.map(r=>text(r.studentId)))],confirmed=ids.length?await Psql.query(`SELECT c."generalId" AS "appointmentGeneralId",a."szyh" AS "studentId",a."yysj" AS "startsAt",a."courseCategoryKey" AS category,a."categoryEvidence" AS evidence FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company"=c."company" AND a."id"::text=c."itemId"::text WHERE c."company"=$1 AND c."modelId"=54 AND c."status"<>-2 AND a."szyh"::text=ANY($2::text[]) AND a."courseCategoryKey" IN ('primary_writing','middle_writing','high_writing') AND length(trim(COALESCE(a."categoryEvidence",'')))>=2`,[co,ids]):[];
  return{items:rows.map(r=>{const decision=writingStageAssessment(r,confirmed);return{...r,...decision,grade:r.grade||r.position||r.basePosition||'',evidence:r.evidence||decision.evidence,categoryKey:r.categoryKey||decision.suggestedCategoryKey,studentName:r.studentName||r.nickname};})};}
 async function writingMappingCommit(context,input,payload){requireRole(context,['ops-manager']);return(await payrollSql('SELECT xs_payroll_writing_mapping($1,$2,$3,$4,$5,$6::timestamptz,$7) AS result',[payrollTenant(context,input),context.current.id,input.targetId,text(payload.categoryKey),text(payload.evidence),dateIso(input.expectedUpdatedAt)||null,reasonOf(input)])).result;}

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 0 - 0
scripts/deploy-admin-functions.mjs


+ 2 - 1
scripts/lib/legacy-appointment-deletions.mjs

@@ -1,6 +1,7 @@
 import {readFileSync} from 'node:fs';
 export function buildAppointmentDeletionGateway(company,windows=[]){
- const code=readFileSync(new URL('../cloud/legacy-appointment-deletions.js',import.meta.url),'utf8').replaceAll('__COMPANY_ID__',JSON.stringify(company)).replaceAll('__WINDOWS__',JSON.stringify(windows));
+ const read=name=>readFileSync(new URL('../cloud/'+name+'.js',import.meta.url),'utf8');
+ const code=(read('legacy-writing-sync-ownership')+'\n'+read('legacy-appointment-deletions')).replaceAll('__COMPANY_ID__',JSON.stringify(company)).replaceAll('__WINDOWS__',JSON.stringify(windows));
  new Function(code);return code;
 }
 export function patchAppointmentDeletionCapability(code){

+ 8 - 1
scripts/lib/legacy-direct-bundle.mjs

@@ -2,6 +2,7 @@ import {readFileSync} from 'node:fs';
 import {specs} from './legacy-direct-specs.mjs';
 import {legacyAddonFields} from './legacy-direct-projection.mjs';
 import {withXiaoshuRuntime} from './xiaoshu-runtime-compat.mjs';
+import {legacyAppointmentDefaults,legacyWritingStageSupport} from '../legacy-appointment-transform.mjs';
 export function buildDirectBundle(columns,windows=[],company='7pIbDBJmKx') {
  const definitions=structuredClone(specs);
  for(const [m,s] of Object.entries(definitions)){
@@ -13,5 +14,11 @@ export function buildDirectBundle(columns,windows=[],company='7pIbDBJmKx') {
  const userSource=readFileSync(new URL('../backfill-legacy-users.mjs',import.meta.url),'utf8');
  const userProjection=userSource.slice(userSource.indexOf('function text(value)'),userSource.indexOf('function requestGroups('));
  const prefix='const company={__type:"Pointer",className:"Company",objectId:'+JSON.stringify(company)+'};\n'+userProjection;
- return withXiaoshuRuntime((prefix+['legacy-finance','legacy-direct-supplement','legacy-direct-control','legacy-direct-sync'].map(n=>readFileSync(new URL('../cloud/'+n+'.js',import.meta.url),'utf8')).join('\n')).replaceAll('__SPECS__',JSON.stringify(definitions)).replaceAll('__WINDOWS__',JSON.stringify(windows)).replaceAll('__COMPANY_ID__',JSON.stringify(company)));
+ const cloudSource=name=>readFileSync(new URL('../cloud/'+name+'.js',import.meta.url),'utf8');
+ const operations=readFileSync(new URL('../deploy-admin-functions.mjs',import.meta.url),'utf8')
+  .match(/const operationsGatewayCode = String.raw`([\s\S]*?)\n`;/)?.[1];
+ if(!operations)throw Error('Unexpected operations gateway definition');
+ const writingSupport=legacyAppointmentDefaults(operations)+legacyWritingStageSupport(cloudSource('payroll-integrity'));
+ const files=['legacy-finance','legacy-direct-supplement','legacy-direct-control','legacy-writing-sync-ownership','legacy-writing-sync','legacy-direct-sync'];
+ return withXiaoshuRuntime((prefix+writingSupport+files.map(cloudSource).join('\n')).replaceAll('__SPECS__',JSON.stringify(definitions)).replaceAll('__WINDOWS__',JSON.stringify(windows)).replaceAll('__COMPANY_ID__',JSON.stringify(company)));
 }

+ 16 - 7
scripts/sql/legacy-appointment-preparation.sql

@@ -3,8 +3,8 @@
 CREATE OR REPLACE FUNCTION xs_prepare_legacy_appointment(co text,aid text,actor text,seed_rules jsonb) RETURNS jsonb LANGUAGE plpgsql AS $$
 DECLARE c "CommonModel";a "CourseAppointment";b "CourseBinding";u "_User";op "_User";
  category text;category_name text;course text;day date;minutes numeric;mode text;rule jsonb;costs jsonb;cost jsonb;
- selected_binding text;
- notes_legacy boolean=false;legacy_trial boolean=false;existing "CourseCreditReservation";before_data jsonb;changed boolean=false;
+ selected_binding text;prepared_rule_id text;
+ notes_legacy boolean=false;legacy_trial boolean=false;sync_quote boolean=false;existing "CourseCreditReservation";before_data jsonb;changed boolean=false;
 BEGIN
  PERFORM pg_advisory_xact_lock(hashtext('xs-credit:'||co));
  SELECT * INTO op FROM "_User" WHERE company=co AND "objectId"=actor;
@@ -83,15 +83,24 @@ BEGIN
  IF EXISTS(SELECT 1 FROM "TeachingCourseCategory" tc WHERE tc.company=co AND tc.key=category AND tc.active=false) THEN RAISE EXCEPTION '该课程分类已停用';END IF;
  minutes=COALESCE(a."durationMinutes",CASE a.dslx WHEN '1' THEN 30 ELSE 60 END);
  mode=CASE WHEN COALESCE(NULLIF(a."deliveryMode",''),a.jffs,'') ~ 'offline|线下|到店|面授' THEN 'offline' ELSE 'online' END;
+ sync_quote=notes_legacy AND COALESCE(a."categoryEvidence",'') LIKE '同步自动核对:%' AND a."teacherPaySnapshot" IS NULL
+  AND COALESCE(jsonb_array_length(a."creditCostsSnapshot"::jsonb),0)=0;
  -- Stored versions suppress the corresponding defaults even when disabled.
- WITH candidates AS (
- SELECT to_jsonb(r)||jsonb_build_object('isDefault',false) AS r FROM "TeachingCompensationRule" r WHERE r.company=co
+ WITH stored AS (
+ SELECT to_jsonb(r)||jsonb_build_object('isDefault',false) AS data,
+  row_number() OVER(PARTITION BY r."effectiveFrom" ORDER BY r.revision DESC,(to_jsonb(r)->>'createdAt') DESC NULLS LAST,r."objectId") AS rank
+ FROM "TeachingCompensationRule" r WHERE r.company=co AND r."categoryKey"=category
+  AND r."durationMinutes"=minutes AND r."deliveryMode"=mode
+ ), candidates AS (
+ SELECT data AS r FROM stored WHERE NOT sync_quote OR rank=1
  UNION ALL SELECT s||jsonb_build_object('isDefault',true) FROM jsonb_array_elements(seed_rules) s WHERE NOT EXISTS(
- SELECT 1 FROM "TeachingCompensationRule" r WHERE r.company=co AND r."categoryKey"=s->>'categoryKey' AND r."durationMinutes"=(s->>'durationMinutes')::numeric AND r."deliveryMode"=s->>'deliveryMode' AND r."effectiveFrom"=s->>'effectiveFrom'))
+ SELECT 1 FROM stored WHERE data->>'effectiveFrom'=s->>'effectiveFrom' AND s->>'categoryKey'=category
+  AND (s->>'durationMinutes')::numeric=minutes AND s->>'deliveryMode'=mode))
  SELECT r INTO rule FROM candidates WHERE COALESCE((r->>'active')::boolean,true) AND r->>'categoryKey'=category AND (r->>'durationMinutes')::numeric=minutes AND r->>'deliveryMode'=mode AND r->>'effectiveFrom'<=day::text ORDER BY r->>'effectiveFrom' DESC,(r->>'isDefault')::boolean,(r->>'revision')::numeric DESC NULLS LAST LIMIT 1;
  costs=COALESCE(a."creditCostsSnapshot"::jsonb,'[]');
  IF jsonb_array_length(costs)=0 THEN costs=rule->'creditCosts';END IF;
  IF rule IS NULL OR costs IS NULL OR jsonb_array_length(costs)=0 THEN RAISE EXCEPTION '缺少适用的工资与课时规则';END IF;
+ prepared_rule_id=CASE WHEN sync_quote THEN rule->>'objectId' ELSE COALESCE(NULLIF(a."teachingRuleId",''),rule->>'objectId') END;
  IF (SELECT count(*)<>count(DISTINCT value->>'account') FROM jsonb_array_elements(costs)) THEN RAISE EXCEPTION '课时凭据含重复账户,请管理员核实';END IF;
  IF NULLIF(a."creditHoldStatus",'') IS NOT NULL AND a."creditHoldStatus" NOT IN ('ready','insufficient') THEN RAISE EXCEPTION '历史预约已标记待处理:%',a."creditHoldStatus";END IF;
  FOR cost IN SELECT value FROM jsonb_array_elements(costs) LOOP
@@ -110,11 +119,11 @@ BEGIN
  END IF;
  IF a."bindingId" IS DISTINCT FROM b."objectId" OR a.kcid::text IS DISTINCT FROM course OR a."courseCategoryKey" IS NULL OR a."teacherPaySnapshot" IS NULL OR COALESCE(jsonb_array_length(a."creditCostsSnapshot"::jsonb),0)=0 OR a."creditHoldStatus" IS DISTINCT FROM 'ready' THEN
   UPDATE "CourseAppointment" SET "bindingId"=b."objectId",kcid=course,"courseCategoryKey"=category,"courseCategoryName"=COALESCE(NULLIF("courseCategoryName",''),category_name),
-   "durationMinutes"=minutes,"deliveryMode"=mode,"teachingRuleId"=COALESCE(NULLIF("teachingRuleId",''),rule->>'objectId'),"teacherPaySnapshot"=COALESCE("teacherPaySnapshot",(rule->>'teacherPay')::numeric),
+   "durationMinutes"=minutes,"deliveryMode"=mode,"teachingRuleId"=prepared_rule_id,"teacherPaySnapshot"=COALESCE("teacherPaySnapshot",(rule->>'teacherPay')::numeric),
    "creditCostsSnapshot"=costs,"creditHoldStatus"='ready',"creditHoldReason"='',"updatedAt"=now() WHERE "objectId"=a."objectId";changed=true;
  END IF;
  IF existing."objectId" IS NULL THEN
-  PERFORM xs_insert('CourseCreditReservation',jsonb_build_object('objectId',xs_object_id(),'company',co,'createdAt',now(),'updatedAt',now(),'sourceKey','legacy-prepare:'||aid,'appointmentId',aid,'appointmentGeneralId',c."generalId",'studentId',u."legacyUserId",'ruleId',COALESCE(NULLIF(a."teachingRuleId",''),rule->>'objectId'),'creditCosts',costs,'state','reserved','reservedAt',now()));changed=true;
+  PERFORM xs_insert('CourseCreditReservation',jsonb_build_object('objectId',xs_object_id(),'company',co,'createdAt',now(),'updatedAt',now(),'sourceKey','legacy-prepare:'||aid,'appointmentId',aid,'appointmentGeneralId',c."generalId",'studentId',u."legacyUserId",'ruleId',prepared_rule_id,'creditCosts',costs,'state','reserved','reservedAt',now()));changed=true;
  END IF;
  IF changed THEN
   PERFORM xs_payroll_audit(co,actor,'prepare-legacy-appointment',aid,'核对旧预约的有效开课与课时凭据',jsonb_build_object('appointment',before_data,'binding',to_jsonb(b)),jsonb_build_object('bindingId',b."objectId",'creditCosts',costs,'courseId',course));

+ 3 - 1
scripts/sql/payroll-integrity.sql

@@ -251,6 +251,8 @@ BEGIN
   IF NOT FOUND OR c."status"=-2 THEN RAISE EXCEPTION '预约已取消或不存在,请重新核对';END IF;
   SELECT * INTO a FROM "CourseAppointment" WHERE "company"=co AND "id"::text=c."itemId"::text FOR UPDATE;
   IF a."updatedAt" IS DISTINCT FROM (item->>'expectedUpdatedAt')::timestamptz OR a."dszt" NOT IN ('0','10') THEN RAISE EXCEPTION '预约已更新,请重新核对';END IF;
+  IF a."dszt"='10' AND a."kcid"::text='398' AND COALESCE(a."categoryEvidence",'') LIKE '同步自动核对:%'
+   AND NOT COALESCE((to_jsonb(a)->>'teachingManaged')::boolean,false) THEN CONTINUE; END IF;
   IF a."dszt"='0' AND (xs_appointment_day(a."bxrq",a."yysj") IS NULL OR xs_appointment_day(a."bxrq",a."yysj")<(now() AT TIME ZONE 'Asia/Shanghai')::date) THEN RAISE EXCEPTION '预约已经到期,请重新核对';END IF;
   SELECT * INTO existing FROM "CourseCreditReservation" WHERE "company"=co AND "appointmentId"=c."objectId" AND "state" IN ('reserved','consumed') LIMIT 1;
   IF FOUND THEN CONTINUE;END IF;
@@ -309,7 +311,7 @@ BEGIN
  SELECT * INTO c FROM "CommonModel" WHERE "company"=co AND "objectId"=aid AND "modelId"=54 FOR UPDATE;
  SELECT * INTO a FROM "CourseAppointment" WHERE "company"=co AND "id"::text=c."itemId"::text FOR UPDATE;
  label:=CASE category WHEN 'primary_writing' THEN '小学语法写作课' WHEN 'middle_writing' THEN '中学语法写作课' WHEN 'high_writing' THEN '高中语法写作课' END;
- IF c."objectId" IS NULL OR a."objectId" IS NULL OR c."status"=-2 OR label IS NULL OR c."subtitle" !~ '阅读|写作|语法|作文|强化' OR length(trim(evidence))<2 THEN RAISE EXCEPTION '预约、语法写作分类或学段证据无效';END IF;
+ IF c."objectId" IS NULL OR a."objectId" IS NULL OR c."status"=-2 OR label IS NULL OR (a."kcid"::text IS DISTINCT FROM '398' AND NOT COALESCE(c."subtitle" ~ '阅读|写作|语法|作文|强化',false)) OR length(trim(evidence))<2 THEN RAISE EXCEPTION '预约、语法写作分类或学段证据无效';END IF;
  IF COALESCE(a."courseCategoryKey",'') IN ('primary_writing','middle_writing','high_writing') AND length(trim(COALESCE(a."categoryEvidence",'')))>=2 THEN
   IF a."courseCategoryKey"=category AND trim(a."categoryEvidence")=trim(evidence) THEN RETURN jsonb_build_object('updated',false,'alreadyConfirmed',true);END IF;
   RAISE EXCEPTION '该预约已由其他人确认,请刷新后核对';

+ 114 - 1
scripts/tests/direct-nightly-sync.test.mjs

@@ -22,12 +22,21 @@ async function call(params,role='super-admin',company='co'){
 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)');
+ 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);
@@ -321,3 +330,107 @@ test('旧预约换编号或改到新系统时段,原子保留新课与时长
  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);
+});

+ 22 - 2
scripts/tests/legacy-appointment-deletions.test.mjs

@@ -19,12 +19,16 @@ before(async()=>{
  await db.exec(readFileSync(new URL('../sql/legacy-direct-sync.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,status numeric,title text,"createdAt" timestamptz,"updatedAt" timestamptz,"teachingManaged" boolean);
  CREATE TABLE "CourseAppointment"("objectId" text PRIMARY KEY,company text,id numeric,"sourceKey" text,dszt text,pl text,"bindingId" text,"creditHoldStatus" text,"courseCategoryKey" text,"payStatus" text,"createdAt" timestamptz,"updatedAt" timestamptz,"teachingManaged" boolean);
+ ALTER TABLE "CourseAppointment" ADD kcid text, ADD "categoryEvidence" text;
+ CREATE TABLE "CourseCreditReservation"(company text,"appointmentId" text);
  CREATE TABLE "LessonRecord"("objectId" text,company text,yyds text);
+ CREATE TABLE "LessonRecordFact"(company text,yyds text);
+ CREATE TABLE "LessonCompletionReport"(company text,"appointmentId" text,"appointmentGeneralId" numeric);
  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);`);
 });
 after(()=>db.close());
 beforeEach(async()=>{
- await db.exec('TRUNCATE "CommonModel","CourseAppointment","LessonRecord","LegacySyncConflict","LegacyDirectBaseline","LegacyDirectBatch","LegacyDirectSourcePage"');
+ await db.exec('TRUNCATE "CommonModel","CourseAppointment","CourseCreditReservation","LessonRecord","LessonRecordFact","LessonCompletionReport","LegacySyncConflict","LegacyDirectBaseline","LegacyDirectBatch","LegacyDirectSourcePage"');
  liveIds=new Set([100]);fail=false;wrongFilter=false;canaryMissing=false;readHook=null;
  context={Psql,URLSearchParams,AbortSignal,Date,Parse:{Config:{get:async()=>({get:key=>({legacyScheduleApiUrl:'https://old.invalid/api',legacyScheduleApiId:'test',legacyScheduleApiKey:'test'}[key])})}},fetch:async url=>{
   const p=new URL(url).searchParams,requested=p.get('ids')?.split(',').map(Number);
@@ -45,7 +49,7 @@ async function call(params,role='super-admin',company='co'){
 async function seed(id,{source='legacy',status='0',managed=false,hold='',binding='',pay='',company='co'}={}){
  const sourceKey=source==='legacy'?'legacy:model:54:general:'+id:'cloud:appointment:'+id;
  await sql('INSERT INTO "CommonModel" VALUES($1,$2,$3,$4,$4,54,99,\'original\',\'2026-10-01\',\'2026-10-01\',$5)',['c'+id,company,sourceKey,id,managed]);
- await sql('INSERT INTO "CourseAppointment" VALUES($1,$2,$3,$4,$5,\'30\',$6,$7,\'\',$8,\'2026-10-01\',\'2026-10-01\',$9)',['a'+id,company,id,sourceKey,status,binding,hold,pay,managed]);
+ await sql('INSERT INTO "CourseAppointment" ("objectId",company,id,"sourceKey",dszt,pl,"bindingId","creditHoldStatus","courseCategoryKey","payStatus","createdAt","updatedAt","teachingManaged") VALUES($1,$2,$3,$4,$5,\'30\',$6,$7,\'\',$8,\'2026-10-01\',\'2026-10-01\',$9)',['a'+id,company,id,sourceKey,status,binding,hold,pay,managed]);
 }
 async function snapshot(){const result=await call({action:'source',page:1});assert.equal(result.success,true,result.message);}
 const status=async id=>(await sql('SELECT status FROM "CommonModel" WHERE "generalId"=$1',[id]))[0].status;
@@ -62,6 +66,22 @@ test('旧系统恢复的编号即使不在快照中,也不能被取消',async(
  await seed(101);await snapshot();liveIds.add(101);
  const result=await call({action:'reconcile'});assert.equal(result.data.cancelled,0);assert.equal(result.data.present,1);assert.equal(Number(await status(101)),99);
 });
+test('源端确认删除时仅取消有源基线且未预留的同步分类预约',async()=>{
+ for(const id of [101,102,103,104])await seed(id);
+ await db.exec(`UPDATE "CourseAppointment" SET kcid='398',"courseCategoryKey"='middle_writing',
+    "categoryEvidence"=CASE WHEN id=104 THEN '人工核对初中' ELSE '同步自动核对:初中' END;
+  INSERT INTO "LegacyDirectBaseline"(company,model,gid,fingerprint)
+    SELECT c.company,54,c."generalId",md5(jsonb_build_array(to_jsonb(c),to_jsonb(a))::text)
+    FROM "CommonModel" c JOIN "CourseAppointment" a ON a.id=c."itemId" WHERE a.id IN (101,102,104);
+  INSERT INTO "CourseCreditReservation" VALUES('co','c102');`);
+ await snapshot();
+ const result=await call({action:'reconcile'});
+ assert.equal(result.success,true,result.message);
+ assert.equal(result.data.cancelled,1);
+ assert.equal(result.data.conflicts,3);
+ assert.equal(Number(await status(101)),-2);
+ for(const id of [102,103,104])assert.equal(Number(await status(id)),99);
+});
 test('预览不改业务数据或保存冲突,预览后仍可执行实际核对',async()=>{
  await seed(101);await seed(102,{status:'30'});await snapshot();
  const result=await call({action:'reconcile',dryRun:true});assert.equal(result.data.wouldCancel,1);assert.equal(result.data.cancelled,0);assert.equal(Number(await status(101)),99);

+ 24 - 0
scripts/tests/legacy-appointment-preparation.test.mjs

@@ -60,6 +60,30 @@ test('旧阅读写作预约经逐人确认高中后免词库核验,保留原
  assert.equal((await prepare(id)).changed,false);
 });
 test('旧阅读写作未确认学段不得自动预留',async()=>{const id=await fixture({kcid:'398',yykcid:'398'});await assert.rejects(prepare(id),/单词|分类|课程/);});
+test('同步匹配的旧写作在正式预留时采用有效新版本,并保留既有扣费边界',async()=>{
+ await db.exec('BEGIN');
+ try{
+  const today=(await one("SELECT to_char(now() AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD') AS day")).day;
+  const quote={kcid:'398',yykcid:'398',courseCategoryKey:'middle_writing',categoryEvidence:'同步自动核对:初中',
+   teachingRuleId:'retired-quote',durationMinutes:60,deliveryMode:'online'};
+  await q(`INSERT INTO "TeachingCompensationRule" VALUES
+   ('co','retired-quote','middle_writing',60,'online',$1,true,99,'[{"account":"SilverCoin","amount":1}]',1),
+   ('co','disabled-quote','middle_writing',60,'online',$1,false,99,'[{"account":"SilverCoin","amount":1}]',2)`,[today]);
+  const id=await fixture(quote);
+  const updated=()=>one('SELECT "teacherPaySnapshot","teachingRuleId","creditCostsSnapshot" FROM "CourseAppointment" WHERE "objectId"=$1',[id.slice(0,-1)]);
+  assert.equal((await updated()).creditCostsSnapshot,null);
+  await prepare(id);
+  const booked=await updated();
+  assert.match(booked.teachingRuleId,/^seed:middle_writing:/);
+  assert.equal(Number(booked.teacherPaySnapshot),50);
+  assert.equal((await one('SELECT "ruleId" FROM "CourseCreditReservation" WHERE "appointmentId"=$1',[id])).ruleId,booked.teachingRuleId);
+  const alreadyStarted=await fixture({...quote,dszt:'10'});
+  await db.exec('SAVEPOINT before_legacy_started');
+  await assert.rejects(prepare(alreadyStarted),/未开始/);
+  await db.exec('ROLLBACK TO SAVEPOINT before_legacy_started');
+  assert.equal((await one('SELECT count(*)::int n FROM "CourseCreditReservation" WHERE "appointmentId"=$1',[alreadyStarted])).n,0);
+ }finally{await db.exec('ROLLBACK');}
+});
 test('旧系统体验课按体验课时预留,不按词库的普通课分类扣费',async()=>{
  await db.exec('BEGIN');try{
   await db.exec(`UPDATE "_User" SET "legacyUserData"='{"UserExp":1,"UserPoint":0,"Purse":0,"SilverCoin":0}' WHERE "objectId"='student';UPDATE "CourseBinding" SET "categoryKey"=NULL,"categoryName"=NULL,"enrollmentStatus"=NULL WHERE "objectId"='binding';`);

+ 28 - 0
scripts/tests/payroll-integrity.test.mjs

@@ -92,6 +92,34 @@ test('所选工资月份的已完课写作预约可逐人核对,其他月份
  assert.ok(!(await context.writingMappingPage(manager,{month:'2026-09'})).items.some(r=>r.appointmentId==='completed-writing-common'));
  await assert.rejects(context.writingMappingPage(manager,{month:'2026-13'}),/月份/);
 });
+test('课程398的待核对预约按课程编号纳入列表,旧标题不影响人工确认',async()=>{
+ await db.exec(`INSERT INTO "CourseAppointment" ("objectId",company,id,szyh,dszt,kcid,yysj) VALUES
+  ('writing-generic-title','co',9151,'20','0','398','2026-10-02 10:00'),
+  ('other-generic-title','co',9152,'20','0','399','2026-10-02 10:00');
+  INSERT INTO "CommonModel" ("objectId",company,"modelId","itemId","generalId",status,subtitle) VALUES
+  ('writing-generic-common','co',54,9151,9151,99,'旧系统预约'),
+  ('other-generic-common','co',54,9152,9152,99,'旧系统预约');`);
+ const list=()=>context.writingMappingPage(manager,{});
+ const waiting=await list();
+ assert.ok(waiting.items.some(r=>r.appointmentId==='writing-generic-common'));
+ assert.ok(!waiting.items.some(r=>r.appointmentId==='other-generic-common'));
+ const saved=await one("SELECT xs_payroll_writing_mapping('co','teacher','writing-generic-common','middle_writing','人工核实初中',NULL,'核对学段') AS result");
+ assert.equal(saved.result.updated,true);
+ assert.ok(!(await list()).items.some(r=>r.appointmentId==='writing-generic-common'));
+});
+test('旧来源已开始的同步核对写作预约不能借历史预留生成新扣费凭据',async()=>{
+ await db.exec(`INSERT INTO "CourseAppointment" ("objectId",company,id,szyh,dszt,kcid,yysj,"updatedAt","courseCategoryKey","categoryEvidence")
+  VALUES ('sync-started-writing','co',9153,'20','10','398','2026-10-02 10:00',now(),'middle_writing','同步自动核对:初中');
+  INSERT INTO "CommonModel" ("objectId",company,"modelId","itemId","generalId",status,subtitle)
+  VALUES ('sync-started-common','co',54,9153,9153,99,'阅读写作');`);
+ const before=await one('SELECT "updatedAt","creditCostsSnapshot" FROM "CourseAppointment" WHERE "objectId"=$1',['sync-started-writing']);
+ const item={appointmentId:'sync-started-common',expectedUpdatedAt:before.updatedAt,status:'ready',
+  categoryKey:'middle_writing',durationMinutes:60,deliveryMode:'online',teachingRuleId:'matched',teacherPay:50,creditCosts:[{account:'SilverCoin',amount:1}]};
+ const saved=await one("SELECT xs_payroll_reservations('co','teacher',$1,'核对历史预留',$2) AS result",[JSON.stringify([item]),await version()]);
+ assert.equal(saved.result.reserved,0);
+ assert.equal((await one('SELECT count(*)::int n FROM "CourseCreditReservation" WHERE "appointmentId"=$1',['sync-started-common'])).n,0);
+ assert.deepEqual(await one('SELECT "updatedAt","creditCostsSnapshot" FROM "CourseAppointment" WHERE "objectId"=$1',['sync-started-writing']),before);
+});
 test('手动同步真实收据显示完成时间,但不能冒充结算准备完成或桥检查点',async()=>{
  const receipt={source:'old-api/WXAPP',status:'completed-with-preserved-conflicts',completedAt:'2026-10-12T08:39:11.787Z',datasets:[{modelId:54,source:100,failed:0,conflicts:2,reconciled:true}]};
  const ctx=vm.createContext({Date,Psql:{query:async()=>[{detail:JSON.stringify({after:receipt})}]}});

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott