import { before, after, test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; import { PGlite } from '@electric-sql/pglite'; const db = new PGlite(); const gateway = {}; vm.createContext(gateway); const source = readFileSync(new URL('../deploy-admin-functions.mjs', import.meta.url), 'utf8'); vm.runInContext(source.match(/const operationsGatewayCode = String.raw`([\s\S]*?)\n`;/)[1], gateway); gateway.companyIdOf = () => 'co'; gateway.companyPointer = () => ({ id: 'co' }); gateway.Psql = { query: async (sql, args) => (await db.query(sql, args)).rows, oneOrNone: async (sql, args) => (await db.query(sql, args)).rows[0] || null, }; gateway.fieldsOf = async () => ({ realName: true, isDisabled: true }); gateway.audit = async () => {}; gateway.availabilityRows = async () => []; gateway.operationalSyncIndicator = async () => ({}); gateway.realtimeCacheWrite = async () => {}; // Parse is external; SQL evidence queries and persisted identity changes use the real database. gateway.Parse = { Query: class { constructor(className) { this.className = className; } async get(id) { if (this.className === 'Company') return { id }; const row = (await db.query('SELECT * FROM "_User" WHERE "objectId"=$1', [id])).rows[0]; return { get: key => row[key], set: (key, value) => { row[key] = value; }, save: async () => db.query('UPDATE "_User" SET "identityType"=$2 WHERE "objectId"=$1', [id, row.identityType]), }; } }, User: class { id = 'new-coach'; fields = {}; set(key, value) { this.fields[key] = value; } setUsername(value) { this.set('username', value); } setPassword() {} async signUp() { const { company, username, realName, isDisabled } = this.fields; await db.query('INSERT INTO "_User" ("objectId",company,username,"realName","isDisabled") VALUES ($1,$2,$3,$4,$5)', [this.id, company.id, username, realName ?? null, isDisabled ?? null]); } async destroy() { await db.query('DELETE FROM "_User" WHERE "objectId"=$1', [this.id]); } }, Object: class { set() {} async save() {} }, }; before(async () => { await db.exec(` CREATE TABLE "_User"("objectId" text,company text,"legacyUserId" int,"legacyGroupId" int,"legacyUserData" jsonb,"isAdmin" boolean,"isDeleted" boolean,"identityType" text,username text,"realName" text,nickname text,"isDisabled" boolean,"createdAt" timestamptz DEFAULT now(),"updatedAt" timestamptz DEFAULT now()); CREATE TABLE "CourseAppointment"(company text,pl text,fxpl text,szyh text,yysj text,bxrq text,dszt text,id int,jssj text); CREATE TABLE "LessonRecord"(company text,jsmz text,xymz text,kclx text,pf text,plpjsj text,"lessonAt" text,id int,yyds text); CREATE TABLE "CommonModel"(company text,"modelId" int,"itemId" int,"generalId" int,"createdAt" timestamptz); CREATE TABLE "DailyStudyRecord"(company text,"userId" int); CREATE TABLE "CourseBinding"(company text,yhid text); CREATE TABLE "PracticeRecord"(company text,yhid text); CREATE TABLE "LegacySyncConflict"("objectId" text,company text,dataset text,"legacyKey" text,resolved boolean); INSERT INTO "_User" ("objectId",company,"legacyUserId","legacyGroupId","legacyUserData","isAdmin","isDeleted","identityType") VALUES ('teacher','co',1535,3,'{}',false,false,'conflict'), ('student','co',2,1,'{}',false,false,'member'), ('ambiguous','co',3,1,'{}',false,false,'conflict'), ('dual-binding','co',4,3,'{}',false,false,'conflict'), ('dual-lesson','co',5,3,'{}',false,false,'conflict'), ('store','co',6,2,'{}',false,false,'store'), ('native-both','co',7,3,'{"UserID":7,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,'coach'), ('legacy-unproven','co',8,3,'{}',false,false,'unknown'); INSERT INTO "CourseAppointment" (company,pl,fxpl,szyh) VALUES ('co','1535','1535','99'),('co','3',null,'99'),('co','4',null,'99'),('co','6',null,'6'),('other','99',null,'1535'); INSERT INTO "LessonRecord" (company,jsmz,xymz) VALUES ('co','5','5'); INSERT INTO "CourseBinding" VALUES ('co','4'),('co','7'); INSERT INTO "PracticeRecord" VALUES ('co','1535'),('co','2'),('co','3'); `); await gateway.refreshIdentityProjection({}, {}); }); after(() => db.close()); const identity = async id => (await db.query('SELECT "identityType" FROM "_User" WHERE "objectId"=$1', [id])).rows[0].identityType; test('正式老师自己的单词练习不再把老师误标为冲突,其他帐套学员证据不串入', async () => { assert.equal(await identity('teacher'), 'coach'); await gateway.refreshIdentityProjection({}, {}); assert.equal(await identity('teacher'), 'coach'); }); test('仅练习的普通学员仍是学员,分组未经确认的双重身份仍需核实', async () => { assert.equal(await identity('student'), 'member'); assert.equal(await identity('ambiguous'), 'conflict'); }); test('老师同时有正式学员课程或课后记录时仍保留冲突,门店角色不改变', async () => { assert.equal(await identity('dual-binding'), 'conflict'); assert.equal(await identity('dual-lesson'), 'conflict'); assert.equal(await identity('store'), 'store'); }); const manager = { roles: ['ops-manager'] }; const snapshot = { appointments: [], live: { allItems: [] } }; const payroll = { coachItems: [], sourceStatus: {} }; const searchCoaches = search => gateway.professionalCoachRows(manager, { search, refresh: true }, snapshot, payroll); test('后台新增陪练后没有排课记录也能立即按姓名搜索,并在重建身份后仍可见', async () => { const created = await gateway.createCoach(manager, { reason: '创建测试老师' }, { username: 'coach_without_lessons', displayName: '零课次陪练', password: 'test-password', }); const found = await searchCoaches('零课次'); assert.equal(found.total, 1); assert.equal(found.items[0].objectId, created.objectId); assert.equal(found.items[0].monthLessons, 0); assert.equal((await gateway.userByLegacyId(manager, {}, created.userId, 3)).identityType, 'coach'); await gateway.refreshIdentityProjection({}, {}); assert.equal((await searchCoaches('coach_without_lessons')).items[0].userId, created.userId); assert.equal(await identity('native-both'), 'conflict'); assert.equal(await identity('legacy-unproven'), 'unknown'); }); test('补录只恢复本帐套后台创建且缺少正确身份的原账号,重复执行无额外更新', async () => { await db.exec(` INSERT INTO "_User" ("objectId",company,"legacyUserId","legacyGroupId","legacyUserData","isAdmin","isDeleted","identityType",username) VALUES ('missing','co',21,3,'{"UserID":21,"GroupID":3,"HoneyName":"漏标陪练","OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,null,'existing_coach'), ('practice-only','co',22,3,'{"UserID":22,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,'member','practising_coach'), ('student-evidence','co',23,3,'{"UserID":23,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,'unknown','student_evidence'), ('deleted','co',24,3,'{"UserID":24,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,true,'unknown','deleted_coach'), ('other-tenant','other',25,3,'{"UserID":25,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,null,'other_coach'); INSERT INTO "PracticeRecord" VALUES ('co','22'); INSERT INTO "CourseBinding" VALUES ('co','23'),('other','21'); `); assert.equal((await searchCoaches('漏标陪练')).total, 0); const sql = readFileSync(new URL('../sql/repair-ops-coach-identity.sql', import.meta.url), 'utf8'); const result = await db.query(sql, ['co']); assert.deepEqual(result.rows.map(row => row.objectId).sort(), ['missing', 'practice-only']); assert.equal((await searchCoaches('漏标陪练')).items[0].userId, 21); assert.equal((await db.query(sql, ['co'])).rows.length, 0); });