smoke-admin-functions.mjs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #!/usr/bin/env node
  2. import { randomBytes } from 'node:crypto';
  3. import { readFile } from 'node:fs/promises';
  4. const APP_ID = process.env.XIAOSHU_PARSE_APP_ID || '7pIbDBJmKx_main';
  5. const MASTER_KEY = process.env.XIAOSHU_MASTER_KEY || '';
  6. const PARSE_URL = (process.env.XIAOSHU_PARSE_URL || 'https://server.xiaoshu.pro/parse').replace(/\/$/, '');
  7. const FUNCTION_URL = (process.env.XIAOSHU_FUNCTION_URL || 'https://server.xiaoshu.pro/api/functions').replace(/\/$/, '');
  8. if (!MASTER_KEY) throw new Error('缺少 XIAOSHU_MASTER_KEY');
  9. async function jsonRequest(url, init = {}, master = false) {
  10. const response = await fetch(url, {
  11. ...init,
  12. headers: {
  13. 'X-Parse-Application-Id': APP_ID,
  14. ...(master ? { 'X-Parse-Master-Key': MASTER_KEY } : {}),
  15. 'Content-Type': 'application/json',
  16. ...(init.headers || {}),
  17. },
  18. });
  19. const payload = await response.json().catch(() => ({}));
  20. if (!response.ok) {
  21. const detail = payload.message || payload.error || payload;
  22. throw new Error(`${response.status}: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`);
  23. }
  24. return payload;
  25. }
  26. async function callFunction(path, token, params) {
  27. const payload = await jsonRequest(`${FUNCTION_URL}/${path}`, {
  28. method: 'POST',
  29. body: JSON.stringify({ token, params }),
  30. });
  31. if (!payload.success) throw new Error(payload.message || `${path} 返回失败`);
  32. return payload.data;
  33. }
  34. async function callLegacyFunction(token, params, expectedStatus = 200) {
  35. const response = await fetch(`${FUNCTION_URL}/xiaoshu/app/gateway`, {
  36. method: 'POST',
  37. headers: { 'X-Parse-Application-Id': APP_ID, 'Content-Type': 'application/json' },
  38. body: JSON.stringify({ ...(token ? { token } : {}), params }),
  39. });
  40. const payload = await response.json().catch(() => ({}));
  41. if (response.status !== expectedStatus) throw new Error(`app gateway ${params.action} 期望 ${expectedStatus},实际 ${response.status}: ${payload.retmsg || payload.error || ''}`);
  42. return payload;
  43. }
  44. async function sourceActions() {
  45. const source = await readFile(new URL('../src/app/core/source-parity.generated.ts', import.meta.url), 'utf8');
  46. const match = source.match(/export const SOURCE_API_ACTIONS = (\[[\s\S]*?\]) as const;/);
  47. if (!match) throw new Error('无法读取 SOURCE_API_ACTIONS');
  48. return JSON.parse(match[1]);
  49. }
  50. let userId = '';
  51. let memberId = '';
  52. let memberLegacyId = 0;
  53. let teamChildId = '';
  54. let coachId = '';
  55. let coachLegacyId = 0;
  56. let temporaryAppointmentId = '';
  57. let temporaryAppointmentObjectId = '';
  58. const temporaryLessonIds = [];
  59. try {
  60. const sample = await jsonRequest(`${PARSE_URL}/classes/Company?limit=1&keys=objectId`, {}, true);
  61. const companyId = sample.results?.[0]?.objectId;
  62. if (!companyId) throw new Error('没有可用于帐套隔离测试的 Company');
  63. const company = { __type: 'Pointer', className: 'Company', objectId: companyId };
  64. const username = `codex_admin_smoke_${Date.now()}`;
  65. const password = randomBytes(24).toString('base64url');
  66. const created = await jsonRequest(`${PARSE_URL}/users`, {
  67. method: 'POST',
  68. body: JSON.stringify({ username, password, isAdmin: true, roles: ['admin'], company }),
  69. }, true);
  70. userId = created.objectId;
  71. const login = await jsonRequest(`${PARSE_URL}/login`, {
  72. method: 'POST',
  73. body: JSON.stringify({ username, password }),
  74. });
  75. if (!login.sessionToken) throw new Error('临时管理员登录未返回 sessionToken');
  76. const memberUsername = `codex_member_smoke_${Date.now()}`;
  77. const memberPassword = randomBytes(24).toString('base64url');
  78. memberLegacyId = 900000000 + Math.floor(Date.now() / 1000) % 90000000;
  79. const member = await jsonRequest(`${PARSE_URL}/users`, {
  80. method: 'POST',
  81. body: JSON.stringify({ username: memberUsername, password: memberPassword, legacyUserId: memberLegacyId, legacyGroupId: 1, legacyUserData: { UserID: memberLegacyId, UserName: memberUsername, HoneyName: '冒烟学员', GroupID: 1, ParentUserID: 0, VIP: 2, Purse: 2, SilverCoin: 2, UserExp: 2, UserPoint: 2 }, company }),
  82. }, true);
  83. memberId = member.objectId;
  84. const childLegacyId = memberLegacyId + 2;
  85. const child = await jsonRequest(`${PARSE_URL}/users`, {
  86. method: 'POST',
  87. body: JSON.stringify({ username: `codex_team_child_${Date.now()}`, password: randomBytes(24).toString('base64url'), legacyUserId: childLegacyId, legacyGroupId: 3, legacyUserData: { UserID: childLegacyId, UserName: `team_child_${childLegacyId}`, HoneyName: '冒烟团队成员', GroupID: 3, ParentUserID: memberLegacyId, VIP: 3, UserExp: 5, UserPwd: 'must-not-leak' }, company }),
  88. }, true);
  89. teamChildId = child.objectId;
  90. const coachUsername = `codex_coach_smoke_${Date.now()}`;
  91. const coachPassword = randomBytes(24).toString('base64url');
  92. coachLegacyId = memberLegacyId + 1;
  93. const coach = await jsonRequest(`${PARSE_URL}/users`, {
  94. method: 'POST',
  95. body: JSON.stringify({ username: coachUsername, password: coachPassword, legacyUserId: coachLegacyId, legacyGroupId: 3, company }),
  96. }, true);
  97. coachId = coach.objectId;
  98. for (const lessonType of [1, 2, 3]) {
  99. const lesson = await jsonRequest(`${PARSE_URL}/classes/LessonRecord`, {
  100. method: 'POST',
  101. body: JSON.stringify({ company, sourceKey: `cloud:smoke-lesson:${coachLegacyId}:${lessonType}`, jsmz: String(coachLegacyId), kclx: String(lessonType) }),
  102. }, true);
  103. temporaryLessonIds.push(lesson.objectId);
  104. }
  105. const memberLogin = await jsonRequest(`${PARSE_URL}/login`, {
  106. method: 'POST',
  107. body: JSON.stringify({ username: memberUsername, password: memberPassword }),
  108. });
  109. const coachLogin = await jsonRequest(`${PARSE_URL}/login`, {
  110. method: 'POST',
  111. body: JSON.stringify({ username: coachUsername, password: coachPassword }),
  112. });
  113. const createdAppointment = await callLegacyFunction(login.sessionToken, { action: 'content_add', content: JSON.stringify({ ModelID: 54, nodeId: 29, inputer: coachUsername, status: 99, title: memberUsername }), addon: JSON.stringify({ szyh: memberLegacyId, kcid: 16, dslx: 1, dszt: 0, pl: coachLegacyId, fxpl: coachLegacyId, sdsd: '19:00' }) });
  114. temporaryAppointmentId = String(createdAppointment.result);
  115. const appointmentSourceKey = `cloud:content_add:${memberLegacyId}:${temporaryAppointmentId}`;
  116. const appointmentWhere = encodeURIComponent(JSON.stringify({ sourceKey: appointmentSourceKey }));
  117. const appointmentRows = await jsonRequest(`${PARSE_URL}/classes/CourseAppointment?where=${appointmentWhere}&limit=1`, {}, true);
  118. temporaryAppointmentObjectId = appointmentRows.results?.[0]?.objectId || '';
  119. if (!temporaryAppointmentObjectId) throw new Error('临时预约副表创建失败');
  120. const meta = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'meta' });
  121. if (meta.identity?.objectId !== userId || !meta.cloudFunctions) throw new Error('管理员 meta 校验失败');
  122. const dashboard = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dashboard' });
  123. if (!Array.isArray(dashboard.metrics) || dashboard.metrics.length !== 8) throw new Error('dashboard 指标校验失败');
  124. const schema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CourseAppointment' });
  125. if (schema.className !== 'CourseAppointment' || !Array.isArray(schema.fields)) throw new Error('schema 校验失败');
  126. const page = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'list', className: 'CourseAppointment', page: 1, pageSize: 2 });
  127. if (!Array.isArray(page.results) || page.pageSize !== 2) throw new Error('资源分页校验失败');
  128. const normalized = await callFunction('xiaoshu/cms/content-normalizer', login.sessionToken, { content: '<p>中文&nbsp;<strong>内容</strong></p><script>alert(1)</script>' });
  129. if (normalized.content !== '中文 内容') throw new Error(`内容清理结果异常:${normalized.content}`);
  130. const exams = await callFunction('xiaoshu/cms/exams/classes', login.sessionToken, { page: 1, pageSize: 2 });
  131. if (!Array.isArray(exams.results)) throw new Error('考试班级投影校验失败');
  132. const guest = await callFunction('xiaoshu/cms/guest/bar', login.sessionToken, { page: 1, pageSize: 2 });
  133. if (!Array.isArray(guest.results)) throw new Error('互动社区投影校验失败');
  134. const migration = await callLegacyFunction('', { action: 'migration_status' });
  135. const sourceActionList = await sourceActions();
  136. const implementedActions = migration.result?.implemented || [];
  137. const blockedActions = Object.keys(migration.result?.blocked || {});
  138. const covered = new Set([...implementedActions, ...blockedActions]);
  139. const missing = sourceActionList.filter((action) => !covered.has(action));
  140. if (missing.length) throw new Error(`app gateway 迁移矩阵缺少:${missing.join(', ')}`);
  141. const sourceBlocked = blockedActions.filter((action) => sourceActionList.includes(action));
  142. const compatibilityActions = blockedActions.filter((action) => !sourceActionList.includes(action)).sort();
  143. const sourceImplemented = implementedActions.filter((action) => sourceActionList.includes(action));
  144. const compatibilityImplemented = implementedActions.filter((action) => !sourceActionList.includes(action)).sort();
  145. if (sourceImplemented.length !== 33 || sourceBlocked.length !== 58) throw new Error(`app gateway 源 action 计数异常:${sourceImplemented.length} 已映射 / ${sourceBlocked.length} 阻塞`);
  146. if (compatibilityImplemented.join(',') !== 'content_add_zt') throw new Error(`app gateway 已实现兼容 action 计数异常:${compatibilityImplemented.join(',')}`);
  147. if (compatibilityActions.join(',') !== 'product_add,product_upd') throw new Error(`app gateway 阻塞兼容 action 计数异常:${compatibilityActions.join(',')}`);
  148. const content = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 2 });
  149. if (!Array.isArray(content.result) || content.result.length !== 2 || Number(content.page?.itemCount) < 89000) throw new Error('公开内容分页校验失败');
  150. const contentExact = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 1, objectId: content.result[0].objectId });
  151. if (contentExact.result?.[0]?.objectId !== content.result[0].objectId || contentExact.page?.itemCount !== 1) throw new Error('内容 objectId 精确查询校验失败');
  152. const contentDetail = await callLegacyFunction('', { action: 'content_get', id: content.result[0].objectId });
  153. if (contentDetail.result?.objectId !== content.result[0].objectId) throw new Error('内容详情 ID 校验失败');
  154. const words = await callLegacyFunction('', { action: 'content_list', modelId: 52, page: 1, pageSize: 1 });
  155. if (Number(words.page?.itemCount) < 89000 || !words.result?.[0]?.GeneralID || words.result?.[0]?.sy === undefined) throw new Error('词库 addon 联表校验失败');
  156. const privateContent = await callLegacyFunction('', { action: 'content_list', modelId: 56, page: 1, pageSize: 1 }, 401);
  157. if (!String(privateContent.retmsg).includes('登录')) throw new Error('学习记录未阻止匿名访问');
  158. const learning = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 56, page: 1, pageSize: 1 });
  159. if (!learning.result?.[0]?.GeneralID || learning.result?.[0]?.xxqs === undefined) throw new Error('学习记录 addon 联表校验失败');
  160. const recordDetail = await callLegacyFunction(login.sessionToken, { action: 'e_record_detail', id: learning.result[0].GeneralID });
  161. if (!Array.isArray(recordDetail.result) || !recordDetail.result.length || !recordDetail.result[0]?.detail?.[0]?.Title) throw new Error('学习记录单词详情联查校验失败');
  162. const appointments = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 54, page: 1, pageSize: 1 });
  163. const appointment = await callLegacyFunction(login.sessionToken, { action: 'e_order_detail', id: appointments.result?.[0]?.GeneralID });
  164. if (!appointment.result?.[0]?.GeneralID || appointment.result[0].kcid === undefined) throw new Error('预约详情联查校验失败');
  165. const memberProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_get', uid: memberLegacyId });
  166. if (memberProfile.result?.honeyName !== '冒烟学员' || memberProfile.addon?.vip !== 2 || memberProfile.addon?.silverCoin !== 2 || JSON.stringify(memberProfile).includes('must-not-leak')) throw new Error('用户旧契约字段或敏感字段过滤异常');
  167. const teamMembers = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_list', puid: memberLegacyId, cpage: 1, psize: 10 });
  168. if (teamMembers.page?.itemCount !== 1 || Number(teamMembers.result?.[0]?.ParentUserID) !== memberLegacyId || Number(teamMembers.result?.[0]?.VIP) !== 3) throw new Error(`团队成员列表异常:${JSON.stringify(teamMembers)}`);
  169. const teamSummary = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_dept', uid: memberLegacyId });
  170. if (teamSummary.result?.childs !== 1 || teamSummary.result?.v3 !== 1) throw new Error(`团队会员统计异常:${JSON.stringify(teamSummary.result)}`);
  171. const childProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_get', uid: childLegacyId });
  172. if (childProfile.result?.userId !== childLegacyId || childProfile.result?.puid !== memberLegacyId || JSON.stringify(childProfile).includes('must-not-leak')) throw new Error('团队成员详情或密码字段过滤异常');
  173. await callLegacyFunction(coachLogin.sessionToken, { action: 'user_get', uid: childLegacyId }, 403);
  174. const coachStudents = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_user_list', cpage: 1, psize: 10 });
  175. if (coachStudents.page?.itemCount !== 1 || Number(coachStudents.result?.[0]?.szyh) !== memberLegacyId || coachStudents.result?.[0]?.honeyname !== '冒烟学员') throw new Error(`陪练学员分组列表异常:${JSON.stringify(coachStudents)}`);
  176. const newWords = await callLegacyFunction(login.sessionToken, { action: 'e_words_list', uid: 58, page: 1, pageSize: 2 });
  177. if (Number(newWords.page?.itemCount) < 1 || !newWords.result?.[0]?.detail?.[0]?.Title) throw new Error('用户生词联查校验失败');
  178. const courseWords = await callLegacyFunction(login.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1000 });
  179. const learnedWord = courseWords.result?.find((word) => Number(word.GeneralID) === 2505);
  180. if (Number(courseWords.page?.itemCount) < 1 || !courseWords.result?.[0]?.detail?.Title || Number(learnedWord?.w_learned) !== 7) throw new Error('课程词库学习进度联查校验失败');
  181. const memory = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list', uid: 58, page: 1, pageSize: 2 });
  182. if (Number(memory.page?.itemCount) < 1 || !memory.result?.[0]?.GeneralID || memory.result[0].learned === undefined) throw new Error('21 天抗遗忘联查校验失败');
  183. const incomeBlocked = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list_tj', uid: 58 }, 501);
  184. if (!String(incomeBlocked.retmsg).includes('计价规则')) throw new Error('复习收入缺失规则未显式阻塞');
  185. const ownEmpty = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}`, page: 1, pageSize: 1 });
  186. if (!Array.isArray(ownEmpty.result) || ownEmpty.page?.itemCount !== 0) throw new Error('普通用户本人记录权限校验失败');
  187. const ownCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1 });
  188. if (!Array.isArray(ownCourseWords.result) || ownCourseWords.result[0]?.w_learned !== 0) throw new Error('普通用户本人课程词库权限校验失败');
  189. const learnedWrite = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, save: 1 });
  190. if (learnedWrite.result?.created !== 1 || learnedWrite.result?.learnedIncremented !== 1) throw new Error('首次学习词进度写入校验失败');
  191. const learnedRead = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1000 });
  192. if (Number(learnedRead.result?.find((word) => Number(word.GeneralID) === 2505)?.w_learned) !== 1) throw new Error('学习次数写后读校验失败');
  193. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 1 });
  194. const addedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  195. if (addedNewWord.page?.itemCount !== 1 || Number(addedNewWord.result?.[0]?.detail?.[0]?.GeneralID) !== 2505) throw new Error('加入生词写后读校验失败');
  196. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 0 });
  197. const removedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  198. if (removedNewWord.page?.itemCount !== 0) throw new Error('移出生词写后读校验失败');
  199. const scheduledStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_add_zt', content: JSON.stringify({ ModelID: 56, nodeId: 291, inputer: memberUsername, status: 99, Hits: 1, title: memberUsername }), addon: JSON.stringify({ UserID: memberLegacyId, dqrq: '20991231', learned: 1, xxqs: JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 0 }]) }) });
  200. if (!/^\d{15}$/.test(String(scheduledStudy.result))) throw new Error('带复习计划的学习记录创建结果异常');
  201. const scheduledDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: scheduledStudy.result });
  202. const reviewDates = String(scheduledDetail.result?.fxrl || '').split(',').filter(Boolean);
  203. if (reviewDates.length !== 15 || !reviewDates.every((date) => /^\d{8}$/.test(date))) throw new Error('15 段抗遗忘复习日期生成失败');
  204. await callLegacyFunction(coachLogin.sessionToken, { action: 'content_update', content: JSON.stringify({ GeneralID: scheduledStudy.result }), addon: JSON.stringify({ con: '越权更新' }) }, 403);
  205. const scheduledUpdate = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_update', content: JSON.stringify({ GeneralID: scheduledStudy.result, Title: '已更新学习记录' }), addon: JSON.stringify({ con: '规范化内容更新', learned: 1 }) });
  206. if (String(scheduledUpdate.result) !== String(scheduledStudy.result)) throw new Error('规范化内容更新返回值异常');
  207. const updatedScheduledDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: scheduledStudy.result });
  208. if (updatedScheduledDetail.result?.con !== '规范化内容更新' || updatedScheduledDetail.result?.Title !== '已更新学习记录') throw new Error('规范化内容双表更新写后读失败');
  209. const assessment = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_add', content: JSON.stringify({ ModelID: 61, nodeId: 389, inputer: memberUsername, status: 99, Hits: 1, title: memberUsername }), addon: JSON.stringify({ UserID: memberLegacyId, askid: 1, prev_score: 0, totalScore: 10, wrong: 2, dontKnow: 1, answerid: 7, df: 7 }) });
  210. if (!/^\d{15}$/.test(String(assessment.result))) throw new Error('规范化测评内容新增结果异常');
  211. const assessmentDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: assessment.result });
  212. if (String(assessmentDetail.result?.df) !== '7' || String(assessmentDetail.result?.prevScore) !== '0' || Number(assessmentDetail.result?.UserID ?? assessmentDetail.result?.userId) !== memberLegacyId) throw new Error('规范化测评内容新增写后读失败');
  213. const missingSchemaCreate = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_add', content: JSON.stringify({ ModelID: 55, nodeId: 255 }), addon: JSON.stringify({ UserID: memberLegacyId, scnr: '[]' }) }, 501);
  214. if (!String(missingSchemaCreate.retmsg).includes('未迁移内容模型 55')) throw new Error('缺 Schema 内容新增未明确拒绝');
  215. const studyAddon = { con: '云函数学习记录冒烟测试', dqrq: '20260818', fxrl: '20260819,20260820', UserID: memberLegacyId, learned: 1, ygg: 0, djq: 0, xxqs: JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 0 }]) };
  216. const createdStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  217. if (!createdStudy.result?.created || !createdStudy.result?.GeneralID || !createdStudy.result?.recordObjectId) throw new Error('预约学习记录首次双表写入校验失败');
  218. const studyDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_record_detail', id: createdStudy.result.GeneralID });
  219. if (studyDetail.result?.[0]?.detail?.[0]?.Title !== 'woman') throw new Error('预约学习记录写后详情校验失败');
  220. studyAddon.xxqs = JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 1 }]);
  221. const updatedStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  222. if (updatedStudy.result?.created || updatedStudy.result?.GeneralID !== createdStudy.result.GeneralID) throw new Error('预约学习记录幂等更新校验失败');
  223. const studyList = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}|dsid=${temporaryAppointmentId}`, page: 1, pageSize: 2 });
  224. if (studyList.page?.itemCount !== 1 || Number(studyList.result?.[0]?.ygg) !== 1 || Number(studyList.result?.[0]?.learned) !== 1) throw new Error('预约学习记录聚合字段写后读校验失败');
  225. const orderContent = JSON.stringify({ GeneralID: temporaryAppointmentId, UpDateTime: '2026-08-18 13:30' });
  226. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 10, content: orderContent }, 403);
  227. const startedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 10, content: orderContent });
  228. if (startedOrder.result?.previousStatus !== 0 || startedOrder.result?.status !== 10) throw new Error('预约开始状态迁移失败');
  229. const endedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  230. if (endedOrder.result?.reviewCount !== 2 || !endedOrder.result?.periodDeducted) throw new Error('预约结束课时与抗遗忘副作用失败');
  231. const repeatedEnd = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  232. if (!repeatedEnd.result?.unchanged) throw new Error('预约结束状态未保持幂等');
  233. const updatedMember = await jsonRequest(`${PARSE_URL}/users/${memberId}`, {}, true);
  234. if (Number(updatedMember.legacyUserData?.Purse) !== 1 || Number(updatedMember.legacyUserData?.UserPoint) !== 1.5) throw new Error(`预约结束课时扣减异常:${JSON.stringify(updatedMember.legacyUserData)}`);
  235. const sideEffectWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:e_order_update:${temporaryAppointmentId}:` } }));
  236. const [periodLogs, pointLogs, memoryRows, memoryCommonRows] = await Promise.all([
  237. jsonRequest(`${PARSE_URL}/classes/UserExpDomP?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  238. jsonRequest(`${PARSE_URL}/classes/UserUserPoint?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  239. jsonRequest(`${PARSE_URL}/classes/MemoryPracticeRecord?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  240. jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  241. ]);
  242. if (periodLogs.count !== 1 || pointLogs.count !== 1 || memoryRows.count !== 2 || memoryCommonRows.count !== 2) throw new Error(`预约结束账本/抗遗忘数量异常:${periodLogs.count}/${pointLogs.count}/${memoryRows.count}/${memoryCommonRows.count}`);
  243. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 20, content: orderContent }, 403);
  244. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 20, content: orderContent });
  245. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 30, content: orderContent });
  246. const completedOrder = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_detail', id: temporaryAppointmentId });
  247. if (Number(completedOrder.result?.[0]?.dszt) !== 30) throw new Error('预约状态机写后读失败');
  248. const coachStats = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_tongji', uid: coachLegacyId });
  249. if (coachStats.result?.t30 !== '1' || coachStats.result?.t60 !== '1' || coachStats.result?.t_tiyan !== '1' || coachStats.result?.t_total !== '3' || coachStats.result?.t_shichang !== '2.5' || coachStats.result?.t_yongji !== '100') throw new Error('陪练预约统计公式校验失败');
  250. const memberStats = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_tongji', uid: memberLegacyId });
  251. if (memberStats.result?.t30 !== '1' || memberStats.result?.t60 !== '0' || memberStats.result?.t_tiyan !== '0' || memberStats.result?.t_total !== '1' || memberStats.result?.t_shichang !== '0.5' || memberStats.result?.t_yongji !== '0') throw new Error(`学员预约与生词统计公式校验失败:${JSON.stringify(memberStats.result)}`);
  252. const deniedCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1 }, 403);
  253. if (!String(deniedCourseWords.retmsg).includes('无权')) throw new Error('普通用户跨用户课程词库未被拒绝');
  254. const denied = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: 'UserId=3', page: 1, pageSize: 1 }, 403);
  255. if (!String(denied.retmsg).includes('无权')) throw new Error('普通用户跨用户记录未被拒绝');
  256. const profile = await callLegacyFunction(login.sessionToken, { action: 'user_get' });
  257. if (profile.retcode !== 0 || profile.result?.objectId !== userId) throw new Error('app gateway 用户会话校验失败');
  258. const blocked = await callLegacyFunction('', { action: 'cart_list' }, 501);
  259. if (!String(blocked.retmsg).startsWith('migration_blocked:')) throw new Error('阻塞接口未返回 migration_blocked');
  260. console.log('Cloud smoke passed: admin auth/tenant/CRUD reads, CMS projections, normalized learning joins, app action coverage, public content, session scope, explicit blocked APIs.');
  261. } finally {
  262. for (const lessonId of temporaryLessonIds) await jsonRequest(`${PARSE_URL}/classes/LessonRecord/${lessonId}`, { method: 'DELETE' }, true).catch((error) => {
  263. console.error(`临时陪练课次清理失败:${error.message}`);
  264. process.exitCode = 1;
  265. });
  266. if (memberLegacyId) {
  267. const commonWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:(stu_record|content_add_zt|content_add):${memberLegacyId}:` } }));
  268. const commonRows = await jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${commonWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  269. for (const row of commonRows.results || []) await jsonRequest(`${PARSE_URL}/classes/CommonModel/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  270. console.error(`临时学习主记录清理失败:${error.message}`);
  271. process.exitCode = 1;
  272. });
  273. const studyWhere = encodeURIComponent(JSON.stringify({ userId: memberLegacyId }));
  274. const studyRows = await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord?where=${studyWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  275. for (const row of studyRows.results || []) await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  276. console.error(`临时学习 addon 清理失败:${error.message}`);
  277. process.exitCode = 1;
  278. });
  279. }
  280. if (temporaryAppointmentObjectId) await jsonRequest(`${PARSE_URL}/classes/CourseAppointment/${temporaryAppointmentObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  281. console.error(`临时预约清理失败:${error.message}`);
  282. process.exitCode = 1;
  283. });
  284. if (temporaryAppointmentId) {
  285. const sideEffectWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:e_order_update:${temporaryAppointmentId}:` } }));
  286. for (const className of ['CommonModel', 'MemoryPracticeRecord', 'UserExpDomP', 'UserUserPoint']) {
  287. const rows = await jsonRequest(`${PARSE_URL}/classes/${className}?where=${sideEffectWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  288. for (const row of rows.results || []) await jsonRequest(`${PARSE_URL}/classes/${className}/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  289. console.error(`临时预约副作用清理失败(${className}):${error.message}`);
  290. process.exitCode = 1;
  291. });
  292. }
  293. }
  294. if (memberLegacyId) {
  295. const assessmentWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:content_add:${memberLegacyId}:` } }));
  296. const assessments = await jsonRequest(`${PARSE_URL}/classes/AssessmentProfile?where=${assessmentWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  297. for (const assessment of assessments.results || []) await jsonRequest(`${PARSE_URL}/classes/AssessmentProfile/${assessment.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  298. console.error(`临时测评记录清理失败:${error.message}`);
  299. process.exitCode = 1;
  300. });
  301. }
  302. if (memberLegacyId) {
  303. const where = encodeURIComponent(JSON.stringify({ yhid: String(memberLegacyId) }));
  304. const practices = await jsonRequest(`${PARSE_URL}/classes/PracticeRecord?where=${where}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  305. for (const practice of practices.results || []) await jsonRequest(`${PARSE_URL}/classes/PracticeRecord/${practice.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  306. console.error(`临时学习进度清理失败:${error.message}`);
  307. process.exitCode = 1;
  308. });
  309. }
  310. if (teamChildId) {
  311. await jsonRequest(`${PARSE_URL}/users/${teamChildId}`, { method: 'DELETE' }, true).catch((error) => {
  312. console.error(`临时团队成员清理失败:${error.message}`);
  313. process.exitCode = 1;
  314. });
  315. }
  316. if (memberId) {
  317. await jsonRequest(`${PARSE_URL}/users/${memberId}`, { method: 'DELETE' }, true).catch((error) => {
  318. console.error(`临时普通用户清理失败:${error.message}`);
  319. process.exitCode = 1;
  320. });
  321. }
  322. if (coachId) {
  323. await jsonRequest(`${PARSE_URL}/users/${coachId}`, { method: 'DELETE' }, true).catch((error) => {
  324. console.error(`临时陪练用户清理失败:${error.message}`);
  325. process.exitCode = 1;
  326. });
  327. }
  328. if (userId) {
  329. await jsonRequest(`${PARSE_URL}/users/${userId}`, { method: 'DELETE' }, true).catch((error) => {
  330. console.error(`临时管理员清理失败:${error.message}`);
  331. process.exitCode = 1;
  332. });
  333. }
  334. }