coach-identity-projection.test.mjs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import { before, after, test } from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { readFileSync } from 'node:fs';
  4. import vm from 'node:vm';
  5. import { PGlite } from '@electric-sql/pglite';
  6. const db = new PGlite();
  7. const gateway = {};
  8. vm.createContext(gateway);
  9. const source = readFileSync(new URL('../deploy-admin-functions.mjs', import.meta.url), 'utf8');
  10. vm.runInContext(source.match(/const operationsGatewayCode = String.raw`([\s\S]*?)\n`;/)[1], gateway);
  11. gateway.companyIdOf = () => 'co';
  12. gateway.companyPointer = () => ({ id: 'co' });
  13. gateway.Psql = {
  14. query: async (sql, args) => (await db.query(sql, args)).rows,
  15. oneOrNone: async (sql, args) => (await db.query(sql, args)).rows[0] || null,
  16. };
  17. gateway.fieldsOf = async () => ({ realName: true, isDisabled: true });
  18. gateway.audit = async () => {};
  19. gateway.availabilityRows = async () => [];
  20. gateway.operationalSyncIndicator = async () => ({});
  21. gateway.realtimeCacheWrite = async () => {};
  22. // Parse is external; SQL evidence queries and persisted identity changes use the real database.
  23. gateway.Parse = {
  24. Query: class {
  25. constructor(className) { this.className = className; }
  26. async get(id) {
  27. if (this.className === 'Company') return { id };
  28. const row = (await db.query('SELECT * FROM "_User" WHERE "objectId"=$1', [id])).rows[0];
  29. return {
  30. get: key => row[key], set: (key, value) => { row[key] = value; },
  31. save: async () => db.query('UPDATE "_User" SET "identityType"=$2 WHERE "objectId"=$1', [id, row.identityType]),
  32. };
  33. }
  34. },
  35. User: class {
  36. id = 'new-coach';
  37. fields = {};
  38. set(key, value) { this.fields[key] = value; }
  39. setUsername(value) { this.set('username', value); }
  40. setPassword() {}
  41. async signUp() {
  42. const { company, username, realName, isDisabled } = this.fields;
  43. await db.query('INSERT INTO "_User" ("objectId",company,username,"realName","isDisabled") VALUES ($1,$2,$3,$4,$5)',
  44. [this.id, company.id, username, realName ?? null, isDisabled ?? null]);
  45. }
  46. async destroy() { await db.query('DELETE FROM "_User" WHERE "objectId"=$1', [this.id]); }
  47. },
  48. Object: class { set() {} async save() {} },
  49. };
  50. before(async () => {
  51. await db.exec(`
  52. 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());
  53. CREATE TABLE "CourseAppointment"(company text,pl text,fxpl text,szyh text,yysj text,bxrq text,dszt text,id int,jssj text);
  54. CREATE TABLE "LessonRecord"(company text,jsmz text,xymz text,kclx text,pf text,plpjsj text,"lessonAt" text,id int,yyds text);
  55. CREATE TABLE "CommonModel"(company text,"modelId" int,"itemId" int,"generalId" int,"createdAt" timestamptz);
  56. CREATE TABLE "DailyStudyRecord"(company text,"userId" int);
  57. CREATE TABLE "CourseBinding"(company text,yhid text);
  58. CREATE TABLE "PracticeRecord"(company text,yhid text);
  59. CREATE TABLE "LegacySyncConflict"("objectId" text,company text,dataset text,"legacyKey" text,resolved boolean);
  60. INSERT INTO "_User" ("objectId",company,"legacyUserId","legacyGroupId","legacyUserData","isAdmin","isDeleted","identityType") VALUES
  61. ('teacher','co',1535,3,'{}',false,false,'conflict'),
  62. ('student','co',2,1,'{}',false,false,'member'),
  63. ('ambiguous','co',3,1,'{}',false,false,'conflict'),
  64. ('dual-binding','co',4,3,'{}',false,false,'conflict'),
  65. ('dual-lesson','co',5,3,'{}',false,false,'conflict'),
  66. ('store','co',6,2,'{}',false,false,'store'),
  67. ('native-both','co',7,3,'{"UserID":7,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,'coach'),
  68. ('legacy-unproven','co',8,3,'{}',false,false,'unknown');
  69. 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');
  70. INSERT INTO "LessonRecord" (company,jsmz,xymz) VALUES ('co','5','5');
  71. INSERT INTO "CourseBinding" VALUES ('co','4'),('co','7');
  72. INSERT INTO "PracticeRecord" VALUES ('co','1535'),('co','2'),('co','3');
  73. `);
  74. await gateway.refreshIdentityProjection({}, {});
  75. });
  76. after(() => db.close());
  77. const identity = async id => (await db.query('SELECT "identityType" FROM "_User" WHERE "objectId"=$1', [id])).rows[0].identityType;
  78. test('正式老师自己的单词练习不再把老师误标为冲突,其他帐套学员证据不串入', async () => {
  79. assert.equal(await identity('teacher'), 'coach');
  80. await gateway.refreshIdentityProjection({}, {});
  81. assert.equal(await identity('teacher'), 'coach');
  82. });
  83. test('仅练习的普通学员仍是学员,分组未经确认的双重身份仍需核实', async () => {
  84. assert.equal(await identity('student'), 'member');
  85. assert.equal(await identity('ambiguous'), 'conflict');
  86. });
  87. test('老师同时有正式学员课程或课后记录时仍保留冲突,门店角色不改变', async () => {
  88. assert.equal(await identity('dual-binding'), 'conflict');
  89. assert.equal(await identity('dual-lesson'), 'conflict');
  90. assert.equal(await identity('store'), 'store');
  91. });
  92. const manager = { roles: ['ops-manager'] };
  93. const snapshot = { appointments: [], live: { allItems: [] } };
  94. const payroll = { coachItems: [], sourceStatus: {} };
  95. const searchCoaches = search => gateway.professionalCoachRows(manager, { search, refresh: true }, snapshot, payroll);
  96. test('后台新增陪练后没有排课记录也能立即按姓名搜索,并在重建身份后仍可见', async () => {
  97. const created = await gateway.createCoach(manager, { reason: '创建测试老师' }, {
  98. username: 'coach_without_lessons', displayName: '零课次陪练', password: 'test-password',
  99. });
  100. const found = await searchCoaches('零课次');
  101. assert.equal(found.total, 1);
  102. assert.equal(found.items[0].objectId, created.objectId);
  103. assert.equal(found.items[0].monthLessons, 0);
  104. assert.equal((await gateway.userByLegacyId(manager, {}, created.userId, 3)).identityType, 'coach');
  105. await gateway.refreshIdentityProjection({}, {});
  106. assert.equal((await searchCoaches('coach_without_lessons')).items[0].userId, created.userId);
  107. assert.equal(await identity('native-both'), 'conflict');
  108. assert.equal(await identity('legacy-unproven'), 'unknown');
  109. });
  110. test('补录只恢复本帐套后台创建且缺少正确身份的原账号,重复执行无额外更新', async () => {
  111. await db.exec(`
  112. INSERT INTO "_User" ("objectId",company,"legacyUserId","legacyGroupId","legacyUserData","isAdmin","isDeleted","identityType",username) VALUES
  113. ('missing','co',21,3,'{"UserID":21,"GroupID":3,"HoneyName":"漏标陪练","OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,null,'existing_coach'),
  114. ('practice-only','co',22,3,'{"UserID":22,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,'member','practising_coach'),
  115. ('student-evidence','co',23,3,'{"UserID":23,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,'unknown','student_evidence'),
  116. ('deleted','co',24,3,'{"UserID":24,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,true,'unknown','deleted_coach'),
  117. ('other-tenant','other',25,3,'{"UserID":25,"GroupID":3,"OpsCreatedAt":"2026-11-27T00:00:00.000Z"}',false,false,null,'other_coach');
  118. INSERT INTO "PracticeRecord" VALUES ('co','22');
  119. INSERT INTO "CourseBinding" VALUES ('co','23'),('other','21');
  120. `);
  121. assert.equal((await searchCoaches('漏标陪练')).total, 0);
  122. const sql = readFileSync(new URL('../sql/repair-ops-coach-identity.sql', import.meta.url), 'utf8');
  123. const result = await db.query(sql, ['co']);
  124. assert.deepEqual(result.rows.map(row => row.objectId).sort(), ['missing', 'practice-only']);
  125. assert.equal((await searchCoaches('漏标陪练')).items[0].userId, 21);
  126. assert.equal((await db.query(sql, ['co'])).rows.length, 0);
  127. });