smoke-admin-functions.mjs 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 callFunctionError(path, token, params, expectedStatus) {
  35. const response = await fetch(`${FUNCTION_URL}/${path}`, {
  36. method: 'POST',
  37. headers: { 'X-Parse-Application-Id': APP_ID, 'Content-Type': 'application/json' },
  38. body: JSON.stringify({ token, params }),
  39. });
  40. const payload = await response.json().catch(() => ({}));
  41. if (response.status !== expectedStatus || payload.success !== false) throw new Error(`${path} 期望 ${expectedStatus} 失败,实际 ${response.status}: ${payload.message || payload.error || ''}`);
  42. return payload;
  43. }
  44. async function callLegacyFunction(token, params, expectedStatus = 200) {
  45. const response = await fetch(`${FUNCTION_URL}/xiaoshu/app/gateway`, {
  46. method: 'POST',
  47. headers: { 'X-Parse-Application-Id': APP_ID, 'Content-Type': 'application/json' },
  48. body: JSON.stringify({ ...(token ? { token } : {}), params }),
  49. });
  50. const payload = await response.json().catch(() => ({}));
  51. if (response.status !== expectedStatus) throw new Error(`app gateway ${params.action} 期望 ${expectedStatus},实际 ${response.status}: ${payload.retmsg || payload.error || ''}`);
  52. return payload;
  53. }
  54. async function sourceActions() {
  55. const source = await readFile(new URL('../src/app/core/source-parity.generated.ts', import.meta.url), 'utf8');
  56. const match = source.match(/export const SOURCE_API_ACTIONS = (\[[\s\S]*?\]) as const;/);
  57. if (!match) throw new Error('无法读取 SOURCE_API_ACTIONS');
  58. return JSON.parse(match[1]);
  59. }
  60. let userId = '';
  61. let adminCreatedUserId = '';
  62. let temporaryGroupObjectId = '';
  63. const temporaryNodeObjectIds = [];
  64. const temporarySpecialObjectIds = [];
  65. const temporaryGuestCategoryObjectIds = [];
  66. const temporaryExamClassObjectIds = [];
  67. const temporaryExamPointObjectIds = [];
  68. const temporaryKnowledgeObjectIds = [];
  69. let temporaryModelObjectId = '';
  70. const temporaryModelFieldObjectIds = [];
  71. let registeredUserId = '';
  72. let memberId = '';
  73. let memberLegacyId = 0;
  74. let teamChildId = '';
  75. let coachId = '';
  76. let coachLegacyId = 0;
  77. let temporaryAppointmentId = '';
  78. let temporaryAppointmentObjectId = '';
  79. let temporaryGuestbookId = '';
  80. let temporaryGuestbookReplyId = '';
  81. let temporaryGuestBarId = '';
  82. let contentHitObjectId = '';
  83. let contentHitOriginal = 0;
  84. const temporaryLessonIds = [];
  85. try {
  86. const sample = await jsonRequest(`${PARSE_URL}/classes/Company?limit=1&keys=objectId`, {}, true);
  87. const companyId = sample.results?.[0]?.objectId;
  88. if (!companyId) throw new Error('没有可用于帐套隔离测试的 Company');
  89. const company = { __type: 'Pointer', className: 'Company', objectId: companyId };
  90. const username = `codex_admin_smoke_${Date.now()}`;
  91. const password = randomBytes(24).toString('base64url');
  92. const created = await jsonRequest(`${PARSE_URL}/users`, {
  93. method: 'POST',
  94. body: JSON.stringify({ username, password, isAdmin: true, roles: ['admin'], company }),
  95. }, true);
  96. userId = created.objectId;
  97. const login = await jsonRequest(`${PARSE_URL}/login`, {
  98. method: 'POST',
  99. body: JSON.stringify({ username, password }),
  100. });
  101. if (!login.sessionToken) throw new Error('临时管理员登录未返回 sessionToken');
  102. const registeredUsername = `codex_register_smoke_${Date.now()}`;
  103. const registered = await callLegacyFunction('', { action: 'user_register', name: registeredUsername, passwd: 'Ab1234' });
  104. registeredUserId = String(registered.result?.objectId || '');
  105. const registeredLegacyId = Number(registered.result?.userId);
  106. if (!registeredUserId || !registeredLegacyId || !registered.result?.sessionToken || Number(registered.result?.groupId) !== 1 || Number(registered.addon?.parentUserId) !== 0) throw new Error(`新用户注册基础字段异常:${JSON.stringify(registered)}`);
  107. const registeredInfo = await callLegacyFunction(registered.result.sessionToken, { action: 'user_get', uid: registeredLegacyId });
  108. if (Number(registeredInfo.result?.userId) !== registeredLegacyId || Number(registeredInfo.result?.groupId) !== 1 || Number(registeredInfo.addon?.Purse) !== 0 || Number(registeredInfo.addon?.UserPoint) !== 0) throw new Error('新用户注册后自查异常');
  109. const registeredByName = await callLegacyFunction('', { action: 'user_info_name', uname: registeredUsername });
  110. if (registeredByName.result?.objectId !== registeredUserId) throw new Error('新用户用户名查重异常');
  111. await jsonRequest(`${PARSE_URL}/users/${registeredUserId}`, { method: 'DELETE' }, true);
  112. registeredUserId = '';
  113. const memberUsername = `codex_member_smoke_${Date.now()}`;
  114. const memberPassword = randomBytes(24).toString('base64url');
  115. memberLegacyId = 900000000 + Math.floor(Date.now() / 1000) % 90000000;
  116. const member = await jsonRequest(`${PARSE_URL}/users`, {
  117. method: 'POST',
  118. 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 }),
  119. }, true);
  120. memberId = member.objectId;
  121. const childLegacyId = memberLegacyId + 2;
  122. const child = await jsonRequest(`${PARSE_URL}/users`, {
  123. method: 'POST',
  124. 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 }),
  125. }, true);
  126. teamChildId = child.objectId;
  127. const coachUsername = `codex_coach_smoke_${Date.now()}`;
  128. const coachPassword = randomBytes(24).toString('base64url');
  129. coachLegacyId = memberLegacyId + 1;
  130. const coach = await jsonRequest(`${PARSE_URL}/users`, {
  131. method: 'POST',
  132. body: JSON.stringify({ username: coachUsername, password: coachPassword, legacyUserId: coachLegacyId, legacyGroupId: 3, company }),
  133. }, true);
  134. coachId = coach.objectId;
  135. for (const lessonType of [1, 2, 3]) {
  136. const lesson = await jsonRequest(`${PARSE_URL}/classes/LessonRecord`, {
  137. method: 'POST',
  138. body: JSON.stringify({ company, sourceKey: `cloud:smoke-lesson:${coachLegacyId}:${lessonType}`, jsmz: String(coachLegacyId), kclx: String(lessonType) }),
  139. }, true);
  140. temporaryLessonIds.push(lesson.objectId);
  141. }
  142. const memberLogin = await jsonRequest(`${PARSE_URL}/login`, {
  143. method: 'POST',
  144. body: JSON.stringify({ username: memberUsername, password: memberPassword }),
  145. });
  146. const coachLogin = await jsonRequest(`${PARSE_URL}/login`, {
  147. method: 'POST',
  148. body: JSON.stringify({ username: coachUsername, password: coachPassword }),
  149. });
  150. const feedbackModel = { UserID: memberLegacyId, Title: '冒烟学员 反馈的意见', TContent: '2026-08-19 请假一天', Cateid: 22 };
  151. const feedback = await callLegacyFunction(memberLogin.sessionToken, { action: 'guestbook_add', model: JSON.stringify(feedbackModel) });
  152. temporaryGuestbookId = String(feedback.result?.objectId || '');
  153. if (!temporaryGuestbookId || Number(feedback.result?.UserID) !== memberLegacyId || feedback.result?.Title !== feedbackModel.Title || feedback.result?.TContent !== feedbackModel.TContent || Number(feedback.result?.Cateid) !== 22) throw new Error(`旧版 model 留言写入异常:${JSON.stringify(feedback)}`);
  154. await callLegacyFunction(memberLogin.sessionToken, { action: 'guestbook_add', model: JSON.stringify({ ...feedbackModel, UserID: coachLegacyId }) }, 403);
  155. const profileModel = { honeyName: '冒烟资料更新', trueName: '测试学员', userFace: '/UploadFiles/smoke-avatar.png', sex: '女', birthday: '2000-01-02', mobile: '13800138000', Email: `${memberUsername}@example.test`, seturl: '/member/smoke', Position: '词汇小英雄' };
  156. const updatedProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update', uid: memberLegacyId, mu: JSON.stringify(profileModel), inviCode: '' });
  157. if (updatedProfile.result?.honeyName !== profileModel.honeyName || updatedProfile.result?.userFace !== profileModel.userFace || updatedProfile.result?.email !== profileModel.Email || updatedProfile.result?.seturl !== profileModel.seturl) throw new Error(`旧版 mu 用户资料更新异常:${JSON.stringify(updatedProfile)}`);
  158. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update', uid: coachLegacyId, mu: JSON.stringify({ honeyName: '越权' }) }, 403);
  159. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update_pwd', uid: memberLegacyId, vcode: '123456', newPass: 'Ab1234', reNewPass: 'Ab1234' }, 501);
  160. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update_pwdall', uid: memberLegacyId, login: 'Ab1234', pay: '123456' }, 501);
  161. 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' }) });
  162. temporaryAppointmentId = String(createdAppointment.result);
  163. const appointmentSourceKey = `cloud:content_add:${memberLegacyId}:${temporaryAppointmentId}`;
  164. const appointmentWhere = encodeURIComponent(JSON.stringify({ sourceKey: appointmentSourceKey }));
  165. const appointmentRows = await jsonRequest(`${PARSE_URL}/classes/CourseAppointment?where=${appointmentWhere}&limit=1`, {}, true);
  166. temporaryAppointmentObjectId = appointmentRows.results?.[0]?.objectId || '';
  167. if (!temporaryAppointmentObjectId) throw new Error('临时预约副表创建失败');
  168. const appointmentCommonRows = await jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${appointmentWhere}&limit=1`, {}, true);
  169. const temporaryAppointmentCommonObjectId = String(appointmentCommonRows.results?.[0]?.objectId || '');
  170. if (!temporaryAppointmentCommonObjectId) throw new Error('临时预约主内容创建失败');
  171. const meta = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'meta' });
  172. if (meta.identity?.objectId !== userId || !meta.cloudFunctions) throw new Error('管理员 meta 校验失败');
  173. const dashboard = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dashboard' });
  174. if (!Array.isArray(dashboard.metrics) || dashboard.metrics.length !== 8) throw new Error('dashboard 指标校验失败');
  175. const catalog = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'catalog' });
  176. if (!Array.isArray(catalog.resources) || catalog.resources.length < 90 || catalog.resources.some((item) => ['_Session', 'Function'].includes(item.className))) throw new Error('后台规范化类目录校验失败');
  177. const managedUsername = `codex_admin_created_${Date.now()}`;
  178. const managedPassword = randomBytes(24).toString('base64url');
  179. const managed = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'createUser', username: managedUsername, password: managedPassword, displayName: '后台开户冒烟', mobile: '13800138001', isAdmin: true, roles: ['admin'] });
  180. adminCreatedUserId = String(managed.objectId || '');
  181. if (!adminCreatedUserId || !Number(managed.userId) || Number(managed.groupId) !== 1 || managed.isAdmin === true || managed.roles?.includes?.('admin') || managed.sessionToken) throw new Error(`管理员开户响应异常:${JSON.stringify(managed)}`);
  182. const managedStored = await jsonRequest(`${PARSE_URL}/users/${adminCreatedUserId}`, {}, true);
  183. if (managedStored.username !== managedUsername || managedStored.isAdmin === true || managedStored.roles?.includes?.('admin') || Number(managedStored.legacyUserId) !== Number(managed.userId) || Number(managedStored.legacyGroupId) !== 1 || Number(managedStored.legacyUserData?.UserID) !== Number(managed.userId) || Number(managedStored.legacyUserData?.Purse) !== 0) throw new Error('管理员开户持久化约束校验失败');
  184. const managedLogin = await jsonRequest(`${PARSE_URL}/login`, { method: 'POST', body: JSON.stringify({ username: managedUsername, password: managedPassword }) });
  185. if (!managedLogin.sessionToken) throw new Error('后台开户用户登录失败');
  186. const locked = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userBatch', className: '_User', action: 'lock', objectIds: [adminCreatedUserId], reason: '云函数冒烟' });
  187. if (locked.updated !== 1 || locked.results?.[0]?.isDisabled !== true || Number(locked.results?.[0]?.legacyUserData?.State) !== 0 || Number(locked.revokedSessions) < 1) throw new Error(`用户停用与会话撤销异常:${JSON.stringify(locked)}`);
  188. await callLegacyFunction('', { action: 'user_login_passwd', name: managedUsername, passwd: managedPassword }, 403);
  189. const unlocked = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userBatch', className: '_User', action: 'unlock', objectIds: [adminCreatedUserId], reason: '恢复冒烟用户' });
  190. if (unlocked.updated !== 1 || unlocked.results?.[0]?.isDisabled !== false || Number(unlocked.results?.[0]?.legacyUserData?.State) !== 1) throw new Error(`用户解锁异常:${JSON.stringify(unlocked)}`);
  191. const temporaryGroup = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGroup', className: 'Group', fields: { groupName: '云函数冒烟临时组', description: '验证帐套内原子组编号', parentGroupId: 0, regSelect: false } });
  192. temporaryGroupObjectId = String(temporaryGroup.objectId || '');
  193. const temporaryGroupNumber = Number(temporaryGroup.groupId);
  194. if (!temporaryGroupObjectId || !temporaryGroupNumber) throw new Error('临时用户组创建失败');
  195. const moved = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userBatch', className: '_User', action: 'move', objectIds: [adminCreatedUserId], groupId: temporaryGroupNumber });
  196. if (moved.updated !== 1 || Number(moved.results?.[0]?.legacyGroupId) !== temporaryGroupNumber || Number(moved.results?.[0]?.legacyUserData?.GroupID) !== temporaryGroupNumber) throw new Error(`用户组同步异常:${JSON.stringify(moved)}`);
  197. const groupDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Group', objectId: temporaryGroupObjectId }, 409);
  198. if (!String(groupDeleteBlocked.message).includes('仍有用户')) throw new Error('用户组引用删除保护未返回明确原因');
  199. const managedAppLogin = await callLegacyFunction('', { action: 'user_login_passwd', name: managedUsername, passwd: managedPassword });
  200. if (!managedAppLogin.result?.sessionToken || Number(managedAppLogin.addon?.State) !== 1) throw new Error('解锁后旧版登录异常');
  201. await jsonRequest(`${PARSE_URL}/users/${adminCreatedUserId}`, { method: 'DELETE' }, true);
  202. adminCreatedUserId = '';
  203. const deletedGroup = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Group', objectId: temporaryGroupObjectId });
  204. if (deletedGroup.objectId !== temporaryGroupObjectId) throw new Error('无引用用户组删除失败');
  205. temporaryGroupObjectId = '';
  206. const schema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CourseAppointment' });
  207. if (schema.className !== 'CourseAppointment' || !Array.isArray(schema.fields)) throw new Error('schema 校验失败');
  208. const contentSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CommonModel' });
  209. const contentFieldMap = Object.fromEntries((contentSchema.fields || []).map((field) => [field.name, field]));
  210. if (contentSchema.creatable !== false || contentFieldMap.status?.writable !== false || contentFieldMap.modelId?.writable !== false || contentFieldMap.itemId?.writable !== false || contentFieldMap.nodeId?.writable !== false) throw new Error('内容结构字段未从通用创建/编辑中隔离');
  211. const nodeSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'Node' });
  212. const nodeFieldMap = Object.fromEntries((nodeSchema.fields || []).map((field) => [field.name, field]));
  213. if (nodeFieldMap.nodeId?.writable !== false || nodeFieldMap.parentId?.writable !== false || nodeFieldMap.depth?.writable !== false || nodeFieldMap.zstatus?.writable !== false || nodeFieldMap.sourceKey?.writable !== false) throw new Error('栏目结构字段未从通用编辑中隔离');
  214. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'save', className: 'Node', fields: { nodeName: '禁止通用新增' } }, 400);
  215. const nodeSuffix = Date.now().toString(36);
  216. const rootNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveNode', className: 'Node', parentId: 0, fields: { nodeName: `云函数冒烟栏目-${nodeSuffix}`, nodeDir: `smoke-${nodeSuffix}`, nodeType: 1, contentModel: '54' } });
  217. temporaryNodeObjectIds.push(String(rootNode.objectId || ''));
  218. const rootNodeId = Number(rootNode.nodeId);
  219. if (!temporaryNodeObjectIds[0] || !rootNodeId || Number(rootNode.parentId) !== 0 || Number(rootNode.depth) !== 1 || rootNode.sourceKey !== `[["NodeID",${rootNodeId}]]`) throw new Error(`栏目原子创建异常:${JSON.stringify(rootNode)}`);
  220. const childNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveNode', className: 'Node', parentId: rootNodeId, fields: { nodeName: `云函数冒烟子栏目-${nodeSuffix}`, nodeDir: `smoke-child-${nodeSuffix}`, nodeType: 1, contentModel: '54' } });
  221. temporaryNodeObjectIds.push(String(childNode.objectId || ''));
  222. const childNodeId = Number(childNode.nodeId);
  223. if (!temporaryNodeObjectIds[1] || !childNodeId || Number(childNode.parentId) !== rootNodeId || Number(childNode.depth) !== 2) throw new Error(`子栏目层级创建异常:${JSON.stringify(childNode)}`);
  224. const duplicateNode = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveNode', className: 'Node', parentId: 0, fields: { nodeName: `云函数冒烟栏目-${nodeSuffix}`, nodeDir: `another-${nodeSuffix}` } }, 409);
  225. if (!String(duplicateNode.message).includes('不能重复')) throw new Error('栏目同级重名保护未返回明确原因');
  226. const cycleNode = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveNode', className: 'Node', objectId: rootNode.objectId, parentId: childNodeId, fields: { ...rootNode, nodeName: rootNode.nodeName, nodeDir: rootNode.nodeDir } }, 409);
  227. if (!String(cycleNode.message).includes('自身或其下级')) throw new Error('栏目层级循环保护未返回明确原因');
  228. const movedNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'move', objectIds: [childNode.objectId], parentId: 0 });
  229. if (movedNode.updated !== 1 || Number(movedNode.results?.[0]?.parentId) !== 0) throw new Error('栏目批量迁移失败');
  230. const recycledNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'recycle', objectIds: [rootNode.objectId] });
  231. if (Number(recycledNode.results?.[0]?.zstatus) !== -2) throw new Error('栏目回收站状态更新失败');
  232. const recoveredNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'recover', objectIds: [rootNode.objectId] });
  233. if (Number(recoveredNode.results?.[0]?.zstatus) !== 99) throw new Error('栏目回收站恢复失败');
  234. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'purge', objectIds: [childNode.objectId] });
  235. temporaryNodeObjectIds.pop();
  236. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'purge', objectIds: [rootNode.objectId] });
  237. temporaryNodeObjectIds.pop();
  238. const specialSuffix = Date.now().toString(36);
  239. const rootSpecial = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', pid: 0, fields: { specName: `云函数冒烟专题-${specialSuffix}`, specDir: `special-${specialSuffix}`, specCate: 0, specDesc: '专题生命周期验证' } });
  240. temporarySpecialObjectIds.push(String(rootSpecial.objectId || ''));
  241. const rootSpecId = Number(rootSpecial.specId);
  242. if (!temporarySpecialObjectIds[0] || !rootSpecId || Number(rootSpecial.pid) !== 0 || rootSpecial.sourceKey !== `[["SpecID",${rootSpecId}]]`) throw new Error(`专题原子创建异常:${JSON.stringify(rootSpecial)}`);
  243. const childSpecial = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', pid: rootSpecId, fields: { specName: `云函数冒烟子专题-${specialSuffix}`, specDir: `special-child-${specialSuffix}` } });
  244. temporarySpecialObjectIds.push(String(childSpecial.objectId || ''));
  245. const childSpecId = Number(childSpecial.specId);
  246. if (!temporarySpecialObjectIds[1] || !childSpecId || Number(childSpecial.pid) !== rootSpecId) throw new Error(`子专题创建异常:${JSON.stringify(childSpecial)}`);
  247. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', pid: 0, fields: { specName: rootSpecial.specName, specDir: `special-other-${specialSuffix}` } }, 409);
  248. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', objectId: rootSpecial.objectId, pid: childSpecId, fields: { ...rootSpecial, specName: rootSpecial.specName, specDir: rootSpecial.specDir } }, 409);
  249. const specialDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Special', objectId: rootSpecial.objectId }, 409);
  250. if (!String(specialDeleteBlocked.message).includes('下级专题')) throw new Error('专题子级引用删除保护未返回明确原因');
  251. const movedSpecial = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'specialBatch', className: 'Special', action: 'move', objectIds: [childSpecial.objectId], pid: 0 });
  252. if (movedSpecial.updated !== 1 || Number(movedSpecial.results?.[0]?.pid) !== 0) throw new Error('专题批量迁移失败');
  253. const mergeBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'specialBatch', className: 'Special', action: 'merge', objectIds: [childSpecial.objectId], targetId: rootSpecId }, 501);
  254. if (!String(mergeBlocked.message).includes('specialId')) throw new Error('专题合并数据阻塞未返回明确原因');
  255. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Special', objectId: childSpecial.objectId });
  256. temporarySpecialObjectIds.pop();
  257. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Special', objectId: rootSpecial.objectId });
  258. temporarySpecialObjectIds.pop();
  259. const categorySuffix = Date.now().toString(36);
  260. const rootCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 1, parentId: 0, fields: { catename: `冒烟贴吧版块-${categorySuffix}`, desc: '分类生命周期验证', needLog: 1 } });
  261. temporaryGuestCategoryObjectIds.push(String(rootCategory.objectId || ''));
  262. const rootCateid = Number(rootCategory.cateid);
  263. if (!temporaryGuestCategoryObjectIds[0] || !rootCateid || Number(rootCategory.gtype) !== 1 || rootCategory.sourceKey !== `[["Cateid",${rootCateid}]]`) throw new Error(`贴吧分类原子创建异常:${JSON.stringify(rootCategory)}`);
  264. const childCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 1, parentId: rootCateid, fields: { catename: `冒烟子版块-${categorySuffix}` } });
  265. temporaryGuestCategoryObjectIds.push(String(childCategory.objectId || ''));
  266. const childCateid = Number(childCategory.cateid);
  267. if (!temporaryGuestCategoryObjectIds[1] || !childCateid || Number(childCategory.parentId) !== rootCateid) throw new Error('贴吧子分类创建失败');
  268. const guestCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 0, parentId: 0, fields: { catename: `冒烟留言分类-${categorySuffix}`, status: 1 } });
  269. temporaryGuestCategoryObjectIds.push(String(guestCategory.objectId || ''));
  270. const barAuthorizationBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barAuthorization', cateId: rootCateid }, 501);
  271. if (!String(barAuthorizationBlocked.message).includes('ZL_Guest_BarAuth')) throw new Error('贴吧逐用户权限数据阻塞未返回明确原因');
  272. const barMedalBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barMedal', objectId: 'missing-post' }, 501);
  273. if (!String(barMedalBlocked.message).includes('ZL_Guest_Medals')) throw new Error('贴吧勋章数据阻塞未返回明确原因');
  274. const temporaryBar = await jsonRequest(`${PARSE_URL}/classes/GuestBar`, { method: 'POST', body: JSON.stringify({ sourceKey: `cloud:smoke-bar:${categorySuffix}`, company, cateId: rootCateid, pid: 0, title: '后台贴吧工作流冒烟', msgContent: '冒烟正文', status: 0, orderFlag: 0, postFlag: '', cdate: { __type: 'Date', iso: new Date().toISOString() } }) }, true);
  275. temporaryGuestBarId = String(temporaryBar.objectId || '');
  276. const barAudited = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'audit', objectIds: [temporaryGuestBarId] });
  277. if (Number(barAudited.results?.[0]?.status) !== 99) throw new Error('贴吧帖子审核失败');
  278. const barElite = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'elite', objectIds: [temporaryGuestBarId] });
  279. if (!String(barElite.results?.[0]?.postFlag).includes('Recommend')) throw new Error('贴吧帖子加精失败');
  280. const barTop = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'top-global', objectIds: [temporaryGuestBarId] });
  281. if (Number(barTop.results?.[0]?.orderFlag) !== 2) throw new Error('贴吧帖子全局置顶失败');
  282. const barMoved = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'move', objectIds: [temporaryGuestBarId], cateId: childCateid });
  283. if (Number(barMoved.results?.[0]?.cateId) !== childCateid) throw new Error('贴吧帖子移动版块失败');
  284. const barRecycled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'recycle', objectIds: [temporaryGuestBarId] });
  285. if (Number(barRecycled.results?.[0]?.status) !== -2) throw new Error('贴吧帖子回收失败');
  286. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'recover', objectIds: [temporaryGuestBarId] });
  287. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 1, parentId: 0, fields: { catename: rootCategory.catename } }, 409);
  288. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', objectId: rootCategory.objectId, gtype: 0, parentId: childCateid, fields: { ...rootCategory, catename: rootCategory.catename } }, 409);
  289. const recommendedCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestCategoryBatch', className: 'Guestcate', action: 'recommend', objectIds: [rootCategory.objectId] });
  290. if (recommendedCategory.results?.[0]?.barInfo !== 'Recommend') throw new Error('贴吧分类推荐失败');
  291. const categoryDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Guestcate', objectId: rootCategory.objectId }, 409);
  292. if (!String(categoryDeleteBlocked.message).includes('引用')) throw new Error('分类子级引用删除保护未返回明确原因');
  293. await jsonRequest(`${PARSE_URL}/classes/GuestBar/${temporaryGuestBarId}`, { method: 'DELETE' }, true);
  294. temporaryGuestBarId = '';
  295. for (const category of [childCategory, rootCategory, guestCategory]) {
  296. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Guestcate', objectId: category.objectId });
  297. temporaryGuestCategoryObjectIds.splice(temporaryGuestCategoryObjectIds.indexOf(String(category.objectId)), 1);
  298. }
  299. const examClassSuffix = Date.now().toString(36);
  300. const rootExamClass = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', parentId: 0, classType: 1, orderId: 0, fields: { cClassName: `冒烟试题分类-${examClassSuffix}` } });
  301. temporaryExamClassObjectIds.push(String(rootExamClass.objectId || ''));
  302. const rootExamClassId = Number(rootExamClass.cId);
  303. if (!temporaryExamClassObjectIds[0] || !rootExamClassId || rootExamClass.sourceKey !== `[["C_id",${rootExamClassId}]]`) throw new Error(`试题分类原子创建异常:${JSON.stringify(rootExamClass)}`);
  304. const childExamClass = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', parentId: rootExamClassId, classType: 2, orderId: 0, fields: { cClassName: `冒烟子试题分类-${examClassSuffix}` } });
  305. temporaryExamClassObjectIds.push(String(childExamClass.objectId || ''));
  306. const childExamClassId = Number(childExamClass.cId);
  307. if (!childExamClassId || Number(childExamClass.cClassid) !== rootExamClassId || Number(childExamClass.cClassType) !== 2) throw new Error('子试题分类创建失败');
  308. const examChildren = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'examClassChildren', className: 'ExamClass', parentId: rootExamClassId });
  309. if (!examChildren.results?.some((entry) => entry.objectId === childExamClass.objectId)) throw new Error('试题子分类接口未返回目标记录');
  310. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', parentId: 0, classType: 1, orderId: 0, fields: { cClassName: rootExamClass.cClassName } }, 409);
  311. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', objectId: rootExamClass.objectId, parentId: childExamClassId, classType: 1, orderId: Number(rootExamClass.cOrderBy) || 0, fields: { cClassName: rootExamClass.cClassName } }, 409);
  312. const examClassDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamClass', objectId: rootExamClass.objectId }, 409);
  313. if (!String(examClassDeleteBlocked.message).includes('下级分类')) throw new Error('试题分类子级引用删除保护未返回明确原因');
  314. const movedExamClass = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', objectId: childExamClass.objectId, parentId: 0, classType: 2, orderId: Number(childExamClass.cOrderBy) || 0, fields: { cClassName: childExamClass.cClassName } });
  315. if (Number(movedExamClass.cClassid) !== 0) throw new Error('试题分类结构移动失败');
  316. const knowledgeSuffix = Date.now().toString(36);
  317. const rootKnowledge = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveKnowledge', className: 'QuestionsKnowledge', classId: rootExamClassId, parentId: 0, orderId: 0, fields: { kName: `冒烟知识点-${knowledgeSuffix}`, status: 1, grade: 0, isSys: 0 } });
  318. temporaryKnowledgeObjectIds.push(String(rootKnowledge.objectId || ''));
  319. const rootKnowledgeId = Number(rootKnowledge.kId);
  320. if (!temporaryKnowledgeObjectIds[0] || !rootKnowledgeId || rootKnowledge.sourceKey !== `[["k_id",${rootKnowledgeId}]]`) throw new Error(`知识点原子创建异常:${JSON.stringify(rootKnowledge)}`);
  321. const childKnowledge = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveKnowledge', className: 'QuestionsKnowledge', classId: rootExamClassId, parentId: rootKnowledgeId, orderId: 0, fields: { kName: `冒烟子知识点-${knowledgeSuffix}`, status: 1, grade: 0, isSys: 0 } });
  322. temporaryKnowledgeObjectIds.push(String(childKnowledge.objectId || ''));
  323. const childKnowledgeId = Number(childKnowledge.kId);
  324. if (!childKnowledgeId || Number(childKnowledge.pid) !== rootKnowledgeId || Number(childKnowledge.kClassId) !== rootExamClassId) throw new Error('子知识点创建失败');
  325. const knowledgeChildren = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'knowledgeChildren', className: 'QuestionsKnowledge', classId: rootExamClassId, parentId: rootKnowledgeId });
  326. if (!knowledgeChildren.results?.some((entry) => entry.objectId === childKnowledge.objectId)) throw new Error('知识点子级接口未返回目标记录');
  327. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveKnowledge', className: 'QuestionsKnowledge', classId: rootExamClassId, parentId: 0, orderId: 0, fields: { kName: rootKnowledge.kName, status: 1, grade: 0, isSys: 0 } }, 409);
  328. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveKnowledge', className: 'QuestionsKnowledge', objectId: rootKnowledge.objectId, classId: rootExamClassId, parentId: childKnowledgeId, orderId: Number(rootKnowledge.kOrderBy) || 0, fields: { kName: rootKnowledge.kName, status: 1, grade: 0, isSys: 0 } }, 409);
  329. const knowledgeDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'QuestionsKnowledge', objectId: rootKnowledge.objectId }, 409);
  330. if (!String(knowledgeDeleteBlocked.message).includes('下级知识点')) throw new Error('知识点子级引用删除保护未返回明确原因');
  331. const movedKnowledge = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveKnowledge', className: 'QuestionsKnowledge', objectId: childKnowledge.objectId, classId: rootExamClassId, parentId: 0, orderId: Number(childKnowledge.kOrderBy) || 0, fields: { kName: childKnowledge.kName, status: 1, grade: 0, isSys: 0 } });
  332. if (Number(movedKnowledge.pid) !== 0) throw new Error('知识点结构移动失败');
  333. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'QuestionsKnowledge', objectId: childKnowledge.objectId });
  334. temporaryKnowledgeObjectIds.pop();
  335. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'QuestionsKnowledge', objectId: rootKnowledge.objectId });
  336. temporaryKnowledgeObjectIds.pop();
  337. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamClass', objectId: childExamClass.objectId });
  338. temporaryExamClassObjectIds.pop();
  339. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamClass', objectId: rootExamClass.objectId });
  340. temporaryExamClassObjectIds.pop();
  341. const examPointSuffix = Date.now().toString(36);
  342. const rootExamPoint = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', parentId: 0, orderId: 0, fields: { testPoint: `冒烟考点-${examPointSuffix}` } });
  343. temporaryExamPointObjectIds.push(String(rootExamPoint.objectId || ''));
  344. const rootExamPointId = Number(rootExamPoint.id);
  345. if (!temporaryExamPointObjectIds[0] || !rootExamPointId || rootExamPoint.sourceKey !== `[["ID",${rootExamPointId}]]`) throw new Error(`考点原子创建异常:${JSON.stringify(rootExamPoint)}`);
  346. const childExamPoint = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', parentId: rootExamPointId, orderId: 0, fields: { testPoint: `冒烟子考点-${examPointSuffix}` } });
  347. temporaryExamPointObjectIds.push(String(childExamPoint.objectId || ''));
  348. const childExamPointId = Number(childExamPoint.id);
  349. if (!childExamPointId || Number(childExamPoint.tid) !== rootExamPointId) throw new Error('子考点创建失败');
  350. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', parentId: 0, orderId: 0, fields: { testPoint: rootExamPoint.testPoint } }, 409);
  351. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', objectId: rootExamPoint.objectId, parentId: childExamPointId, orderId: Number(rootExamPoint.orderBy) || 0, fields: { testPoint: rootExamPoint.testPoint } }, 409);
  352. const examPointDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamPoint', objectId: rootExamPoint.objectId }, 409);
  353. if (!String(examPointDeleteBlocked.message).includes('下级考点')) throw new Error('考点子级引用删除保护未返回明确原因');
  354. const movedExamPoint = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', objectId: childExamPoint.objectId, parentId: 0, orderId: Number(childExamPoint.orderBy) || 0, fields: { testPoint: childExamPoint.testPoint } });
  355. if (Number(movedExamPoint.tid) !== 0) throw new Error('考点结构移动失败');
  356. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamPoint', objectId: childExamPoint.objectId });
  357. temporaryExamPointObjectIds.pop();
  358. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamPoint', objectId: rootExamPoint.objectId });
  359. temporaryExamPointObjectIds.pop();
  360. const metadataSuffix = Date.now().toString(36);
  361. const temporaryModelId = 800000000 + Math.floor(Date.now() / 1000) % 100000000;
  362. const tempModel = await jsonRequest(`${PARSE_URL}/classes/Model`, { method: 'POST', body: JSON.stringify({ sourceKey: `cloud:smoke-model:${metadataSuffix}`, company, modelId: temporaryModelId, modelName: `冒烟模型-${metadataSuffix}`, tableName: `ZL_C_Smoke_${metadataSuffix}`, modelType: 1, itemName: '记录', itemUnit: '条', multiFlag: true }) }, true);
  363. temporaryModelObjectId = String(tempModel.objectId || '');
  364. const updatedModel = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveModelMetadata', className: 'Model', objectId: temporaryModelObjectId, fields: { modelName: `冒烟模型更新-${metadataSuffix}`, description: '仅元数据更新', tableName: 'malicious_table', modelId: 1 } });
  365. if (Number(updatedModel.modelId) !== temporaryModelId || updatedModel.tableName !== `ZL_C_Smoke_${metadataSuffix}` || updatedModel.description !== '仅元数据更新') throw new Error(`模型结构字段隔离异常:${JSON.stringify(updatedModel)}`);
  366. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveModelMetadata', className: 'Model', fields: { modelName: '禁止新增模型' } }, 501);
  367. for (let index = 0; index < 2; index++) {
  368. const field = await jsonRequest(`${PARSE_URL}/classes/ModelField`, { method: 'POST', body: JSON.stringify({ sourceKey: `cloud:smoke-model-field:${metadataSuffix}:${index}`, company, fieldId: temporaryModelId + index + 1, modelId: temporaryModelId, fieldName: `smokeField${index}`, fieldAlias: `冒烟字段${index}`, fieldType: 'TextType', orderId: index, isShow: true }) }, true);
  369. temporaryModelFieldObjectIds.push(String(field.objectId || ''));
  370. }
  371. const updatedField = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveModelFieldMetadata', className: 'ModelField', objectId: temporaryModelFieldObjectIds[0], fields: { fieldAlias: '更新后的字段别名', fieldTips: '仅展示元数据', fieldName: 'maliciousField', fieldType: 'SqlType', modelId: 1 } });
  372. if (updatedField.fieldAlias !== '更新后的字段别名' || updatedField.fieldName !== 'smokeField0' || updatedField.fieldType !== 'TextType' || Number(updatedField.modelId) !== temporaryModelId) throw new Error(`模型字段结构隔离异常:${JSON.stringify(updatedField)}`);
  373. const reorderedFields = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'modelFieldOrder', className: 'ModelField', items: [{ objectId: temporaryModelFieldObjectIds[0], orderId: 2 }, { objectId: temporaryModelFieldObjectIds[1], orderId: 1 }] });
  374. if (reorderedFields.updated !== 2 || Number(reorderedFields.modelId) !== temporaryModelId) throw new Error('模型字段排序失败');
  375. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ModelField', objectId: temporaryModelFieldObjectIds[0] }, 501);
  376. const updatedGuestbook = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestbook', className: 'Guestbook', objectId: temporaryGuestbookId, fields: { title: feedbackModel.Title, tcontent: '管理员规范化编辑', gid: 999, status: -2, cateid: 999 } });
  377. if (updatedGuestbook.tcontent !== '管理员规范化编辑' || Number(updatedGuestbook.gid) === 999 || Number(updatedGuestbook.cateid) === 999 || Number(updatedGuestbook.status) === -2) throw new Error(`留言结构字段隔离异常:${JSON.stringify(updatedGuestbook)}`);
  378. const guestUnaudited = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'unaudit', objectIds: [temporaryGuestbookId] });
  379. if (Number(guestUnaudited.results?.[0]?.status) !== 0) throw new Error('留言取消审核失败');
  380. const guestRecycled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'recycle', objectIds: [temporaryGuestbookId] });
  381. if (Number(guestRecycled.results?.[0]?.status) !== -2) throw new Error('留言回收失败');
  382. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'recover', objectIds: [temporaryGuestbookId] });
  383. const guestReply = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookReply', className: 'Guestbook', parentObjectId: temporaryGuestbookId, title: '管理员冒烟回复', content: '云函数回复正文' });
  384. temporaryGuestbookReplyId = String(guestReply.objectId || '');
  385. if (!temporaryGuestbookReplyId || Number(guestReply.parentid) !== Number(updatedGuestbook.gid) || Number(guestReply.status) !== 99 || !Number(guestReply.gid)) throw new Error(`管理员留言回复异常:${JSON.stringify(guestReply)}`);
  386. const guestDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'purge', objectIds: [temporaryGuestbookId] }, 409);
  387. if (!String(guestDeleteBlocked.message).includes('仍有回复')) throw new Error('留言回复引用删除保护未返回明确原因');
  388. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'purge', objectIds: [temporaryGuestbookReplyId] });
  389. temporaryGuestbookReplyId = '';
  390. const contentPending = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'status', objectIds: [temporaryAppointmentCommonObjectId], status: 0 });
  391. if (contentPending.updated !== 1 || Number(contentPending.results?.[0]?.status) !== 0) throw new Error('内容待审核状态更新失败');
  392. const contentRecycled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'recycle', objectIds: [temporaryAppointmentCommonObjectId] });
  393. if (Number(contentRecycled.results?.[0]?.status) !== -2) throw new Error('内容回收站状态更新失败');
  394. const contentRecovered = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'recover', objectIds: [temporaryAppointmentCommonObjectId] });
  395. if (Number(contentRecovered.results?.[0]?.status) !== 0) throw new Error('内容回收站恢复失败');
  396. const contentMoved = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'move', objectIds: [temporaryAppointmentCommonObjectId], nodeId: 29 });
  397. if (Number(contentMoved.results?.[0]?.nodeId) !== 29) throw new Error('内容节点移动失败');
  398. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'status', objectIds: [temporaryAppointmentCommonObjectId], status: 99 });
  399. const page = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'list', className: 'CourseAppointment', page: 1, pageSize: 2 });
  400. if (!Array.isArray(page.results) || page.pageSize !== 2) throw new Error('资源分页校验失败');
  401. const normalized = await callFunction('xiaoshu/cms/content-normalizer', login.sessionToken, { content: '<p>中文&nbsp;<strong>内容</strong></p><script>alert(1)</script>' });
  402. if (normalized.content !== '中文 内容') throw new Error(`内容清理结果异常:${normalized.content}`);
  403. const exams = await callFunction('xiaoshu/cms/exams/classes', login.sessionToken, { page: 1, pageSize: 2 });
  404. if (!Array.isArray(exams.results)) throw new Error('考试班级投影校验失败');
  405. const guest = await callFunction('xiaoshu/cms/guest/bar', login.sessionToken, { page: 1, pageSize: 2 });
  406. if (!Array.isArray(guest.results)) throw new Error('互动社区投影校验失败');
  407. const migration = await callLegacyFunction('', { action: 'migration_status' });
  408. const sourceActionList = await sourceActions();
  409. const implementedActions = migration.result?.implemented || [];
  410. const blockedActions = Object.keys(migration.result?.blocked || {});
  411. const covered = new Set([...implementedActions, ...blockedActions]);
  412. const missing = sourceActionList.filter((action) => !covered.has(action));
  413. if (missing.length) throw new Error(`app gateway 迁移矩阵缺少:${missing.join(', ')}`);
  414. const sourceBlocked = blockedActions.filter((action) => sourceActionList.includes(action));
  415. const compatibilityActions = blockedActions.filter((action) => !sourceActionList.includes(action)).sort();
  416. const sourceImplemented = implementedActions.filter((action) => sourceActionList.includes(action));
  417. const compatibilityImplemented = implementedActions.filter((action) => !sourceActionList.includes(action)).sort();
  418. if (sourceImplemented.length !== 28 || sourceBlocked.length !== 63) throw new Error(`app gateway 源 action 计数异常:${sourceImplemented.length} 已映射 / ${sourceBlocked.length} 阻塞`);
  419. if (compatibilityImplemented.join(',') !== 'content_add_zt') throw new Error(`app gateway 已实现兼容 action 计数异常:${compatibilityImplemented.join(',')}`);
  420. if (compatibilityActions.join(',') !== 'product_add,product_upd') throw new Error(`app gateway 阻塞兼容 action 计数异常:${compatibilityActions.join(',')}`);
  421. const content = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 2 });
  422. if (!Array.isArray(content.result) || content.result.length !== 2 || Number(content.page?.itemCount) < 89000) throw new Error('公开内容分页校验失败');
  423. const contentExact = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 1, objectId: content.result[0].objectId });
  424. if (contentExact.result?.[0]?.objectId !== content.result[0].objectId || contentExact.page?.itemCount !== 1) throw new Error('内容 objectId 精确查询校验失败');
  425. const contentDetail = await callLegacyFunction('', { action: 'content_get', id: content.result[0].objectId });
  426. if (!Array.isArray(contentDetail.result) || contentDetail.result[0]?.objectId !== content.result[0].objectId) throw new Error('内容详情旧数组契约校验失败');
  427. contentHitObjectId = String(content.result[0].objectId);
  428. contentHitOriginal = Number(content.result[0].hits ?? content.result[0].Hits ?? 0);
  429. const contentHit = await callLegacyFunction('', { action: 'content_uphis', id: contentHitObjectId, num: 999 });
  430. if (Number(contentHit.result?.hits) !== contentHitOriginal + 1) throw new Error(`公开内容浏览量未固定原子加一:${JSON.stringify(contentHit)}`);
  431. await jsonRequest(`${PARSE_URL}/classes/CommonModel/${contentHitObjectId}`, { method: 'PUT', body: JSON.stringify({ hits: contentHitOriginal }) }, true);
  432. contentHitObjectId = '';
  433. await callLegacyFunction('', { action: 'content_uphis', id: temporaryAppointmentId }, 401);
  434. const appUpdate = await callLegacyFunction('', { action: 'app_update' });
  435. if (Number(appUpdate.result?.ver) !== 113 || appUpdate.result?.nver !== '1.1.8' || !String(appUpdate.result?.path).startsWith('https://') || appUpdate.result?.size !== null || appUpdate.result?.sizeUnavailable !== true) throw new Error(`应用版本旧契约别名异常:${JSON.stringify(appUpdate)}`);
  436. const gameNode = await callLegacyFunction('', { action: 'node_get', id: 77 });
  437. if (gameNode.result?.NodeID === undefined || gameNode.result?.ConsumePoint === undefined || gameNode.result?.ConsumeDeposit === undefined) throw new Error(`栏目详情游戏消费字段别名异常:${JSON.stringify(gameNode.result)}`);
  438. const words = await callLegacyFunction('', { action: 'content_list', modelId: 52, page: 1, pageSize: 1 });
  439. if (Number(words.page?.itemCount) < 89000 || !words.result?.[0]?.GeneralID || words.result?.[0]?.sy === undefined) throw new Error('词库 addon 联表校验失败');
  440. const privateContent = await callLegacyFunction('', { action: 'content_list', modelId: 56, page: 1, pageSize: 1 }, 401);
  441. if (!String(privateContent.retmsg).includes('登录')) throw new Error('学习记录未阻止匿名访问');
  442. const learning = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 56, page: 1, pageSize: 1 });
  443. if (!learning.result?.[0]?.GeneralID || learning.result?.[0]?.xxqs === undefined) throw new Error('学习记录 addon 联表校验失败');
  444. const recordDetail = await callLegacyFunction(login.sessionToken, { action: 'e_record_detail', id: learning.result[0].GeneralID });
  445. if (!Array.isArray(recordDetail.result) || !recordDetail.result.length || !recordDetail.result[0]?.detail?.[0]?.Title) throw new Error('学习记录单词详情联查校验失败');
  446. const appointments = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 54, page: 1, pageSize: 1 });
  447. const appointment = await callLegacyFunction(login.sessionToken, { action: 'e_order_detail', id: appointments.result?.[0]?.GeneralID });
  448. if (!appointment.result?.[0]?.GeneralID || appointment.result[0].kcid === undefined) throw new Error('预约详情联查校验失败');
  449. const memberProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_get', uid: memberLegacyId });
  450. if (memberProfile.result?.honeyName !== profileModel.honeyName || memberProfile.addon?.vip !== 2 || memberProfile.addon?.silverCoin !== 2 || JSON.stringify(memberProfile).includes('must-not-leak')) throw new Error('用户旧契约字段或敏感字段过滤异常');
  451. const teamMembers = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_list', puid: memberLegacyId, cpage: 1, psize: 10 });
  452. if (teamMembers.page?.itemCount !== 1 || Number(teamMembers.result?.[0]?.ParentUserID) !== memberLegacyId || Number(teamMembers.result?.[0]?.VIP) !== 3) throw new Error(`团队成员列表异常:${JSON.stringify(teamMembers)}`);
  453. const teamSummary = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_dept', uid: memberLegacyId });
  454. if (teamSummary.result?.childs !== 1 || teamSummary.result?.v3 !== 1) throw new Error(`团队会员统计异常:${JSON.stringify(teamSummary.result)}`);
  455. const childProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_get', uid: childLegacyId });
  456. if (childProfile.result?.userId !== childLegacyId || childProfile.result?.puid !== memberLegacyId || JSON.stringify(childProfile).includes('must-not-leak')) throw new Error('团队成员详情或密码字段过滤异常');
  457. await callLegacyFunction(coachLogin.sessionToken, { action: 'user_get', uid: childLegacyId }, 403);
  458. const coachStudents = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_user_list', cpage: 1, psize: 10 });
  459. if (coachStudents.page?.itemCount !== 1 || Number(coachStudents.result?.[0]?.szyh) !== memberLegacyId || coachStudents.result?.[0]?.honeyname !== profileModel.honeyName) throw new Error(`陪练学员分组列表异常:${JSON.stringify(coachStudents)}`);
  460. const newWords = await callLegacyFunction(login.sessionToken, { action: 'e_words_list', uid: 58, page: 1, pageSize: 2 });
  461. if (Number(newWords.page?.itemCount) < 1 || !newWords.result?.[0]?.detail?.[0]?.Title) throw new Error('用户生词联查校验失败');
  462. const courseWords = await callLegacyFunction(login.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1000 });
  463. const learnedWord = courseWords.result?.find((word) => Number(word.GeneralID) === 2505);
  464. if (Number(courseWords.page?.itemCount) < 1 || !courseWords.result?.[0]?.detail?.Title || Number(learnedWord?.w_learned) !== 7) throw new Error('课程词库学习进度联查校验失败');
  465. const memory = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list', uid: 58, page: 1, pageSize: 2 });
  466. if (Number(memory.page?.itemCount) < 1 || !memory.result?.[0]?.GeneralID || memory.result[0].learned === undefined) throw new Error('21 天抗遗忘联查校验失败');
  467. const incomeBlocked = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list_tj', uid: 58 }, 501);
  468. if (!String(incomeBlocked.retmsg).includes('计价规则')) throw new Error('复习收入缺失规则未显式阻塞');
  469. const ownEmpty = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}`, page: 1, pageSize: 1 });
  470. if (!Array.isArray(ownEmpty.result) || ownEmpty.page?.itemCount !== 0) throw new Error('普通用户本人记录权限校验失败');
  471. const ownCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1 });
  472. if (!Array.isArray(ownCourseWords.result) || ownCourseWords.result[0]?.w_learned !== 0) throw new Error('普通用户本人课程词库权限校验失败');
  473. const learnedWrite = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, save: 1 });
  474. if (learnedWrite.result?.created !== 1 || learnedWrite.result?.learnedIncremented !== 1) throw new Error('首次学习词进度写入校验失败');
  475. await callLegacyFunction('', { action: 'node_list', pid: 16, ifunit: 1, userId: memberLegacyId }, 401);
  476. const unitNodes = await callLegacyFunction(memberLogin.sessionToken, { action: 'node_list', pid: 16, ifunit: 1, userId: memberLegacyId, pageSize: 100 });
  477. const learnedUnit = unitNodes.result?.find((node) => Number(node.NodeID) === 40);
  478. if (!learnedUnit || Number(learnedUnit.total) < 1 || Number(learnedUnit.yx_word) !== 1 || Number(learnedUnit.process) !== Math.round(100 / Number(learnedUnit.total))) throw new Error(`单元已学进度异常:${JSON.stringify(learnedUnit)}`);
  479. const learnedRead = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1000 });
  480. if (Number(learnedRead.result?.find((word) => Number(word.GeneralID) === 2505)?.w_learned) !== 1) throw new Error('学习次数写后读校验失败');
  481. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 1 });
  482. const addedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  483. if (addedNewWord.page?.itemCount !== 1 || Number(addedNewWord.result?.[0]?.detail?.[0]?.GeneralID) !== 2505) throw new Error('加入生词写后读校验失败');
  484. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 0 });
  485. const removedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  486. if (removedNewWord.page?.itemCount !== 0) throw new Error('移出生词写后读校验失败');
  487. 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 }]) }) });
  488. if (!/^\d{15}$/.test(String(scheduledStudy.result))) throw new Error('带复习计划的学习记录创建结果异常');
  489. const scheduledDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: scheduledStudy.result });
  490. const reviewDates = String(scheduledDetail.result?.[0]?.fxrl || '').split(',').filter(Boolean);
  491. if (reviewDates.length !== 15 || !reviewDates.every((date) => /^\d{8}$/.test(date))) throw new Error('15 段抗遗忘复习日期生成失败');
  492. await callLegacyFunction(coachLogin.sessionToken, { action: 'content_update', content: JSON.stringify({ GeneralID: scheduledStudy.result }), addon: JSON.stringify({ con: '越权更新' }) }, 403);
  493. const scheduledUpdate = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_update', content: JSON.stringify({ GeneralID: scheduledStudy.result, Title: '已更新学习记录' }), addon: JSON.stringify({ con: '规范化内容更新', learned: 1 }) });
  494. if (String(scheduledUpdate.result) !== String(scheduledStudy.result)) throw new Error('规范化内容更新返回值异常');
  495. const updatedScheduledDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: scheduledStudy.result });
  496. if (updatedScheduledDetail.result?.[0]?.con !== '规范化内容更新' || updatedScheduledDetail.result?.[0]?.Title !== '已更新学习记录') throw new Error('规范化内容双表更新写后读失败');
  497. 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 }) });
  498. if (!/^\d{15}$/.test(String(assessment.result))) throw new Error('规范化测评内容新增结果异常');
  499. const assessmentDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: assessment.result });
  500. if (String(assessmentDetail.result?.[0]?.df) !== '7' || String(assessmentDetail.result?.[0]?.prevScore) !== '0' || Number(assessmentDetail.result?.[0]?.UserID ?? assessmentDetail.result?.[0]?.userId) !== memberLegacyId) throw new Error('规范化测评内容新增写后读失败');
  501. const missingSchemaCreate = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_add', content: JSON.stringify({ ModelID: 55, nodeId: 255 }), addon: JSON.stringify({ UserID: memberLegacyId, scnr: '[]' }) }, 501);
  502. if (!String(missingSchemaCreate.retmsg).includes('未迁移内容模型 55')) throw new Error('缺 Schema 内容新增未明确拒绝');
  503. 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 }]) };
  504. const createdStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  505. if (!createdStudy.result?.created || !createdStudy.result?.GeneralID || !createdStudy.result?.recordObjectId) throw new Error('预约学习记录首次双表写入校验失败');
  506. const studyDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_record_detail', id: createdStudy.result.GeneralID });
  507. if (studyDetail.result?.[0]?.detail?.[0]?.Title !== 'woman') throw new Error('预约学习记录写后详情校验失败');
  508. studyAddon.xxqs = JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 1 }]);
  509. const updatedStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  510. if (updatedStudy.result?.created || updatedStudy.result?.GeneralID !== createdStudy.result.GeneralID) throw new Error('预约学习记录幂等更新校验失败');
  511. const studyList = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}|dsid=${temporaryAppointmentId}`, page: 1, pageSize: 2 });
  512. if (studyList.page?.itemCount !== 1 || Number(studyList.result?.[0]?.ygg) !== 1 || Number(studyList.result?.[0]?.learned) !== 1) throw new Error('预约学习记录聚合字段写后读校验失败');
  513. const orderContent = JSON.stringify({ GeneralID: temporaryAppointmentId, UpDateTime: '2026-08-18 13:30' });
  514. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 10, content: orderContent }, 403);
  515. const startedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 10, content: orderContent });
  516. if (startedOrder.result?.previousStatus !== 0 || startedOrder.result?.status !== 10) throw new Error('预约开始状态迁移失败');
  517. const endedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  518. if (endedOrder.result?.reviewCount !== 2 || !endedOrder.result?.periodDeducted) throw new Error('预约结束课时与抗遗忘副作用失败');
  519. const repeatedEnd = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  520. if (!repeatedEnd.result?.unchanged) throw new Error('预约结束状态未保持幂等');
  521. const updatedMember = await jsonRequest(`${PARSE_URL}/users/${memberId}`, {}, true);
  522. if (Number(updatedMember.legacyUserData?.Purse) !== 1 || Number(updatedMember.legacyUserData?.UserPoint) !== 1.5) throw new Error(`预约结束课时扣减异常:${JSON.stringify(updatedMember.legacyUserData)}`);
  523. const sideEffectWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:e_order_update:${temporaryAppointmentId}:` } }));
  524. const [periodLogs, pointLogs, memoryRows, memoryCommonRows] = await Promise.all([
  525. jsonRequest(`${PARSE_URL}/classes/UserExpDomP?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  526. jsonRequest(`${PARSE_URL}/classes/UserUserPoint?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  527. jsonRequest(`${PARSE_URL}/classes/MemoryPracticeRecord?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  528. jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  529. ]);
  530. if (periodLogs.count !== 1 || pointLogs.count !== 1 || memoryRows.count !== 2 || memoryCommonRows.count !== 2) throw new Error(`预约结束账本/抗遗忘数量异常:${periodLogs.count}/${pointLogs.count}/${memoryRows.count}/${memoryCommonRows.count}`);
  531. const purseHistory = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_point_list', uid: memberLegacyId, stype: 1, cpage: 1, psize: 10 });
  532. if (purseHistory.page?.itemCount !== 1 || Number(purseHistory.result?.[0]?.score) !== -1 || !purseHistory.result?.[0]?.ExpHisID || purseHistory.result?.[0]?.Detail === undefined || purseHistory.addon?.purseFeeRuleUnavailable !== true) throw new Error(`余额账本读取异常:${JSON.stringify(purseHistory)}`);
  533. const couponHistory = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_point_list', uid: memberLegacyId, stype: 4, cpage: 1, psize: 10 });
  534. if (couponHistory.page?.itemCount !== 1 || Number(couponHistory.result?.[0]?.score) !== -0.5 || !couponHistory.result?.[0]?.HisTime) throw new Error(`点券账本读取异常:${JSON.stringify(couponHistory)}`);
  535. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_point_list', uid: memberLegacyId, stype: 7 }, 400);
  536. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 20, content: orderContent }, 403);
  537. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 20, content: orderContent });
  538. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 30, content: orderContent });
  539. const completedOrder = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_detail', id: temporaryAppointmentId });
  540. if (Number(completedOrder.result?.[0]?.dszt) !== 30) throw new Error('预约状态机写后读失败');
  541. const coachStats = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_tongji', uid: coachLegacyId });
  542. 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('陪练预约统计公式校验失败');
  543. const memberStats = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_tongji', uid: memberLegacyId });
  544. 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)}`);
  545. const deniedCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1 }, 403);
  546. if (!String(deniedCourseWords.retmsg).includes('无权')) throw new Error('普通用户跨用户课程词库未被拒绝');
  547. const denied = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: 'UserId=3', page: 1, pageSize: 1 }, 403);
  548. if (!String(denied.retmsg).includes('无权')) throw new Error('普通用户跨用户记录未被拒绝');
  549. const profile = await callLegacyFunction(login.sessionToken, { action: 'user_get' });
  550. if (profile.retcode !== 0 || profile.result?.objectId !== userId) throw new Error('app gateway 用户会话校验失败');
  551. const blocked = await callLegacyFunction('', { action: 'cart_list' }, 501);
  552. if (!String(blocked.retmsg).startsWith('migration_blocked:')) throw new Error('阻塞接口未返回 migration_blocked');
  553. const productBlocked = await callLegacyFunction('', { action: 'product_list' }, 501);
  554. if (!String(productBlocked.retmsg).includes('ZL_Commodities')) throw new Error('缺商品主表的读取接口未明确阻塞');
  555. console.log('Cloud smoke passed: admin auth/tenant/account lifecycle/group sync/node/special/guest-category/bar/exam-class/exam-point/knowledge/model/guestbook lifecycle/content workflow/CRUD reads, CMS projections, normalized learning joins, app action coverage, public content, session scope, explicit blocked APIs.');
  556. } finally {
  557. if (contentHitObjectId) await jsonRequest(`${PARSE_URL}/classes/CommonModel/${contentHitObjectId}`, { method: 'PUT', body: JSON.stringify({ hits: contentHitOriginal }) }, true).catch((error) => {
  558. console.error(`公开内容浏览量恢复失败:${error.message}`);
  559. process.exitCode = 1;
  560. });
  561. if (registeredUserId) await jsonRequest(`${PARSE_URL}/users/${registeredUserId}`, { method: 'DELETE' }, true).catch((error) => {
  562. console.error(`临时注册用户清理失败:${error.message}`);
  563. process.exitCode = 1;
  564. });
  565. if (adminCreatedUserId) await jsonRequest(`${PARSE_URL}/users/${adminCreatedUserId}`, { method: 'DELETE' }, true).catch((error) => {
  566. console.error(`管理员开户临时用户清理失败:${error.message}`);
  567. process.exitCode = 1;
  568. });
  569. if (temporaryGroupObjectId) await jsonRequest(`${PARSE_URL}/classes/Group/${temporaryGroupObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  570. console.error(`临时用户组清理失败:${error.message}`);
  571. process.exitCode = 1;
  572. });
  573. for (const nodeId of temporaryNodeObjectIds) if (nodeId) await jsonRequest(`${PARSE_URL}/classes/Node/${nodeId}`, { method: 'DELETE' }, true).catch((error) => {
  574. console.error(`临时栏目清理失败:${error.message}`);
  575. process.exitCode = 1;
  576. });
  577. for (const specialId of temporarySpecialObjectIds) if (specialId) await jsonRequest(`${PARSE_URL}/classes/Special/${specialId}`, { method: 'DELETE' }, true).catch((error) => {
  578. console.error(`临时专题清理失败:${error.message}`);
  579. process.exitCode = 1;
  580. });
  581. for (const categoryId of temporaryGuestCategoryObjectIds) if (categoryId) await jsonRequest(`${PARSE_URL}/classes/Guestcate/${categoryId}`, { method: 'DELETE' }, true).catch((error) => {
  582. console.error(`临时留言/贴吧分类清理失败:${error.message}`);
  583. process.exitCode = 1;
  584. });
  585. for (const knowledgeId of [...temporaryKnowledgeObjectIds].reverse()) if (knowledgeId) await jsonRequest(`${PARSE_URL}/classes/QuestionsKnowledge/${knowledgeId}`, { method: 'DELETE' }, true).catch((error) => {
  586. console.error(`临时知识点清理失败:${error.message}`);
  587. process.exitCode = 1;
  588. });
  589. for (const examClassId of [...temporaryExamClassObjectIds].reverse()) if (examClassId) await jsonRequest(`${PARSE_URL}/classes/ExamClass/${examClassId}`, { method: 'DELETE' }, true).catch((error) => {
  590. console.error(`临时试题分类清理失败:${error.message}`);
  591. process.exitCode = 1;
  592. });
  593. for (const examPointId of [...temporaryExamPointObjectIds].reverse()) if (examPointId) await jsonRequest(`${PARSE_URL}/classes/ExamPoint/${examPointId}`, { method: 'DELETE' }, true).catch((error) => {
  594. console.error(`临时考点清理失败:${error.message}`);
  595. process.exitCode = 1;
  596. });
  597. for (const fieldId of temporaryModelFieldObjectIds) if (fieldId) await jsonRequest(`${PARSE_URL}/classes/ModelField/${fieldId}`, { method: 'DELETE' }, true).catch((error) => {
  598. console.error(`临时模型字段清理失败:${error.message}`);
  599. process.exitCode = 1;
  600. });
  601. if (temporaryModelObjectId) await jsonRequest(`${PARSE_URL}/classes/Model/${temporaryModelObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  602. console.error(`临时模型清理失败:${error.message}`);
  603. process.exitCode = 1;
  604. });
  605. if (temporaryGuestbookId) await jsonRequest(`${PARSE_URL}/classes/Guestbook/${temporaryGuestbookId}`, { method: 'DELETE' }, true).catch((error) => {
  606. console.error(`临时留言清理失败:${error.message}`);
  607. process.exitCode = 1;
  608. });
  609. if (temporaryGuestbookReplyId) await jsonRequest(`${PARSE_URL}/classes/Guestbook/${temporaryGuestbookReplyId}`, { method: 'DELETE' }, true).catch((error) => {
  610. console.error(`临时管理员留言回复清理失败:${error.message}`);
  611. process.exitCode = 1;
  612. });
  613. if (temporaryGuestBarId) await jsonRequest(`${PARSE_URL}/classes/GuestBar/${temporaryGuestBarId}`, { method: 'DELETE' }, true).catch((error) => {
  614. console.error(`临时贴吧帖子清理失败:${error.message}`);
  615. process.exitCode = 1;
  616. });
  617. for (const lessonId of temporaryLessonIds) await jsonRequest(`${PARSE_URL}/classes/LessonRecord/${lessonId}`, { method: 'DELETE' }, true).catch((error) => {
  618. console.error(`临时陪练课次清理失败:${error.message}`);
  619. process.exitCode = 1;
  620. });
  621. if (memberLegacyId) {
  622. const commonWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:(stu_record|content_add_zt|content_add):${memberLegacyId}:` } }));
  623. const commonRows = await jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${commonWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  624. for (const row of commonRows.results || []) await jsonRequest(`${PARSE_URL}/classes/CommonModel/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  625. console.error(`临时学习主记录清理失败:${error.message}`);
  626. process.exitCode = 1;
  627. });
  628. const studyWhere = encodeURIComponent(JSON.stringify({ userId: memberLegacyId }));
  629. const studyRows = await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord?where=${studyWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  630. for (const row of studyRows.results || []) await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  631. console.error(`临时学习 addon 清理失败:${error.message}`);
  632. process.exitCode = 1;
  633. });
  634. }
  635. if (temporaryAppointmentObjectId) await jsonRequest(`${PARSE_URL}/classes/CourseAppointment/${temporaryAppointmentObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  636. console.error(`临时预约清理失败:${error.message}`);
  637. process.exitCode = 1;
  638. });
  639. if (temporaryAppointmentId) {
  640. const sideEffectWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:e_order_update:${temporaryAppointmentId}:` } }));
  641. for (const className of ['CommonModel', 'MemoryPracticeRecord', 'UserExpDomP', 'UserUserPoint']) {
  642. const rows = await jsonRequest(`${PARSE_URL}/classes/${className}?where=${sideEffectWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  643. for (const row of rows.results || []) await jsonRequest(`${PARSE_URL}/classes/${className}/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  644. console.error(`临时预约副作用清理失败(${className}):${error.message}`);
  645. process.exitCode = 1;
  646. });
  647. }
  648. }
  649. if (memberLegacyId) {
  650. const assessmentWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:content_add:${memberLegacyId}:` } }));
  651. const assessments = await jsonRequest(`${PARSE_URL}/classes/AssessmentProfile?where=${assessmentWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  652. for (const assessment of assessments.results || []) await jsonRequest(`${PARSE_URL}/classes/AssessmentProfile/${assessment.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  653. console.error(`临时测评记录清理失败:${error.message}`);
  654. process.exitCode = 1;
  655. });
  656. }
  657. if (memberLegacyId) {
  658. const where = encodeURIComponent(JSON.stringify({ yhid: String(memberLegacyId) }));
  659. const practices = await jsonRequest(`${PARSE_URL}/classes/PracticeRecord?where=${where}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  660. for (const practice of practices.results || []) await jsonRequest(`${PARSE_URL}/classes/PracticeRecord/${practice.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  661. console.error(`临时学习进度清理失败:${error.message}`);
  662. process.exitCode = 1;
  663. });
  664. }
  665. if (teamChildId) {
  666. await jsonRequest(`${PARSE_URL}/users/${teamChildId}`, { method: 'DELETE' }, true).catch((error) => {
  667. console.error(`临时团队成员清理失败:${error.message}`);
  668. process.exitCode = 1;
  669. });
  670. }
  671. if (memberId) {
  672. await jsonRequest(`${PARSE_URL}/users/${memberId}`, { method: 'DELETE' }, true).catch((error) => {
  673. console.error(`临时普通用户清理失败:${error.message}`);
  674. process.exitCode = 1;
  675. });
  676. }
  677. if (coachId) {
  678. await jsonRequest(`${PARSE_URL}/users/${coachId}`, { method: 'DELETE' }, true).catch((error) => {
  679. console.error(`临时陪练用户清理失败:${error.message}`);
  680. process.exitCode = 1;
  681. });
  682. }
  683. if (userId) {
  684. await jsonRequest(`${PARSE_URL}/users/${userId}`, { method: 'DELETE' }, true).catch((error) => {
  685. console.error(`临时管理员清理失败:${error.message}`);
  686. process.exitCode = 1;
  687. });
  688. }
  689. }