Эх сурвалжийг харах

fix(teaching): show evidenced legacy lessons and earned reviews in teacher history

彭峰 4 цаг өмнө
parent
commit
81b8bd8c3e

+ 2 - 2
projects/xiaoshu-mobile/src/app/features/course-center/course-center-page.component.html

@@ -124,10 +124,10 @@
           <h3>{{ group.date }}</h3>
           <div class="schedule-list">
             @for (item of group.items; track $index) {
-              <article [class.has-lesson-pay]="isHistory && isCoach && !item['cancelled']" [attr.data-schedule-id]="scheduleId(item)" (click)="open(item, $event)">
+              <article [class.has-lesson-pay]="isHistory && isCoach && (!item['cancelled'] || legacyHistoryLesson(item))" [attr.data-schedule-id]="scheduleId(item)" (click)="open(item, $event)">
                 @if (historyOrder()) { <div class="record-time"><span class="record-number" [attr.aria-label]="'序号 ' + recordNumber(item)">{{ recordNumber(item) }}</span><time>{{ scheduleTime(item) }}</time></div> } @else { <time>{{ scheduleTime(item) }}</time> }
                 <div class="schedule-copy"><strong>{{ scheduleTitle(item) }}</strong>@if (scheduleSubtitle(item)) { <span>{{ scheduleSubtitle(item) }}</span> }</div>
-                @if (isHistory && isCoach && !item['cancelled']) { <div class="lesson-pay"><strong>{{ item['payStatus'] === 'earned' ? '陪练费用 ¥' + ($any(item['teacherPay']) | number:'1.2-2') : '费用待核对' }}</strong><small [class.feedback-pending]="item['feedbackStatus'] !== 'submitted'">{{item['feedbackStatus']==='submitted'?'反馈已提交':'反馈待补'}}</small></div> }
+                @if (isHistory && isCoach && (!item['cancelled'] || legacyHistoryLesson(item))) { <div class="lesson-pay"><strong>{{ item['payStatus'] === 'earned' ? '陪练费用 ¥' + ($any(item['teacherPay']) | number:'1.2-2') : '费用待核对' }}</strong>@if (!legacyHistoryLesson(item)) { <small [class.feedback-pending]="item['feedbackStatus'] !== 'submitted'">{{item['feedbackStatus']==='submitted'?'反馈已提交':'反馈待补'}}</small> }</div> }
                 <span class="status" [class]="'status ' + statusClass(item)">{{ statusText(item) }}</span>
                 @if (isCoach) { <button type="button" class="report-button" (click)="report(item, $event)" aria-label="学习报表" title="学习报表"><lucide-icon [img]="icons.BarChart3" [size]="18" /></button> }
                 <lucide-icon class="chevron" [img]="icons.ChevronRight" [size]="18" />

+ 12 - 3
projects/xiaoshu-mobile/src/app/features/course-center/course-center-page.component.ts

@@ -340,14 +340,19 @@ export class CourseCenterPageComponent implements OnInit, OnDestroy {
   scheduleId(item: Item): unknown { return item['GeneralID'] ?? item['ID'] ?? item['id']; }
 
   statusText(item: Item): string {
+    if (this.legacyHistoryLesson(item)) return '旧系统已授课';
     if(item['cancelled']===true)return '已取消';
     if (this.isOverdueUnfinished(item)) return '计划未完成';
     return ({ 0: '未开始', 10: '已开始', 11: '已训练', 20: '已评价', 30: '已结课' } as Record<number, string>)[this.rawStatus(item)] ?? '--';
   }
 
-  statusClass(item: Item): string { return this.isOverdueUnfinished(item) ? 'status-11' : `status-${this.rawStatus(item)}`; }
+  statusClass(item: Item): string { if (this.legacyHistoryLesson(item)) return 'status-30'; return this.isOverdueUnfinished(item) ? 'status-11' : `status-${this.rawStatus(item)}`; }
 
-  isFinished(item: Item): boolean { return item['cancelled']!==true && this.rawStatus(item) >= 30; }
+  legacyHistoryLesson(item: Item): boolean {
+    return this.isHistory && this.isCoach && Boolean(item['legacyLessonId']) && (item['cancelled']===true || this.rawStatus(item)<30);
+  }
+
+  isFinished(item: Item): boolean { return this.legacyHistoryLesson(item) || (item['cancelled']!==true && this.rawStatus(item) >= 30); }
 
   setScheduleFilter(filter: ScheduleFilter): void {
     this.scheduleFilter.set(filter);
@@ -404,6 +409,10 @@ export class CourseCenterPageComponent implements OnInit, OnDestroy {
 
   open(item: Item, event?: Event): void {
     this.saveScheduleScroll(item, event);
+    if (this.legacyHistoryLesson(item)) {
+      void this.router.navigate(['/pages/shop/baobiao'], { queryParams: { sid: this.scheduleId(item) } });
+      return;
+    }
     if (!this.isCoach) {
       this.storeAppointmentSnapshot(item);
       void this.router.navigate(['/pages/shop/stu_get_order'], { queryParams: { id: this.scheduleId(item) }, state: { appointmentSnapshot: item } });
@@ -431,7 +440,7 @@ export class CourseCenterPageComponent implements OnInit, OnDestroy {
   report(item: Item, event: Event): void {
     event.stopPropagation();
     this.saveScheduleScroll(item, event);
-    if (this.rawStatus(item) > 10) {
+    if (this.legacyHistoryLesson(item) || this.rawStatus(item) > 10) {
       void this.router.navigate(['/pages/shop/baobiao'], { queryParams: { sid: this.scheduleId(item) } });
       return;
     }

+ 17 - 1
scripts/cloud/mobile-teaching.js

@@ -73,7 +73,11 @@ async function appReviewPage(input,current) {
   // Empty writing records are deliberate notes reviews; other empty sources remain hidden.
   // OFFSET 0 keeps source checks correlated instead of evaluating every empty study in the tenant.
   const notesSource=notesReviewSourceSql();
-  clauses.push('NOT EXISTS (SELECT 1 FROM "CommonModel" sc JOIN "DailyStudyRecord" d ON d."company"=sc."company" AND d."id"=sc."itemId" WHERE sc."company"=m."company" AND sc."modelId"=56 AND sc."generalId"::text=m."xxjlid"::text AND COALESCE(d."learned",0)=0 AND COALESCE(NULLIF(BTRIM(d."xxqs"),\'\'),\'[]\')=\'[]\' AND NOT ('+notesSource+') OFFSET 0)');
+  const hasStudyContent='NOT EXISTS (SELECT 1 FROM "CommonModel" sc JOIN "DailyStudyRecord" d ON d."company"=sc."company" AND d."id"=sc."itemId" WHERE sc."company"=m."company" AND sc."modelId"=56 AND sc."generalId"::text=m."xxjlid"::text AND COALESCE(d."learned",0)=0 AND COALESCE(NULLIF(BTRIM(d."xxqs"),\'\'),\'[]\')=\'[]\' AND NOT ('+notesSource+') OFFSET 0)';
+  // A completed review with its own earned receipt remains in the teacher's history
+  // even if the old study no longer has words to practise.
+  const receiptHistory=coach && input.status==='completed' && !input.scope;
+  clauses.push(receiptHistory ? '('+hasStudyContent+' OR (m.fxzt=\'1\' AND EXISTS (SELECT 1 FROM "ReviewRewardIncome" earned WHERE earned.company=m.company AND earned."taskId"=m."objectId" AND earned."coachId"=m.plid AND earned.status=\'earned\' OFFSET 0)))' : hasStudyContent);
   const add=(sql,value)=>{args.push(value);clauses.push(sql.replace('?', '$'+args.length));};
   const studentsPromise=coach&&includeMetadata? Psql.query('SELECT m."yhid"::text AS id,COALESCE(MAX(NULLIF(BTRIM(u."realName"),\'\')),MAX(NULLIF(BTRIM(u."nickname"),\'\')),MAX(NULLIF(BTRIM(u."legacyUserData"->>\'HoneyName\'),\'\')),MAX(NULLIF(BTRIM(u."username"),\'\')),\'学员 \'||m."yhid"::text) AS name,COUNT(*)::int AS "taskCount" FROM "MemoryPracticeRecord" m LEFT JOIN "_User" u ON u."company"=m."company" AND u."legacyUserId"=m."yhid" WHERE '+clauses.join(' AND ')+' GROUP BY m."yhid"',[...args]):Promise.resolve([]);
   if(coach&&number(input.studentId))add('m."yhid"::text=?',String(input.studentId));
@@ -124,6 +128,18 @@ async function mobileAtomicWrite(input,current,operations,scope='',db=Psql) {
   return row.result;
 }
 
+function companionLegacyLessonJoin() {
+  // Aggregate by booking before joining so a duplicate source cannot create two history entries.
+  return ` LEFT JOIN (
+    SELECT l.yyds,l.xymz,MIN(lc."generalId") AS "legacyLessonId"
+    FROM "LessonRecord" l JOIN "CommonModel" lc ON lc.company=l.company AND lc."modelId"=59
+      AND lc."itemId"=l.id AND lc.status=99 AND lc."sourceKey"=l."sourceKey"
+      AND l."sourceKey"='legacy:model:59:general:'||lc."generalId"::text
+    WHERE l.company=$1 AND l.jsmz=$2
+    GROUP BY l.yyds,l.xymz HAVING COUNT(*)=1
+  ) legacy ON legacy.yyds=c."generalId"::text AND legacy.xymz=a.szyh
+    AND c."sourceKey"=a."sourceKey" AND a."sourceKey"='legacy:model:54:general:'||c."generalId"::text`;
+}
 // Empty profile fields must not hide the student's legacy display name.
 function companionStudentNameSql() {
   return `COALESCE(NULLIF(BTRIM(u."realName"),''),NULLIF(BTRIM(u."nickname"),''),NULLIF(BTRIM(u."legacyUserData"->>'HoneyName'),''),NULLIF(BTRIM(SPLIT_PART(REPLACE(c."title",'(','('),'(',1)),''),NULLIF(BTRIM(u."username"),''),'学员 '||a."szyh")`;

+ 1 - 1
scripts/cloud/teacher-earnings.js

@@ -80,7 +80,7 @@ async function teacherIncomeSummary(companyId,coachId) {
   return {lessonIncome:lessons.lessonIncome,reviewIncome,totalIncome:(Math.round(lessons.lessonIncome*100)+Math.round(reviewIncome*100))/100,pendingPayCount:lessons.pendingPayCount};
 }
 async function teacherSchedulePay(rows,coachId) {
-  const ids=rows.filter(r=>Number(r.dszt)>=30&&Number(r.commonStatus)!==-2).map(r=>String(r.generalId));
+  const ids=rows.filter(r=>(Number(r.dszt)>=30&&Number(r.commonStatus)!==-2)||r.legacyLessonId).map(r=>String(r.generalId));
   if(!ids.length)return rows;
   const [earnings,reports]=await Promise.all([teacherLessonEarnings(DEFAULT_COMPANY_ID,coachId,ids),Psql.query('SELECT "appointmentGeneralId"::text AS id,"feedbackStatus" FROM "LessonCompletionReport" WHERE company=$1 AND "coachId"=$2 AND "appointmentGeneralId"::text=ANY($3::text[])',[DEFAULT_COMPANY_ID,Number(coachId),ids])]);
   return rows.map(row=>{const matches=earnings.lines.filter(l=>String(l.appointmentGeneralId)===String(row.generalId)),line=matches[0],valid=matches.length===1&&!line.exception;return {...row,teacherPay:valid?line.amount:null,payStatus:valid?'earned':'pending',payReason:line?.exception||'工资待核对',feedbackStatus:reports.find(r=>r.id===String(row.generalId))?.feedbackStatus||'pending'};});

+ 15 - 10
scripts/deploy-admin-functions.mjs

@@ -2845,7 +2845,7 @@ function appOverviewToday() {
   const parts=new Intl.DateTimeFormat('en-US',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(new Date()),values={};for(const part of parts)values[part.type]=part.value;return values.year+'-'+values.month+'-'+values.day;
 }
 function appOverviewScheduleRow(source) {
-  return { teacherPay:source.teacherPay,payStatus:source.payStatus,payReason:source.payReason,feedbackStatus:source.feedbackStatus,objectId:String(source.objectId||source.appointmentObjectId||''),GeneralID:number(source.generalId||source.id),ID:number(source.generalId||source.id),Title:String(source.title||source.courseTitle||'课程预约'),Title2:String(source.courseTitle||''),CreateTime:firstValue(source.createTime,source.createdAt),cancelled:number(source.commonStatus)===-2,status:number(source.commonStatus,99),durationMinutes:source.durationMinutes,bindingId:source.bindingId,courseCategoryKey:source.courseCategoryKey,courseCategoryName:source.courseCategoryName,pl:source.pl,bxrq:source.bxrq,dslx:source.dslx,dszt:source.dszt,fxpl:source.fxpl,jffs:source.jffs,jssj:source.jssj,kcid:source.kcid,kssj:source.kssj,plxm:source.plxm,scsj:source.scsj,sdsd:source.sdsd,szmd:source.szmd,szyh:source.szyh,yysj:source.yysj,yykcid:source.yykcid };
+  return { legacyLessonId:source.legacyLessonId,teacherPay:source.teacherPay,payStatus:source.payStatus,payReason:source.payReason,feedbackStatus:source.feedbackStatus,objectId:String(source.objectId||source.appointmentObjectId||''),GeneralID:number(source.generalId||source.id),ID:number(source.generalId||source.id),Title:String(source.title||source.courseTitle||'课程预约'),Title2:String(source.courseTitle||''),CreateTime:firstValue(source.createTime,source.createdAt),cancelled:number(source.commonStatus)===-2,status:number(source.commonStatus,99),durationMinutes:source.durationMinutes,bindingId:source.bindingId,courseCategoryKey:source.courseCategoryKey,courseCategoryName:source.courseCategoryName,pl:source.pl,bxrq:source.bxrq,dslx:source.dslx,dszt:source.dszt,fxpl:source.fxpl,jffs:source.jffs,jssj:source.jssj,kcid:source.kcid,kssj:source.kssj,plxm:source.plxm,scsj:source.scsj,sdsd:source.sdsd,szmd:source.szmd,szyh:source.szyh,yysj:source.yysj,yykcid:source.yykcid };
 }
 function appOverviewCourseRow(source) {
   return { objectId:String(source.objectId||source.bindingObjectId||''),GeneralID:number(source.generalId||source.id),ID:number(source.generalId||source.id),Title:String(source.title||source.courseTitle||'课程内容'),Title2:String(source.courseTitle||''),CreateTime:firstValue(source.createTime,source.createdAt),bindingId:String(source.bindingObjectId||source.objectId||''),categoryKey:source.categoryKey,categoryName:source.categoryName,id:source.id,yxx:source.yxx,cksl:source.cksl,kcid:source.kcid,syjd:source.syjd,yhid:source.yhid };
@@ -3030,22 +3030,27 @@ async function appCompanionOverview(input,current) {
   const args=[DEFAULT_COMPANY_ID,String(uid)],clauses=['a."company"=$1','a."'+(coach?'pl':'szyh')+'"=$2'];
   const date="to_char(xs_appointment_day(a.\"bxrq\",a.\"yysj\"),'YYYY-MM-DD')";
   const add=(sql,value)=>{args.push(value);clauses.push(sql.replace('?', '$'+args.length));};
-  if(history)clauses.push('(a."dszt"::numeric>=30 OR c."status"=-2)');else clauses.push('COALESCE(c."status",99)<>-2');
+  const teacherHistory=coach&&history;
+  const delivered='a."dszt"::numeric>=30 AND COALESCE(c."status",99)<>-2';
+  const finished=teacherHistory?'(('+delivered+') OR legacy."legacyLessonId" IS NOT NULL)':'('+delivered+')';
+  const lessonColumn=teacherHistory?',legacy."legacyLessonId"':'';
+  if(history)clauses.push('('+finished+' OR c."status"=-2)');else clauses.push('COALESCE(c."status",99)<>-2');
   if(coach&&number(input.studentId))add('a."szyh"=?',String(input.studentId));
   if(input.search)add('c."title" ILIKE ?','%'+String(input.search).trim().slice(0,100)+'%');
   if(input.month&&/^\d{4}-\d{2}$/.test(input.month))add('LEFT('+date+',7)=?',input.month);
-  const join=' FROM "CourseAppointment" a LEFT JOIN "CommonModel" c ON c."company"=a."company" AND c."modelId"=54 AND c."itemId"=a."id"';
+  const bookingJoin=' FROM "CourseAppointment" a LEFT JOIN "CommonModel" c ON c."company"=a."company" AND c."modelId"=54 AND c."itemId"=a."id"';
+  const join=bookingJoin+(teacherHistory?companionLegacyLessonJoin():'');
   const summaryWhere=clauses.join(' AND '),summaryArgs=[...args];
-  const readDates=()=>Psql.query('SELECT '+date+' AS date,COUNT(*) FILTER(WHERE a."dszt"::numeric>=30 AND COALESCE(c."status",99)<>-2)::int finished,COUNT(*) FILTER(WHERE a."dszt"::numeric<30 AND COALESCE(c."status",99)<>-2)::int planned'+join+' WHERE '+summaryWhere+' GROUP BY '+date,summaryArgs);
-  const readStudentOptions=()=>coach?Psql.query('SELECT a."szyh" AS id,MAX('+companionStudentNameSql()+') AS name,COUNT(*)::int count'+join+' LEFT JOIN "_User" u ON u."company"=a."company" AND u."legacyUserId"::text=a."szyh" WHERE a."company"=$1 AND a."pl"=$2 AND COALESCE(c."status",99)<>-2 GROUP BY a."szyh" ORDER BY name',[DEFAULT_COMPANY_ID,String(uid)]):[];
+  const readDates=()=>Psql.query('SELECT '+date+' AS date,COUNT(*) FILTER(WHERE '+finished+')::int finished,COUNT(*) FILTER(WHERE NOT '+finished+' AND COALESCE(c."status",99)<>-2)::int planned'+join+' WHERE '+summaryWhere+' GROUP BY '+date,summaryArgs);
+  const readStudentOptions=()=>coach?Psql.query('SELECT a."szyh" AS id,MAX('+companionStudentNameSql()+') AS name,COUNT(*)::int count'+bookingJoin+' LEFT JOIN "_User" u ON u."company"=a."company" AND u."legacyUserId"::text=a."szyh" WHERE a."company"=$1 AND a."pl"=$2 AND COALESCE(c."status",99)<>-2 GROUP BY a."szyh" ORDER BY name',[DEFAULT_COMPANY_ID,String(uid)]):[];
   if(input.dateStart)add(date+'>=?',String(input.dateStart));
   if(input.dateEnd)add(date+'<=?',String(input.dateEnd));
-  if(input.filter==='finished')clauses.push('a."dszt"::numeric>=30 AND COALESCE(c."status",99)<>-2');
-  if(input.filter==='pending'){clauses.push('a."dszt"::numeric<30 AND COALESCE(c."status",99)<>-2');add(date+'<?',appOverviewToday());}
+  if(input.filter==='finished')clauses.push(finished);
+  if(input.filter==='pending'){clauses.push('NOT '+finished+' AND COALESCE(c."status",99)<>-2');add(date+'<?',appOverviewToday());}
   const where=clauses.join(' AND '),readCount=()=>Psql.one('SELECT COUNT(*)::int total'+join+' WHERE '+where,args);
-  const readRows=()=>Psql.query('SELECT c."generalId",c."title",c."createTime",c."status" AS "commonStatus",a.*,n."nodeName" AS "courseTitle"'+join+' LEFT JOIN "Node" n ON n."company"=a."company" AND n."nodeId"::text=a."kcid" WHERE '+where+' ORDER BY a."yysj" '+(history||input.filter==='finished'?'DESC':'ASC')+',a."id" DESC LIMIT $'+(args.length+1)+' OFFSET $'+(args.length+2),[...args,p.size,(p.index-1)*p.size]);
+  const readRows=()=>Psql.query('SELECT c."generalId",c."title",c."createTime",c."status" AS "commonStatus",a.*,n."nodeName" AS "courseTitle"'+lessonColumn+join+' LEFT JOIN "Node" n ON n."company"=a."company" AND n."nodeId"::text=a."kcid" WHERE '+where+' ORDER BY a."yysj" '+(history||input.filter==='finished'?'DESC':'ASC')+',a."id" DESC LIMIT $'+(args.length+1)+' OFFSET $'+(args.length+2),[...args,p.size,(p.index-1)*p.size]);
   const readCourses=()=>coach?[]:Psql.query('SELECT c."generalId",c."title",b.*,b."objectId" AS "bindingObjectId",n."nodeName" AS "courseTitle" FROM "CourseBinding" b JOIN "CommonModel" c ON c."company"=b."company" AND c."modelId"=58 AND c."itemId"=b."id" LEFT JOIN "Node" n ON n."company"=b."company" AND n."nodeId"::text=b."kcid" WHERE b."company"=$1 AND b."yhid"=$2 AND b."enrollmentStatus"=\'active\' AND c."status"=99 AND COALESCE(n."zstatus",99)=99 ORDER BY b."id" DESC',[DEFAULT_COMPANY_ID,String(uid)]);
-  const readAllRows=()=>coach&&history?Psql.query('SELECT c."generalId",c."status" AS "commonStatus",a.dszt'+join+' WHERE '+where,args):[];
+  const readAllRows=()=>coach&&history?Psql.query('SELECT c."generalId",c."status" AS "commonStatus",a.dszt'+lessonColumn+join+' WHERE '+where,args):[];
   // Each request reads fresh data; only independent reads overlap, with bounded database pressure.
   const reads=[readDates,readStudentOptions,readCount,readRows,readCourses,readAllRows],results=[];
   let nextRead=0,readError;
@@ -3060,7 +3065,7 @@ async function appCompanionOverview(input,current) {
   let earningsSummary, scheduleRows=rows;
   if(coach&&history){
     const paidRows=await teacherSchedulePay(allRows,uid);
-    earningsSummary={amount:paidRows.reduce((sum,row)=>sum+(Number(row.commonStatus)!==-2&&row.payStatus==='earned'?Math.round(Number(row.teacherPay)*100):0),0)/100,pendingCount:paidRows.filter(row=>Number(row.commonStatus)!==-2&&row.payStatus!=='earned').length};
+    earningsSummary={amount:paidRows.reduce((sum,row)=>sum+((Number(row.commonStatus)!==-2||row.legacyLessonId)&&row.payStatus==='earned'?Math.round(Number(row.teacherPay)*100):0),0)/100,pendingCount:paidRows.filter(row=>(Number(row.commonStatus)!==-2||row.legacyLessonId)&&row.payStatus!=='earned').length};
     const payById=new Map(paidRows.map(row=>[String(row.generalId),row]));
     scheduleRows=rows.map(row=>{
       const pay=payById.get(String(row.generalId));

+ 14 - 0
scripts/tests/companion-student-names.test.mjs

@@ -10,3 +10,17 @@ test('排课学员姓名跳过空白字段,兼容旧昵称、预约标题和
   for(const [realName,nickname,legacy,title,username,expected]of rows){const result=await db.query(`SELECT ${expression} AS name FROM (SELECT $1::text "realName",$2::text nickname,$3::jsonb "legacyUserData",$5::text username) u CROSS JOIN (SELECT $4::text title) c CROSS JOIN (SELECT '213'::text szyh) a`,[realName,nickname,legacy,title,username]);assert.equal(result.rows[0].name,expected);}
  }finally{await db.close();}
 });
+test('旧课历史按原预约、实际老师和学员取唯一有效课记,允许课堂换教材',async()=>{
+ const join=runInNewContext(readFileSync(new URL('../cloud/mobile-teaching.js',import.meta.url),'utf8')+';companionLegacyLessonJoin()');
+ const db=new PGlite();try{
+  await db.exec(`CREATE TABLE "CommonModel"(company text,"modelId" int,"itemId" int,"generalId" int,status int,"sourceKey" text);
+    CREATE TABLE "LessonRecord"(company text,id int,yyds text,jsmz text,xymz text,kcid text,"sourceKey" text);
+    CREATE TABLE "CourseAppointment"(company text,id int,szyh text,pl text,kcid text,"sourceKey" text);
+    INSERT INTO "CommonModel" SELECT 'co',54,i,i,-2,'legacy:model:54:general:'||i FROM generate_series(1,6)i;
+    INSERT INTO "CourseAppointment" SELECT 'co',i,'student','coach','planned','legacy:model:54:general:'||i FROM generate_series(1,6)i;
+    INSERT INTO "CommonModel" SELECT 'co',59,i,i+20,CASE WHEN i=2 THEN -2 ELSE 99 END,'legacy:model:59:general:'||(i+20) FROM generate_series(1,7)i;
+    INSERT INTO "LessonRecord" SELECT 'co',i,CASE WHEN i=7 THEN '5' ELSE i::text END,CASE WHEN i=3 THEN 'other' ELSE 'coach' END,CASE WHEN i=4 THEN 'other' ELSE 'student' END,'actual',CASE WHEN i=6 THEN 'native' ELSE 'legacy:model:59:general:'||(i+20) END FROM generate_series(1,7)i;`);
+  const rows=await db.query('SELECT legacy."legacyLessonId" AS id FROM "CourseAppointment" a JOIN "CommonModel" c ON c.company=a.company AND c."modelId"=54 AND c."itemId"=a.id'+join+' WHERE a.company=$1 AND a.pl=$2 ORDER BY a.id',['co','coach']);
+  assert.deepEqual(rows.rows.map(row=>row.id),[21,null,null,null,null,null]);
+ }finally{await db.close();}
+});

+ 1 - 1
scripts/tests/fixtures/teacher-review-schema.sql

@@ -3,7 +3,7 @@ CREATE TABLE "MemoryPracticeRecord"("objectId" text,company text,id numeric,plid
   CREATE TABLE "DailyStudyRecord"(company text,id numeric,learned numeric,xxqs text,dqrq text,"createdAt" timestamptz);
   CREATE TABLE "Node"(company text,"nodeId" numeric,"nodeName" text);
   CREATE TABLE "_User"(company text,"legacyUserId" numeric,"realName" text,nickname text,username text,"legacyUserData" jsonb);
-  CREATE TABLE "ReviewRewardIncome"(company text,"taskId" text,amount numeric,status text,"ineligibleReason" text,"completedAt" timestamptz,"originalAmount" numeric,"correctionAmount" numeric,"correctionReason" text);
+  CREATE TABLE "ReviewRewardIncome"("coachId" numeric,company text,"taskId" text,amount numeric,status text,"ineligibleReason" text,"completedAt" timestamptz,"originalAmount" numeric,"correctionAmount" numeric,"correctionReason" text);
   INSERT INTO "MemoryPracticeRecord" SELECT 'r'||i,'co',i,30,20,100,1,CASE WHEN i=2 THEN '1' ELSE '0' END,CASE WHEN i<3 THEN '2026-10-14' WHEN i=3 THEN '2026-10-13' ELSE '2026-10-20' END,'2026-10-20 10:00:00' FROM generate_series(1,50) i;
   INSERT INTO "MemoryPracticeRecord" VALUES ('other','co',100,31,21,101,1,'0','2026-10-14','2026-10-14');
   INSERT INTO "CommonModel" (company,"modelId","generalId","itemId") SELECT company,60,id+1000,id FROM "MemoryPracticeRecord";

+ 7 - 0
scripts/tests/review-income-query.test.mjs

@@ -17,5 +17,12 @@ test('income lookup stays correlated to visible teacher tasks and preserves all/
   assert.equal((await ctx.appReviewPage({status:'completed',month:'2020-01'},coach)).summary.income,0);
   assert.equal(incomeQueries.length,3);
   for(const sql of incomeQueries)assert.match(sql,/JOIN LATERAL \(SELECT r\."amount" FROM "ReviewRewardIncome"[\s\S]*r\."taskId"=m\."objectId" OFFSET 0\) r ON TRUE/,'fee view must be looked up after teacher task selection, not expanded across all tenant rewards');
+  await db.exec(`INSERT INTO "CommonModel"(company,"modelId","generalId","itemId") VALUES('co',56,100,8);
+    INSERT INTO "DailyStudyRecord"(company,id,learned,xxqs) VALUES('co',8,0,'[]');`);
+  assert.equal((await ctx.appReviewPage({status:'completed'},coach)).page.itemCount,0);
+  await db.exec(`UPDATE "ReviewRewardIncome" SET "coachId"=30 WHERE company='co' AND "taskId"='r2'`);
+  const earned=await ctx.appReviewPage({status:'completed'},coach);
+  assert.equal(earned.page.itemCount,1);assert.equal(earned.summary.income,0.5);
+  assert.equal((await ctx.appReviewPage({scope:'today'},coach)).page.itemCount,0);
  }finally{await db.close();}
 });

+ 1 - 1
scripts/tests/teacher-earnings.test.mjs

@@ -36,7 +36,7 @@ test('陪练费用合计覆盖全部分页并排除取消、区分零元和待
  const all=Array.from({length:25},(_,i)=>({generalId:i+1,dszt:30,commonStatus:i===24?-2:99,teacherPay:i===0?0:45,payStatus:i===23?'pending':'earned'}));
  const queries=[];
  let payCalculations=0;
- const ctx=vm.createContext({DEFAULT_COMPANY_ID:'co',number:Number,authorizeRequestedUser:async()=>30,assertLessonTenant:()=>{},mobilePage:()=>({index:1,size:20}),mobilePageMeta:(total)=>({itemCount:total}),companionStudentNameSql:()=>"'学员'",databaseAppointmentVersions:async()=>({}),mobileSource:()=>({}),appOverviewScheduleRow:r=>r,appOverviewCourseRow:r=>r,teacherSchedulePay:async rows=>{payCalculations++;return rows.map(row=>({...row,teacherPay:row.generalId===1?0:45,payStatus:row.generalId===24?'pending':'earned',feedbackStatus:'submitted'}));},Psql:{one:async()=>({total:25}),query:async(sql,args)=>{queries.push({sql,args});return sql.startsWith('SELECT c."generalId"')?(sql.includes(' LIMIT ')?all.slice(0,20):all):[];}}});
+ const ctx=vm.createContext({DEFAULT_COMPANY_ID:'co',number:Number,authorizeRequestedUser:async()=>30,assertLessonTenant:()=>{},mobilePage:()=>({index:1,size:20}),mobilePageMeta:(total)=>({itemCount:total}),companionLegacyLessonJoin:()=>' LEFT JOIN legacy ON true',companionStudentNameSql:()=>"'学员'",databaseAppointmentVersions:async()=>({}),mobileSource:()=>({}),appOverviewScheduleRow:r=>r,appOverviewCourseRow:r=>r,teacherSchedulePay:async rows=>{payCalculations++;return rows.map(row=>({...row,teacherPay:row.generalId===1?0:45,payStatus:row.generalId===24?'pending':'earned',feedbackStatus:'submitted'}));},Psql:{one:async()=>({total:25}),query:async(sql,args)=>{queries.push({sql,args});return sql.startsWith('SELECT c."generalId"')?(sql.includes(' LIMIT ')?all.slice(0,20):all):[];}}});
  vm.runInContext(fn,ctx);
  const result=await ctx.appCompanionOverview({history:true,source:'database',month:'2026-09'},{get:()=>3});
  assert.equal(result.schedules.length,20);assert.equal(result.earningsSummary.amount,990);assert.equal(result.earningsSummary.pendingCount,1);