smoke-admin-functions.mjs 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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 temporaryExamTeacherId = '';
  70. const temporaryDictionaryCategoryIds = [];
  71. const temporaryDictionaryItemIds = [];
  72. const temporaryGradeCategoryIds = [];
  73. const temporaryGradeOptionIds = [];
  74. let temporaryModelObjectId = '';
  75. const temporaryModelFieldObjectIds = [];
  76. let registeredUserId = '';
  77. let memberId = '';
  78. let memberLegacyId = 0;
  79. let teamChildId = '';
  80. let coachId = '';
  81. let coachLegacyId = 0;
  82. let temporaryAppointmentId = '';
  83. let temporaryAppointmentObjectId = '';
  84. let temporaryGuestbookId = '';
  85. let temporaryGuestbookReplyId = '';
  86. let temporaryGuestBarId = '';
  87. let contentHitObjectId = '';
  88. let contentHitOriginal = 0;
  89. let adZoneRestore = null;
  90. let adInfoRestore = null;
  91. let fontShapeRestore = null;
  92. let temporaryFontShapeId = '';
  93. let temporaryFontShapeTypeId = '';
  94. let surveyRestore = null;
  95. let surveyQuestionRestore = null;
  96. let temporarySurveyId = '';
  97. const temporarySurveyQuestionIds = [];
  98. let temporarySurveyAnswerId = '';
  99. let serviceSeatRestore = null;
  100. let serviceCodeRestore = null;
  101. let temporaryServiceSeatId = '';
  102. let temporaryServiceCodeId = '';
  103. let storeApplicationRestore = null;
  104. let storeStyleRestore = null;
  105. let temporaryStoreApplicationId = '';
  106. let temporaryStoreStyleId = '';
  107. let contentTagsRestore = null;
  108. let userLevelRestore = null;
  109. let temporaryUserLevelId = '';
  110. let baikeRestore = null;
  111. const temporaryLessonIds = [];
  112. try {
  113. const sample = await jsonRequest(`${PARSE_URL}/classes/Company?limit=1&keys=objectId`, {}, true);
  114. const companyId = sample.results?.[0]?.objectId;
  115. if (!companyId) throw new Error('没有可用于帐套隔离测试的 Company');
  116. const company = { __type: 'Pointer', className: 'Company', objectId: companyId };
  117. const username = `codex_admin_smoke_${Date.now()}`;
  118. const password = randomBytes(24).toString('base64url');
  119. const created = await jsonRequest(`${PARSE_URL}/users`, {
  120. method: 'POST',
  121. body: JSON.stringify({ username, password, isAdmin: true, roles: ['admin'], company }),
  122. }, true);
  123. userId = created.objectId;
  124. const login = await jsonRequest(`${PARSE_URL}/login`, {
  125. method: 'POST',
  126. body: JSON.stringify({ username, password }),
  127. });
  128. if (!login.sessionToken) throw new Error('临时管理员登录未返回 sessionToken');
  129. const registeredUsername = `codex_register_smoke_${Date.now()}`;
  130. const registered = await callLegacyFunction('', { action: 'user_register', name: registeredUsername, passwd: 'Ab1234' });
  131. registeredUserId = String(registered.result?.objectId || '');
  132. const registeredLegacyId = Number(registered.result?.userId);
  133. if (!registeredUserId || !registeredLegacyId || !registered.result?.sessionToken || Number(registered.result?.groupId) !== 1 || Number(registered.addon?.parentUserId) !== 0) throw new Error(`新用户注册基础字段异常:${JSON.stringify(registered)}`);
  134. const registeredInfo = await callLegacyFunction(registered.result.sessionToken, { action: 'user_get', uid: registeredLegacyId });
  135. if (Number(registeredInfo.result?.userId) !== registeredLegacyId || Number(registeredInfo.result?.groupId) !== 1 || Number(registeredInfo.addon?.Purse) !== 0 || Number(registeredInfo.addon?.UserPoint) !== 0) throw new Error('新用户注册后自查异常');
  136. const registeredByName = await callLegacyFunction('', { action: 'user_info_name', uname: registeredUsername });
  137. if (registeredByName.result?.objectId !== registeredUserId) throw new Error('新用户用户名查重异常');
  138. await jsonRequest(`${PARSE_URL}/users/${registeredUserId}`, { method: 'DELETE' }, true);
  139. registeredUserId = '';
  140. const memberUsername = `codex_member_smoke_${Date.now()}`;
  141. const memberPassword = randomBytes(24).toString('base64url');
  142. memberLegacyId = 900000000 + Math.floor(Date.now() / 1000) % 90000000;
  143. const member = await jsonRequest(`${PARSE_URL}/users`, {
  144. method: 'POST',
  145. 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 }),
  146. }, true);
  147. memberId = member.objectId;
  148. const childLegacyId = memberLegacyId + 2;
  149. const child = await jsonRequest(`${PARSE_URL}/users`, {
  150. method: 'POST',
  151. 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 }),
  152. }, true);
  153. teamChildId = child.objectId;
  154. const coachUsername = `codex_coach_smoke_${Date.now()}`;
  155. const coachPassword = randomBytes(24).toString('base64url');
  156. coachLegacyId = memberLegacyId + 1;
  157. const coach = await jsonRequest(`${PARSE_URL}/users`, {
  158. method: 'POST',
  159. body: JSON.stringify({ username: coachUsername, password: coachPassword, legacyUserId: coachLegacyId, legacyGroupId: 3, company }),
  160. }, true);
  161. coachId = coach.objectId;
  162. for (const lessonType of [1, 2, 3]) {
  163. const lesson = await jsonRequest(`${PARSE_URL}/classes/LessonRecord`, {
  164. method: 'POST',
  165. body: JSON.stringify({ company, sourceKey: `cloud:smoke-lesson:${coachLegacyId}:${lessonType}`, jsmz: String(coachLegacyId), kclx: String(lessonType) }),
  166. }, true);
  167. temporaryLessonIds.push(lesson.objectId);
  168. }
  169. const memberLogin = await jsonRequest(`${PARSE_URL}/login`, {
  170. method: 'POST',
  171. body: JSON.stringify({ username: memberUsername, password: memberPassword }),
  172. });
  173. const coachLogin = await jsonRequest(`${PARSE_URL}/login`, {
  174. method: 'POST',
  175. body: JSON.stringify({ username: coachUsername, password: coachPassword }),
  176. });
  177. const feedbackModel = { UserID: memberLegacyId, Title: '冒烟学员 反馈的意见', TContent: '2026-08-19 请假一天', Cateid: 22 };
  178. const feedback = await callLegacyFunction(memberLogin.sessionToken, { action: 'guestbook_add', model: JSON.stringify(feedbackModel) });
  179. temporaryGuestbookId = String(feedback.result?.objectId || '');
  180. 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)}`);
  181. await callLegacyFunction(memberLogin.sessionToken, { action: 'guestbook_add', model: JSON.stringify({ ...feedbackModel, UserID: coachLegacyId }) }, 403);
  182. const profileModel = { honeyName: '冒烟资料更新', trueName: '测试学员', userFace: '/UploadFiles/smoke-avatar.png', sex: '女', birthday: '2000-01-02', mobile: '13800138000', Email: `${memberUsername}@example.test`, seturl: '/member/smoke', Position: '词汇小英雄' };
  183. const updatedProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update', uid: memberLegacyId, mu: JSON.stringify(profileModel), inviCode: '' });
  184. 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)}`);
  185. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update', uid: coachLegacyId, mu: JSON.stringify({ honeyName: '越权' }) }, 403);
  186. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update_pwd', uid: memberLegacyId, vcode: '123456', newPass: 'Ab1234', reNewPass: 'Ab1234' }, 501);
  187. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_update_pwdall', uid: memberLegacyId, login: 'Ab1234', pay: '123456' }, 501);
  188. 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' }) });
  189. temporaryAppointmentId = String(createdAppointment.result);
  190. const appointmentSourceKey = `cloud:content_add:${memberLegacyId}:${temporaryAppointmentId}`;
  191. const appointmentWhere = encodeURIComponent(JSON.stringify({ sourceKey: appointmentSourceKey }));
  192. const appointmentRows = await jsonRequest(`${PARSE_URL}/classes/CourseAppointment?where=${appointmentWhere}&limit=1`, {}, true);
  193. temporaryAppointmentObjectId = appointmentRows.results?.[0]?.objectId || '';
  194. if (!temporaryAppointmentObjectId) throw new Error('临时预约副表创建失败');
  195. const appointmentCommonRows = await jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${appointmentWhere}&limit=1`, {}, true);
  196. const temporaryAppointmentCommonObjectId = String(appointmentCommonRows.results?.[0]?.objectId || '');
  197. if (!temporaryAppointmentCommonObjectId) throw new Error('临时预约主内容创建失败');
  198. const meta = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'meta' });
  199. if (meta.identity?.objectId !== userId || !meta.cloudFunctions) throw new Error('管理员 meta 校验失败');
  200. const dashboard = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dashboard' });
  201. if (!Array.isArray(dashboard.metrics) || dashboard.metrics.length !== 8) throw new Error('dashboard 指标校验失败');
  202. const catalog = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'catalog' });
  203. if (!Array.isArray(catalog.resources) || catalog.resources.length < 90 || catalog.resources.some((item) => ['_Session', 'Function'].includes(item.className))) throw new Error('后台规范化类目录校验失败');
  204. const managedUsername = `codex_admin_created_${Date.now()}`;
  205. const managedPassword = randomBytes(24).toString('base64url');
  206. const managed = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'createUser', username: managedUsername, password: managedPassword, displayName: '后台开户冒烟', mobile: '13800138001', isAdmin: true, roles: ['admin'] });
  207. adminCreatedUserId = String(managed.objectId || '');
  208. if (!adminCreatedUserId || !Number(managed.userId) || Number(managed.groupId) !== 1 || managed.isAdmin === true || managed.roles?.includes?.('admin') || managed.sessionToken) throw new Error(`管理员开户响应异常:${JSON.stringify(managed)}`);
  209. const managedStored = await jsonRequest(`${PARSE_URL}/users/${adminCreatedUserId}`, {}, true);
  210. 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('管理员开户持久化约束校验失败');
  211. const managedLogin = await jsonRequest(`${PARSE_URL}/login`, { method: 'POST', body: JSON.stringify({ username: managedUsername, password: managedPassword }) });
  212. if (!managedLogin.sessionToken) throw new Error('后台开户用户登录失败');
  213. const locked = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userBatch', className: '_User', action: 'lock', objectIds: [adminCreatedUserId], reason: '云函数冒烟' });
  214. 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)}`);
  215. await callLegacyFunction('', { action: 'user_login_passwd', name: managedUsername, passwd: managedPassword }, 403);
  216. const unlocked = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userBatch', className: '_User', action: 'unlock', objectIds: [adminCreatedUserId], reason: '恢复冒烟用户' });
  217. if (unlocked.updated !== 1 || unlocked.results?.[0]?.isDisabled !== false || Number(unlocked.results?.[0]?.legacyUserData?.State) !== 1) throw new Error(`用户解锁异常:${JSON.stringify(unlocked)}`);
  218. const temporaryGroup = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGroup', className: 'Group', fields: { groupName: '云函数冒烟临时组', description: '验证帐套内原子组编号', parentGroupId: 0, regSelect: false } });
  219. temporaryGroupObjectId = String(temporaryGroup.objectId || '');
  220. const temporaryGroupNumber = Number(temporaryGroup.groupId);
  221. if (!temporaryGroupObjectId || !temporaryGroupNumber) throw new Error('临时用户组创建失败');
  222. const moved = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userBatch', className: '_User', action: 'move', objectIds: [adminCreatedUserId], groupId: temporaryGroupNumber });
  223. if (moved.updated !== 1 || Number(moved.results?.[0]?.legacyGroupId) !== temporaryGroupNumber || Number(moved.results?.[0]?.legacyUserData?.GroupID) !== temporaryGroupNumber) throw new Error(`用户组同步异常:${JSON.stringify(moved)}`);
  224. const groupDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Group', objectId: temporaryGroupObjectId }, 409);
  225. if (!String(groupDeleteBlocked.message).includes('仍有用户')) throw new Error('用户组引用删除保护未返回明确原因');
  226. const managedAppLogin = await callLegacyFunction('', { action: 'user_login_passwd', name: managedUsername, passwd: managedPassword });
  227. if (!managedAppLogin.result?.sessionToken || Number(managedAppLogin.addon?.State) !== 1) throw new Error('解锁后旧版登录异常');
  228. await jsonRequest(`${PARSE_URL}/users/${adminCreatedUserId}`, { method: 'DELETE' }, true);
  229. adminCreatedUserId = '';
  230. const deletedGroup = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Group', objectId: temporaryGroupObjectId });
  231. if (deletedGroup.objectId !== temporaryGroupObjectId) throw new Error('无引用用户组删除失败');
  232. temporaryGroupObjectId = '';
  233. const schema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CourseAppointment' });
  234. if (schema.className !== 'CourseAppointment' || !Array.isArray(schema.fields)) throw new Error('schema 校验失败');
  235. const contentSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CommonModel' });
  236. const contentFieldMap = Object.fromEntries((contentSchema.fields || []).map((field) => [field.name, field]));
  237. if (contentSchema.creatable !== false || contentFieldMap.status?.writable !== false || contentFieldMap.modelId?.writable !== false || contentFieldMap.itemId?.writable !== false || contentFieldMap.nodeId?.writable !== false) throw new Error('内容结构字段未从通用创建/编辑中隔离');
  238. const nodeSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'Node' });
  239. const nodeFieldMap = Object.fromEntries((nodeSchema.fields || []).map((field) => [field.name, field]));
  240. if (nodeFieldMap.nodeId?.writable !== false || nodeFieldMap.parentId?.writable !== false || nodeFieldMap.depth?.writable !== false || nodeFieldMap.zstatus?.writable !== false || nodeFieldMap.sourceKey?.writable !== false) throw new Error('栏目结构字段未从通用编辑中隔离');
  241. const holidaySchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'SysHoliday' });
  242. const holidayFieldMap = Object.fromEntries((holidaySchema.fields || []).map((field) => [field.name, field]));
  243. if (holidaySchema.creatable !== false || ['id','cdate','cadminId','cuserId','sourceKey'].some((name) => holidayFieldMap[name]?.writable !== false)) throw new Error('节假日系统字段未从新增或通用编辑中隔离');
  244. const holidayPage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'list', className: 'SysHoliday', page: 1, pageSize: 20 });
  245. if (!Array.isArray(holidayPage.results)) throw new Error('节假日列表返回异常');
  246. const searchNavigationSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'Search' });
  247. const searchNavigationFieldMap = Object.fromEntries((searchNavigationSchema.fields || []).map((field) => [field.name, field]));
  248. if (searchNavigationSchema.creatable !== false || ['id','type','state','time','adminId','orderId','linkType','linkState','sourceKey'].some((name) => searchNavigationFieldMap[name]?.writable !== false)) throw new Error('快捷入口结构字段未从新增或通用编辑中隔离');
  249. const searchNavigationPage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'searchNavigations', className: 'Search', type: 1, state: -100, elite: -100, page: 1, pageSize: 20 });
  250. if (!Array.isArray(searchNavigationPage.results) || !searchNavigationPage.results.length || searchNavigationPage.results.some((entry) => Number(entry.type) !== 1)) throw new Error('后台快捷入口筛选列表返回异常');
  251. const apiCatalog = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'apiCatalog' });
  252. if (!Array.isArray(apiCatalog.results) || apiCatalog.results.length < 9 || apiCatalog.results.some((entry) => !String(entry.path || '').startsWith('xiaoshu/') || Object.prototype.hasOwnProperty.call(entry, 'code'))) throw new Error('云函数接口目录缺失或泄露了源码');
  253. const adZoneSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'AdZone' });
  254. const adZoneFieldMap = Object.fromEntries((adZoneSchema.fields || []).map((field) => [field.name, field]));
  255. if (adZoneSchema.creatable !== false || ['id','cdate','cadmin','image','sourceKey'].some((name) => adZoneFieldMap[name]?.writable !== false)) throw new Error('广告位系统字段未从新增或通用编辑中隔离');
  256. const adInfoSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'AdInfo' });
  257. const adInfoFieldMap = Object.fromEntries((adInfoSchema.fields || []).map((field) => [field.name, field]));
  258. if (adInfoSchema.creatable !== false || ['id','cdate','zoneId','ztype','extend1','extend2','extend3','sourceKey'].some((name) => adInfoFieldMap[name]?.writable !== false)) throw new Error('广告内容系统字段未从新增或通用编辑中隔离');
  259. const adZonePage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'adZones', className: 'AdZone', page: 1, pageSize: 20, status: -100, type: '' });
  260. const sampleAdZone = adZonePage.results?.[0]; if (!sampleAdZone?.objectId || !sampleAdZone.id) throw new Error('广告位专用列表没有返回历史广告位');
  261. const adInfoPage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'adInfos', className: 'AdInfo', page: 1, pageSize: 20, status: -100, zoneId: String(sampleAdZone.id) });
  262. const sampleAdInfo = adInfoPage.results?.[0]; if (!sampleAdInfo?.objectId || String(sampleAdInfo.zoneId) !== String(sampleAdZone.id)) throw new Error('广告内容按广告位筛选异常');
  263. const zoneCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveAdZone', className: 'AdZone', fields: {} }, 501);
  264. const infoCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveAdInfo', className: 'AdInfo', fields: {} }, 501);
  265. if (!String(zoneCreateBlocked.message).includes('AdZone.id') || !String(infoCreateBlocked.message).includes('AdInfo.id')) throw new Error('广告新增未返回旧 ID 明确阻塞原因');
  266. adZoneRestore = { objectId: sampleAdZone.objectId, remind: String(sampleAdZone.remind || ''), zstatus: Number(sampleAdZone.zstatus) };
  267. const zoneProbeRemind = `${adZoneRestore.remind} [angular-smoke]`.trim();
  268. const updatedAdZone = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveAdZone', className: 'AdZone', objectId: sampleAdZone.objectId, fields: { ...sampleAdZone, remind: zoneProbeRemind } });
  269. if (updatedAdZone.remind !== zoneProbeRemind) throw new Error('广告位专用编辑未写入备注');
  270. const zoneToggleAction = adZoneRestore.zstatus === 99 ? 'pause' : 'active'; const toggledZone = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'adZoneBatch', className: 'AdZone', action: zoneToggleAction, objectIds: [sampleAdZone.objectId] });
  271. if (Number(toggledZone.results?.[0]?.zstatus) !== (zoneToggleAction === 'active' ? 99 : 0)) throw new Error('广告位启停批量操作异常');
  272. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveAdZone', className: 'AdZone', objectId: sampleAdZone.objectId, fields: { ...sampleAdZone, remind: adZoneRestore.remind, zstatus: adZoneRestore.zstatus } }); adZoneRestore = null;
  273. adInfoRestore = { objectId: sampleAdInfo.objectId, remind: String(sampleAdInfo.remind || ''), zstatus: Number(sampleAdInfo.zstatus) };
  274. const infoProbeRemind = `${adInfoRestore.remind} [angular-smoke]`.trim();
  275. const updatedAdInfo = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveAdInfo', className: 'AdInfo', objectId: sampleAdInfo.objectId, zoneId: String(sampleAdInfo.zoneId), fields: { ...sampleAdInfo, remind: infoProbeRemind } });
  276. if (updatedAdInfo.remind !== infoProbeRemind) throw new Error('广告内容专用编辑未写入备注');
  277. const infoToggleAction = adInfoRestore.zstatus === 99 ? 'unaudit' : 'audit'; const toggledInfo = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'adInfoBatch', className: 'AdInfo', action: infoToggleAction, objectIds: [sampleAdInfo.objectId] });
  278. if (Number(toggledInfo.results?.[0]?.zstatus) !== (infoToggleAction === 'audit' ? 99 : 0)) throw new Error('广告内容审核批量操作异常');
  279. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveAdInfo', className: 'AdInfo', objectId: sampleAdInfo.objectId, zoneId: String(sampleAdInfo.zoneId), fields: { ...sampleAdInfo, remind: adInfoRestore.remind, zstatus: adInfoRestore.zstatus } }); adInfoRestore = null;
  280. const adPreview = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'adPreview', zoneObjectId: sampleAdZone.objectId }); if (!adPreview.zone?.objectId || !Array.isArray(adPreview.results)) throw new Error('广告位当前生效广告预览异常');
  281. const fontShapeTypeSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'FontPicShapeType' }); const fontShapeTypeFieldMap = Object.fromEntries((fontShapeTypeSchema.fields || []).map((field) => [field.name, field])); if (fontShapeTypeSchema.creatable !== false || ['id','sourceKey','createTime','updateTime'].some((name) => fontShapeTypeFieldMap[name]?.writable !== false)) throw new Error('图形分类系统字段未隔离');
  282. const fontShapeSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'FontPicShape' }); const fontShapeFieldMap = Object.fromEntries((fontShapeSchema.fields || []).map((field) => [field.name, field])); if (fontShapeSchema.creatable !== false || ['id','shape','typeId','userId','userName','sourceKey','createTime','updateTime'].some((name) => fontShapeFieldMap[name]?.writable !== false)) throw new Error('图形素材系统字段未隔离');
  283. const fontShapeTypes = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'fontShapeTypes', className: 'FontPicShapeType', page: 1, pageSize: 1000, search: '' }); if (!fontShapeTypes.results?.length) throw new Error('图形分类列表缺少历史数据');
  284. const allFontShapes = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'fontShapes', className: 'FontPicShape', page: 1, pageSize: 20, typeId: 0, search: '' }); const sampleFontShape = allFontShapes.results?.[0]; const sampleFontShapeType = fontShapeTypes.results.find((entry) => Number(entry.id) === Number(sampleFontShape?.typeId)); if (!sampleFontShape?.objectId || !sampleFontShapeType?.objectId) throw new Error('图形素材与分类历史关系异常'); const filteredFontShapes = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'fontShapes', className: 'FontPicShape', page: 1, pageSize: 20, typeId: Number(sampleFontShapeType.id), search: '' }); if (!filteredFontShapes.results?.length || filteredFontShapes.results.some((entry) => Number(entry.typeId) !== Number(sampleFontShapeType.id))) throw new Error('图形素材按分类筛选异常');
  285. const fontShapeCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveFontShape', className: 'FontPicShape', fields: {} }, 501); const fontShapeTypeCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveFontShapeType', className: 'FontPicShapeType', fields: {} }, 501); if (!String(fontShapeCreateBlocked.message).includes('FontPicShape.id') || !String(fontShapeTypeCreateBlocked.message).includes('FontPicShapeType.id')) throw new Error('图形素材新增未返回旧 ID 阻塞原因');
  286. for (const action of ['Index','FontPicInfo','FontPicInfo_Submit','FontPic_API','Draft','DraftInfo','DraftInfo_Submit','Draft_API']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyFontPicBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`旧字体图动作 ${action} 未返回明确阻塞原因`); }
  287. fontShapeRestore = { objectId: sampleFontShape.objectId, shape: String(sampleFontShape.shape || ''), remarks: String(sampleFontShape.remarks || ''), typeId: Number(sampleFontShape.typeId), updateTime: sampleFontShape.updateTime };
  288. const shapeProbeRemarks = `${fontShapeRestore.remarks} [angular-smoke]`.trim(); const updatedShape = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveFontShape', className: 'FontPicShape', objectId: sampleFontShape.objectId, typeId: fontShapeRestore.typeId, fields: { ...sampleFontShape, remarks: shapeProbeRemarks } }); if (updatedShape.remarks !== shapeProbeRemarks || Number(updatedShape.typeId) !== fontShapeRestore.typeId || String(updatedShape.shape || '') !== fontShapeRestore.shape) throw new Error('图形素材元数据专用编辑异常');
  289. const fileBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveFontShape', className: 'FontPicShape', objectId: sampleFontShape.objectId, typeId: fontShapeRestore.typeId, fields: { ...sampleFontShape, remarks: shapeProbeRemarks }, file: { name: 'font-shape-smoke.png', mimeType: 'image/png', base64: 'iVBORw0KGgo=' } }, 501); if (!String(fileBlocked.message).includes('文件适配器') || !String(fileBlocked.message).includes('PostgreSQL')) throw new Error('图形文件基础设施阻塞未返回明确原因');
  290. const shapeRestoreBody = { shape: fontShapeRestore.shape, remarks: fontShapeRestore.remarks, typeId: fontShapeRestore.typeId, ...(fontShapeRestore.updateTime ? { updateTime: fontShapeRestore.updateTime } : {}) }; await jsonRequest(`${PARSE_URL}/classes/FontPicShape/${fontShapeRestore.objectId}`, { method: 'PUT', body: JSON.stringify(shapeRestoreBody) }, true); fontShapeRestore = null;
  291. const originalTypeRemarks = String(sampleFontShapeType.remarks || ''); const updatedShapeType = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveFontShapeType', className: 'FontPicShapeType', objectId: sampleFontShapeType.objectId, fields: { ...sampleFontShapeType, remarks: `${originalTypeRemarks} [angular-smoke]`.trim() } }); if (!String(updatedShapeType.remarks).endsWith('[angular-smoke]')) throw new Error('图形分类专用编辑失败'); await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveFontShapeType', className: 'FontPicShapeType', objectId: sampleFontShapeType.objectId, fields: { ...sampleFontShapeType, remarks: originalTypeRemarks } });
  292. const referencedTypeDelete = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'fontShapeTypeBatch', className: 'FontPicShapeType', action: 'delete', objectIds: [sampleFontShapeType.objectId] }, 409); if (!String(referencedTypeDelete.message).includes('素材引用')) throw new Error('图形分类引用删除保护未返回明确原因');
  293. const tempType = await jsonRequest(`${PARSE_URL}/classes/FontPicShapeType`, { method: 'POST', body: JSON.stringify({ name: '__font_shape_type_batch_smoke__', remarks: 'temporary', sourceKey: `smoke-font-shape-type-${Date.now()}`, company }) }, true); temporaryFontShapeTypeId = tempType.objectId; const deletedTempType = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'fontShapeTypeBatch', className: 'FontPicShapeType', action: 'delete', objectIds: [temporaryFontShapeTypeId] }); if (deletedTempType.updated !== 1) throw new Error('图形分类批量删除失败'); temporaryFontShapeTypeId = '';
  294. const tempShape = await jsonRequest(`${PARSE_URL}/classes/FontPicShape`, { method: 'POST', body: JSON.stringify({ name: '__font_shape_batch_smoke__', shape: '', typeId: Number(sampleFontShapeType.id), remarks: 'temporary', sourceKey: `smoke-font-shape-${Date.now()}`, company }) }, true); temporaryFontShapeId = tempShape.objectId; const deletedTempShape = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'fontShapeBatch', className: 'FontPicShape', action: 'delete', objectIds: [temporaryFontShapeId] }); if (deletedTempShape.updated !== 1) throw new Error('图形素材批量删除失败'); temporaryFontShapeId = '';
  295. const surveySchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'DesignAsk' }); const surveyFieldMap = Object.fromEntries((surveySchema.fields || []).map((field) => [field.name, field])); if (surveySchema.creatable !== false || surveySchema.writable !== true || ['id','cdate','cuser','adminId','sourceKey'].some((name) => surveyFieldMap[name]?.writable !== false)) throw new Error('问卷系统字段未隔离');
  296. const surveyQuestionSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'DesignQuestion' }); const surveyQuestionFieldMap = Object.fromEntries((surveyQuestionSchema.fields || []).map((field) => [field.name, field])); if (surveyQuestionSchema.creatable !== false || surveyQuestionSchema.writable !== true || ['id','askId','cdate','cuser','orderId','sourceKey'].some((name) => surveyQuestionFieldMap[name]?.writable !== false)) throw new Error('问卷题目系统字段未隔离');
  297. const surveyAnswerSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'DesignAnswer' }); if (surveyAnswerSchema.writable !== false || surveyAnswerSchema.creatable !== false) throw new Error('问卷答卷未保持只读');
  298. const surveys = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveys', className: 'DesignAsk', page: 1, pageSize: 100, search: '', status: -100 }); const sampleSurvey = surveys.results?.find((entry) => new Date(entry.endDate?.iso || entry.endDate).getTime() > Date.now()); if (surveys.total < 2 || !sampleSurvey?.objectId || !Number(sampleSurvey.id)) throw new Error('旧问卷列表未绕过兼容层错误 count'); const surveyId = Number(sampleSurvey.id);
  299. const surveyQuestions = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyQuestions', className: 'DesignQuestion', askId: surveyId, page: 1, pageSize: 100, search: '' }); const sampleSurveyQuestion = surveyQuestions.results?.[0]; if (!sampleSurveyQuestion?.objectId || surveyQuestions.results.some((entry) => Number(entry.askId) !== surveyId)) throw new Error('问卷题目归属筛选异常');
  300. const surveyResults = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyResults', className: 'DesignAnswer', askId: surveyId, page: 1, pageSize: 100 }); if (!surveyResults.results?.length || surveyResults.results.some((entry) => Number(entry.askId) !== surveyId)) throw new Error('问卷答卷归属筛选异常');
  301. const surveyChart = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyResultChart', askId: surveyId }); if (surveyChart.responseCount !== surveyResults.total || !Array.isArray(surveyChart.questions) || !surveyChart.questions.length || surveyChart.questions.some((question) => !Array.isArray(question.options))) throw new Error('问卷结果统计异常');
  302. const surveyCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSurvey', className: 'DesignAsk', fields: {} }, 501); const surveyQuestionCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSurveyQuestion', className: 'DesignQuestion', fields: {} }, 501); if (!String(surveyCreateBlocked.message).includes('DesignAsk.id') || !String(surveyQuestionCreateBlocked.message).includes('DesignQuestion.id')) throw new Error('问卷新增未返回旧 ID 阻塞原因');
  303. surveyRestore = { objectId: sampleSurvey.objectId, fields: { title: sampleSurvey.title, category: sampleSurvey.category, remind: sampleSurvey.remind, preViewImg: sampleSurvey.preViewImg, startDate: { __type: 'Date', iso: String(sampleSurvey.startDate?.iso || sampleSurvey.startDate) }, endDate: { __type: 'Date', iso: String(sampleSurvey.endDate?.iso || sampleSurvey.endDate) }, ztype: Number(sampleSurvey.ztype || 0), ipinterval: Number(sampleSurvey.ipinterval || 0), zstatus: Number(sampleSurvey.zstatus || 0), isIplimit: Number(sampleSurvey.isIplimit || 0), isNeedLogin: Number(sampleSurvey.isNeedLogin || 0), isShowResult: Number(sampleSurvey.isShowResult || 0), isEnableVcode: Number(sampleSurvey.isEnableVcode || 0) } }; const surveyProbeRemind = `${String(sampleSurvey.remind || '')} [angular-smoke]`.trim(); const updatedSurvey = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSurvey', className: 'DesignAsk', objectId: sampleSurvey.objectId, fields: { ...sampleSurvey, remind: surveyProbeRemind, ztype: Number(sampleSurvey.ztype || 0), ipinterval: Number(sampleSurvey.ipinterval || 0), zstatus: Number(sampleSurvey.zstatus || 0), isIplimit: Number(sampleSurvey.isIplimit || 0), isNeedLogin: Number(sampleSurvey.isNeedLogin || 0), isShowResult: Number(sampleSurvey.isShowResult || 0), isEnableVcode: Number(sampleSurvey.isEnableVcode || 0) } }); if (updatedSurvey.remind !== surveyProbeRemind) throw new Error('问卷专用编辑失败'); const surveyToggleAction = Number(sampleSurvey.zstatus) === 99 ? 'stop' : 'start'; const toggledSurvey = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyBatch', className: 'DesignAsk', action: surveyToggleAction, objectIds: [sampleSurvey.objectId] }); if (Number(toggledSurvey.results?.[0]?.zstatus) !== (surveyToggleAction === 'start' ? 99 : 0)) throw new Error('问卷启停失败'); await jsonRequest(`${PARSE_URL}/classes/DesignAsk/${surveyRestore.objectId}`, { method: 'PUT', body: JSON.stringify(surveyRestore.fields) }, true); surveyRestore = null;
  304. surveyQuestionRestore = { objectId: sampleSurveyQuestion.objectId, fields: { qtitle: sampleSurveyQuestion.qtitle, qcontent: sampleSurveyQuestion.qcontent, qtype: sampleSurveyQuestion.qtype, qoption: sampleSurveyQuestion.qoption, qflag: sampleSurveyQuestion.qflag, required: Number(sampleSurveyQuestion.required || 0) } }; const questionProbeContent = `${String(sampleSurveyQuestion.qcontent || '')} [angular-smoke]`.trim(); const updatedSurveyQuestion = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSurveyQuestion', className: 'DesignQuestion', objectId: sampleSurveyQuestion.objectId, fields: { ...sampleSurveyQuestion, qcontent: questionProbeContent } }); if (updatedSurveyQuestion.qcontent !== questionProbeContent || Number(updatedSurveyQuestion.askId) !== surveyId) throw new Error('问卷题目专用编辑失败'); await jsonRequest(`${PARSE_URL}/classes/DesignQuestion/${surveyQuestionRestore.objectId}`, { method: 'PUT', body: JSON.stringify(surveyQuestionRestore.fields) }, true); surveyQuestionRestore = null;
  305. const temporarySurvey = await jsonRequest(`${PARSE_URL}/classes/DesignAsk`, { method: 'POST', body: JSON.stringify({ title: '__survey_batch_smoke__', startDate: { __type: 'Date', iso: new Date().toISOString() }, endDate: { __type: 'Date', iso: new Date(Date.now() + 86400000).toISOString() }, sourceKey: `smoke-survey-${Date.now()}`, company }) }, true); temporarySurveyId = temporarySurvey.objectId; const deletedTemporarySurvey = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyBatch', className: 'DesignAsk', action: 'delete', objectIds: [temporarySurveyId] }); if (deletedTemporarySurvey.updated !== 1) throw new Error('问卷批量删除失败'); temporarySurveyId = '';
  306. for (let index = 0; index < 2; index++) { const createdQuestion = await jsonRequest(`${PARSE_URL}/classes/DesignQuestion`, { method: 'POST', body: JSON.stringify({ askId: surveyId, qtitle: `__survey_sort_smoke_${index}__`, qtype: 'radio', qoption: JSON.stringify([{ text: 'A', value: 'A' }]), qflag: '{}', required: 0, orderId: 0, sourceKey: `smoke-survey-question-${Date.now()}-${index}`, company }) }, true); temporarySurveyQuestionIds.push(createdQuestion.objectId); } const sortedQuestions = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyBatch', className: 'DesignQuestion', action: 'sort', objectIds: [...temporarySurveyQuestionIds], orders: temporarySurveyQuestionIds.map((objectId, index) => ({ objectId, orderId: 700 + index })) }); if (sortedQuestions.results?.map((entry) => Number(entry.orderId)).sort().join(',') !== '700,701') throw new Error('问卷题目批量排序失败'); const deletedTemporaryQuestions = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyBatch', className: 'DesignQuestion', action: 'delete', objectIds: [...temporarySurveyQuestionIds] }); if (deletedTemporaryQuestions.updated !== 2) throw new Error('问卷题目批量删除失败'); temporarySurveyQuestionIds.length = 0;
  307. const temporaryAnswer = await jsonRequest(`${PARSE_URL}/classes/DesignAnswer`, { method: 'POST', body: JSON.stringify({ askId: surveyId, answer: '[]', sourceKey: `smoke-survey-answer-${Date.now()}`, company }) }, true); temporarySurveyAnswerId = temporaryAnswer.objectId; const deletedTemporaryAnswer = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'surveyBatch', className: 'DesignAnswer', action: 'delete', objectIds: [temporarySurveyAnswerId] }); if (deletedTemporaryAnswer.updated !== 1) throw new Error('问卷答卷批量删除失败'); temporarySurveyAnswerId = '';
  308. const serviceSeatSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'ServiceSeat' }); const serviceSeatFieldMap = Object.fromEntries((serviceSeatSchema.fields || []).map((field) => [field.name, field])); if (serviceSeatSchema.creatable !== true || ['sId','sAdminId','sRemrk','sDateTime','sourceKey'].some((name) => serviceSeatFieldMap[name]?.writable !== false)) throw new Error('客服席位系统字段未隔离');
  309. const serviceCodeSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'Temp' }); const serviceCodeFieldMap = Object.fromEntries((serviceCodeSchema.fields || []).map((field) => [field.name, field])); if (serviceCodeSchema.creatable !== false || ['id','useType','str3','str5','str6','describe','cdate','userId','sourceKey'].some((name) => serviceCodeFieldMap[name]?.writable !== false)) throw new Error('客服欢迎语系统字段未隔离');
  310. const serviceSeats = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'serviceSeats', className: 'ServiceSeat', page: 1, pageSize: 20, search: '' }); const sampleServiceSeat = serviceSeats.results?.[0]; if (!sampleServiceSeat?.objectId || !Number(sampleServiceSeat.sId) || !sampleServiceSeat.sRemrk) throw new Error('客服席位历史数据读取异常');
  311. const serviceCodes = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'serviceCodes', className: 'Temp', page: 1, pageSize: 20, search: '' }); const sampleServiceCode = serviceCodes.results?.[0]; if (!sampleServiceCode?.objectId || Number(sampleServiceCode.useType) !== 12) throw new Error('客服欢迎语历史数据读取异常');
  312. serviceSeatRestore = { objectId: sampleServiceSeat.objectId, fields: { sName: sampleServiceSeat.sName, sFaceImg: sampleServiceSeat.sFaceImg, sRemrk: sampleServiceSeat.sRemrk, sAdminId: Number(sampleServiceSeat.sAdminId || 0), sDefault: Number(sampleServiceSeat.sDefault || 0), sIndex: Number(sampleServiceSeat.sIndex || 0), sDateTime: sampleServiceSeat.sDateTime } }; const seatProbeName = `${String(sampleServiceSeat.sName || '')} [angular-smoke]`.trim(); const updatedServiceSeat = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveServiceSeat', className: 'ServiceSeat', objectId: sampleServiceSeat.objectId, username: sampleServiceSeat.sRemrk, fields: { ...sampleServiceSeat, sName: seatProbeName, sDefault: Number(sampleServiceSeat.sDefault || 0), sIndex: Number(sampleServiceSeat.sIndex || 0) } }); if (updatedServiceSeat.sName !== seatProbeName || Number(updatedServiceSeat.sAdminId) !== Number(sampleServiceSeat.sAdminId)) throw new Error('客服席位专用编辑失败'); await jsonRequest(`${PARSE_URL}/classes/ServiceSeat/${serviceSeatRestore.objectId}`, { method: 'PUT', body: JSON.stringify(serviceSeatRestore.fields) }, true); serviceSeatRestore = null;
  313. const weakAccountBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveServiceSeat', className: 'ServiceSeat', username: `missing_service_${Date.now()}`, fields: { sName: '临时客服', sDefault: 0, sIndex: 0 } }, 501); if (!String(weakAccountBlocked.message).includes('固定密码 123456')) throw new Error('客服弱密码开户未返回明确安全阻塞');
  314. const createdServiceSeat = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveServiceSeat', className: 'ServiceSeat', username: sampleServiceSeat.sRemrk, fields: { sName: '__service_seat_create_smoke__', sFaceImg: '', sDefault: 0, sIndex: 999 } }); temporaryServiceSeatId = String(createdServiceSeat.objectId || ''); if (!temporaryServiceSeatId || !Number(createdServiceSeat.sId) || createdServiceSeat.sourceKey !== `[["S_ID",${Number(createdServiceSeat.sId)}]]`) throw new Error('客服席位原子编号创建异常'); const deletedServiceSeat = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'serviceBatch', className: 'ServiceSeat', action: 'delete', objectIds: [temporaryServiceSeatId] }); if (deletedServiceSeat.updated !== 1) throw new Error('客服席位批量删除失败'); temporaryServiceSeatId = '';
  315. serviceCodeRestore = { objectId: sampleServiceCode.objectId, fields: { str1: sampleServiceCode.str1, str2: sampleServiceCode.str2, str4: sampleServiceCode.str4 } }; const codeProbeName = `${String(sampleServiceCode.str1 || '')} [angular-smoke]`.trim(); const updatedServiceCode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveServiceCode', className: 'Temp', objectId: sampleServiceCode.objectId, fields: { ...sampleServiceCode, str1: codeProbeName } }); if (updatedServiceCode.str1 !== codeProbeName || Number(updatedServiceCode.useType) !== 12) throw new Error('客服欢迎语专用编辑失败'); await jsonRequest(`${PARSE_URL}/classes/Temp/${serviceCodeRestore.objectId}`, { method: 'PUT', body: JSON.stringify(serviceCodeRestore.fields) }, true); serviceCodeRestore = null;
  316. const serviceCodeCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveServiceCode', className: 'Temp', fields: {} }, 501); if (!String(serviceCodeCreateBlocked.message).includes('Temp.id')) throw new Error('客服欢迎语新增未返回旧 ID 阻塞原因'); const directServiceCode = await jsonRequest(`${PARSE_URL}/classes/Temp`, { method: 'POST', body: JSON.stringify({ useType: 12, str1: '__service_code_delete_smoke__', str2: 'temporary', str3: `smoke-${Date.now()}`, str4: 'def', sourceKey: `smoke-service-code-${Date.now()}`, company }) }, true); temporaryServiceCodeId = directServiceCode.objectId; const readDirectServiceCode = await jsonRequest(`${PARSE_URL}/classes/Temp/${temporaryServiceCodeId}`, {}, true); if (readDirectServiceCode.id != null) throw new Error('客服欢迎语省略 id 的创建探测意外生成了旧编号'); const deletedServiceCode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'serviceBatch', className: 'Temp', action: 'delete', objectIds: [temporaryServiceCodeId] }); if (deletedServiceCode.updated !== 1) throw new Error('客服欢迎语批量删除失败'); temporaryServiceCodeId = '';
  317. for (const action of ['MsgEx','MsgInfo','MsgList','chat_del']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyServiceChatBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`旧客服消息动作 ${action} 未返回明确阻塞原因`); }
  318. const storeApplicationSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'StoreApplication' }); const storeApplicationFieldMap = Object.fromEntries((storeApplicationSchema.fields || []).map((field) => [field.name, field])); if (storeApplicationSchema.creatable !== false || ['id','userId','userName','addTime','storeState','storeCommendState','storeModelId','sourceKey'].some((name) => storeApplicationFieldMap[name]?.writable !== false)) throw new Error('店铺系统字段未隔离');
  319. const storeStyleSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'StoreStyle' }); const storeStyleFieldMap = Object.fromEntries((storeStyleSchema.fields || []).map((field) => [field.name, field])); if (storeStyleSchema.creatable !== false || ['id','cdate','zstatus','sourceKey'].some((name) => storeStyleFieldMap[name]?.writable !== false)) throw new Error('店铺样式系统字段未隔离');
  320. const storeApplications = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeApplications', className: 'StoreApplication', page: 1, pageSize: 100, search: '', status: -100 }); const sampleStoreApplication = storeApplications.results?.find((entry) => entry.userName === 'admin') || storeApplications.results?.[0]; if (storeApplications.total < 1 || !sampleStoreApplication?.objectId || !Number(sampleStoreApplication.id) || !sampleStoreApplication.userName) throw new Error('店铺历史数据读取异常');
  321. const storeStyles = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeStyles', className: 'StoreStyle', page: 1, pageSize: 100, search: '' }); const sampleStoreStyle = storeStyles.results?.[0]; if (storeStyles.total < 1 || !sampleStoreStyle?.objectId || !Number(sampleStoreStyle.id)) throw new Error('店铺样式历史数据读取异常');
  322. const storeCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveStoreApplication', className: 'StoreApplication', fields: {} }, 501); const storeStyleCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveStoreStyle', className: 'StoreStyle', fields: {} }, 501); if (!String(storeCreateBlocked.message).includes('StoreApplication.id') || !String(storeStyleCreateBlocked.message).includes('StoreStyle.id')) throw new Error('店铺新增未返回旧 ID 阻塞原因');
  323. storeApplicationRestore = { objectId: sampleStoreApplication.objectId, fields: { storeName: sampleStoreApplication.storeName, lxr: sampleStoreApplication.lxr, tel: sampleStoreApplication.tel, addr: sampleStoreApplication.addr, area: sampleStoreApplication.area, logo: sampleStoreApplication.logo, pics: sampleStoreApplication.pics, weibo: sampleStoreApplication.weibo, map: sampleStoreApplication.map, content: sampleStoreApplication.content, synopsis: sampleStoreApplication.synopsis, shopType: sampleStoreApplication.shopType, videoUrl: sampleStoreApplication.videoUrl, userId: Number(sampleStoreApplication.userId || 0), userName: sampleStoreApplication.userName, storeStyleId: Number(sampleStoreApplication.storeStyleId || 0), storeState: Number(sampleStoreApplication.storeState || 0), storeCommendState: Number(sampleStoreApplication.storeCommendState || 0) } }; const storeProbeSynopsis = `${String(sampleStoreApplication.synopsis || '')} [angular-smoke]`.trim(); const updatedStoreApplication = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveStoreApplication', className: 'StoreApplication', objectId: sampleStoreApplication.objectId, username: sampleStoreApplication.userName, styleId: Number(sampleStoreApplication.storeStyleId || 0), fields: { ...sampleStoreApplication, synopsis: storeProbeSynopsis } }); if (updatedStoreApplication.synopsis !== storeProbeSynopsis || Number(updatedStoreApplication.userId) !== Number(sampleStoreApplication.userId)) throw new Error('店铺专用编辑失败'); const storeAuditAction = Number(sampleStoreApplication.storeState) === 99 ? 'unaudit' : 'audit'; const auditedStore = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeBatch', className: 'StoreApplication', action: storeAuditAction, objectIds: [sampleStoreApplication.objectId] }); if (Number(auditedStore.results?.[0]?.storeState) !== (storeAuditAction === 'audit' ? 99 : -1)) throw new Error('店铺审核状态更新失败'); const recommendedStore = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeBatch', className: 'StoreApplication', action: 'elite', objectIds: [sampleStoreApplication.objectId] }); if (Number(recommendedStore.results?.[0]?.storeCommendState) !== 1 || Number(recommendedStore.results?.[0]?.storeState) !== 99) throw new Error('店铺推荐失败'); await jsonRequest(`${PARSE_URL}/classes/StoreApplication/${storeApplicationRestore.objectId}`, { method: 'PUT', body: JSON.stringify(storeApplicationRestore.fields) }, true); storeApplicationRestore = null;
  324. const storeDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeBatch', className: 'StoreApplication', action: 'delete', objectIds: [sampleStoreApplication.objectId] }, 501); if (!String(storeDeleteBlocked.message).includes('ZL_Commodities')) throw new Error('店铺真实删除未返回商品主表阻塞原因');
  325. storeStyleRestore = { objectId: sampleStoreStyle.objectId, fields: { styleName: sampleStoreStyle.styleName, remind: sampleStoreStyle.remind, thumbnail: sampleStoreStyle.thumbnail, templateIndex: sampleStoreStyle.templateIndex, templateContent: sampleStoreStyle.templateContent, templateList: sampleStoreStyle.templateList } }; const styleProbeRemind = `${String(sampleStoreStyle.remind || '')} [angular-smoke]`.trim(); const updatedStoreStyle = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveStoreStyle', className: 'StoreStyle', objectId: sampleStoreStyle.objectId, fields: { ...sampleStoreStyle, remind: styleProbeRemind } }); if (updatedStoreStyle.remind !== styleProbeRemind) throw new Error('店铺样式专用编辑失败'); await jsonRequest(`${PARSE_URL}/classes/StoreStyle/${storeStyleRestore.objectId}`, { method: 'PUT', body: JSON.stringify(storeStyleRestore.fields) }, true); storeStyleRestore = null;
  326. const temporaryStoreApplication = await jsonRequest(`${PARSE_URL}/classes/StoreApplication`, { method: 'POST', body: JSON.stringify({ storeName: '__store_style_ref_smoke__', userId: Number(sampleStoreApplication.userId), userName: sampleStoreApplication.userName, storeStyleId: Number(sampleStoreStyle.id), storeState: 0, sourceKey: `smoke-store-application-${Date.now()}`, company }) }, true); temporaryStoreApplicationId = temporaryStoreApplication.objectId; const referencedStoreStyle = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeBatch', className: 'StoreStyle', action: 'delete', objectIds: [sampleStoreStyle.objectId] }, 409); if (!String(referencedStoreStyle.message).includes('店铺引用')) throw new Error('店铺样式引用删除保护未返回明确原因'); await jsonRequest(`${PARSE_URL}/classes/StoreApplication/${temporaryStoreApplicationId}`, { method: 'DELETE' }, true); temporaryStoreApplicationId = '';
  327. const temporaryStoreStyle = await jsonRequest(`${PARSE_URL}/classes/StoreStyle`, { method: 'POST', body: JSON.stringify({ styleName: '__store_style_delete_smoke__', templateIndex: 'index.html', templateContent: 'content.html', templateList: 'list.html', sourceKey: `smoke-store-style-${Date.now()}`, company }) }, true); temporaryStoreStyleId = temporaryStoreStyle.objectId; const readTemporaryStoreStyle = await jsonRequest(`${PARSE_URL}/classes/StoreStyle/${temporaryStoreStyleId}`, {}, true); if (readTemporaryStoreStyle.id != null) throw new Error('店铺样式省略 id 的创建探测意外生成了旧编号'); const deletedStoreStyle = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'storeBatch', className: 'StoreStyle', action: 'delete', objectIds: [temporaryStoreStyleId] }); if (deletedStoreStyle.updated !== 1) throw new Error('店铺样式批量删除失败'); temporaryStoreStyleId = '';
  328. const productPageBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyStoreProductBlocker' }, 501); if (!String(productPageBlocked.message).includes('ZL_Commodities')) throw new Error('店铺商品页未返回商品主表阻塞原因');
  329. const contentTagSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'ContentTagKey' }); if (contentTagSchema.className !== 'ContentTagKey' || contentTagSchema.writable !== true || contentTagSchema.creatable !== false || contentTagSchema.fields?.some((field) => field.writable)) throw new Error('内容标签虚拟 Schema 异常');
  330. const contentTagPage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentTagKeys', className: 'ContentTagKey', page: 1, pageSize: 20, search: '' }); const originalContentTags = Array.isArray(contentTagPage.results?.[0]?.tags) ? contentTagPage.results[0].tags.map(String) : []; contentTagsRestore = originalContentTags; const tagProbe = `angular-smoke-${Date.now()}`; const probeContentTags = originalContentTags.length >= 1000 ? [...originalContentTags.slice(0, 999), tagProbe] : [...originalContentTags, tagProbe]; const savedContentTags = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveContentTagKeys', className: 'ContentTagKey', objectId: 'global-content-tags', tags: probeContentTags }); if (savedContentTags.count !== probeContentTags.length || savedContentTags.tags?.at(-1) !== tagProbe) throw new Error('内容标签 Parse Config 保存异常'); const readContentTags = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'getContentTagKeys', className: 'ContentTagKey', objectId: 'global-content-tags' }); if (readContentTags.tags?.at(-1) !== tagProbe) throw new Error('内容标签 Parse Config 写后读失败'); await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveContentTagKeys', className: 'ContentTagKey', objectId: 'global-content-tags', tags: originalContentTags }); contentTagsRestore = null;
  331. for (const action of ['Comment','Commont_API','ConAudit_API','ConAudit_SJ_API','ConAudit','ConAuditDetail','VerBak','VerBak_Del']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyContentAddonBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`内容附加动作 ${action} 未返回明确数据阻塞`); }
  332. for (const action of ['Vendor','Vendor_API','VendorAdd','VendorAdd_Submit']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyShopVendorBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`旧供应商动作 ${action} 未返回明确数据阻塞`); }
  333. const userLevelSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'UserLevel' }); const userLevelFieldMap = Object.fromEntries((userLevelSchema.fields || []).map((field) => [field.name, field])); if (userLevelSchema.creatable !== false || ['id','cdate','ztype','addon1','addon2','addon3','addon4','addon5','orderId','storeId','zstatus','sourceKey','discountRate'].some((name) => userLevelFieldMap[name]?.writable !== false) || ['alias','pointRate','image','remark'].some((name) => userLevelFieldMap[name]?.writable !== true)) throw new Error('积分等级 Schema 字段隔离异常');
  334. const userLevels = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userLevels', className: 'UserLevel', page: 1, pageSize: 100, search: '' }); const sampleUserLevel = userLevels.results?.[0]; if (userLevels.total < 1 || !sampleUserLevel?.objectId || !Number(sampleUserLevel.id) || !sampleUserLevel.alias) throw new Error('积分等级历史数据读取异常');
  335. const userLevelCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveUserLevel', className: 'UserLevel', fields: {} }, 501); if (!String(userLevelCreateBlocked.message).includes('UserLevel.id')) throw new Error('积分等级新增未返回旧 ID 阻塞原因'); userLevelRestore = { objectId: sampleUserLevel.objectId, fields: { alias: sampleUserLevel.alias, pointRate: Number(sampleUserLevel.pointRate || 0), image: sampleUserLevel.image, remark: sampleUserLevel.remark } }; const levelProbeRemark = `${String(sampleUserLevel.remark || '')} [angular-smoke]`.trim(); const savedUserLevel = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveUserLevel', className: 'UserLevel', objectId: sampleUserLevel.objectId, fields: { ...sampleUserLevel, pointRate: Number(sampleUserLevel.pointRate || 0), remark: levelProbeRemark } }); if (savedUserLevel.remark !== levelProbeRemark || Number(savedUserLevel.id) !== Number(sampleUserLevel.id)) throw new Error('积分等级专用编辑失败'); await jsonRequest(`${PARSE_URL}/classes/UserLevel/${userLevelRestore.objectId}`, { method: 'PUT', body: JSON.stringify(userLevelRestore.fields) }, true); userLevelRestore = null;
  336. const directUserLevel = await jsonRequest(`${PARSE_URL}/classes/UserLevel`, { method: 'POST', body: JSON.stringify({ alias: '__user_level_delete_smoke__', pointRate: 999999, image: '', remark: 'temporary', sourceKey: `smoke-user-level-${Date.now()}`, company }) }, true); temporaryUserLevelId = directUserLevel.objectId; const readDirectUserLevel = await jsonRequest(`${PARSE_URL}/classes/UserLevel/${temporaryUserLevelId}`, {}, true); if (readDirectUserLevel.id != null) throw new Error('积分等级省略 id 的创建探测意外生成了旧编号'); const deletedUserLevel = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userLevelBatch', className: 'UserLevel', action: 'delete', objectIds: [temporaryUserLevelId] }); if (deletedUserLevel.updated !== 1) throw new Error('积分等级批量删除失败'); temporaryUserLevelId = '';
  337. const userMoneySchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'UserMoneyLog' }); if (userMoneySchema.writable !== false || userMoneySchema.creatable !== false || userMoneySchema.fields?.some((field) => field.writable)) throw new Error('资金积分流水虚拟 Schema 应全部只读'); const moneyPage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userMoneyLogs', className: 'UserMoneyLog', type: 1, page: 1, pageSize: 20, search: '', startDate: '', endDate: '' }); const sampleMoneyLog = moneyPage.results?.[0]; if (moneyPage.total < 1 || !String(sampleMoneyLog?.objectId || '').startsWith('UserExpDomP:') || sampleMoneyLog.moneyTypeLabel !== '余额') throw new Error('余额流水规范化聚合异常'); const moneyDetail = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'getUserMoneyLog', className: 'UserMoneyLog', objectId: sampleMoneyLog.objectId }); if (moneyDetail.objectId !== sampleMoneyLog.objectId || moneyDetail.recordObjectId !== sampleMoneyLog.recordObjectId) throw new Error('资金流水详情读取异常'); const moneyDate = String(sampleMoneyLog.hisTime?.iso || sampleMoneyLog.hisTime || '').slice(0,10); const filteredMoney = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userMoneyLogs', className: 'UserMoneyLog', type: 1, page: 1, pageSize: 20, search: String(sampleMoneyLog.userId || ''), startDate: moneyDate, endDate: moneyDate }); if (filteredMoney.total < 1) throw new Error('资金流水用户/日期筛选失败'); for (const type of [2,3,4,5,6]) { const ledger = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'userMoneyLogs', className: 'UserMoneyLog', type, page: 1, pageSize: 1, search: '', startDate: '', endDate: '' }); if (ledger.className !== 'UserMoneyLog') throw new Error(`资金流水类型 ${type} 未正确路由`); }
  338. for (const action of ['ThirdInfo','ThirdInfo_Submit','SigninList','RealNameAuth','RealNameAuthAdd','RealNameAuth_API']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyUserAddonBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`旧用户附加动作 ${action} 未返回明确阻塞原因`); }
  339. for (const action of ['Default','AskInfo','AskAdd','AskAdd_Submit','Ask_API','AnswerList','AnswerAdd','AnswerAdd_Submit','Answer_API','Config','Config_Submit']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyAskBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`旧问答动作 ${action} 未返回明确阻塞原因`); }
  340. const baikeSchema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'Baike' }); if (baikeSchema.writable !== false || baikeSchema.fields?.some((field) => field.writable)) throw new Error('百科主词条 Schema 应保持只读'); const baikePage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'baikeEntries', className: 'Baike', page: 1, pageSize: 20, search: '', status: -100, elite: -100 }); const sampleBaike = baikePage.results?.[0]; if (baikePage.total < 1 || !sampleBaike?.objectId || !Number(sampleBaike.id)) throw new Error('百科历史主词条读取异常'); baikeRestore = { objectId: sampleBaike.objectId, fields: { status: Number(sampleBaike.status || 0), elite: Number(sampleBaike.elite || 0) } }; const baikeAuditAction = Number(sampleBaike.status) === 1 ? 'unaudit' : 'audit'; const auditedBaike = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'baikeBatch', className: 'Baike', action: baikeAuditAction, objectIds: [sampleBaike.objectId] }); if (Number(auditedBaike.results?.[0]?.status) !== (baikeAuditAction === 'audit' ? 1 : 0)) throw new Error('百科审核状态更新失败'); const baikeEliteAction = Number(sampleBaike.elite) === 1 ? 'unelite' : 'elite'; const eliteBaike = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'baikeBatch', className: 'Baike', action: baikeEliteAction, objectIds: [sampleBaike.objectId] }); if (Number(eliteBaike.results?.[0]?.elite) !== (baikeEliteAction === 'elite' ? 1 : 0)) throw new Error('百科推荐状态更新失败'); await jsonRequest(`${PARSE_URL}/classes/Baike/${baikeRestore.objectId}`, { method: 'PUT', body: JSON.stringify(baikeRestore.fields) }, true); baikeRestore = null; for (const action of ['BKVersionList','Version_API','BKList','Config','Config_Submit']) { const blocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyBaikeBlocker', action }, 501); if (!String(blocked.message).startsWith('migration_blocked:')) throw new Error(`旧百科动作 ${action} 未返回明确阻塞原因`); }
  341. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'save', className: 'Node', fields: { nodeName: '禁止通用新增' } }, 400);
  342. const nodeSuffix = Date.now().toString(36);
  343. 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' } });
  344. temporaryNodeObjectIds.push(String(rootNode.objectId || ''));
  345. const rootNodeId = Number(rootNode.nodeId);
  346. if (!temporaryNodeObjectIds[0] || !rootNodeId || Number(rootNode.parentId) !== 0 || Number(rootNode.depth) !== 1 || rootNode.sourceKey !== `[["NodeID",${rootNodeId}]]`) throw new Error(`栏目原子创建异常:${JSON.stringify(rootNode)}`);
  347. 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' } });
  348. temporaryNodeObjectIds.push(String(childNode.objectId || ''));
  349. const childNodeId = Number(childNode.nodeId);
  350. if (!temporaryNodeObjectIds[1] || !childNodeId || Number(childNode.parentId) !== rootNodeId || Number(childNode.depth) !== 2) throw new Error(`子栏目层级创建异常:${JSON.stringify(childNode)}`);
  351. const duplicateNode = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveNode', className: 'Node', parentId: 0, fields: { nodeName: `云函数冒烟栏目-${nodeSuffix}`, nodeDir: `another-${nodeSuffix}` } }, 409);
  352. if (!String(duplicateNode.message).includes('不能重复')) throw new Error('栏目同级重名保护未返回明确原因');
  353. 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);
  354. if (!String(cycleNode.message).includes('自身或其下级')) throw new Error('栏目层级循环保护未返回明确原因');
  355. const movedNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'move', objectIds: [childNode.objectId], parentId: 0 });
  356. if (movedNode.updated !== 1 || Number(movedNode.results?.[0]?.parentId) !== 0) throw new Error('栏目批量迁移失败');
  357. const recycledNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'recycle', objectIds: [rootNode.objectId] });
  358. if (Number(recycledNode.results?.[0]?.zstatus) !== -2) throw new Error('栏目回收站状态更新失败');
  359. const recoveredNode = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'recover', objectIds: [rootNode.objectId] });
  360. if (Number(recoveredNode.results?.[0]?.zstatus) !== 99) throw new Error('栏目回收站恢复失败');
  361. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'purge', objectIds: [childNode.objectId] });
  362. temporaryNodeObjectIds.pop();
  363. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'nodeBatch', className: 'Node', action: 'purge', objectIds: [rootNode.objectId] });
  364. temporaryNodeObjectIds.pop();
  365. const specialSuffix = Date.now().toString(36);
  366. const rootSpecial = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', pid: 0, fields: { specName: `云函数冒烟专题-${specialSuffix}`, specDir: `special-${specialSuffix}`, specCate: 0, specDesc: '专题生命周期验证' } });
  367. temporarySpecialObjectIds.push(String(rootSpecial.objectId || ''));
  368. const rootSpecId = Number(rootSpecial.specId);
  369. if (!temporarySpecialObjectIds[0] || !rootSpecId || Number(rootSpecial.pid) !== 0 || rootSpecial.sourceKey !== `[["SpecID",${rootSpecId}]]`) throw new Error(`专题原子创建异常:${JSON.stringify(rootSpecial)}`);
  370. const childSpecial = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', pid: rootSpecId, fields: { specName: `云函数冒烟子专题-${specialSuffix}`, specDir: `special-child-${specialSuffix}` } });
  371. temporarySpecialObjectIds.push(String(childSpecial.objectId || ''));
  372. const childSpecId = Number(childSpecial.specId);
  373. if (!temporarySpecialObjectIds[1] || !childSpecId || Number(childSpecial.pid) !== rootSpecId) throw new Error(`子专题创建异常:${JSON.stringify(childSpecial)}`);
  374. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSpecial', className: 'Special', pid: 0, fields: { specName: rootSpecial.specName, specDir: `special-other-${specialSuffix}` } }, 409);
  375. 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);
  376. const specialDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Special', objectId: rootSpecial.objectId }, 409);
  377. if (!String(specialDeleteBlocked.message).includes('下级专题')) throw new Error('专题子级引用删除保护未返回明确原因');
  378. const movedSpecial = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'specialBatch', className: 'Special', action: 'move', objectIds: [childSpecial.objectId], pid: 0 });
  379. if (movedSpecial.updated !== 1 || Number(movedSpecial.results?.[0]?.pid) !== 0) throw new Error('专题批量迁移失败');
  380. const mergeBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'specialBatch', className: 'Special', action: 'merge', objectIds: [childSpecial.objectId], targetId: rootSpecId }, 501);
  381. if (!String(mergeBlocked.message).includes('specialId')) throw new Error('专题合并数据阻塞未返回明确原因');
  382. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Special', objectId: childSpecial.objectId });
  383. temporarySpecialObjectIds.pop();
  384. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Special', objectId: rootSpecial.objectId });
  385. temporarySpecialObjectIds.pop();
  386. const categorySuffix = Date.now().toString(36);
  387. const rootCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 1, parentId: 0, fields: { catename: `冒烟贴吧版块-${categorySuffix}`, desc: '分类生命周期验证', needLog: 1 } });
  388. temporaryGuestCategoryObjectIds.push(String(rootCategory.objectId || ''));
  389. const rootCateid = Number(rootCategory.cateid);
  390. if (!temporaryGuestCategoryObjectIds[0] || !rootCateid || Number(rootCategory.gtype) !== 1 || rootCategory.sourceKey !== `[["Cateid",${rootCateid}]]`) throw new Error(`贴吧分类原子创建异常:${JSON.stringify(rootCategory)}`);
  391. const childCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 1, parentId: rootCateid, fields: { catename: `冒烟子版块-${categorySuffix}` } });
  392. temporaryGuestCategoryObjectIds.push(String(childCategory.objectId || ''));
  393. const childCateid = Number(childCategory.cateid);
  394. if (!temporaryGuestCategoryObjectIds[1] || !childCateid || Number(childCategory.parentId) !== rootCateid) throw new Error('贴吧子分类创建失败');
  395. const guestCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 0, parentId: 0, fields: { catename: `冒烟留言分类-${categorySuffix}`, status: 1 } });
  396. temporaryGuestCategoryObjectIds.push(String(guestCategory.objectId || ''));
  397. const barAuthorizationBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barAuthorization', cateId: rootCateid }, 501);
  398. if (!String(barAuthorizationBlocked.message).includes('ZL_Guest_BarAuth')) throw new Error('贴吧逐用户权限数据阻塞未返回明确原因');
  399. const barMedalBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barMedal', objectId: 'missing-post' }, 501);
  400. if (!String(barMedalBlocked.message).includes('ZL_Guest_Medals')) throw new Error('贴吧勋章数据阻塞未返回明确原因');
  401. 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);
  402. temporaryGuestBarId = String(temporaryBar.objectId || '');
  403. const barAudited = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'audit', objectIds: [temporaryGuestBarId] });
  404. if (Number(barAudited.results?.[0]?.status) !== 99) throw new Error('贴吧帖子审核失败');
  405. const barElite = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'elite', objectIds: [temporaryGuestBarId] });
  406. if (!String(barElite.results?.[0]?.postFlag).includes('Recommend')) throw new Error('贴吧帖子加精失败');
  407. const barTop = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'top-global', objectIds: [temporaryGuestBarId] });
  408. if (Number(barTop.results?.[0]?.orderFlag) !== 2) throw new Error('贴吧帖子全局置顶失败');
  409. const barMoved = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'move', objectIds: [temporaryGuestBarId], cateId: childCateid });
  410. if (Number(barMoved.results?.[0]?.cateId) !== childCateid) throw new Error('贴吧帖子移动版块失败');
  411. const barRecycled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'recycle', objectIds: [temporaryGuestBarId] });
  412. if (Number(barRecycled.results?.[0]?.status) !== -2) throw new Error('贴吧帖子回收失败');
  413. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'barBatch', className: 'GuestBar', action: 'recover', objectIds: [temporaryGuestBarId] });
  414. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', gtype: 1, parentId: 0, fields: { catename: rootCategory.catename } }, 409);
  415. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGuestCategory', className: 'Guestcate', objectId: rootCategory.objectId, gtype: 0, parentId: childCateid, fields: { ...rootCategory, catename: rootCategory.catename } }, 409);
  416. const recommendedCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestCategoryBatch', className: 'Guestcate', action: 'recommend', objectIds: [rootCategory.objectId] });
  417. if (recommendedCategory.results?.[0]?.barInfo !== 'Recommend') throw new Error('贴吧分类推荐失败');
  418. const categoryDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Guestcate', objectId: rootCategory.objectId }, 409);
  419. if (!String(categoryDeleteBlocked.message).includes('引用')) throw new Error('分类子级引用删除保护未返回明确原因');
  420. await jsonRequest(`${PARSE_URL}/classes/GuestBar/${temporaryGuestBarId}`, { method: 'DELETE' }, true);
  421. temporaryGuestBarId = '';
  422. for (const category of [childCategory, rootCategory, guestCategory]) {
  423. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'Guestcate', objectId: category.objectId });
  424. temporaryGuestCategoryObjectIds.splice(temporaryGuestCategoryObjectIds.indexOf(String(category.objectId)), 1);
  425. }
  426. const examClassSuffix = Date.now().toString(36);
  427. const rootExamClass = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', parentId: 0, classType: 1, orderId: 0, fields: { cClassName: `冒烟试题分类-${examClassSuffix}` } });
  428. temporaryExamClassObjectIds.push(String(rootExamClass.objectId || ''));
  429. const rootExamClassId = Number(rootExamClass.cId);
  430. if (!temporaryExamClassObjectIds[0] || !rootExamClassId || rootExamClass.sourceKey !== `[["C_id",${rootExamClassId}]]`) throw new Error(`试题分类原子创建异常:${JSON.stringify(rootExamClass)}`);
  431. const childExamClass = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', parentId: rootExamClassId, classType: 2, orderId: 0, fields: { cClassName: `冒烟子试题分类-${examClassSuffix}` } });
  432. temporaryExamClassObjectIds.push(String(childExamClass.objectId || ''));
  433. const childExamClassId = Number(childExamClass.cId);
  434. if (!childExamClassId || Number(childExamClass.cClassid) !== rootExamClassId || Number(childExamClass.cClassType) !== 2) throw new Error('子试题分类创建失败');
  435. const examChildren = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'examClassChildren', className: 'ExamClass', parentId: rootExamClassId });
  436. if (!examChildren.results?.some((entry) => entry.objectId === childExamClass.objectId)) throw new Error('试题子分类接口未返回目标记录');
  437. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamClass', className: 'ExamClass', parentId: 0, classType: 1, orderId: 0, fields: { cClassName: rootExamClass.cClassName } }, 409);
  438. 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);
  439. const examClassDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamClass', objectId: rootExamClass.objectId }, 409);
  440. if (!String(examClassDeleteBlocked.message).includes('下级分类')) throw new Error('试题分类子级引用删除保护未返回明确原因');
  441. 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 } });
  442. if (Number(movedExamClass.cClassid) !== 0) throw new Error('试题分类结构移动失败');
  443. const knowledgeSuffix = Date.now().toString(36);
  444. 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 } });
  445. temporaryKnowledgeObjectIds.push(String(rootKnowledge.objectId || ''));
  446. const rootKnowledgeId = Number(rootKnowledge.kId);
  447. if (!temporaryKnowledgeObjectIds[0] || !rootKnowledgeId || rootKnowledge.sourceKey !== `[["k_id",${rootKnowledgeId}]]`) throw new Error(`知识点原子创建异常:${JSON.stringify(rootKnowledge)}`);
  448. 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 } });
  449. temporaryKnowledgeObjectIds.push(String(childKnowledge.objectId || ''));
  450. const childKnowledgeId = Number(childKnowledge.kId);
  451. if (!childKnowledgeId || Number(childKnowledge.pid) !== rootKnowledgeId || Number(childKnowledge.kClassId) !== rootExamClassId) throw new Error('子知识点创建失败');
  452. const knowledgeChildren = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'knowledgeChildren', className: 'QuestionsKnowledge', classId: rootExamClassId, parentId: rootKnowledgeId });
  453. if (!knowledgeChildren.results?.some((entry) => entry.objectId === childKnowledge.objectId)) throw new Error('知识点子级接口未返回目标记录');
  454. 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);
  455. 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);
  456. const knowledgeDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'QuestionsKnowledge', objectId: rootKnowledge.objectId }, 409);
  457. if (!String(knowledgeDeleteBlocked.message).includes('下级知识点')) throw new Error('知识点子级引用删除保护未返回明确原因');
  458. 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 } });
  459. if (Number(movedKnowledge.pid) !== 0) throw new Error('知识点结构移动失败');
  460. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'QuestionsKnowledge', objectId: childKnowledge.objectId });
  461. temporaryKnowledgeObjectIds.pop();
  462. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'QuestionsKnowledge', objectId: rootKnowledge.objectId });
  463. temporaryKnowledgeObjectIds.pop();
  464. const examTeacher = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamTeacher', className: 'ExTeacher', classId: rootExamClassId, fields: { tname: `冒烟考试教师-${examClassSuffix}`, post: '测试岗位', teach: '测试科目', fileUpload: '', remark: '教师生命周期验证' } });
  465. temporaryExamTeacherId = String(examTeacher.objectId || '');
  466. const examTeacherLegacyId = Number(examTeacher.id);
  467. if (!temporaryExamTeacherId || !examTeacherLegacyId || Number(examTeacher.tclsss) !== rootExamClassId || examTeacher.sourceKey !== `[["ID",${examTeacherLegacyId}]]`) throw new Error(`考试教师原子创建异常:${JSON.stringify(examTeacher)}`);
  468. const updatedExamTeacher = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamTeacher', className: 'ExTeacher', objectId: temporaryExamTeacherId, classId: childExamClassId, fields: { tname: examTeacher.tname, post: '更新岗位', teach: '更新科目', fileUpload: '', remark: '已更新' } });
  469. if (Number(updatedExamTeacher.tclsss) !== childExamClassId || updatedExamTeacher.post !== '更新岗位') throw new Error('考试教师更新失败');
  470. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExTeacher', objectId: temporaryExamTeacherId });
  471. temporaryExamTeacherId = '';
  472. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamClass', objectId: childExamClass.objectId });
  473. temporaryExamClassObjectIds.pop();
  474. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamClass', objectId: rootExamClass.objectId });
  475. temporaryExamClassObjectIds.pop();
  476. const dictionarySuffix = Date.now().toString(36);
  477. const existingDictionaryItems = await jsonRequest(`${PARSE_URL}/classes/Datadic?limit=1000`, {}, true);
  478. const highestExistingCategoryRef = Math.max(0, ...(existingDictionaryItems.results || []).map((entry) => Number(entry.diccate) || 0));
  479. const dictionaryCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveDictionaryCategory', className: 'Datadiccategory', fields: { categoryname: `冒烟字典分类-${dictionarySuffix}`, isused: true } });
  480. temporaryDictionaryCategoryIds.push(String(dictionaryCategory.objectId || ''));
  481. const dictionaryCategoryId = Number(dictionaryCategory.diccateid);
  482. if (!temporaryDictionaryCategoryIds[0] || dictionaryCategoryId <= highestExistingCategoryRef || dictionaryCategory.sourceKey !== `[["Diccateid",${dictionaryCategoryId}]]`) throw new Error(`字典分类原子编号或既有引用避让异常:${JSON.stringify(dictionaryCategory)}`);
  483. const selectableCategories = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dictionaryCategories', enabledOnly: true });
  484. if (!selectableCategories.results?.some((entry) => entry.objectId === dictionaryCategory.objectId)) throw new Error('字典分类选择接口未返回新建分类');
  485. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveDictionaryCategory', className: 'Datadiccategory', fields: { categoryname: dictionaryCategory.categoryname, isused: true } }, 409);
  486. const dictionaryItem = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveDictionaryItem', className: 'Datadic', categoryId: dictionaryCategoryId, fields: { dicname: `冒烟字典项-${dictionarySuffix}`, isused: true } });
  487. temporaryDictionaryItemIds.push(String(dictionaryItem.objectId || ''));
  488. const dictionaryItemId = Number(dictionaryItem.dicid);
  489. if (!temporaryDictionaryItemIds[0] || !dictionaryItemId || Number(dictionaryItem.diccate) !== dictionaryCategoryId || dictionaryItem.sourceKey !== `[["Dicid",${dictionaryItemId}]]`) throw new Error(`字典项原子创建异常:${JSON.stringify(dictionaryItem)}`);
  490. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveDictionaryItem', className: 'Datadic', categoryId: dictionaryCategoryId, fields: { dicname: dictionaryItem.dicname, isused: true } }, 409);
  491. const dictionaryCategoryDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dictionaryBatch', className: 'Datadiccategory', action: 'delete', objectIds: [dictionaryCategory.objectId] }, 409);
  492. if (!String(dictionaryCategoryDeleteBlocked.message).includes('仍有字典项')) throw new Error('字典分类引用删除保护未返回明确原因');
  493. const dictionaryDisabled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dictionaryBatch', className: 'Datadic', action: 'disable', objectIds: [dictionaryItem.objectId] });
  494. if (dictionaryDisabled.results?.[0]?.isused !== false) throw new Error('字典项批量停用失败');
  495. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dictionaryBatch', className: 'Datadic', action: 'enable', objectIds: [dictionaryItem.objectId] });
  496. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dictionaryBatch', className: 'Datadic', action: 'delete', objectIds: [dictionaryItem.objectId] });
  497. temporaryDictionaryItemIds.pop();
  498. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dictionaryBatch', className: 'Datadiccategory', action: 'delete', objectIds: [dictionaryCategory.objectId] });
  499. temporaryDictionaryCategoryIds.pop();
  500. const gradeSuffix = Date.now().toString(36);
  501. const gradeCategory = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeCategory', className: 'GradeCate', fields: { cateName: `冒烟多级字典-${gradeSuffix}`, remark: '多级字典生命周期验证', gradeField: '省份|城市' } });
  502. temporaryGradeCategoryIds.push(String(gradeCategory.objectId || ''));
  503. const gradeCategoryId = Number(gradeCategory.cateId);
  504. if (!temporaryGradeCategoryIds[0] || !gradeCategoryId || gradeCategory.sourceKey !== `[["CateID",${gradeCategoryId}]]` || gradeCategory.gradeField !== '省份|城市') throw new Error(`多级字典分类原子创建异常:${JSON.stringify(gradeCategory)}`);
  505. const gradeCategoryList = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeCategories' });
  506. if (!gradeCategoryList.results?.some((entry) => entry.objectId === gradeCategory.objectId)) throw new Error('多级字典分类选择接口未返回新建分类');
  507. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeCategory', className: 'GradeCate', fields: { cateName: gradeCategory.cateName, gradeField: '一级|二级' } }, 409);
  508. const rootGrade = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeOption', className: 'Grade', categoryId: gradeCategoryId, parentId: 0, fields: { gradeName: `冒烟省份-${gradeSuffix}` } });
  509. temporaryGradeOptionIds.push(String(rootGrade.objectId || ''));
  510. const rootGradeId = Number(rootGrade.gradeId);
  511. if (!temporaryGradeOptionIds[0] || !rootGradeId || Number(rootGrade.grade) !== 1 || Number(rootGrade.parentId) !== 0 || rootGrade.sourceKey !== `[["GradeID",${rootGradeId}]]`) throw new Error(`一级字典选项创建异常:${JSON.stringify(rootGrade)}`);
  512. const childGrade = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeOption', className: 'Grade', categoryId: gradeCategoryId, parentId: rootGradeId, fields: { gradeName: `冒烟城市-${gradeSuffix}` } });
  513. temporaryGradeOptionIds.push(String(childGrade.objectId || ''));
  514. const childGradeId = Number(childGrade.gradeId);
  515. if (!childGradeId || Number(childGrade.parentId) !== rootGradeId || Number(childGrade.grade) !== 2 || Number(childGrade.cate) !== gradeCategoryId) throw new Error('二级字典选项创建失败');
  516. const gradePage = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeOptions', categoryId: gradeCategoryId, parentId: rootGradeId, page: 1, pageSize: 20 });
  517. if (!gradePage.results?.some((entry) => entry.objectId === childGrade.objectId)) throw new Error('多级字典分层列表未返回子选项');
  518. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeOption', className: 'Grade', categoryId: gradeCategoryId, parentId: rootGradeId, fields: { gradeName: childGrade.gradeName } }, 409);
  519. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeOption', className: 'Grade', categoryId: gradeCategoryId, parentId: childGradeId, fields: { gradeName: '越界三级选项' } }, 409);
  520. const updatedChildGrade = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveGradeOption', className: 'Grade', objectId: childGrade.objectId, categoryId: 999999, parentId: 0, fields: { gradeName: `${childGrade.gradeName}-更新`, cate: 999999, parentId: 0, grade: 1 } });
  521. if (Number(updatedChildGrade.cate) !== gradeCategoryId || Number(updatedChildGrade.parentId) !== rootGradeId || Number(updatedChildGrade.grade) !== 2) throw new Error('多级字典选项编辑篡改了结构字段');
  522. const gradeCategoryDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeBatch', className: 'GradeCate', action: 'delete', objectIds: [gradeCategory.objectId] }, 409);
  523. if (!String(gradeCategoryDeleteBlocked.message).includes('仍有选项')) throw new Error('多级字典分类引用删除保护未返回明确原因');
  524. const rootGradeDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeBatch', className: 'Grade', action: 'delete', objectIds: [rootGrade.objectId] }, 409);
  525. if (!String(rootGradeDeleteBlocked.message).includes('下级选项')) throw new Error('多级字典子级删除保护未返回明确原因');
  526. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeBatch', className: 'Grade', action: 'delete', objectIds: [childGrade.objectId] }); temporaryGradeOptionIds.pop();
  527. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeBatch', className: 'Grade', action: 'delete', objectIds: [rootGrade.objectId] }); temporaryGradeOptionIds.pop();
  528. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'gradeBatch', className: 'GradeCate', action: 'delete', objectIds: [gradeCategory.objectId] }); temporaryGradeCategoryIds.pop();
  529. const currencyCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveCurrency', className: 'Currency', fields: { title: '禁止无旧 ID 货币', currencyName: 'TST', currencySymbol: 'T$', currentExchange: 1.25, remark: '应被阻塞' } }, 501);
  530. if (!String(currencyCreateBlocked.message).includes('保留 id')) throw new Error('货币新增未返回明确旧 ID 阻塞原因');
  531. const holidayCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveHoliday', className: 'SysHoliday', fields: { name: '禁止无旧 ID 节假日' } }, 501);
  532. if (!String(holidayCreateBlocked.message).includes('保留 id')) throw new Error('节假日新增未返回明确旧 ID 阻塞原因');
  533. const searchNavigationCreateBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveSearchNavigation', className: 'Search', fields: { name: '禁止无旧 ID 快捷入口' } }, 501);
  534. if (!String(searchNavigationCreateBlocked.message).includes('保留 id')) throw new Error('快捷入口新增未返回明确旧 ID 阻塞原因');
  535. const searchNavigationStartBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'searchNavigationBatch', className: 'Search', action: 'starturl', objectIds: ['not-used'] }, 501);
  536. if (!String(searchNavigationStartBlocked.message).includes('SiteConfig')) throw new Error('快捷入口全局起始页未返回明确阻塞原因');
  537. for (const action of ['APIInfo_Submit','APIInfo_SwaggerClose','APIInfo_SwaggerOpen','LicenceFile_API','close_system','Hotkey','HotkeyAdd','HotkeyAdd_Submit','Hotkey_API','Prize','Prize_Submit']) {
  538. const configBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'legacyConfigBlocker', action }, 501);
  539. if (!String(configBlocked.message).startsWith('migration_blocked:')) throw new Error(`旧配置动作 ${action} 未返回明确阻塞原因`);
  540. }
  541. if (dictionaryCategory.company?.__type !== 'Pointer' || JSON.stringify(dictionaryCategory).match(/accessToken|mch_key|"ak"|"sk"/i)) throw new Error('后台响应展开了帐套敏感配置');
  542. const examPointSuffix = Date.now().toString(36);
  543. const rootExamPoint = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', parentId: 0, orderId: 0, fields: { testPoint: `冒烟考点-${examPointSuffix}` } });
  544. temporaryExamPointObjectIds.push(String(rootExamPoint.objectId || ''));
  545. const rootExamPointId = Number(rootExamPoint.id);
  546. if (!temporaryExamPointObjectIds[0] || !rootExamPointId || rootExamPoint.sourceKey !== `[["ID",${rootExamPointId}]]`) throw new Error(`考点原子创建异常:${JSON.stringify(rootExamPoint)}`);
  547. const childExamPoint = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', parentId: rootExamPointId, orderId: 0, fields: { testPoint: `冒烟子考点-${examPointSuffix}` } });
  548. temporaryExamPointObjectIds.push(String(childExamPoint.objectId || ''));
  549. const childExamPointId = Number(childExamPoint.id);
  550. if (!childExamPointId || Number(childExamPoint.tid) !== rootExamPointId) throw new Error('子考点创建失败');
  551. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveExamPoint', className: 'ExamPoint', parentId: 0, orderId: 0, fields: { testPoint: rootExamPoint.testPoint } }, 409);
  552. 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);
  553. const examPointDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamPoint', objectId: rootExamPoint.objectId }, 409);
  554. if (!String(examPointDeleteBlocked.message).includes('下级考点')) throw new Error('考点子级引用删除保护未返回明确原因');
  555. 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 } });
  556. if (Number(movedExamPoint.tid) !== 0) throw new Error('考点结构移动失败');
  557. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamPoint', objectId: childExamPoint.objectId });
  558. temporaryExamPointObjectIds.pop();
  559. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ExamPoint', objectId: rootExamPoint.objectId });
  560. temporaryExamPointObjectIds.pop();
  561. const metadataSuffix = Date.now().toString(36);
  562. const temporaryModelId = 800000000 + Math.floor(Date.now() / 1000) % 100000000;
  563. 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);
  564. temporaryModelObjectId = String(tempModel.objectId || '');
  565. const updatedModel = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveModelMetadata', className: 'Model', objectId: temporaryModelObjectId, fields: { modelName: `冒烟模型更新-${metadataSuffix}`, description: '仅元数据更新', tableName: 'malicious_table', modelId: 1 } });
  566. if (Number(updatedModel.modelId) !== temporaryModelId || updatedModel.tableName !== `ZL_C_Smoke_${metadataSuffix}` || updatedModel.description !== '仅元数据更新') throw new Error(`模型结构字段隔离异常:${JSON.stringify(updatedModel)}`);
  567. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'saveModelMetadata', className: 'Model', fields: { modelName: '禁止新增模型' } }, 501);
  568. for (let index = 0; index < 2; index++) {
  569. 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);
  570. temporaryModelFieldObjectIds.push(String(field.objectId || ''));
  571. }
  572. 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 } });
  573. if (updatedField.fieldAlias !== '更新后的字段别名' || updatedField.fieldName !== 'smokeField0' || updatedField.fieldType !== 'TextType' || Number(updatedField.modelId) !== temporaryModelId) throw new Error(`模型字段结构隔离异常:${JSON.stringify(updatedField)}`);
  574. const reorderedFields = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'modelFieldOrder', className: 'ModelField', items: [{ objectId: temporaryModelFieldObjectIds[0], orderId: 2 }, { objectId: temporaryModelFieldObjectIds[1], orderId: 1 }] });
  575. if (reorderedFields.updated !== 2 || Number(reorderedFields.modelId) !== temporaryModelId) throw new Error('模型字段排序失败');
  576. await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'delete', className: 'ModelField', objectId: temporaryModelFieldObjectIds[0] }, 501);
  577. 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 } });
  578. if (updatedGuestbook.tcontent !== '管理员规范化编辑' || Number(updatedGuestbook.gid) === 999 || Number(updatedGuestbook.cateid) === 999 || Number(updatedGuestbook.status) === -2) throw new Error(`留言结构字段隔离异常:${JSON.stringify(updatedGuestbook)}`);
  579. const guestUnaudited = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'unaudit', objectIds: [temporaryGuestbookId] });
  580. if (Number(guestUnaudited.results?.[0]?.status) !== 0) throw new Error('留言取消审核失败');
  581. const guestRecycled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'recycle', objectIds: [temporaryGuestbookId] });
  582. if (Number(guestRecycled.results?.[0]?.status) !== -2) throw new Error('留言回收失败');
  583. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'recover', objectIds: [temporaryGuestbookId] });
  584. const guestReply = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookReply', className: 'Guestbook', parentObjectId: temporaryGuestbookId, title: '管理员冒烟回复', content: '云函数回复正文' });
  585. temporaryGuestbookReplyId = String(guestReply.objectId || '');
  586. if (!temporaryGuestbookReplyId || Number(guestReply.parentid) !== Number(updatedGuestbook.gid) || Number(guestReply.status) !== 99 || !Number(guestReply.gid)) throw new Error(`管理员留言回复异常:${JSON.stringify(guestReply)}`);
  587. const guestDeleteBlocked = await callFunctionError('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'purge', objectIds: [temporaryGuestbookId] }, 409);
  588. if (!String(guestDeleteBlocked.message).includes('仍有回复')) throw new Error('留言回复引用删除保护未返回明确原因');
  589. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'guestbookBatch', className: 'Guestbook', action: 'purge', objectIds: [temporaryGuestbookReplyId] });
  590. temporaryGuestbookReplyId = '';
  591. const contentPending = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'status', objectIds: [temporaryAppointmentCommonObjectId], status: 0 });
  592. if (contentPending.updated !== 1 || Number(contentPending.results?.[0]?.status) !== 0) throw new Error('内容待审核状态更新失败');
  593. const contentRecycled = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'recycle', objectIds: [temporaryAppointmentCommonObjectId] });
  594. if (Number(contentRecycled.results?.[0]?.status) !== -2) throw new Error('内容回收站状态更新失败');
  595. const contentRecovered = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'recover', objectIds: [temporaryAppointmentCommonObjectId] });
  596. if (Number(contentRecovered.results?.[0]?.status) !== 0) throw new Error('内容回收站恢复失败');
  597. const contentMoved = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'move', objectIds: [temporaryAppointmentCommonObjectId], nodeId: 29 });
  598. if (Number(contentMoved.results?.[0]?.nodeId) !== 29) throw new Error('内容节点移动失败');
  599. await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'contentBatch', className: 'CommonModel', action: 'status', objectIds: [temporaryAppointmentCommonObjectId], status: 99 });
  600. const page = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'list', className: 'CourseAppointment', page: 1, pageSize: 2 });
  601. if (!Array.isArray(page.results) || page.pageSize !== 2) throw new Error('资源分页校验失败');
  602. const normalized = await callFunction('xiaoshu/cms/content-normalizer', login.sessionToken, { content: '<p>中文&nbsp;<strong>内容</strong></p><script>alert(1)</script>' });
  603. if (normalized.content !== '中文 内容') throw new Error(`内容清理结果异常:${normalized.content}`);
  604. const exams = await callFunction('xiaoshu/cms/exams/classes', login.sessionToken, { page: 1, pageSize: 2 });
  605. if (!Array.isArray(exams.results)) throw new Error('考试班级投影校验失败');
  606. const guest = await callFunction('xiaoshu/cms/guest/bar', login.sessionToken, { page: 1, pageSize: 2 });
  607. if (!Array.isArray(guest.results)) throw new Error('互动社区投影校验失败');
  608. const migration = await callLegacyFunction('', { action: 'migration_status' });
  609. const sourceActionList = await sourceActions();
  610. const implementedActions = migration.result?.implemented || [];
  611. const blockedActions = Object.keys(migration.result?.blocked || {});
  612. const covered = new Set([...implementedActions, ...blockedActions]);
  613. const missing = sourceActionList.filter((action) => !covered.has(action));
  614. if (missing.length) throw new Error(`app gateway 迁移矩阵缺少:${missing.join(', ')}`);
  615. const sourceBlocked = blockedActions.filter((action) => sourceActionList.includes(action));
  616. const compatibilityActions = blockedActions.filter((action) => !sourceActionList.includes(action)).sort();
  617. const sourceImplemented = implementedActions.filter((action) => sourceActionList.includes(action));
  618. const compatibilityImplemented = implementedActions.filter((action) => !sourceActionList.includes(action)).sort();
  619. if (sourceImplemented.length !== 28 || sourceBlocked.length !== 63) throw new Error(`app gateway 源 action 计数异常:${sourceImplemented.length} 已映射 / ${sourceBlocked.length} 阻塞`);
  620. if (compatibilityImplemented.join(',') !== 'content_add_zt') throw new Error(`app gateway 已实现兼容 action 计数异常:${compatibilityImplemented.join(',')}`);
  621. if (compatibilityActions.join(',') !== 'product_add,product_upd') throw new Error(`app gateway 阻塞兼容 action 计数异常:${compatibilityActions.join(',')}`);
  622. const content = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 2 });
  623. if (!Array.isArray(content.result) || content.result.length !== 2 || Number(content.page?.itemCount) < 89000) throw new Error('公开内容分页校验失败');
  624. const contentExact = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 1, objectId: content.result[0].objectId });
  625. if (contentExact.result?.[0]?.objectId !== content.result[0].objectId || contentExact.page?.itemCount !== 1) throw new Error('内容 objectId 精确查询校验失败');
  626. const contentDetail = await callLegacyFunction('', { action: 'content_get', id: content.result[0].objectId });
  627. if (!Array.isArray(contentDetail.result) || contentDetail.result[0]?.objectId !== content.result[0].objectId) throw new Error('内容详情旧数组契约校验失败');
  628. contentHitObjectId = String(content.result[0].objectId);
  629. contentHitOriginal = Number(content.result[0].hits ?? content.result[0].Hits ?? 0);
  630. const contentHit = await callLegacyFunction('', { action: 'content_uphis', id: contentHitObjectId, num: 999 });
  631. if (Number(contentHit.result?.hits) !== contentHitOriginal + 1) throw new Error(`公开内容浏览量未固定原子加一:${JSON.stringify(contentHit)}`);
  632. await jsonRequest(`${PARSE_URL}/classes/CommonModel/${contentHitObjectId}`, { method: 'PUT', body: JSON.stringify({ hits: contentHitOriginal }) }, true);
  633. contentHitObjectId = '';
  634. await callLegacyFunction('', { action: 'content_uphis', id: temporaryAppointmentId }, 401);
  635. const appUpdate = await callLegacyFunction('', { action: 'app_update' });
  636. 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)}`);
  637. const gameNode = await callLegacyFunction('', { action: 'node_get', id: 77 });
  638. if (gameNode.result?.NodeID === undefined || gameNode.result?.ConsumePoint === undefined || gameNode.result?.ConsumeDeposit === undefined) throw new Error(`栏目详情游戏消费字段别名异常:${JSON.stringify(gameNode.result)}`);
  639. const words = await callLegacyFunction('', { action: 'content_list', modelId: 52, page: 1, pageSize: 1 });
  640. if (Number(words.page?.itemCount) < 89000 || !words.result?.[0]?.GeneralID || words.result?.[0]?.sy === undefined) throw new Error('词库 addon 联表校验失败');
  641. const privateContent = await callLegacyFunction('', { action: 'content_list', modelId: 56, page: 1, pageSize: 1 }, 401);
  642. if (!String(privateContent.retmsg).includes('登录')) throw new Error('学习记录未阻止匿名访问');
  643. const learning = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 56, page: 1, pageSize: 1 });
  644. if (!learning.result?.[0]?.GeneralID || learning.result?.[0]?.xxqs === undefined) throw new Error('学习记录 addon 联表校验失败');
  645. const recordDetail = await callLegacyFunction(login.sessionToken, { action: 'e_record_detail', id: learning.result[0].GeneralID });
  646. if (!Array.isArray(recordDetail.result) || !recordDetail.result.length || !recordDetail.result[0]?.detail?.[0]?.Title) throw new Error('学习记录单词详情联查校验失败');
  647. const appointments = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 54, page: 1, pageSize: 1 });
  648. const appointment = await callLegacyFunction(login.sessionToken, { action: 'e_order_detail', id: appointments.result?.[0]?.GeneralID });
  649. if (!appointment.result?.[0]?.GeneralID || appointment.result[0].kcid === undefined) throw new Error('预约详情联查校验失败');
  650. const memberProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_get', uid: memberLegacyId });
  651. if (memberProfile.result?.honeyName !== profileModel.honeyName || memberProfile.addon?.vip !== 2 || memberProfile.addon?.silverCoin !== 2 || JSON.stringify(memberProfile).includes('must-not-leak')) throw new Error('用户旧契约字段或敏感字段过滤异常');
  652. const teamMembers = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_list', puid: memberLegacyId, cpage: 1, psize: 10 });
  653. if (teamMembers.page?.itemCount !== 1 || Number(teamMembers.result?.[0]?.ParentUserID) !== memberLegacyId || Number(teamMembers.result?.[0]?.VIP) !== 3) throw new Error(`团队成员列表异常:${JSON.stringify(teamMembers)}`);
  654. const teamSummary = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_dept', uid: memberLegacyId });
  655. if (teamSummary.result?.childs !== 1 || teamSummary.result?.v3 !== 1) throw new Error(`团队会员统计异常:${JSON.stringify(teamSummary.result)}`);
  656. const childProfile = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_get', uid: childLegacyId });
  657. if (childProfile.result?.userId !== childLegacyId || childProfile.result?.puid !== memberLegacyId || JSON.stringify(childProfile).includes('must-not-leak')) throw new Error('团队成员详情或密码字段过滤异常');
  658. await callLegacyFunction(coachLogin.sessionToken, { action: 'user_get', uid: childLegacyId }, 403);
  659. const coachStudents = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_user_list', cpage: 1, psize: 10 });
  660. if (coachStudents.page?.itemCount !== 1 || Number(coachStudents.result?.[0]?.szyh) !== memberLegacyId || coachStudents.result?.[0]?.honeyname !== profileModel.honeyName) throw new Error(`陪练学员分组列表异常:${JSON.stringify(coachStudents)}`);
  661. const newWords = await callLegacyFunction(login.sessionToken, { action: 'e_words_list', uid: 58, page: 1, pageSize: 2 });
  662. if (Number(newWords.page?.itemCount) < 1 || !newWords.result?.[0]?.detail?.[0]?.Title) throw new Error('用户生词联查校验失败');
  663. const courseWords = await callLegacyFunction(login.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1000 });
  664. const learnedWord = courseWords.result?.find((word) => Number(word.GeneralID) === 2505);
  665. if (Number(courseWords.page?.itemCount) < 1 || !courseWords.result?.[0]?.detail?.Title || Number(learnedWord?.w_learned) !== 7) throw new Error('课程词库学习进度联查校验失败');
  666. const memory = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list', uid: 58, page: 1, pageSize: 2 });
  667. if (Number(memory.page?.itemCount) < 1 || !memory.result?.[0]?.GeneralID || memory.result[0].learned === undefined) throw new Error('21 天抗遗忘联查校验失败');
  668. const incomeBlocked = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list_tj', uid: 58 }, 501);
  669. if (!String(incomeBlocked.retmsg).includes('计价规则')) throw new Error('复习收入缺失规则未显式阻塞');
  670. const ownEmpty = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}`, page: 1, pageSize: 1 });
  671. if (!Array.isArray(ownEmpty.result) || ownEmpty.page?.itemCount !== 0) throw new Error('普通用户本人记录权限校验失败');
  672. const ownCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1 });
  673. if (!Array.isArray(ownCourseWords.result) || ownCourseWords.result[0]?.w_learned !== 0) throw new Error('普通用户本人课程词库权限校验失败');
  674. const learnedWrite = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, save: 1 });
  675. if (learnedWrite.result?.created !== 1 || learnedWrite.result?.learnedIncremented !== 1) throw new Error('首次学习词进度写入校验失败');
  676. await callLegacyFunction('', { action: 'node_list', pid: 16, ifunit: 1, userId: memberLegacyId }, 401);
  677. const unitNodes = await callLegacyFunction(memberLogin.sessionToken, { action: 'node_list', pid: 16, ifunit: 1, userId: memberLegacyId, pageSize: 100 });
  678. const learnedUnit = unitNodes.result?.find((node) => Number(node.NodeID) === 40);
  679. 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)}`);
  680. const learnedRead = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1000 });
  681. if (Number(learnedRead.result?.find((word) => Number(word.GeneralID) === 2505)?.w_learned) !== 1) throw new Error('学习次数写后读校验失败');
  682. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 1 });
  683. const addedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  684. if (addedNewWord.page?.itemCount !== 1 || Number(addedNewWord.result?.[0]?.detail?.[0]?.GeneralID) !== 2505) throw new Error('加入生词写后读校验失败');
  685. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 0 });
  686. const removedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  687. if (removedNewWord.page?.itemCount !== 0) throw new Error('移出生词写后读校验失败');
  688. 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 }]) }) });
  689. if (!/^\d{15}$/.test(String(scheduledStudy.result))) throw new Error('带复习计划的学习记录创建结果异常');
  690. const scheduledDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: scheduledStudy.result });
  691. const reviewDates = String(scheduledDetail.result?.[0]?.fxrl || '').split(',').filter(Boolean);
  692. if (reviewDates.length !== 15 || !reviewDates.every((date) => /^\d{8}$/.test(date))) throw new Error('15 段抗遗忘复习日期生成失败');
  693. await callLegacyFunction(coachLogin.sessionToken, { action: 'content_update', content: JSON.stringify({ GeneralID: scheduledStudy.result }), addon: JSON.stringify({ con: '越权更新' }) }, 403);
  694. const scheduledUpdate = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_update', content: JSON.stringify({ GeneralID: scheduledStudy.result, Title: '已更新学习记录' }), addon: JSON.stringify({ con: '规范化内容更新', learned: 1 }) });
  695. if (String(scheduledUpdate.result) !== String(scheduledStudy.result)) throw new Error('规范化内容更新返回值异常');
  696. const updatedScheduledDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: scheduledStudy.result });
  697. if (updatedScheduledDetail.result?.[0]?.con !== '规范化内容更新' || updatedScheduledDetail.result?.[0]?.Title !== '已更新学习记录') throw new Error('规范化内容双表更新写后读失败');
  698. 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 }) });
  699. if (!/^\d{15}$/.test(String(assessment.result))) throw new Error('规范化测评内容新增结果异常');
  700. const assessmentDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_get', id: assessment.result });
  701. 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('规范化测评内容新增写后读失败');
  702. const missingSchemaCreate = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_add', content: JSON.stringify({ ModelID: 55, nodeId: 255 }), addon: JSON.stringify({ UserID: memberLegacyId, scnr: '[]' }) }, 501);
  703. if (!String(missingSchemaCreate.retmsg).includes('未迁移内容模型 55')) throw new Error('缺 Schema 内容新增未明确拒绝');
  704. 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 }]) };
  705. const createdStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  706. if (!createdStudy.result?.created || !createdStudy.result?.GeneralID || !createdStudy.result?.recordObjectId) throw new Error('预约学习记录首次双表写入校验失败');
  707. const studyDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_record_detail', id: createdStudy.result.GeneralID });
  708. if (studyDetail.result?.[0]?.detail?.[0]?.Title !== 'woman') throw new Error('预约学习记录写后详情校验失败');
  709. studyAddon.xxqs = JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 1 }]);
  710. const updatedStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  711. if (updatedStudy.result?.created || updatedStudy.result?.GeneralID !== createdStudy.result.GeneralID) throw new Error('预约学习记录幂等更新校验失败');
  712. const studyList = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}|dsid=${temporaryAppointmentId}`, page: 1, pageSize: 2 });
  713. if (studyList.page?.itemCount !== 1 || Number(studyList.result?.[0]?.ygg) !== 1 || Number(studyList.result?.[0]?.learned) !== 1) throw new Error('预约学习记录聚合字段写后读校验失败');
  714. const orderContent = JSON.stringify({ GeneralID: temporaryAppointmentId, UpDateTime: '2026-08-18 13:30' });
  715. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 10, content: orderContent }, 403);
  716. const startedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 10, content: orderContent });
  717. if (startedOrder.result?.previousStatus !== 0 || startedOrder.result?.status !== 10) throw new Error('预约开始状态迁移失败');
  718. const endedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  719. if (endedOrder.result?.reviewCount !== 2 || !endedOrder.result?.periodDeducted) throw new Error('预约结束课时与抗遗忘副作用失败');
  720. const repeatedEnd = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  721. if (!repeatedEnd.result?.unchanged) throw new Error('预约结束状态未保持幂等');
  722. const updatedMember = await jsonRequest(`${PARSE_URL}/users/${memberId}`, {}, true);
  723. if (Number(updatedMember.legacyUserData?.Purse) !== 1 || Number(updatedMember.legacyUserData?.UserPoint) !== 1.5) throw new Error(`预约结束课时扣减异常:${JSON.stringify(updatedMember.legacyUserData)}`);
  724. const sideEffectWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:e_order_update:${temporaryAppointmentId}:` } }));
  725. const [periodLogs, pointLogs, memoryRows, memoryCommonRows] = await Promise.all([
  726. jsonRequest(`${PARSE_URL}/classes/UserExpDomP?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  727. jsonRequest(`${PARSE_URL}/classes/UserUserPoint?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  728. jsonRequest(`${PARSE_URL}/classes/MemoryPracticeRecord?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  729. jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${sideEffectWhere}&count=1&limit=0`, {}, true),
  730. ]);
  731. if (periodLogs.count !== 1 || pointLogs.count !== 1 || memoryRows.count !== 2 || memoryCommonRows.count !== 2) throw new Error(`预约结束账本/抗遗忘数量异常:${periodLogs.count}/${pointLogs.count}/${memoryRows.count}/${memoryCommonRows.count}`);
  732. const purseHistory = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_point_list', uid: memberLegacyId, stype: 1, cpage: 1, psize: 10 });
  733. 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)}`);
  734. const couponHistory = await callLegacyFunction(memberLogin.sessionToken, { action: 'user_point_list', uid: memberLegacyId, stype: 4, cpage: 1, psize: 10 });
  735. if (couponHistory.page?.itemCount !== 1 || Number(couponHistory.result?.[0]?.score) !== -0.5 || !couponHistory.result?.[0]?.HisTime) throw new Error(`点券账本读取异常:${JSON.stringify(couponHistory)}`);
  736. await callLegacyFunction(memberLogin.sessionToken, { action: 'user_point_list', uid: memberLegacyId, stype: 7 }, 400);
  737. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 20, content: orderContent }, 403);
  738. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 20, content: orderContent });
  739. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 30, content: orderContent });
  740. const completedOrder = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_detail', id: temporaryAppointmentId });
  741. if (Number(completedOrder.result?.[0]?.dszt) !== 30) throw new Error('预约状态机写后读失败');
  742. const coachStats = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_tongji', uid: coachLegacyId });
  743. 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('陪练预约统计公式校验失败');
  744. const memberStats = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_tongji', uid: memberLegacyId });
  745. 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)}`);
  746. const deniedCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1 }, 403);
  747. if (!String(deniedCourseWords.retmsg).includes('无权')) throw new Error('普通用户跨用户课程词库未被拒绝');
  748. const denied = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: 'UserId=3', page: 1, pageSize: 1 }, 403);
  749. if (!String(denied.retmsg).includes('无权')) throw new Error('普通用户跨用户记录未被拒绝');
  750. const profile = await callLegacyFunction(login.sessionToken, { action: 'user_get' });
  751. if (profile.retcode !== 0 || profile.result?.objectId !== userId) throw new Error('app gateway 用户会话校验失败');
  752. const blocked = await callLegacyFunction('', { action: 'cart_list' }, 501);
  753. if (!String(blocked.retmsg).startsWith('migration_blocked:')) throw new Error('阻塞接口未返回 migration_blocked');
  754. const productBlocked = await callLegacyFunction('', { action: 'product_list' }, 501);
  755. if (!String(productBlocked.retmsg).includes('ZL_Commodities')) throw new Error('缺商品主表的读取接口未明确阻塞');
  756. console.log('Cloud smoke passed: admin auth/tenant/account lifecycle/group sync/node/special/guest-category/bar/exam-class/exam-point/knowledge/exam-teacher/dictionary/grade-dictionary/currency/holiday/search-navigation/advertising/font-shapes/surveys/customer-service/stores/content-tags/shop-vendor-blockers/user-level/money-ledgers/user-addon-blockers/ask-blockers/baike/api-catalog/config-blockers/model/guestbook lifecycle/content workflow/CRUD reads, CMS projections, normalized learning joins, app action coverage, public content, session scope, explicit blocked APIs.');
  757. } finally {
  758. if (adZoneRestore) await jsonRequest(`${PARSE_URL}/classes/AdZone/${adZoneRestore.objectId}`, { method: 'PUT', body: JSON.stringify({ remind: adZoneRestore.remind, zstatus: adZoneRestore.zstatus }) }, true).catch((error) => { console.error(`广告位冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  759. if (adInfoRestore) await jsonRequest(`${PARSE_URL}/classes/AdInfo/${adInfoRestore.objectId}`, { method: 'PUT', body: JSON.stringify({ remind: adInfoRestore.remind, zstatus: adInfoRestore.zstatus }) }, true).catch((error) => { console.error(`广告内容冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  760. if (fontShapeRestore) await jsonRequest(`${PARSE_URL}/classes/FontPicShape/${fontShapeRestore.objectId}`, { method: 'PUT', body: JSON.stringify({ shape: fontShapeRestore.shape, remarks: fontShapeRestore.remarks, typeId: fontShapeRestore.typeId, ...(fontShapeRestore.updateTime ? { updateTime: fontShapeRestore.updateTime } : {}) }) }, true).catch((error) => { console.error(`图形素材冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  761. if (temporaryFontShapeId) await jsonRequest(`${PARSE_URL}/classes/FontPicShape/${temporaryFontShapeId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时图形素材清理失败:${error.message}`); process.exitCode = 1; });
  762. if (temporaryFontShapeTypeId) await jsonRequest(`${PARSE_URL}/classes/FontPicShapeType/${temporaryFontShapeTypeId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时图形分类清理失败:${error.message}`); process.exitCode = 1; });
  763. if (surveyRestore) await jsonRequest(`${PARSE_URL}/classes/DesignAsk/${surveyRestore.objectId}`, { method: 'PUT', body: JSON.stringify(surveyRestore.fields) }, true).catch((error) => { console.error(`问卷冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  764. if (surveyQuestionRestore) await jsonRequest(`${PARSE_URL}/classes/DesignQuestion/${surveyQuestionRestore.objectId}`, { method: 'PUT', body: JSON.stringify(surveyQuestionRestore.fields) }, true).catch((error) => { console.error(`问卷题目冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  765. if (temporarySurveyAnswerId) await jsonRequest(`${PARSE_URL}/classes/DesignAnswer/${temporarySurveyAnswerId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时问卷答卷清理失败:${error.message}`); process.exitCode = 1; });
  766. for (const objectId of temporarySurveyQuestionIds) await jsonRequest(`${PARSE_URL}/classes/DesignQuestion/${objectId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时问卷题目清理失败:${error.message}`); process.exitCode = 1; });
  767. if (temporarySurveyId) await jsonRequest(`${PARSE_URL}/classes/DesignAsk/${temporarySurveyId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时问卷清理失败:${error.message}`); process.exitCode = 1; });
  768. if (serviceSeatRestore) await jsonRequest(`${PARSE_URL}/classes/ServiceSeat/${serviceSeatRestore.objectId}`, { method: 'PUT', body: JSON.stringify(serviceSeatRestore.fields) }, true).catch((error) => { console.error(`客服席位冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  769. if (serviceCodeRestore) await jsonRequest(`${PARSE_URL}/classes/Temp/${serviceCodeRestore.objectId}`, { method: 'PUT', body: JSON.stringify(serviceCodeRestore.fields) }, true).catch((error) => { console.error(`客服欢迎语冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  770. if (temporaryServiceSeatId) await jsonRequest(`${PARSE_URL}/classes/ServiceSeat/${temporaryServiceSeatId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时客服席位清理失败:${error.message}`); process.exitCode = 1; });
  771. if (temporaryServiceCodeId) await jsonRequest(`${PARSE_URL}/classes/Temp/${temporaryServiceCodeId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时客服欢迎语清理失败:${error.message}`); process.exitCode = 1; });
  772. if (storeApplicationRestore) await jsonRequest(`${PARSE_URL}/classes/StoreApplication/${storeApplicationRestore.objectId}`, { method: 'PUT', body: JSON.stringify(storeApplicationRestore.fields) }, true).catch((error) => { console.error(`店铺冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  773. if (storeStyleRestore) await jsonRequest(`${PARSE_URL}/classes/StoreStyle/${storeStyleRestore.objectId}`, { method: 'PUT', body: JSON.stringify(storeStyleRestore.fields) }, true).catch((error) => { console.error(`店铺样式冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  774. if (temporaryStoreApplicationId) await jsonRequest(`${PARSE_URL}/classes/StoreApplication/${temporaryStoreApplicationId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时店铺清理失败:${error.message}`); process.exitCode = 1; });
  775. if (temporaryStoreStyleId) await jsonRequest(`${PARSE_URL}/classes/StoreStyle/${temporaryStoreStyleId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时店铺样式清理失败:${error.message}`); process.exitCode = 1; });
  776. if (contentTagsRestore) await jsonRequest(`${PARSE_URL}/config`, { method: 'PUT', body: JSON.stringify({ params: { legacyContentTags: contentTagsRestore } }) }, true).catch((error) => { console.error(`内容标签冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  777. if (userLevelRestore) await jsonRequest(`${PARSE_URL}/classes/UserLevel/${userLevelRestore.objectId}`, { method: 'PUT', body: JSON.stringify(userLevelRestore.fields) }, true).catch((error) => { console.error(`积分等级冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  778. if (temporaryUserLevelId) await jsonRequest(`${PARSE_URL}/classes/UserLevel/${temporaryUserLevelId}`, { method: 'DELETE' }, true).catch((error) => { console.error(`临时积分等级清理失败:${error.message}`); process.exitCode = 1; });
  779. if (baikeRestore) await jsonRequest(`${PARSE_URL}/classes/Baike/${baikeRestore.objectId}`, { method: 'PUT', body: JSON.stringify(baikeRestore.fields) }, true).catch((error) => { console.error(`百科冒烟数据恢复失败:${error.message}`); process.exitCode = 1; });
  780. if (contentHitObjectId) await jsonRequest(`${PARSE_URL}/classes/CommonModel/${contentHitObjectId}`, { method: 'PUT', body: JSON.stringify({ hits: contentHitOriginal }) }, true).catch((error) => {
  781. console.error(`公开内容浏览量恢复失败:${error.message}`);
  782. process.exitCode = 1;
  783. });
  784. if (registeredUserId) await jsonRequest(`${PARSE_URL}/users/${registeredUserId}`, { method: 'DELETE' }, true).catch((error) => {
  785. console.error(`临时注册用户清理失败:${error.message}`);
  786. process.exitCode = 1;
  787. });
  788. if (adminCreatedUserId) await jsonRequest(`${PARSE_URL}/users/${adminCreatedUserId}`, { method: 'DELETE' }, true).catch((error) => {
  789. console.error(`管理员开户临时用户清理失败:${error.message}`);
  790. process.exitCode = 1;
  791. });
  792. if (temporaryGroupObjectId) await jsonRequest(`${PARSE_URL}/classes/Group/${temporaryGroupObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  793. console.error(`临时用户组清理失败:${error.message}`);
  794. process.exitCode = 1;
  795. });
  796. for (const nodeId of temporaryNodeObjectIds) if (nodeId) await jsonRequest(`${PARSE_URL}/classes/Node/${nodeId}`, { method: 'DELETE' }, true).catch((error) => {
  797. console.error(`临时栏目清理失败:${error.message}`);
  798. process.exitCode = 1;
  799. });
  800. for (const specialId of temporarySpecialObjectIds) if (specialId) await jsonRequest(`${PARSE_URL}/classes/Special/${specialId}`, { method: 'DELETE' }, true).catch((error) => {
  801. console.error(`临时专题清理失败:${error.message}`);
  802. process.exitCode = 1;
  803. });
  804. for (const categoryId of temporaryGuestCategoryObjectIds) if (categoryId) await jsonRequest(`${PARSE_URL}/classes/Guestcate/${categoryId}`, { method: 'DELETE' }, true).catch((error) => {
  805. console.error(`临时留言/贴吧分类清理失败:${error.message}`);
  806. process.exitCode = 1;
  807. });
  808. for (const knowledgeId of [...temporaryKnowledgeObjectIds].reverse()) if (knowledgeId) await jsonRequest(`${PARSE_URL}/classes/QuestionsKnowledge/${knowledgeId}`, { method: 'DELETE' }, true).catch((error) => {
  809. console.error(`临时知识点清理失败:${error.message}`);
  810. process.exitCode = 1;
  811. });
  812. if (temporaryExamTeacherId) await jsonRequest(`${PARSE_URL}/classes/ExTeacher/${temporaryExamTeacherId}`, { method: 'DELETE' }, true).catch((error) => {
  813. console.error(`临时考试教师清理失败:${error.message}`);
  814. process.exitCode = 1;
  815. });
  816. for (const dictionaryItemId of temporaryDictionaryItemIds) if (dictionaryItemId) await jsonRequest(`${PARSE_URL}/classes/Datadic/${dictionaryItemId}`, { method: 'DELETE' }, true).catch((error) => {
  817. console.error(`临时字典项清理失败:${error.message}`);
  818. process.exitCode = 1;
  819. });
  820. for (const dictionaryCategoryId of temporaryDictionaryCategoryIds) if (dictionaryCategoryId) await jsonRequest(`${PARSE_URL}/classes/Datadiccategory/${dictionaryCategoryId}`, { method: 'DELETE' }, true).catch((error) => {
  821. console.error(`临时字典分类清理失败:${error.message}`);
  822. process.exitCode = 1;
  823. });
  824. for (const gradeOptionId of [...temporaryGradeOptionIds].reverse()) if (gradeOptionId) await jsonRequest(`${PARSE_URL}/classes/Grade/${gradeOptionId}`, { method: 'DELETE' }, true).catch((error) => {
  825. console.error(`临时多级字典选项清理失败:${error.message}`);
  826. process.exitCode = 1;
  827. });
  828. for (const gradeCategoryId of temporaryGradeCategoryIds) if (gradeCategoryId) await jsonRequest(`${PARSE_URL}/classes/GradeCate/${gradeCategoryId}`, { method: 'DELETE' }, true).catch((error) => {
  829. console.error(`临时多级字典分类清理失败:${error.message}`);
  830. process.exitCode = 1;
  831. });
  832. for (const examClassId of [...temporaryExamClassObjectIds].reverse()) if (examClassId) await jsonRequest(`${PARSE_URL}/classes/ExamClass/${examClassId}`, { method: 'DELETE' }, true).catch((error) => {
  833. console.error(`临时试题分类清理失败:${error.message}`);
  834. process.exitCode = 1;
  835. });
  836. for (const examPointId of [...temporaryExamPointObjectIds].reverse()) if (examPointId) await jsonRequest(`${PARSE_URL}/classes/ExamPoint/${examPointId}`, { method: 'DELETE' }, true).catch((error) => {
  837. console.error(`临时考点清理失败:${error.message}`);
  838. process.exitCode = 1;
  839. });
  840. for (const fieldId of temporaryModelFieldObjectIds) if (fieldId) await jsonRequest(`${PARSE_URL}/classes/ModelField/${fieldId}`, { method: 'DELETE' }, true).catch((error) => {
  841. console.error(`临时模型字段清理失败:${error.message}`);
  842. process.exitCode = 1;
  843. });
  844. if (temporaryModelObjectId) await jsonRequest(`${PARSE_URL}/classes/Model/${temporaryModelObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  845. console.error(`临时模型清理失败:${error.message}`);
  846. process.exitCode = 1;
  847. });
  848. if (temporaryGuestbookId) await jsonRequest(`${PARSE_URL}/classes/Guestbook/${temporaryGuestbookId}`, { method: 'DELETE' }, true).catch((error) => {
  849. console.error(`临时留言清理失败:${error.message}`);
  850. process.exitCode = 1;
  851. });
  852. if (temporaryGuestbookReplyId) await jsonRequest(`${PARSE_URL}/classes/Guestbook/${temporaryGuestbookReplyId}`, { method: 'DELETE' }, true).catch((error) => {
  853. console.error(`临时管理员留言回复清理失败:${error.message}`);
  854. process.exitCode = 1;
  855. });
  856. if (temporaryGuestBarId) await jsonRequest(`${PARSE_URL}/classes/GuestBar/${temporaryGuestBarId}`, { method: 'DELETE' }, true).catch((error) => {
  857. console.error(`临时贴吧帖子清理失败:${error.message}`);
  858. process.exitCode = 1;
  859. });
  860. for (const lessonId of temporaryLessonIds) await jsonRequest(`${PARSE_URL}/classes/LessonRecord/${lessonId}`, { method: 'DELETE' }, true).catch((error) => {
  861. console.error(`临时陪练课次清理失败:${error.message}`);
  862. process.exitCode = 1;
  863. });
  864. if (memberLegacyId) {
  865. const commonWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:(stu_record|content_add_zt|content_add):${memberLegacyId}:` } }));
  866. const commonRows = await jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${commonWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  867. for (const row of commonRows.results || []) await jsonRequest(`${PARSE_URL}/classes/CommonModel/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  868. console.error(`临时学习主记录清理失败:${error.message}`);
  869. process.exitCode = 1;
  870. });
  871. const studyWhere = encodeURIComponent(JSON.stringify({ userId: memberLegacyId }));
  872. const studyRows = await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord?where=${studyWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  873. for (const row of studyRows.results || []) await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  874. console.error(`临时学习 addon 清理失败:${error.message}`);
  875. process.exitCode = 1;
  876. });
  877. }
  878. if (temporaryAppointmentObjectId) await jsonRequest(`${PARSE_URL}/classes/CourseAppointment/${temporaryAppointmentObjectId}`, { method: 'DELETE' }, true).catch((error) => {
  879. console.error(`临时预约清理失败:${error.message}`);
  880. process.exitCode = 1;
  881. });
  882. if (temporaryAppointmentId) {
  883. const sideEffectWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:e_order_update:${temporaryAppointmentId}:` } }));
  884. for (const className of ['CommonModel', 'MemoryPracticeRecord', 'UserExpDomP', 'UserUserPoint']) {
  885. const rows = await jsonRequest(`${PARSE_URL}/classes/${className}?where=${sideEffectWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  886. for (const row of rows.results || []) await jsonRequest(`${PARSE_URL}/classes/${className}/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  887. console.error(`临时预约副作用清理失败(${className}):${error.message}`);
  888. process.exitCode = 1;
  889. });
  890. }
  891. }
  892. if (memberLegacyId) {
  893. const assessmentWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:content_add:${memberLegacyId}:` } }));
  894. const assessments = await jsonRequest(`${PARSE_URL}/classes/AssessmentProfile?where=${assessmentWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  895. for (const assessment of assessments.results || []) await jsonRequest(`${PARSE_URL}/classes/AssessmentProfile/${assessment.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  896. console.error(`临时测评记录清理失败:${error.message}`);
  897. process.exitCode = 1;
  898. });
  899. }
  900. if (memberLegacyId) {
  901. const where = encodeURIComponent(JSON.stringify({ yhid: String(memberLegacyId) }));
  902. const practices = await jsonRequest(`${PARSE_URL}/classes/PracticeRecord?where=${where}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  903. for (const practice of practices.results || []) await jsonRequest(`${PARSE_URL}/classes/PracticeRecord/${practice.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  904. console.error(`临时学习进度清理失败:${error.message}`);
  905. process.exitCode = 1;
  906. });
  907. }
  908. if (teamChildId) {
  909. await jsonRequest(`${PARSE_URL}/users/${teamChildId}`, { method: 'DELETE' }, true).catch((error) => {
  910. console.error(`临时团队成员清理失败:${error.message}`);
  911. process.exitCode = 1;
  912. });
  913. }
  914. if (memberId) {
  915. await jsonRequest(`${PARSE_URL}/users/${memberId}`, { method: 'DELETE' }, true).catch((error) => {
  916. console.error(`临时普通用户清理失败:${error.message}`);
  917. process.exitCode = 1;
  918. });
  919. }
  920. if (coachId) {
  921. await jsonRequest(`${PARSE_URL}/users/${coachId}`, { method: 'DELETE' }, true).catch((error) => {
  922. console.error(`临时陪练用户清理失败:${error.message}`);
  923. process.exitCode = 1;
  924. });
  925. }
  926. if (userId) {
  927. await jsonRequest(`${PARSE_URL}/users/${userId}`, { method: 'DELETE' }, true).catch((error) => {
  928. console.error(`临时管理员清理失败:${error.message}`);
  929. process.exitCode = 1;
  930. });
  931. }
  932. }