ソースを参照

Handle overdue appointments and verify legacy teaching history reads

彭峰 12 時間 前
親
コミット
a761c170d6

+ 4 - 1
projects/xiaoshu-admin/src/app/pages/operations-schedule.component.html

@@ -118,7 +118,10 @@
       <div class="schedule-detail-cancel"><label for="schedule-cancel-reason">取消原因</label><textarea id="schedule-cancel-reason" rows="2" [ngModel]="cancelReason()" (ngModelChange)="cancelReason.set($event)" placeholder="填写取消原因后确认,操作将记录在业务日志中"></textarea></div>
     } @else if(item.readOnly){<p class="notice">这条排课来自旧系统实时数据。当前没有安全的旧系统写回通道,新后台暂不能取消;请在原业务端取消后重新同步。</p>}
     @if(detailError()){<p class="notice error" role="alert">{{detailError()}}</p>}
-    <footer>@if(!item.readOnly&&!isStore()){<button type="button" (click)="viewFeedback(item)">查看教学记录</button>}<button type="button" (click)="closeDetails()" [disabled]="saving()">关闭</button>@if(rowActions(item).canEdit){<button type="button" (click)="editFromDetails(item)">修改排课</button>}@if(rowActions(item).canCancel){<button class="danger-action" type="button" (click)="cancelFromDetails()" [disabled]="saving()">{{saving()?'正在取消…':'确认取消排课'}}</button>}</footer>
+    @if(statusTone(item)==='status-overdue' && item.statusCode===10 && !item.readOnly){
+      <p class="notice">请核对是否实际授课。误开可填写原因取消并释放预留,已授课可由任课老师结课。</p>
+    }
+    <footer>@if(rowActions(item).canComplete){<button type="button" (click)="action(item,'ops/appointments/complete')" [disabled]="saving()">{{rowActions(item).completeLabel}}</button>}@if(!item.readOnly&&!isStore()){<button type="button" (click)="viewFeedback(item)">查看教学记录</button>}<button type="button" (click)="closeDetails()" [disabled]="saving()">关闭</button>@if(rowActions(item).canEdit){<button type="button" (click)="editFromDetails(item)">修改排课</button>}@if(rowActions(item).canCancel){<button class="danger-action" type="button" (click)="cancelFromDetails()" [disabled]="saving()">{{saving()?'正在取消…':'确认取消排课'}}</button>}</footer>
   </aside>
 }
 

+ 14 - 0
projects/xiaoshu-admin/src/app/pages/operations-schedule.component.spec.ts

@@ -333,6 +333,20 @@ describe('排课页面复用后的会员与开课数据', () => {
     expect(schedule).toHaveBeenCalledTimes(2);expect(fixture.componentInstance.data()?.members[0].userId).toBe(1935);
     fixture.componentInstance.onOperationsRouteAttach();flushMicrotasks();expect(schedule).toHaveBeenCalledTimes(2);
   }));
+  it('按会员所选日期和唯一预约打开明细,同日另一节不能替代缺失的预约',fakeAsync(()=>{
+    const page=fixture.componentInstance;
+    const day='2000-11-07';
+    const first={targetId:'first',generalId:1,statusCode:10,startsAt:day+'T02:00:00Z'} as ScheduleAppointment;
+    const second={...first,targetId:'second',generalId:2,statusCode:30};
+    schedule.and.resolveTo({...empty(),appointments:[second,first]});
+    function select(id:string){
+      route.snapshot.queryParamMap=convertToParamMap({appointmentId:id,date:day});
+      params.next(route.snapshot.queryParamMap);flushMicrotasks();
+    }
+    select('first');expect(schedule).toHaveBeenCalledWith(day,day,0,true);
+    expect(page.detail()?.targetId).toBe('first');expect(page.drawerOpen()).toBeFalse();
+    select('missing');expect(page.detail()).toBeNull();expect(page.error()).toContain('找不到这笔预约');
+  }));
   it('缓存页面收到会员排课入口时先读取新数据再选择会员,同一会员再次进入也可打开', fakeAsync(() => {
     schedule.and.callFake(async()=>current());
     fixture.componentInstance.onOperationsRouteAttach();navigateToMember();flushMicrotasks();

+ 46 - 2
projects/xiaoshu-admin/src/app/pages/operations-schedule.component.ts

@@ -216,7 +216,30 @@ export class OperationsScheduleComponent implements OnInit, OnDestroy {
   }
   private async activateSchedule():Promise<void> {
     const request = ++this.activationRequest;
-    const id = Number(this.route.snapshot.queryParamMap.get('studentId'));
+    const params = this.route.snapshot.queryParamMap;
+    const appointmentId = params.get('appointmentId');
+    if (appointmentId) {
+      this.attachedIntent = false;
+      this.handledStudentId = 0;
+      this.detail.set(null);
+      this.drawerOpen.set(false);
+      const date = params.get('date') || '';
+      if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(Date.parse(date)) || new Date(date).toISOString().slice(0, 10) !== date) {
+        this.error.set('预约日期无效,请从会员预约记录重新进入');
+        return;
+      }
+      this.initialRange = false;
+      this.date.set(date);
+      this.view.set('day');
+      this.coachFilter.set(0);
+      await this.load();
+      if (this.destroyed || request !== this.activationRequest || this.error()) return;
+      const item = this.data()?.appointments.find(row => row.targetId === appointmentId);
+      if (item) this.openDetails(item);
+      else this.error.set('当天课表中找不到这笔预约,请刷新会员预约记录');
+      return;
+    }
+    const id = Number(params.get('studentId'));
     const selectMember = id > 0 && (this.attachedIntent || id !== this.handledStudentId);
     this.attachedIntent = false;
     if (!this.data() || this.loadedRevision !== this.dataRevision || selectMember) await this.load();
@@ -307,5 +330,26 @@ export class OperationsScheduleComponent implements OnInit, OnDestroy {
     finally{if(request===this.preflightRequest)this.checking.set(false);}
   }
   async save():Promise<void>{if(this.saving())return;if(!this.selectedMemberObjectId()||(!this.textbookFree()&&!this.courseId())||!this.reason().trim()){this.error.set('请选择会员、课程并填写操作原因');return;}if(!this.studentId()){this.error.set('该会员缺少旧系统排课编号,暂时不能保存;请先补齐该会员的迁移标识');return;}if(!this.preview()){this.error.set('请先检查冲突并确认逐项预检结果');return;}if(!this.canSavePreview()){this.error.set('当前没有可以提交的排课,请先调整冲突项');return;}this.saving.set(true);this.error.set('');try{const editing=this.editing(),skipConflicts=!editing&&this.previewConflictCount()>0&&this.previewCandidates().length>1;const fingerprint=JSON.stringify([editing?.targetId||'',this.payload(),skipConflicts,this.reason()]);if(this.saveFingerprint!==fingerprint){this.saveFingerprint=fingerprint;this.saveKey=crypto.randomUUID();}const result=await this.operations.mutate<{created?:number;skipped?:number}>(editing?'ops/appointments/update':'ops/appointments/create',editing?.targetId||'',this.reason(),{...this.payload(),skipConflicts},editing?.updatedAt||'',this.saveKey);this.saveFingerprint='';this.saveKey='';this.message.set(editing?'排课已更新':result.skipped?`已创建 ${result.created||0} 节排课,跳过 ${result.skipped} 节冲突项`:`已创建 ${result.created||1} 节排课`);this.drawerOpen.set(false);await this.load();}catch(error){this.error.set(error instanceof Error?error.message:'排课保存失败');}finally{this.saving.set(false);}}
-  async action(item:ScheduleAppointment,operation:string):Promise<void>{if(item.readOnly){this.message.set('实时业务数据暂不支持从新后台修改,请在原业务端完成操作。');return;}const reason=globalThis.prompt(operation.endsWith('restore')?'请输入恢复原因':operation.endsWith('complete')?'请输入确认完成原因':'请输入取消原因');if(!reason?.trim())return;this.saving.set(true);try{await this.operations.mutate(operation,item.targetId,reason,{},item.updatedAt);await this.load();}catch(error){this.error.set(error instanceof Error?error.message:'操作失败');}finally{this.saving.set(false);}}
+  async action(item: ScheduleAppointment, operation: string): Promise<void> {
+    if (this.saving()) return;
+    if (item.readOnly) {
+      this.message.set('实时业务数据暂不支持从新后台修改,请在原业务端完成操作。');
+      return;
+    }
+    const prompt = operation.endsWith('restore') ? '请输入恢复原因'
+      : operation.endsWith('complete') ? '确认本节实际授课后填写补录原因,将按预约规则处理课时和训练记录' : '请输入取消原因';
+    const reason = globalThis.prompt(prompt)?.trim();
+    if (!reason) return;
+    this.saving.set(true);
+    this.detailError.set('');
+    try {
+      await this.operations.mutate(operation, item.targetId, reason, {}, item.updatedAt);
+      if (this.detail()?.targetId === item.targetId) this.detail.set(null);
+      await this.load();
+    } catch (error) {
+      const message = error instanceof Error ? error.message : '操作失败';
+      if (this.detail()?.targetId === item.targetId) this.detailError.set(message);
+      else this.error.set(message);
+    } finally { this.saving.set(false); }
+  }
 }

+ 15 - 1
projects/xiaoshu-admin/src/app/pages/operations-user-detail.component.html

@@ -37,7 +37,21 @@
     @case ('courses') {
       <section class="panel"><header><div><h2>已开课程</h2><span>查看学习进度,取消绑定进入回收站并可恢复</span></div></header>@if (detail.permissions.canEdit) { <app-member-enrollment [studentId]="detail.userId" [refreshVersion]="refreshVersion()" (changed)="refreshBusiness()" /> }@if(detail.permissions.canManage){<label class="course-reason"><span>课程回收 / 恢复原因</span><input [ngModel]="reason()" (ngModelChange)="reason.set($event)" placeholder="操作下方已开课程前填写,至少 2 个字" maxlength="500" /></label>}<div class="record-table"><table><thead><tr><th>分类与课程</th><th>已学/内容数量</th><th>进度</th><th>状态</th><th>操作</th></tr></thead><tbody>@for (row of related().courses; track row['targetId']) { <tr><td>{{ row['categoryName'] || '待确认分类' }} · {{ row['courseName'] || '未命名课程' }}</td><td>{{ row['learnedCount'] || 0 }} / {{ row['openedCount'] || 0 }}</td><td>{{ row['progressStage'] || '未记录' }}</td><td>{{ row['enrollmentStatus'] === 'pending' ? '分类待确认' : row['statusLabel'] }}</td><td>@if (detail.permissions.canManage) { <button type="button" (click)="toggleCourse(row)" [disabled]="saving() || sectionLoading()">{{ $any(row['status']) === -2 ? '恢复' : '移入回收站' }}</button> }</td></tr> } @empty { <tr><td colspan="5">暂无课程绑定</td></tr> }</tbody></table></div></section>
     }
-    @case ('appointments') { <section class="panel"><header><div><h2>预约记录</h2><span>查看课程、陪练、预约时间和业务状态</span></div></header><div class="record-table"><table><thead><tr><th>课程</th><th>陪练老师</th><th>预约时间</th><th>课型</th><th>状态</th></tr></thead><tbody>@for (row of related().appointments; track row['targetId']) { <tr><td>{{ row['courseName'] }}</td><td>{{ row['coachName'] || '待分配' }}</td><td>{{ $any(row['appointmentAt'] || row['startsAt']) | date:'yyyy-MM-dd HH:mm' }}</td><td>{{ row['classTypeLabel'] }}</td><td>{{ row['statusLabel'] }}</td></tr> } @empty { <tr><td colspan="5">暂无预约记录</td></tr> }</tbody></table></div></section> }
+    @case ('appointments') {
+      <section class="panel"><header><div><h2>预约记录</h2><span>查看课程、陪练、预约时间和业务状态</span></div></header>
+        <div class="record-table"><table><thead><tr><th>课程</th><th>陪练老师</th><th>预约时间</th><th>课型</th><th>状态</th></tr></thead>
+          <tbody>@for (row of related().appointments; track row['targetId']) {
+            <tr><td>{{ row['courseName'] }}</td><td>{{ row['coachName'] || '待分配' }}</td>
+              <td>{{ $any(row['appointmentAt'] || row['startsAt']) | date:'yyyy-MM-dd HH:mm':'+0800' }}</td><td>{{ row['classTypeLabel'] }}</td>
+              <td>{{ row['statusLabel'] }}
+                @if (row['reviewDate'] && detail.permissions.canEdit) {
+                  <a class="action-link compact" routerLink="/admin/schedule" [queryParams]="{appointmentId: row['targetId'], date: row['reviewDate']}">核对预约</a>
+                }
+              </td></tr>
+          } @empty { <tr><td colspan="5">暂无预约记录</td></tr> }</tbody>
+        </table></div>
+      </section>
+    }
     @case ('lessons') { <app-lesson-records [studentId]="detail.userId" [embedded]="true" [refreshVersion]="refreshVersion()" /> }
     @case ('reports') { <section class="panel"><header><div><h2>单词学习报表</h2><span>查看该会员每次学习的掌握情况和复习计划</span></div><a class="primary action-link" routerLink="/admin/learning-reports" [queryParams]="{ studentObjectId: detail.objectId }">进入报表中心</a></header><div class="date-filters"><app-operations-date-filter label="开始日期" [value]="reportFrom()" (valueChange)="reportFrom.set($event)" /><app-operations-date-filter label="结束日期" [value]="reportTo()" (valueChange)="reportTo.set($event)" /><button type="button" class="primary" (click)="filterReports()" [disabled]="sectionLoading()">查询</button><button type="button" (click)="filterReports(true)" [disabled]="sectionLoading()">重置</button></div><div class="record-table"><table><thead><tr><th>学习日期</th><th>课程</th><th>陪练老师</th><th>学习结果</th><th>掌握率</th><th>状态</th><th>操作</th></tr></thead><tbody>@for (row of related().reports; track row['targetId']) { <tr><td>{{ row['studyDate'] || '日期缺失' }}</td><td>{{ row['courseName'] }}</td><td>{{ row['coachName'] }}</td><td>{{ row['learnedCount'] }} 个 · 掌握 {{ row['masteredCount'] }} · 待复习 {{ row['reviewDueCount'] }}</td><td>{{ row['masteryRate'] }}%</td><td>{{ row['statusLabel'] }}</td><td><a class="action-link compact" [routerLink]="['/admin/learning-reports']" [queryParams]="{ studentObjectId: detail.objectId, report: row['targetId'] }">查看报表</a></td></tr> } @empty { <tr><td colspan="7">暂无学习报表</td></tr> }</tbody></table></div></section> }
     @case ('balances') { <app-member-credit-account [objectId]="detail.objectId" [refreshVersion]="refreshVersion()" (changed)="refreshBusiness()" /> }

+ 17 - 0
projects/xiaoshu-admin/src/app/pages/operations-user-detail.component.spec.ts

@@ -22,6 +22,23 @@ describe('会员详情业务交互', () => {
     const c=TestBed.createComponent(OperationsUserDetailComponent).componentInstance;await c.load();await c.selectTab('appointments');await c.changePage(2);
     expect(c.pageCount()).toBe(3);expect(operations.request.calls.mostRecent().args).toEqual(['ops/appointments/list',{page:2,pageSize:20,studentId:1845}]);
   });
+  it('只在跨日未结束的可写预约显示通往原预约的核对入口',async()=>{
+    const base={statusCode:10,statusLabel:'上课中',startsAt:'2000-11-06T16:30:00Z',readOnly:false,cancelled:false};
+    operations.request.and.resolveTo({items:[
+      {...base,targetId:'stale'}, {...base,targetId:'cancelled',cancelled:true,statusLabel:'已取消'},
+      {...base,targetId:'finished',statusCode:30,statusLabel:'已完课'}, {...base,targetId:'live',readOnly:true},
+      {...base,targetId:'today',startsAt:new Date().toISOString()},
+    ],total:5});
+    const fixture=TestBed.createComponent(OperationsUserDetailComponent);
+    fixture.detectChanges();await fixture.whenStable();
+    await fixture.componentInstance.selectTab('appointments');fixture.detectChanges();
+    const links=fixture.nativeElement.querySelectorAll('.record-table a');
+    expect(links.length).toBe(1);
+    expect(links[0].getAttribute('href')).toContain('appointmentId=stale&date=2000-11-07');
+    const statuses=Array.from(fixture.nativeElement.querySelectorAll('tbody td:last-child'),(td:any)=>td.textContent.trim());
+    expect(statuses[0]).toContain('逾期未结束');
+    expect(statuses.slice(1)).toEqual(['已取消','已完课','逾期未结束','上课中']);
+  });
   it('刷新同时更新详情、当前记录和嵌入账户组件',async()=>{
     const c=TestBed.createComponent(OperationsUserDetailComponent).componentInstance;await c.load();await c.selectTab('balances');operations.request.calls.reset();await c.refreshBusiness();
     expect(c.refreshVersion()).toBe(1);expect(operations.request).not.toHaveBeenCalledWith('ops/money-logs/list',{page:1,pageSize:20,studentId:1845});

+ 16 - 2
projects/xiaoshu-admin/src/app/pages/operations-user-detail.component.ts

@@ -9,8 +9,9 @@ import { ChangeDetectionStrategy, Component, OnInit, computed, inject, signal }
 import { FormsModule } from '@angular/forms';
 import { ActivatedRoute, RouterLink } from '@angular/router';
 import { ArrowLeft, BookOpen, CalendarDays, ClipboardList, Clock3, Eye, FileChartColumn, FileClock, GraduationCap, LoaderCircle, LucideAngularModule, MessageSquarePlus, RefreshCw, Save, ShieldAlert, UserRound, WalletCards } from 'lucide-angular';
-import { MemberAgentOption, OperationsUserDetail } from '../admin.models';
+import { MemberAgentOption, OperationsUserDetail, ScheduleAppointment } from '../admin.models';
 import { OperationsListKind, OperationsService } from '../operations.service';
+import { scheduleStatusTone } from './operations-schedule-status';
 
 type MemberTab = 'overview' | 'courses' | 'appointments' | 'lessons' | 'reports' | 'balances' | 'audit';
 
@@ -43,7 +44,7 @@ export class OperationsUserDetailComponent implements OnInit {
   async selectTab(tab: MemberTab): Promise<void> { ++this.sectionSerial; this.tab.set(tab); this.recordPage.set(1); this.recordTotal.set(0); this.sectionLoading.set(false); this.error.set(''); if (tab !== 'overview') await this.loadSection(tab); }
   async changePage(page: number): Promise<void> { if(this.sectionLoading() || page<1 || page>this.pageCount()) return; this.recordPage.set(page); await this.loadSection(); }
   async filterReports(clear=false): Promise<void> { if(clear){this.reportFrom.set('');this.reportTo.set('');} if(this.reportFrom()&&this.reportTo()&&this.reportFrom()>this.reportTo()){this.error.set('开始日期不能晚于结束日期');return;}this.recordPage.set(1);await this.loadSection('reports'); }
-  private kindFor(tab: MemberTab): OperationsListKind | null { return ({ courses: 'course-bindings', appointments: 'appointments', lessons: 'lessons', balances: 'money-logs' } as Partial<Record<MemberTab, OperationsListKind>>)[tab] || null; }
+  private kindFor(tab: MemberTab): OperationsListKind | null { return ({ courses: 'course-bindings', lessons: 'lessons', balances: 'money-logs' } as Partial<Record<MemberTab, OperationsListKind>>)[tab] || null; }
   async loadSection(tab = this.tab()): Promise<void> {
     if(tab==='lessons'||tab==='balances')return;
     const user = this.user(); if (!user || tab === 'overview') return;
@@ -53,6 +54,19 @@ export class OperationsUserDetailComponent implements OnInit {
       if (tab === 'audit') {
         const [notes, audit] = await Promise.all([this.operations.memberRows('ops/users/notes', user.objectId), this.operations.memberRows('ops/users/audit', user.objectId)]);
         if(serial!==this.sectionSerial)return; this.notes.set(notes.items); items=audit.items; total=items.length;
+      } else if (tab === 'appointments') {
+        const page = await this.operations.request<{items: ScheduleAppointment[]; total: number}>('ops/appointments/list', {
+          page: this.recordPage(), pageSize: this.pageSize, studentId: user.userId,
+        });
+        items = page.items.map(row => {
+          const overdue = row.statusCode === 10 && scheduleStatusTone(row) === 'status-overdue';
+          return {
+            ...row, statusLabel: overdue ? '逾期未结束' : row.statusLabel,
+            reviewDate: overdue && row.startsAt && !row.readOnly && row.targetId
+              ? new Date(row.startsAt).toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' }) : '',
+          };
+        });
+        total = page.total;
       } else if (tab === 'reports') {
         const page=await this.operations.learningReports(this.recordPage(), this.pageSize, '', {studentObjectId:user.objectId,dateFrom:this.reportFrom(),dateTo:this.reportTo()}, false);
         items=page.items; total=page.total;

+ 21 - 4
scripts/sql/member-enrollment.sql

@@ -244,7 +244,7 @@ BEGIN
  RETURN u."objectId";
 END $$;
 CREATE OR REPLACE FUNCTION xs_complete_appointment(co text,aid text,actor text) RETURNS jsonb LANGUAGE plpgsql AS $$
-DECLARE a "CourseAppointment"; c "CommonModel"; u "_User"; existing text; lid text=xs_object_id(); lc text=xs_object_id(); ident bigint; cost jsonb; before_value numeric; tx text; charged boolean=false;
+DECLARE a "CourseAppointment"; c "CommonModel"; u "_User"; existing text; lid text=xs_object_id(); lc text=xs_object_id(); ident bigint; cost jsonb; before_value numeric; tx text; charged boolean=false; lesson_time timestamptz=now();
 BEGIN
  PERFORM pg_advisory_xact_lock(hashtext('xs-credit:'||co));
  -- Acquire user before appointment/reservation locks, matching transfer and reservation lock ordering.
@@ -253,15 +253,28 @@ BEGIN
  SELECT * INTO u FROM "_User" WHERE "company"=co AND "legacyUserId"::text=a."szyh"::text FOR UPDATE;
  IF u."objectId" IS NULL THEN RAISE EXCEPTION '预约学员不存在';END IF;
  SELECT "objectId" INTO existing FROM "LessonRecord" WHERE "company"=co AND "yyds"::text=c."generalId"::text LIMIT 1;
+ IF existing IS NOT NULL AND a.dszt='10' THEN
+  RAISE EXCEPTION '该预约已有上课记录但仍标为上课中,请核对原课时流水和记录';
+ END IF;
  IF existing IS NOT NULL THEN RETURN jsonb_build_object('lessonId',existing,'idempotent',true,'periodDeducted',false);END IF;
  SELECT * INTO a FROM "CourseAppointment" WHERE "objectId"=a."objectId" FOR UPDATE;
  IF a."dszt"::text NOT IN ('10','11') OR COALESCE(NULLIF(a."pl"::text,''),a."fxpl"::text,'0')='0' THEN RAISE EXCEPTION '预约尚未上课或未分配教师';END IF;
  PERFORM xs_validate_appointment(co,aid);
  SELECT EXISTS(SELECT 1 FROM "CourseCreditReservation" WHERE "company"=co AND "appointmentId"=aid AND "state"='consumed') INTO charged;
+ IF xs_appointment_day(a.bxrq,a.yysj)<(now() AT TIME ZONE 'Asia/Shanghai')::date THEN
+  IF charged OR (SELECT count(*) FROM "CourseCreditReservation" WHERE company=co AND "appointmentId"=aid
+     AND "studentId"::text=a.szyh::text AND state='reserved' AND "creditCosts"::jsonb=a."creditCostsSnapshot"::jsonb)<>1 THEN
+   RAISE EXCEPTION '跨日补录缺少匹配的未消费预留,请先核对原课时流水';
+  END IF;
+  -- Preserve the lesson's business date while recording the debit at its actual posting time.
+  IF NULLIF(trim(a.kssj),'') IS NULL THEN RAISE EXCEPTION '跨日补录缺少实际上课时间,请先核对上课记录'; END IF;
+  lesson_time=CASE WHEN a.kssj ~ '(Z|[+-][0-9]{2}(:?[0-9]{2})?)$' THEN a.kssj::timestamptz
+    ELSE a.kssj::timestamp AT TIME ZONE 'Asia/Shanghai' END;
+ END IF;
  tx='complete:'||aid;
  IF NOT charged THEN
   PERFORM set_config('xiaoshu.credit_write','yes',true);
-  UPDATE "CourseCreditReservation" SET "state"='consumed',"consumedAt"=now(),"updatedAt"=now() WHERE "company"=co AND "appointmentId"=aid;
+  UPDATE "CourseCreditReservation" SET "state"='consumed',"consumedAt"=now(),"updatedAt"=now() WHERE "company"=co AND "appointmentId"=aid AND state='reserved';
   FOR cost IN SELECT value FROM jsonb_array_elements(a."creditCostsSnapshot"::jsonb) LOOP
    before_value=COALESCE((u."legacyUserData"->>(cost->>'account'))::numeric,0);
    u."legacyUserData"=jsonb_set(u."legacyUserData",ARRAY[cost->>'account'],to_jsonb(before_value-(cost->>'amount')::numeric));
@@ -270,7 +283,7 @@ BEGIN
   UPDATE "_User" SET "legacyUserData"=u."legacyUserData","updatedAt"=now() WHERE "objectId"=u."objectId";
  END IF;
  ident=nextval('xiaoshu_business_id');
- PERFORM xs_insert('LessonRecord',jsonb_build_object('objectId',lid,'company',co,'id',ident,'sourceKey',tx,'createdAt',now(),'updatedAt',now(),'xymz',a."szyh",'jsmz',COALESCE(NULLIF(a."pl"::text,''),a."fxpl"::text),'kcid',a."kcid",'kclx',a."dslx",'kcmc',c."subtitle",'yyds',c."generalId"::text,'jffs',a."jffs",'kzsj','[]','lessonAt',now(),'bindingId',a."bindingId",'courseCategoryKey',a."courseCategoryKey",'courseCategoryName',a."courseCategoryName",'teacherPaySnapshot',a."teacherPaySnapshot",'creditCostsSnapshot',a."creditCostsSnapshot"));
+ PERFORM xs_insert('LessonRecord',jsonb_build_object('objectId',lid,'company',co,'id',ident,'sourceKey',tx,'createdAt',now(),'updatedAt',now(),'xymz',a."szyh",'jsmz',COALESCE(NULLIF(a."pl"::text,''),a."fxpl"::text),'kcid',a."kcid",'kclx',a."dslx",'kcmc',c."subtitle",'yyds',c."generalId"::text,'jffs',a."jffs",'kzsj','[]','lessonAt',lesson_time,'bindingId',a."bindingId",'courseCategoryKey',a."courseCategoryKey",'courseCategoryName',a."courseCategoryName",'teacherPaySnapshot',a."teacherPaySnapshot",'creditCostsSnapshot',a."creditCostsSnapshot"));
  PERFORM xs_insert('CommonModel',jsonb_build_object('objectId',lc,'company',co,'createdAt',now(),'updatedAt',now(),'sourceKey',tx,'generalId',nextval('xiaoshu_business_id'),'itemId',ident,'modelId',59,'nodeId',296,'tableName','ZL_C_skjl','title',c."title",'inputer',actor,'status',99));
  UPDATE "CourseAppointment" SET "dszt"='11',"jssj"=COALESCE(NULLIF("jssj",''),now()::text),"updatedAt"=now() WHERE "objectId"=a."objectId";
  RETURN jsonb_build_object('lessonId',lid,'idempotent',false,'periodDeducted',NOT charged);
@@ -364,7 +377,11 @@ BEGIN
   UPDATE "CourseCreditReservation" SET "state"='reserved',"updatedAt"=now() WHERE "company"=co AND "appointmentId"=aid;
   IF NOT FOUND THEN PERFORM xs_insert('CourseCreditReservation',jsonb_build_object('objectId',xs_object_id(),'company',co,'createdAt',now(),'updatedAt',now(),'sourceKey','cloud:appointment-reservation:'||aid,'appointmentId',aid,'studentId',u."legacyUserId",'creditCosts',a."creditCostsSnapshot",'state','reserved'));END IF;
  ELSE
-  UPDATE "CourseCreditReservation" SET "state"='released',"updatedAt"=now() WHERE "company"=co AND "appointmentId"=aid;
+  IF a.dszt='10' AND (EXISTS(SELECT 1 FROM "LessonRecord" WHERE company=co AND yyds::text=c."generalId"::text)
+    OR EXISTS(SELECT 1 FROM "CourseCreditReservation" WHERE company=co AND "appointmentId"=aid AND state='consumed')) THEN
+   RAISE EXCEPTION '该预约已有上课记录或课时消费,请先核对原流水,不能按误开取消';
+  END IF;
+  UPDATE "CourseCreditReservation" SET "state"='released',"updatedAt"=now() WHERE "company"=co AND "appointmentId"=aid AND state='reserved';
   UPDATE "CommonModel" SET "status"=-2,"updatedAt"=now() WHERE "objectId"=aid;
  END IF;
  PERFORM xs_insert('EnrollmentCommand',jsonb_build_object('objectId',xs_object_id(),'company',co,'createdAt',now(),'updatedAt',now(),'idempotencyKey',xs_object_id(),'request',jsonb_build_object('appointmentId',aid,'restore',restore,'actor',actor,'reason',reason),'result','{}'::jsonb));

+ 15 - 10
scripts/tests/fixtures/mobile-read-performance-baseline.js

@@ -1,4 +1,4 @@
-// Baseline captured before bounded concurrent mobile reads, 2026-11-10.
+// Serial reference for the bounded-read performance tests. Includes legacy teaching evidence in teacher history.
 async function appCompanionOverview(input,current) {
   const uid=await authorizeRequestedUser(current,input.uid),coach=number(current.get('legacyGroupId'))===3,history=input.history===true,p=mobilePage(input);
   assertLessonTenant(current);
@@ -6,26 +6,31 @@ 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 dates=await 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 studentOptions=coach?await 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 dates=await 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 studentOptions=coach?await 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 '),count=await Psql.one('SELECT COUNT(*)::int total'+join+' WHERE '+where,args);
-  const rows=await 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?'DESC':'ASC')+',a."id" DESC LIMIT $'+(args.length+1)+' OFFSET $'+(args.length+2),[...args,p.size,(p.index-1)*p.size]);
+  const rows=await 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 courses=coach?[]:await 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)]);
   let earningsSummary, scheduleRows=rows;
   if(coach&&history){
-    const allRows=await Psql.query('SELECT c."generalId",c."status" AS "commonStatus",a.dszt'+join+' WHERE '+where,args);
+    const allRows=await Psql.query('SELECT c."generalId",c."status" AS "commonStatus",a.dszt'+lessonColumn+join+' WHERE '+where,args);
     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));

+ 35 - 0
scripts/tests/member-enrollment.test.mjs

@@ -238,3 +238,38 @@ test('体验和自学排课原子关联教材,复用绑定,失败回滚,
  await assert.rejects(saveSchedule([e],'direct-textbook-no-credit'),/不足/);
  assert.equal((await one('SELECT count(*)::int n FROM "CourseBinding" WHERE yhid=\'99\'')).n,0);
 });
+
+test('跨日误开可单独释放,已有课记或消费须核对,实际授课补录使用原上课时间',async()=>{
+ await db.exec('BEGIN');
+ try {
+  const binding=(await one(`SELECT "objectId" FROM "CourseBinding" WHERE "categoryKey"='word' AND yhid='20' LIMIT 1`)).objectId;
+  const day='2001-11-07';
+  const saved=await saveSchedule([scheduleEntry(binding,day+' 10:00')],'overdue-recovery');
+  const aid=saved.targetIds[0],common=await one('SELECT * FROM "CommonModel" WHERE "objectId"=$1',[aid]);
+  await query(`UPDATE "CourseAppointment" SET dszt='10',kssj='2001-11-07 09:52:33+08' WHERE company='co' AND id=$1`,[common.itemId]);
+  const cancel=()=>query("SELECT xs_schedule_cancel('co',$1,false,'admin','核实误开')",[aid]);
+  const correct=()=>one("SELECT xs_admin_lesson_correction('co',$1,'admin','已核实授课') AS result",[aid]);
+  const originalHold=(await one('SELECT "objectId" FROM "CourseCreditReservation" WHERE "appointmentId"=$1',[aid])).objectId;
+  const hold=async()=>(await one('SELECT state FROM "CourseCreditReservation" WHERE "objectId"=$1',[originalHold])).state;
+  const before=await balance('student');
+  await db.exec('SAVEPOINT initial');
+  await cancel();assert.equal(await hold(),'released');assert.equal(await balance('student'),before);
+  await db.exec('ROLLBACK TO initial');
+  await query('INSERT INTO "LessonRecord" ("objectId",company,yyds) VALUES ($1,$2,$3)',['old-lesson','co',String(common.generalId)]);
+  await db.exec('SAVEPOINT has_record');
+  await assert.rejects(cancel(),/已有上课记录/);await db.exec('ROLLBACK TO has_record');
+  await assert.rejects(correct(),/已有上课记录/);await db.exec('ROLLBACK TO initial');
+  await query(`UPDATE "CourseCreditReservation" SET state='consumed' WHERE "appointmentId"=$1`,[aid]);
+  await db.exec('SAVEPOINT consumed');
+  await assert.rejects(cancel(),/课时消费/);await db.exec('ROLLBACK TO consumed');
+  await assert.rejects(correct(),/原课时流水/);await db.exec('ROLLBACK TO initial');
+  await query(`INSERT INTO "CourseCreditReservation" ("objectId",company,"appointmentId","studentId",state)
+    VALUES ('past-release','co',$1,20,'released')`,[aid]);
+  const {result}=await correct();
+  assert.equal((await one(`SELECT state FROM "CourseCreditReservation" WHERE "objectId"='past-release'`)).state,'released');
+  const lesson=await one(`SELECT "lessonAt" FROM "LessonRecord" WHERE "objectId"=$1`,[result.lessonId]);
+  assert.equal(new Date(lesson.lessonAt).toISOString(),'2001-11-07T01:52:33.000Z');
+  assert.equal(await hold(),'consumed');assert.equal(await balance('student'),before-1);
+  assert.equal((await correct()).result.idempotent,true);assert.equal(await balance('student'),before-1);
+ } finally {await db.exec('ROLLBACK');}
+});

+ 8 - 3
scripts/tests/mobile-read-performance.test.mjs

@@ -3,12 +3,14 @@ import assert from 'node:assert/strict';
 import {readFileSync} from 'node:fs';
 import vm from 'node:vm';
 const source=readFileSync(new URL('../deploy-admin-functions.mjs',import.meta.url),'utf8');
+const teachingCode=readFileSync(new URL('../cloud/mobile-teaching.js',import.meta.url),'utf8');
+const companionLegacyLessonJoin=vm.runInNewContext(teachingCode+';companionLegacyLessonJoin');
 const baseline=readFileSync(new URL('./fixtures/mobile-read-performance-baseline.js',import.meta.url),'utf8');
 const currentSource=source.slice(source.indexOf('async function appCompanionOverview('),source.indexOf('async function ',source.indexOf('async function appAccountOverview(')+10));
 const plain=value=>JSON.parse(JSON.stringify(value));
 function harness(code,{coach=true,deny=false,delay=false,failQuery=false}={}){
  const calls=[],sideReads=[];const sideRead=(name,value)=>async()=>{sideReads.push(name);return value;};let active=0,peak=0,payCalls=0,authorized=false;
- const rows=[{generalId:1,commonStatus:99,dszt:'30',teacherPay:0,payStatus:'earned'},{generalId:2,commonStatus:99,dszt:'30',teacherPay:45,payStatus:'earned'},{generalId:3,commonStatus:99,dszt:'30',payStatus:'pending'},{generalId:4,commonStatus:-2,dszt:'30',teacherPay:45,payStatus:'earned'}];
+ const rows=[{generalId:1,commonStatus:99,dszt:'30',teacherPay:0,payStatus:'earned'},{generalId:2,commonStatus:99,dszt:'30',teacherPay:45,payStatus:'earned'},{generalId:3,commonStatus:99,dszt:'30',payStatus:'pending'},{generalId:4,commonStatus:-2,dszt:'30',teacherPay:45,payStatus:'earned'},{generalId:5,commonStatus:-2,dszt:'10',legacyLessonId:'901',teacherPay:35,payStatus:'earned'}];
  const query=async(sql,args)=>{
   assert.equal(authorized,true,'authorization must precede business queries');
   calls.push({sql,args:plain(args)});active++;peak=Math.max(peak,active);
@@ -22,7 +24,7 @@ function harness(code,{coach=true,deny=false,delay=false,failQuery=false}={}){
  };
  const ctx=vm.createContext({Promise,Date,DEFAULT_COMPANY_ID:'co',number:(v,f=0)=>Number(v)||f,
   authorizeRequestedUser:async()=>{if(deny)throw Error('denied');authorized=true;return 30;},
-  assertLessonTenant:()=>{assert.equal(authorized,true);},mobilePage:()=>({index:1,size:2}),mobilePageMeta:(total,p)=>({itemCount:total,pageSize:p.size}),companionStudentNameSql:()=>"'学生'",
+  assertLessonTenant:()=>{assert.equal(authorized,true);},mobilePage:()=>({index:1,size:2}),mobilePageMeta:(total,p)=>({itemCount:total,pageSize:p.size}),companionLegacyLessonJoin,companionStudentNameSql:()=>"'学生'",
   databaseAppointmentVersions:sideRead('databaseVersion',{version:'db-v'}),appLiveVersionSnapshot:sideRead('liveVersion',{version:'v'}),mobileSource:()=>({source:'database'}),appOverviewToday:()=> '2026-11-10',appOverviewScheduleRow:r=>r,appOverviewCourseRow:r=>r,
   teacherSchedulePay:async r=>{payCalls++;return r;},legacyData:()=>({GroupID:coach?3:1}),legacyUser:()=>({UserID:30,Purse:8}),legacyUserAddon:()=>({Purse:7.5,UserPoint:2}),
   teacherIncomeSummary:sideRead('income',{amount:45}),syncLegacyReviews:sideRead('syncReviews',{state:'current'}),syncLegacyAppointments:sideRead('syncAppointments',{state:'current',items:[]}),withLegacyAppointmentVersion:v=>v,
@@ -33,7 +35,10 @@ function harness(code,{coach=true,deny=false,delay=false,failQuery=false}={}){
 for(const coach of [true,false])for(const history of [true,false])test(`companion preserves exact SQL, arguments, output and earnings (coach=${coach}, history=${history})`,async()=>{
  const input={source:'database',history,month:'2026-11',dateStart:'2026-11-01',dateEnd:'2026-11-30',filter:'pending',studentId:20,search:'学生'};
  const before=harness(baseline,{coach}),after=harness(currentSource,{coach,delay:true});
- assert.deepEqual(plain(await after.ctx.appCompanionOverview(input,after.current)),plain(await before.ctx.appCompanionOverview(input,before.current)));
+ const actual=plain(await after.ctx.appCompanionOverview(input,after.current));
+ assert.deepEqual(actual,plain(await before.ctx.appCompanionOverview(input,before.current)));
+ if(coach&&history)assert.deepEqual(actual.earningsSummary,{amount:80,pendingCount:1});
+ assert.equal(after.calls.some(({sql})=>sql.includes('legacy."legacyLessonId"')),coach&&history);
  const sortCalls=c=>c.map(v=>JSON.stringify(v)).sort();assert.deepEqual(sortCalls(after.calls),sortCalls(before.calls));
  assert.equal(after.stats().payCalls,coach&&history?1:0);
  assert.ok(after.stats().peak>1,'independent cold reads should overlap');assert.ok(after.stats().peak<=3,'at most three SQL reads in flight');assert.equal(after.stats().active,0);