Ver Fonte

fix(schedule): hide cancelled appointments in the scheduling center

彭峰 há 5 horas atrás
pai
commit
2d53619b58

+ 1 - 1
projects/xiaoshu-admin/src/app/pages/operations-schedule-status.ts

@@ -22,7 +22,6 @@ export type ScheduleStatusFilter =
   | 'archived'
   | 'overdue'
   | 'unverified'
-  | 'cancelled'
   | 'unassigned';
 
 const scheduleStatusLabels: Partial<Record<number, string>> = {
@@ -68,6 +67,7 @@ export function scheduleMatchesStatus(
   filter: ScheduleStatusFilter,
   now = Date.now(),
 ): boolean {
+  if (item.cancelled) return false;
   if (filter === 'all') return true;
   if (filter === 'unassigned') return !item.coachId || item.coachAccountMissing === true;
   return scheduleStatusTone(item, now) === `status-${filter}`;

+ 2 - 3
projects/xiaoshu-admin/src/app/pages/operations-schedule.component.html

@@ -47,12 +47,12 @@
 <section class="schedule-filterbar" aria-label="排课记录筛选">
   <div class="planner-filter-fields">
   <label class="schedule-search"><span>搜索排课</span><span class="filter-control"><lucide-icon [img]="icons.Search" [size]="16"/><input type="search" [ngModel]="scheduleSearchInput()" (ngModelChange)="scheduleSearchInput.set($event)" (keydown.enter)="applyScheduleFilters()" placeholder="学员、陪练、课程或业务ID"/></span></label>
-  <label class="status-filter"><span>业务状态</span><select [ngModel]="statusFilterInput()" (ngModelChange)="statusFilterInput.set($event)"><option value="all">全部状态</option><option value="upcoming">待开始</option><option value="live">训练中</option><option value="coach-ended">陪练已结束</option><option value="confirmed">学员已确认</option><option value="completed">已完课</option><option value="archived">已归档</option><option value="overdue">逾期未完成</option><option value="unverified">状态待核对</option><option value="cancelled">已取消</option><option value="unassigned">待分配 / 账号异常</option></select></label>
+  <label class="status-filter"><span>业务状态</span><select [ngModel]="statusFilterInput()" (ngModelChange)="statusFilterInput.set($event)"><option value="all">全部状态</option><option value="upcoming">待开始</option><option value="live">训练中</option><option value="coach-ended">陪练已结束</option><option value="confirmed">学员已确认</option><option value="completed">已完课</option><option value="archived">已归档</option><option value="overdue">逾期未完成</option><option value="unverified">状态待核对</option><option value="unassigned">待分配 / 账号异常</option></select></label>
   <div class="filter-actions">
     <button class="find-button" type="button" (click)="applyScheduleFilters()" [disabled]="searching()"><lucide-icon [img]="searching()?icons.LoaderCircle:icons.Search" [size]="16" [class.spin]="searching()" />{{searching()?'正在查找':'查找'}}</button>
     <button class="reset-button" type="button" (click)="clearScheduleFilters()" [disabled]="searching()"><lucide-icon [img]="icons.RotateCcw" [size]="15" />重置</button>
   </div>
-  <div class="filter-result" role="status"><strong>{{visibleAppointments().length}}</strong><span>条筛选结果</span><small>当前范围共 {{data()?.appointments?.length||0}} 条</small></div>
+  <div class="filter-result" role="status"><strong>{{visibleAppointments().length}}</strong><span>条筛选结果</span><small>当前范围共 {{activeAppointments()}} 条</small></div>
   </div>
 </section>
 </section>
@@ -84,7 +84,6 @@
       <span class="status-archived"><i></i>已归档</span>
       <span class="status-overdue"><i></i>逾期未完成</span>
       <span class="status-unverified"><i></i>状态待核对</span>
-      <span class="status-cancelled"><i></i>已取消</span>
     </div>
   </header>
   @if(view()==='list'){

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

@@ -86,6 +86,10 @@ describe('排课状态视觉分类', () => {
 
   it('支持运营人员按业务状态和待分配异常筛选', () => {
     const upcoming = { cancelled: false, statusCode: 0, endsAt: '2026-08-21T01:00:00.000Z', coachId: 88, coachAccountMissing: false };
+    const cancelled = { ...upcoming, cancelled: true, coachId: 0 };
+    for (const filter of ['all', 'unassigned', 'upcoming'] as const) {
+      expect(scheduleMatchesStatus(cancelled, filter, now)).toBeFalse();
+    }
     expect(scheduleMatchesStatus(upcoming, 'upcoming', now)).toBeTrue();
     expect(scheduleMatchesStatus(upcoming, 'overdue', now)).toBeFalse();
     expect(scheduleMatchesStatus({ ...upcoming, coachId: 0 }, 'unassigned', now)).toBeTrue();

+ 5 - 5
projects/xiaoshu-admin/src/app/pages/schedule-bulk-manager.component.spec.ts

@@ -20,20 +20,20 @@ describe('跨日期预约批量管理',()=>{
  });
  it('按姓名跨日期查询,全选所有匹配页,排除已取消和训练中课程,并可取消单项',async()=>{
   const c=TestBed.createComponent(ScheduleBulkManagerComponent).componentInstance;c.searchInput='杨珍';await c.searchAppointments();
-  expect(ops.list).toHaveBeenCalledWith('appointments',1,25,'杨珍',{dateFrom:'',dateTo:''});await c.selectAllMatching();expect(c.selected().size).toBe(199);expect(c.selected().has('a199')).toBeFalse();expect(c.selected().has('a200')).toBeFalse();
+  expect(ops.list).toHaveBeenCalledWith('appointments',1,25,'杨珍',{dateFrom:'',dateTo:'',excludeCancelled:true});await c.selectAllMatching();expect(c.selected().size).toBe(199);expect(c.selected().has('a199')).toBeFalse();expect(c.selected().has('a200')).toBeFalse();
   c.toggleRow(rows[0] as any);expect(c.selected().size).toBe(198);
  });
  it('批量请求附带版本和未开始保护,部分失败保留待核对项',async()=>{
   const c=TestBed.createComponent(ScheduleBulkManagerComponent).componentInstance;c.searchInput='杨珍';await c.searchAppointments();c.toggleRow(rows[0] as any);c.toggleRow(rows[1] as any);
-  spyOn(window,'confirm').and.returnValue(true);ops.mutate.and.callFake(async(_op,id)=>{if(id==='a1')throw Error('预约已变更');return {} as any;});
+  spyOn(window,'confirm').and.returnValue(true);ops.mutate.and.callFake(async(_op,id)=>{if(id==='a1')throw Error('预约已变更');ops.list.and.resolveTo({items:rows.slice(1,26),total:199} as any);return {} as any;});
   await c.cancelSelected();expect(ops.mutate.calls.count()).toBe(2);expect(ops.mutate.calls.allArgs()[0]).toEqual(['ops/appointments/cancel','a0','批量调整排课',{onlyUnstarted:true},rows[0].updatedAt]);
   expect(c.selected().has('a0')).toBeFalse();expect(c.selected().has('a1')).toBeTrue();expect(c.message()).toContain('1');expect(c.error()).toContain('预约已变更');
-  expect(c.rows()[0].cancelled).toBeTrue();expect(c.canSelect({...rows[0],statusUnverified:true} as any)).toBeFalse();
+  expect(c.rows().some(row=>row.targetId==='a0')).toBeFalse();expect(c.canSelect({...rows[0],statusUnverified:true} as any)).toBeFalse();
  });
  it('查询、翻页、每页条数与跨页全选使用已应用的预约日期范围',async()=>{
   const c=TestBed.createComponent(ScheduleBulkManagerComponent).componentInstance as any;
   c.searchInput='杨珍';c.dateFromInput='2026-11-01';c.dateToInput='2026-11-30';await c.searchAppointments();
-  const filters={dateFrom:'2026-11-01',dateTo:'2026-11-30'};
+  const filters={dateFrom:'2026-11-01',dateTo:'2026-11-30',excludeCancelled:true};
   expect(ops.list).toHaveBeenCalledWith('appointments',1,25,'杨珍',filters);
   await c.changePage(2);expect(ops.list).toHaveBeenCalledWith('appointments',2,25,'杨珍',filters);
   await c.changePageSize(50);expect(ops.list).toHaveBeenCalledWith('appointments',1,50,'杨珍',filters);
@@ -61,7 +61,7 @@ describe('跨日期预约批量管理',()=>{
   c.searchInput='杨珍';c.dateFromInput='2026-11-01';c.dateToInput='2026-11-30';await c.searchAppointments();c.toggleRow(rows[0] as any);
   await c.resetFilters();
   expect(c.searchInput).toBe('');expect(c.dateFromInput).toBe('');expect(c.dateToInput).toBe('');expect(c.selected().size).toBe(0);
-  expect(ops.list).toHaveBeenCalledWith('appointments',1,25,'',{dateFrom:'',dateTo:''});
+  expect(ops.list).toHaveBeenCalledWith('appointments',1,25,'',{dateFrom:'',dateTo:'',excludeCancelled:true});
  });
  it('新日期查询失败后不能勾选或取消旧列表中的预约',async()=>{
   const c=TestBed.createComponent(ScheduleBulkManagerComponent).componentInstance;

+ 6 - 3
projects/xiaoshu-admin/src/app/pages/schedule-bulk-manager.component.ts

@@ -23,7 +23,7 @@ export class ScheduleBulkManagerComponent implements OnInit {
  ngOnInit():void{void this.loadPage();}
  canSelect(row:ScheduleAppointment):boolean{return Boolean(row.targetId&&row.updatedAt)&&!row.readOnly&&!row.statusUnverified&&!row.cancelled&&Number(row.statusCode)===0;}
  hasPendingFilters():boolean{return this.searchInput.trim()!==this.query()||this.dateFromInput!==this.dateFrom()||this.dateToInput!==this.dateTo();}
- private filters():Record<string,unknown>{return{dateFrom:this.dateFrom(),dateTo:this.dateTo()};}
+ private filters():Record<string,unknown>{return{dateFrom:this.dateFrom(),dateTo:this.dateTo(),excludeCancelled:true};}
  async searchAppointments():Promise<void>{
   if(this.loading()||this.selecting()||this.saving())return;
   if(this.dateFromInput&&this.dateToInput&&this.dateFromInput>this.dateToInput){this.error.set('开始日期不能晚于结束日期');return;}
@@ -65,10 +65,13 @@ export class ScheduleBulkManagerComponent implements OnInit {
   this.saving.set(true);this.error.set('');this.message.set('');this.progress.set({done:0,total:items.length});let index=0;const succeeded:string[]=[],failed:{row:ScheduleAppointment;message:string}[]=[];
   const worker=async()=>{while(index<items.length){const row=items[index++];try{await cancelAppointmentWithReadback(this.operations,row,reason,true);succeeded.push(row.targetId);}catch(e){failed.push({row,message:e instanceof Error?e.message:'结果待核对'});}finally{this.progress.update(p=>({...p,done:p.done+1}));}}};
   try{await this.operations.batchMutations(async()=>{await worker();this.selected.update(current=>{const next=new Map(current);for(const id of succeeded)next.delete(id);return next;});
-   const completed=new Set(succeeded);this.rows.update(rows=>rows.map(row=>completed.has(row.targetId)?{...row,cancelled:true,statusLabel:'已取消'}:row));
+   const completed=new Set(succeeded);this.rows.update(rows=>rows.filter(row=>!completed.has(row.targetId)));
+   this.total.update(total=>Math.max(0,total-completed.size));
    this.message.set(`已取消 ${succeeded.length} 条${failed.length?`,${failed.length} 条未成功或待核对`:''}`);if(failed.length)this.error.set(failed.slice(0,5).map(x=>`${x.row.studentName} ${x.row.startsAt?new Date(x.row.startsAt).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false}):''}:${x.message}`).join(';')+(failed.length>5?';其余请刷新核对':''));
    this.changed.emit();
-  });}finally{this.saving.set(false);}
+  });
+   if(succeeded.length){const cancellationError=this.error();await this.loadPage();if(cancellationError)this.error.set([cancellationError,this.error()].filter(Boolean).join(';'));}
+  }finally{this.saving.set(false);}
   // Unverified targets stay selected; only explicit user action can submit them again.
  }
  close():void{if(!this.saving()&&!this.selecting()){this.closed.emit();if(this.progress().total>0&&this.selected().size)this.changed.emit();}}

+ 1 - 0
scripts/deploy-admin-functions.mjs

@@ -3444,6 +3444,7 @@ async function businessRecordSqlPage(kind,sql,args,input){
  if(input._storeId){values.push(String(input._storeId));where+=(where?' AND ':' WHERE ')+"record.\"studentLegacy\"->>'ParentUserID'=$"+values.length;}
  const appointmentAt="COALESCE(CASE WHEN \"yysj\" ~ '[ T][0-9]{1,2}:[0-9]{2}' THEN xs_payroll_time(\"yysj\") END,xs_payroll_time(NULLIF(\"bxrq\",'')||' '||COALESCE(NULLIF(\"sdsd\",''),'00:00')))";
  if(kind==='appointments'){
+  if(paging.filters.excludeCancelled===true)where+=(where?' AND ':' WHERE ')+'record."commonStatus" IS DISTINCT FROM -2';
   const from=text(paging.filters.dateFrom),to=text(paging.filters.dateTo);
   for(const date of [from,to])if(date){const parsed=new Date(date+'T00:00:00Z');if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||Number.isNaN(parsed.getTime())||parsed.toISOString().slice(0,10)!==date)fail(400,'预约日期无效');}
   if(from&&to&&from>to)fail(400,'开始日期不能晚于结束日期');

+ 3 - 0
scripts/tests/business-record-pagination.test.mjs

@@ -60,6 +60,9 @@ test('跨日期预约按实际预约时间倒序后分页,忽略更新时间
   }
   assert.deepEqual(items.map(row=>row.targetId),['z-tie','february','separate-date','fallback-date','date-only','later-time','utc','january','december','unknown']);
   const range=await ctx.businessRecordSqlPage('appointments','SELECT * FROM appointments WHERE company=$1',['co'],{page:2,pageSize:2,search:'目标学员',filters:{dateFrom:'2027-01-02',dateTo:'2027-01-02'}});
+  await db.exec(`ALTER TABLE appointments ADD COLUMN "commonStatus" int; UPDATE appointments SET "commonStatus"=-2 WHERE "targetId"='later-time'`);
+  const visible=await ctx.businessRecordSqlPage('appointments','SELECT * FROM appointments WHERE company=$1',['co'],{page:1,pageSize:2,search:'目标学员',filters:{dateFrom:'2027-01-02',dateTo:'2027-01-02',excludeCancelled:true}});
+  assert.equal(visible.total,3);assert.deepEqual(visible.items.map(row=>row.targetId),['date-only','utc']);
   assert.equal(range.total,4);assert.deepEqual(range.items.map(row=>row.targetId),['utc','january']);
  }finally{await db.close();}
 });