deploy-admin-functions.mjs 251 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. #!/usr/bin/env node
  2. const APP_ID = process.env.XIAOSHU_PARSE_APP_ID || '7pIbDBJmKx_main';
  3. const MASTER_KEY = process.env.XIAOSHU_MASTER_KEY || '';
  4. const PARSE_URL = (process.env.XIAOSHU_PARSE_URL || 'https://server.xiaoshu.pro/parse').replace(/\/$/, '');
  5. const validateOnly = process.argv.includes('--validate');
  6. const adminGatewayCode = String.raw`
  7. const CLASS_LABELS = {
  8. _User: '用户管理', Company: '帐套管理', Profile: '员工档案', Group: '用户组', Role: '角色', Permission: '权限', Department: '组织部门',
  9. CourseBinding: '课程绑定', CourseAppointment: '课程预约', LessonRecord: '上课记录', DailyStudyRecord: '每日学习记录', PracticeRecord: '练习记录', MemoryPracticeRecord: '抗遗忘记录',
  10. VocabularyWord: '词库', CommonModel: '通用内容', ContentArticle: '文章内容', ContentPublish: '内容发布', Node: '栏目节点', NodeAuth: '节点权限', Model: '内容模型', ModelField: '模型字段',
  11. ExamClass: '试题分类', ExamSysQuestions: '考试题库', ExamSysPapers: '试卷', ExamType: '考试类型', ExamPoint: '知识点', PaperQuestions: '试卷题目',
  12. Datadiccategory: '数据字典分类', Datadic: '数据字典项',
  13. GradeCate: '多级字典分类', Grade: '多级字典选项',
  14. Currency: '货币管理', SysHoliday: '节假日管理',
  15. Product: '商品', StoreProduct: '门店商品', StoreApplication: '门店申请', ShopFareTlp: '运费模板', ShopMoneyRegular: '金额规则', PayPlat: '支付平台',
  16. GuestBar: '互动社区', Guestbook: '留言', Guestcate: '留言分类', Feedback: '反馈', Baike: '百科', Search: '后台快捷入口', AdZone: '广告位管理', AdInfo: '广告内容管理', Agency: '代理机构', DeliveryCenter: '交付中心'
  17. };
  18. const ALLOWED_CLASSES = new Set([
  19. 'PageTemplate','PaperQuestions','PayPlat','Permission','PlatComp','App','DesignAnswer','DesignAsk','Attachment','DesignPage','DesignQuestion','DesignRes','Feedback','DesignScence','StudentAchieve','ContentArticle','DesignSiteInfo','Profile','AdInfo','AdZone','ARoleAuth','Baike','ExamSysQuestions','ContactInfo','VocabularyWord','AssessmentProfile','Agency','MemoryPracticeRecord','DeliveryCenter','CourseBinding','PracticeRecord','CourseAppointment','Account','SurveyItem','SurveyLog','LessonRecord','DailyStudyRecord','CommonModel','ContentPublish','Company','_Role','_User','CRMSAttr','Currency','Datadic','Datadiccategory','DesignTlp','DocModel','DocPermission','ExamClass','ExamSysPapers','ExamType','ExamPoint','ExTeacher','FontPicShape','FontPicShapeType','Grade','GradeCate','Group','GroupModel','GuestBar','Guestbook','Guestcate','MailTemp','Manager','MisProcedure','MisProLevel','MisSign','MisType','PageStyle','Model','ModelField','Node','NodeAuth','NodeModelTemplate','Product','PlatUserRole','Pub','PubTw','PubWTHD','PubZXDC','PublishNode','QuestionsKnowledge','Role','StoreProduct','SafeMobile','Search','SenTask','ServiceSeat','ShopFareTlp','ShopMoneyRegular','Special','StoreApplication','StoreStyle','SysCSSManage','SysHoliday','SysLog','Temp','ThirdPlatInfo','UserCredit','UserDummyPoint','UserFriendGroup','UserLevel','UserSIcon','UserUserPoint','UserExpDomP','UserExpHis'
  20. ]);
  21. const READ_ONLY_CLASSES = new Set(['_Role','Permission','PayPlat','ThirdPlatInfo','GuestBar']);
  22. const SYSTEM_FIELDS = new Set(['objectId','createdAt','updatedAt','ACL','company','password','authData','sessionToken','legacyPasswordHash','legacyPasswordHashType','appPassword','newapiToken','fmodeApiToken','useMasterKey','adminPassword','randNumber','adminRoleKey','isAdmin','roles','role','isDisabled','legacyUserId','legacyGroupId','legacyUserData','groupId']);
  23. const HIDDEN_FIELDS = new Set(['password','authData','sessionToken','legacyPasswordHash','legacyPasswordHashType','appPassword','newapiToken','fmodeApiToken','useMasterKey','adminPassword','randNumber','apiKey','appSecret','secret','token']);
  24. const GENERIC_WRITE_TYPES = new Set(['String','Number','Boolean','Date','Pointer','Object','Array']);
  25. const CLASS_SYSTEM_FIELDS = {
  26. CommonModel: new Set(['generalId','modelId','nodeId','itemId','tableName','status','isDeleted','sourceKey','orderId']),
  27. Node: new Set(['nodeId','parentId','depth','child','orderId','zstatus','sourceKey','cuser','cuname','editDate']),
  28. Special: new Set(['specId','pid','orderId','sourceKey','cuser','editDate']),
  29. Model: new Set(['modelId','modelType','tableName','sourceKey','nodeId','fromModel','multiFlag','sysModel']),
  30. ModelField: new Set(['fieldId','modelId','fieldName','fieldType','sourceKey','sysType','orderId']),
  31. Guestbook: new Set(['gid','parentid','cateid','userid','status','sourceKey','gdate','ip']),
  32. Guestcate: new Set(['cateid','parentId','gtype','sourceKey','orderId']),
  33. GuestBar: new Set(['id','cateId','pid','replyId','replyUserId','cuser','cuname','cdate','status','sourceKey','orderFlag','postFlag']),
  34. ExamClass: new Set(['cId','cClassid','cOrderBy','cClassType','sourceKey']),
  35. ExamPoint: new Set(['id','tid','orderBy','addUser','addTime','sourceKey']),
  36. QuestionsKnowledge: new Set(['kId','kClassId','kOrderBy','pid','cuser','cdate','sourceKey']),
  37. ExTeacher: new Set(['id','tclsss','addUser','creatTime','sourceKey']),
  38. Datadiccategory: new Set(['diccateid','sourceKey']),
  39. Datadic: new Set(['dicid','diccate','sourceKey']),
  40. GradeCate: new Set(['cateId','sourceKey']),
  41. Grade: new Set(['gradeId','cate','parentId','grade','sourceKey']),
  42. Currency: new Set(['id','sourceKey']),
  43. SysHoliday: new Set(['id','cdate','cadminId','cuserId','sourceKey']),
  44. Search: new Set(['id','type','state','time','adminId','orderId','linkType','linkState','sourceKey']),
  45. AdZone: new Set(['id','cdate','cadmin','image','sourceKey']),
  46. AdInfo: new Set(['id','cdate','zoneId','ztype','extend1','extend2','extend3','sourceKey'])
  47. };
  48. function inputOf(request) {
  49. const body = request.body || {};
  50. return body.params && typeof body.params === 'object' ? body.params : body;
  51. }
  52. function fail(status, message) { const error = new Error(message); error.status = status; throw error; }
  53. function pointerId(value) { return value && (value.id || value.objectId || (value.__type === 'Pointer' && value.objectId)); }
  54. function escapeRegex(value) { return String(value).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'); }
  55. function safeValue(value, depth = 0) {
  56. if (value == null || depth > 4) return value;
  57. if (Array.isArray(value)) return value.map((item) => safeValue(item, depth + 1));
  58. if (value instanceof Date) return value.toISOString();
  59. if (value && typeof value === 'object' && ['Object','Pointer'].includes(value.__type) && value.className && value.objectId) return { __type: 'Pointer', className: String(value.className), objectId: String(value.objectId) };
  60. if (value && typeof value.toJSON === 'function') return safeValue(value.toJSON(), depth + 1);
  61. if (typeof value === 'object') {
  62. const output = {};
  63. for (const [key, item] of Object.entries(value)) {
  64. if (HIDDEN_FIELDS.has(key) || /(?:password|secret|token|masterkey|privatekey|mch_key|^ak$|^sk$)/i.test(key)) continue;
  65. output[key] = safeValue(item, depth + 1);
  66. }
  67. return output;
  68. }
  69. return value;
  70. }
  71. function isVisible(object) { const value = object && typeof object.get === 'function' ? object.get('isDeleted') : object && object.isDeleted; return ![true, 1, '1', 'true', 'True', 'TRUE'].includes(value); }
  72. async function requireAdmin(request) {
  73. const current = request.user || (typeof user !== 'undefined' ? user : null);
  74. if (!current) fail(401, '管理员会话已失效');
  75. await current.fetch({ useMasterKey: true });
  76. if (current.get('isDisabled') === true || current.get('isDeleted') === true) fail(403, '管理员账号已停用');
  77. const roles = Array.isArray(current.get('roles')) ? current.get('roles').map(String) : [];
  78. const role = String(current.get('role') || '');
  79. const roleKey = String(current.get('adminRoleKey') || '');
  80. const isSuperAdmin = roleKey === 'super-admin' || roles.includes('super-admin');
  81. const isAdmin = current.get('isAdmin') === true || role === 'admin' || roles.includes('admin') || isSuperAdmin;
  82. if (!isAdmin) fail(403, '当前账号未被授权为后台管理员');
  83. const company = request.company || current.get('company') || null;
  84. if (!company && !isSuperAdmin) fail(403, '管理员账号尚未分配帐套');
  85. return { current, roles, isSuperAdmin, company };
  86. }
  87. function isAdminAccount(target) {
  88. const roles = Array.isArray(target.get('roles')) ? target.get('roles').map(String) : [];
  89. return target.get('isAdmin') === true || target.get('role') === 'admin' || roles.includes('admin') || target.get('adminRoleKey') === 'super-admin' || roles.includes('super-admin');
  90. }
  91. function assertCanManageUser(context, target, action) {
  92. if (action === 'lock' && target.id === context.current.id) fail(400, '不能停用当前登录账号');
  93. if (isAdminAccount(target) && target.id !== context.current.id && !context.isSuperAdmin) fail(403, '只有超级管理员可以管理其他管理员账号');
  94. }
  95. async function revokeSessions(targets) {
  96. let revoked = 0;
  97. while (targets.length) {
  98. const query = new Parse.Query('_Session'); query.containedIn('user', targets); query.limit(1000);
  99. const sessions = await query.find({ useMasterKey: true });
  100. if (!sessions.length) break;
  101. await Parse.Object.destroyAll(sessions, { useMasterKey: true }); revoked += sessions.length;
  102. if (sessions.length < 1000) break;
  103. }
  104. return revoked;
  105. }
  106. function assertClass(className) {
  107. if (!ALLOWED_CLASSES.has(className)) fail(400, '不允许访问该数据类');
  108. }
  109. function isSystemField(className, name) { return SYSTEM_FIELDS.has(name) || Boolean(CLASS_SYSTEM_FIELDS[className] && CLASS_SYSTEM_FIELDS[className].has(name)); }
  110. async function schemaFor(className) {
  111. assertClass(className);
  112. const schema = await new Parse.Schema(className).get({ useMasterKey: true });
  113. return schema && schema.fields ? schema.fields : {};
  114. }
  115. function applyTenant(query, fields, context, requestedCompanyId) {
  116. if (!fields.company) return;
  117. if (context.isSuperAdmin && requestedCompanyId) {
  118. query.equalTo('company', Parse.Object.createWithoutData('Company', String(requestedCompanyId)));
  119. } else if (context.company) {
  120. query.equalTo('company', context.company);
  121. }
  122. }
  123. function serializeObject(object) { return safeValue(object.toJSON()); }
  124. function toParseValue(field, value) {
  125. if (value == null || value === '') return value;
  126. if (field.type === 'Pointer') {
  127. const objectId = pointerId(value) || value;
  128. return Parse.Object.createWithoutData(field.targetClass, String(objectId));
  129. }
  130. if (field.type === 'Date') {
  131. const date = new Date(value.iso || value);
  132. if (Number.isNaN(date.getTime())) fail(400, '日期字段格式无效');
  133. return date;
  134. }
  135. if (field.type === 'Number') {
  136. const number = Number(value);
  137. if (!Number.isFinite(number)) fail(400, '数字字段格式无效');
  138. return number;
  139. }
  140. if (field.type === 'Boolean') return value === true || value === 'true';
  141. if (field.type === 'Array') { if (!Array.isArray(value)) fail(400, '数组字段格式无效'); return value; }
  142. if (field.type === 'Object') { if (!value || typeof value !== 'object' || Array.isArray(value)) fail(400, '对象字段格式无效'); return value; }
  143. if (!GENERIC_WRITE_TYPES.has(field.type)) fail(400, '该字段类型不允许通用编辑: ' + field.type);
  144. return value;
  145. }
  146. async function countClass(className, context) {
  147. const fields = await schemaFor(className);
  148. const query = new Parse.Query(className);
  149. applyTenant(query, fields, context);
  150. if (fields.isDeleted) query.notEqualTo('isDeleted', true);
  151. return query.count({ useMasterKey: true });
  152. }
  153. async function audit(context, action, className, objectId) {
  154. try {
  155. const log = new Parse.Object('SysLog');
  156. const schema = await new Parse.Schema('SysLog').get({ useMasterKey: true });
  157. const fields = schema.fields || {};
  158. if (fields.company && context.company) log.set('company', context.company);
  159. if (fields.userId) log.set('userId', context.current.id);
  160. if (fields.userName) log.set('userName', String(context.current.get('username') || ''));
  161. if (fields.remind) log.set('remind', '[AngularAdmin] ' + action + ' ' + className + '/' + objectId);
  162. if (fields.logType) log.set('logType', 'angular-admin');
  163. await log.save(null, { useMasterKey: true });
  164. } catch (_) { /* 审计表字段来自旧系统,失败不能覆盖主操作结果。 */ }
  165. }
  166. async function handler(request, response) {
  167. try {
  168. const input = inputOf(request);
  169. const operation = String(input.operation || 'meta');
  170. const context = await requireAdmin(request);
  171. if (operation === 'meta') {
  172. const functionQuery = new Parse.Query('Function');
  173. functionQuery.notEqualTo('enabled', false);
  174. const cloudFunctions = await functionQuery.count({ useMasterKey: true });
  175. return response.json({ success: true, data: {
  176. identity: { objectId: context.current.id, username: String(context.current.get('username') || ''), displayName: String(context.current.get('realName') || context.current.get('realname') || context.current.get('nickname') || context.current.get('username') || ''), company: safeValue(context.company), roles: context.roles, isSuperAdmin: context.isSuperAdmin },
  177. classes: ALLOWED_CLASSES.size, cloudFunctions
  178. }});
  179. }
  180. if (operation === 'dashboard') {
  181. const metrics = [
  182. ['_User','用户总数'],['CourseBinding','课程绑定'],['CourseAppointment','课程预约'],['PracticeRecord','练习记录'],['LessonRecord','上课记录'],['DailyStudyRecord','每日学习'],['VocabularyWord','词库单词'],['CommonModel','内容记录']
  183. ];
  184. const counts = await Promise.all(metrics.map(async ([className, label]) => ({ className, label, count: await countClass(className, context), route: '/admin/resources/' + className })));
  185. const functionQuery = new Parse.Query('Function'); functionQuery.notEqualTo('enabled', false);
  186. let registeredRecords = 195452;
  187. try { const row = await Psql.oneOrNone('SELECT COUNT(*)::int AS count FROM cms.record_registry'); if (row) registeredRecords = Number(row.count); } catch (_) {}
  188. return response.json({ success: true, data: { identity: { objectId: context.current.id, username: String(context.current.get('username') || ''), displayName: String(context.current.get('realName') || context.current.get('nickname') || context.current.get('username') || ''), company: safeValue(context.company), roles: context.roles, isSuperAdmin: context.isSuperAdmin }, metrics: counts, migration: { sourceObjects: 338, migratedClasses: 96, registeredRecords, cloudFunctions: await functionQuery.count({ useMasterKey: true }) } } });
  189. }
  190. if (operation === 'catalog') {
  191. const resources = [...ALLOWED_CLASSES].sort().map((className) => ({ className, label: CLASS_LABELS[className] || className, writable: !READ_ONLY_CLASSES.has(className), route: '/admin/resources/' + className }));
  192. return response.json({ success: true, data: { total: resources.length, resources } });
  193. }
  194. if (operation === 'apiCatalog') {
  195. const query = new Parse.Query('Function'); query.ascending('path'); query.limit(1000); const rows = await query.find({ useMasterKey: true });
  196. const results = rows.filter((entry) => entry.get('isDeleted') !== true && String(entry.get('path') || '').startsWith('xiaoshu/')).map((entry) => ({ objectId: entry.id, name: String(entry.get('name') || ''), desc: String(entry.get('desc') || ''), path: String(entry.get('path') || ''), type: String(entry.get('type') || 'standalone'), paramList: Array.isArray(entry.get('paramList')) ? safeValue(entry.get('paramList')) : [], respType: String(entry.get('respType') || 'json'), updatedAt: safeValue(entry.updatedAt) }));
  197. return response.json({ success: true, data: { total: results.length, results } });
  198. }
  199. if (operation === 'legacyConfigBlocker') {
  200. const action = String(input.action || ''); const blockers = {
  201. APIInfo_Submit: '旧 API_ID/API_Key/API_AdminKey、IP 访问策略与目标 sessionToken/云函数权限模型不等价,且没有能对全部函数生效的站点配置层',
  202. APIInfo_SwaggerClose: '目标云函数引擎没有帐套级 Swagger 实时调试关闭开关',
  203. APIInfo_SwaggerOpen: '目标云函数引擎没有帐套级 Swagger 实时调试开启开关',
  204. LicenceFile_API: '目标 Schema 缺少许可、隐私、协议与版权文档存储,云函数也不能写旧 wwwroot/Config 文件',
  205. close_system: '云函数运行时不存在可通过 app_offline.htm 关闭的单体 ASP.NET 进程',
  206. Hotkey: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,旧 XML 配置文件也不在云函数运行时',
  207. HotkeyAdd: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,无法生成可全局生效的快捷键',
  208. HotkeyAdd_Submit: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,不能伪造保存成功',
  209. Hotkey_API: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,启停、删除、重载和脚本匹配无可操作对象',
  210. Prize: '目标 Schema 没有 PrizeConfig/PrizeTask 配置模型及签到、任务规则数据',
  211. Prize_Submit: '目标 Schema 没有 PrizeConfig/PrizeTask 配置模型,无法持久化奖励积分、重复周期和过期规则'
  212. };
  213. if (!Object.prototype.hasOwnProperty.call(blockers, action)) fail(400, '不支持的旧配置动作'); fail(501, 'migration_blocked: ' + blockers[action]);
  214. }
  215. if (operation === 'createUser') {
  216. const username = String(input.username || '').trim();
  217. const password = typeof input.password === 'string' ? input.password : '';
  218. const displayName = String(input.displayName || '').trim();
  219. const mobile = String(input.mobile || '').trim();
  220. const inviteUsername = String(input.inviteUsername || '').trim();
  221. if (username.length < 3 || username.length > 64) fail(400, '账号长度应为 3 至 64 位');
  222. if (password.length < 8 || password.length > 72) fail(400, '密码长度应为 8 至 72 位');
  223. if (displayName.length > 100) fail(400, '显示名不能超过 100 位');
  224. if (mobile.length > 32) fail(400, '手机号不能超过 32 位');
  225. let companyId = pointerId(context.company);
  226. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  227. if (!companyId) fail(400, '开户必须指定帐套');
  228. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  229. const userFields = await schemaFor('_User');
  230. if (!userFields.company) fail(500, '用户表缺少帐套字段');
  231. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "_User" WHERE "company"=$1 AND "username"=$2 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) LIMIT 1', [companyId, username]);
  232. if (duplicate) fail(409, '此用户名已被使用');
  233. let parentId = 0;
  234. if (inviteUsername) {
  235. const inviter = await Psql.oneOrNone('SELECT COALESCE("legacyUserId", CASE WHEN COALESCE("legacyUserData"->>\'UserID\',\'\') ~ \'^[0-9]+$\' THEN ("legacyUserData"->>\'UserID\')::numeric END) AS id FROM "_User" WHERE "company"=$1 AND "username"=$2 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) LIMIT 1', [companyId, inviteUsername]);
  236. parentId = Number(inviter && inviter.id) || 0;
  237. if (!parentId) fail(400, '邀请账号不存在');
  238. }
  239. const created = new Parse.User();
  240. created.setUsername(username); created.setPassword(password); created.set('company', company);
  241. if (userFields.type) created.set('type', 'user');
  242. if (userFields.isDisabled) created.set('isDisabled', false);
  243. if (userFields.isDeleted) created.set('isDeleted', false);
  244. if (userFields.legacyGroupId) created.set('legacyGroupId', 1);
  245. if (userFields.nickname) created.set('nickname', displayName || username);
  246. if (mobile && userFields.mobile) created.set('mobile', mobile);
  247. if (userFields.isAdmin) created.set('isAdmin', false);
  248. if (userFields.roles) created.set('roles', []);
  249. try { await created.signUp(null, { useMasterKey: true }); }
  250. catch (error) { if (Number(error && error.code) === 202) fail(409, '此用户名已被使用'); throw error; }
  251. try {
  252. const regTime = new Date().toISOString();
  253. const legacyData = { UserID:0,UserName:username,HoneyName:displayName || username,GroupID:1,ParentUserID:parentId,VIP:0,RegTime:regTime,Purse:0,SilverCoin:0,UserExp:0,UserPoint:0,boffExp:0,State:1 };
  254. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-legacy-user-id\'))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("legacyUserId"),0)+1 AS id FROM "_User",lock_row WHERE "company"=$1 AND COALESCE("legacyUserId",0)>0) UPDATE "_User" SET "legacyUserId"=next_id.id,"legacyGroupId"=1,"legacyUserData"=jsonb_set($3::jsonb,\'{UserID}\',to_jsonb(next_id.id),true),"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, created.id, JSON.stringify(legacyData)]);
  255. const legacyUserId = Number(rows[0] && rows[0].id) || 0;
  256. if (!legacyUserId) throw new Error('无法分配旧系统用户 ID');
  257. await created.fetch({ useMasterKey: true });
  258. await audit({ ...context, company }, 'create-user', '_User', created.id);
  259. return response.json({ success: true, data: { ...serializeObject(created), userId: legacyUserId, groupId: 1 } });
  260. } catch (error) {
  261. await created.destroy({ useMasterKey: true }).catch(() => undefined);
  262. throw error;
  263. }
  264. }
  265. if (operation === 'userBatch') {
  266. const action = String(input.action || '');
  267. if (!['lock','unlock','move'].includes(action)) fail(400, '不支持的用户批量操作');
  268. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  269. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  270. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个用户');
  271. const userFields = await schemaFor('_User');
  272. const query = new Parse.Query('_User'); applyTenant(query, userFields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  273. const targets = await query.find({ useMasterKey: true });
  274. if (targets.length !== objectIds.length) fail(404, '部分用户不存在或不属于当前帐套');
  275. for (const target of targets) assertCanManageUser(context, target, action);
  276. let group = null;
  277. let groupId = 0;
  278. if (action === 'move') {
  279. groupId = Number(input.groupId);
  280. if (!Number.isInteger(groupId) || groupId < 1) fail(400, '请选择有效用户组');
  281. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  282. if (companyIds.length !== 1) fail(400, '批量移动的用户必须属于同一帐套');
  283. const groupRow = await Psql.oneOrNone('SELECT "objectId" FROM "Group" WHERE "company"=$1 AND "groupId"=$2 LIMIT 1', [companyIds[0], groupId]);
  284. if (!groupRow) fail(404, '目标用户组不存在或不属于当前帐套');
  285. group = await new Parse.Query('Group').get(String(groupRow.objectId), { useMasterKey: true });
  286. }
  287. const now = new Date();
  288. for (const target of targets) {
  289. const legacyData = { ...(target.get('legacyUserData') || {}) };
  290. if (action === 'move') {
  291. target.set('legacyGroupId', groupId); legacyData.GroupID = groupId;
  292. } else {
  293. const disabled = action === 'lock'; target.set('isDisabled', disabled); legacyData.State = disabled ? 0 : 1;
  294. if (userFields.statusAction) target.set('statusAction', disabled ? 'admin-lock' : 'admin-unlock');
  295. if (userFields.statusReason) target.set('statusReason', String(input.reason || '').trim().slice(0, 200));
  296. if (userFields.statusUpdatedAt) target.set('statusUpdatedAt', now);
  297. if (userFields.statusUpdatedBy) target.set('statusUpdatedBy', context.current.id);
  298. }
  299. target.set('legacyUserData', legacyData);
  300. }
  301. await Parse.Object.saveAll(targets, { useMasterKey: true });
  302. const revokedSessions = action === 'lock' ? await revokeSessions(targets) : 0;
  303. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'user-' + action, '_User', target.id);
  304. return response.json({ success: true, data: { action, updated: targets.length, revokedSessions, group: group ? serializeObject(group) : null, results: targets.map(serializeObject) } });
  305. }
  306. if (operation === 'saveGroup') {
  307. const objectId = String(input.objectId || '');
  308. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  309. const groupName = String(payload.groupName || '').trim();
  310. const description = String(payload.description || groupName).trim();
  311. const parentGroupId = payload.parentGroupId === undefined || payload.parentGroupId === '' ? 0 : Number(payload.parentGroupId);
  312. if (!groupName || groupName.length > 100) fail(400, '用户组名称为必填项且不能超过 100 位');
  313. if (description.length > 500) fail(400, '用户组说明不能超过 500 位');
  314. if (!Number.isInteger(parentGroupId) || parentGroupId < 0) fail(400, '父用户组编号无效');
  315. let companyId = pointerId(context.company);
  316. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  317. if (!companyId) fail(400, '用户组必须指定帐套');
  318. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  319. const groupFields = await schemaFor('Group');
  320. let target;
  321. let currentGroupId = 0;
  322. if (objectId) {
  323. const query = new Parse.Query('Group'); applyTenant(query, groupFields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  324. currentGroupId = Number(target.get('groupId')) || 0;
  325. } else target = new Parse.Object('Group');
  326. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "Group" WHERE "company"=$1 AND LOWER(COALESCE("groupName",\'\'))=LOWER($2) AND ($3=\'\' OR "objectId"<>$3) LIMIT 1', [companyId, groupName, objectId]);
  327. if (duplicate) fail(409, '当前帐套已存在同名用户组');
  328. if (parentGroupId) {
  329. let cursor = parentGroupId; const visited = new Set();
  330. while (cursor) {
  331. if (cursor === currentGroupId || visited.has(cursor)) fail(400, '父用户组不能形成循环');
  332. visited.add(cursor);
  333. const parent = await Psql.oneOrNone('SELECT "parentGroupId" AS parent_id FROM "Group" WHERE "company"=$1 AND "groupId"=$2 LIMIT 1', [companyId, cursor]);
  334. if (!parent) fail(404, '父用户组不存在或不属于当前帐套');
  335. cursor = Number(parent.parent_id) || 0;
  336. if (visited.size > 100) fail(400, '用户组层级过深');
  337. }
  338. }
  339. target.set('company', company); target.set('groupName', groupName); target.set('description', description); target.set('parentGroupId', parentGroupId);
  340. const stringFields = ['otherName','enroll','signImg'];
  341. const numberFields = ['orderId','companyGroup','vipgroup','rebateRate','credit','vipnum','upPoint','upSicon','favCount','consumeType','ccountPerDay','upGradeMoney'];
  342. for (const name of stringFields) if (payload[name] !== undefined && groupFields[name]) target.set(name, String(payload[name] || '').trim());
  343. for (const name of numberFields) if (payload[name] !== undefined && payload[name] !== '') { const value = Number(payload[name]); if (!Number.isFinite(value)) fail(400, name + ' 必须是数字'); if (groupFields[name]) target.set(name, value); }
  344. if (payload.regSelect !== undefined && groupFields.regSelect) target.set('regSelect', payload.regSelect === true || payload.regSelect === 'true');
  345. if (!objectId && groupFields.sourceKey) target.set('sourceKey', 'cloud:admin-group:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10));
  346. await target.save(null, { useMasterKey: true });
  347. if (!objectId) {
  348. try {
  349. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-group-id\'))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("groupId"),0)+1 AS id FROM "Group",lock_row WHERE "company"=$1 AND COALESCE("groupId",0)>0) UPDATE "Group" SET "groupId"=next_id.id,"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id]);
  350. currentGroupId = Number(rows[0] && rows[0].id) || 0;
  351. if (!currentGroupId) throw new Error('无法分配用户组编号');
  352. } catch (error) { await target.destroy({ useMasterKey: true }).catch(() => undefined); throw error; }
  353. }
  354. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-group' : 'create-group', 'Group', target.id);
  355. return response.json({ success: true, data: serializeObject(target) });
  356. }
  357. if (operation === 'saveNode') {
  358. const objectId = String(input.objectId || '');
  359. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  360. const nodeName = String(payload.nodeName || '').trim();
  361. const nodeDir = String(payload.nodeDir || '').trim();
  362. const parentId = Number(input.parentId == null ? payload.parentId || 0 : input.parentId);
  363. if (!nodeName || nodeName.length > 100) fail(400, '栏目名称长度应为 1 至 100 位');
  364. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父节点编号无效');
  365. let companyId = pointerId(context.company);
  366. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  367. if (!companyId) fail(400, '栏目必须指定帐套');
  368. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  369. const fields = await schemaFor('Node');
  370. let target;
  371. let currentNodeId = 0;
  372. if (objectId) {
  373. const query = new Parse.Query('Node'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  374. companyId = pointerId(target.get('company')) || companyId;
  375. currentNodeId = Number(target.get('nodeId')) || 0;
  376. } else target = new Parse.Object('Node');
  377. let parentDepth = 0;
  378. if (parentId > 0) {
  379. const parent = await Psql.oneOrNone('SELECT "nodeId","depth" FROM "Node" WHERE "company"=$1 AND "nodeId"=$2 AND COALESCE("zstatus",99)<>-2 LIMIT 1', [companyId, parentId]);
  380. if (!parent) fail(404, '父节点不存在、已回收或不属于当前帐套');
  381. parentDepth = Number(parent.depth) || 0;
  382. if (currentNodeId) {
  383. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "nodeId","parentId",ARRAY["nodeId"::text] AS path FROM "Node" WHERE "company"=$1 AND "nodeId"=$2 UNION ALL SELECT n."nodeId",n."parentId",chain.path||n."nodeId"::text FROM "Node" n JOIN chain ON n."nodeId"=chain."parentId" WHERE n."company"=$1 AND NOT n."nodeId"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "nodeId"=$3 LIMIT 1', [companyId, parentId, currentNodeId]);
  384. if (cycle) fail(409, '不能把栏目移动到自身或其下级栏目');
  385. }
  386. }
  387. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "Node" WHERE "company"=$1 AND COALESCE("parentId",0)=$2 AND "objectId"<>$3 AND COALESCE("zstatus",99)<>-2 AND (LOWER(TRIM(COALESCE("nodeName",\'\')))=LOWER($4) OR ($5<>\'\' AND LOWER(TRIM(COALESCE("nodeDir",\'\')))=LOWER($5))) LIMIT 1', [companyId, parentId, objectId, nodeName, nodeDir]);
  388. if (duplicate) fail(409, '同一父栏目下的栏目名称或目录名不能重复');
  389. for (const [name, value] of Object.entries(payload)) {
  390. if (!fields[name] || isSystemField('Node', name)) continue;
  391. if (!GENERIC_WRITE_TYPES.has(fields[name].type)) fail(400, '字段不允许编辑: ' + name);
  392. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  393. }
  394. target.set('nodeName', nodeName); target.set('nodeDir', nodeDir); target.set('parentId', parentId); target.set('depth', parentDepth + 1); target.set('company', company);
  395. if (!objectId) {
  396. target.set('sourceKey', 'cloud:admin-node:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10));
  397. target.set('zstatus', 99); target.set('child', 0); target.set('cdate', new Date());
  398. if (fields.cuser) target.set('cuser', Number(context.current.get('legacyUserId')) || 0);
  399. if (fields.cuname) target.set('cuname', String(context.current.get('username') || ''));
  400. }
  401. if (fields.editDate) target.set('editDate', new Date());
  402. try { await target.save(null, { useMasterKey: true }); }
  403. catch (error) { fail(422, '栏目初始写入失败: ' + String(error && error.message || error)); }
  404. try {
  405. if (!objectId) {
  406. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-node-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("nodeId"),0)+1 AS id FROM "Node",lock_row WHERE "company"=$1 AND COALESCE("nodeId",0)>0), next_order AS MATERIALIZED (SELECT COALESCE(MAX("orderId"),0)+1 AS id FROM "Node",lock_row WHERE "company"=$1 AND COALESCE("parentId",0)=$3 AND "objectId"<>$2) UPDATE "Node" SET "nodeId"=next_id.id,"orderId"=next_order.id,"sourceKey"=\'[["NodeID",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id,next_order WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id, parentId]);
  407. currentNodeId = Number(rows[0] && rows[0].id) || 0;
  408. if (!currentNodeId) throw new Error('无法分配栏目编号');
  409. }
  410. await Psql.query('WITH RECURSIVE tree AS (SELECT "objectId","nodeId",$3::numeric AS depth FROM "Node" WHERE "company"=$1 AND "objectId"=$2 UNION ALL SELECT n."objectId",n."nodeId",tree.depth+1 FROM "Node" n JOIN tree ON n."parentId"=tree."nodeId" WHERE n."company"=$1) UPDATE "Node" n SET "depth"=tree.depth,"updatedAt"=NOW() FROM tree WHERE n."objectId"=tree."objectId"', [companyId, target.id, parentDepth + 1]);
  411. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '栏目结构写入失败: ' + String(error && error.message || error)); }
  412. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-node' : 'create-node', 'Node', target.id);
  413. return response.json({ success: true, data: serializeObject(target) });
  414. }
  415. if (operation === 'nodeBatch') {
  416. const action = String(input.action || '');
  417. if (!['recycle','recover','move','purge'].includes(action)) fail(400, '不支持的栏目批量操作');
  418. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  419. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  420. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个栏目');
  421. const fields = await schemaFor('Node');
  422. const query = new Parse.Query('Node'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  423. const targets = await query.find({ useMasterKey: true });
  424. if (targets.length !== objectIds.length) fail(404, '部分栏目不存在或不属于当前帐套');
  425. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  426. if (companyIds.length !== 1) fail(400, '批量操作的栏目必须属于同一帐套');
  427. const companyId = companyIds[0];
  428. const nodeIds = targets.map((target) => Number(target.get('nodeId')) || 0);
  429. if (nodeIds.some((nodeId) => nodeId < 1)) fail(409, '栏目缺少有效旧系统编号');
  430. let parentId = null;
  431. let parentDepth = 0;
  432. if (action === 'move') {
  433. parentId = Number(input.parentId);
  434. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '目标父节点编号无效');
  435. if (parentId > 0) {
  436. const parent = await Psql.oneOrNone('SELECT "nodeId","depth" FROM "Node" WHERE "company"=$1 AND "nodeId"=$2 AND COALESCE("zstatus",99)<>-2 LIMIT 1', [companyId, parentId]);
  437. if (!parent) fail(404, '目标父节点不存在、已回收或不属于当前帐套');
  438. parentDepth = Number(parent.depth) || 0;
  439. for (const nodeId of nodeIds) {
  440. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "nodeId","parentId",ARRAY["nodeId"::text] AS path FROM "Node" WHERE "company"=$1 AND "nodeId"=$2 UNION ALL SELECT n."nodeId",n."parentId",chain.path||n."nodeId"::text FROM "Node" n JOIN chain ON n."nodeId"=chain."parentId" WHERE n."company"=$1 AND NOT n."nodeId"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "nodeId"=$3 LIMIT 1', [companyId, parentId, nodeId]);
  441. if (cycle) fail(409, '不能把栏目移动到自身或其下级栏目');
  442. }
  443. }
  444. for (const target of targets) { target.set('parentId', parentId); target.set('depth', parentDepth + 1); if (fields.editDate) target.set('editDate', new Date()); }
  445. await Parse.Object.saveAll(targets, { useMasterKey: true });
  446. for (const target of targets) await Psql.query('WITH RECURSIVE tree AS (SELECT "objectId","nodeId",$3::numeric AS depth FROM "Node" WHERE "company"=$1 AND "objectId"=$2 UNION ALL SELECT n."objectId",n."nodeId",tree.depth+1 FROM "Node" n JOIN tree ON n."parentId"=tree."nodeId" WHERE n."company"=$1) UPDATE "Node" n SET "depth"=tree.depth,"updatedAt"=NOW() FROM tree WHERE n."objectId"=tree."objectId"', [companyId, target.id, parentDepth + 1]);
  447. } else if (action === 'purge') {
  448. const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "CommonModel" WHERE "company"=$1 AND "nodeId"=ANY($2::numeric[])) AS contents,(SELECT COUNT(*)::int FROM "Node" WHERE "company"=$1 AND "parentId"=ANY($2::numeric[]) AND NOT ("nodeId"=ANY($2::numeric[]))) AS children,(SELECT COUNT(*)::int FROM "NodeAuth" WHERE "nodeId"=ANY($2::numeric[])) AS auth,(SELECT COUNT(*)::int FROM "NodeModelTemplate" WHERE "nodeId"=ANY($2::numeric[])) AS templates', [companyId, nodeIds]);
  449. if (Number(refs.contents) || Number(refs.children) || Number(refs.auth) || Number(refs.templates)) fail(409, '栏目仍被内容、下级栏目、权限或模板引用,不能永久删除');
  450. await Parse.Object.destroyAll(targets, { useMasterKey: true });
  451. } else {
  452. const status = action === 'recycle' ? -2 : 99;
  453. for (const target of targets) { target.set('zstatus', status); if (fields.editDate) target.set('editDate', new Date()); }
  454. await Parse.Object.saveAll(targets, { useMasterKey: true });
  455. }
  456. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'node-' + action, 'Node', target.id);
  457. return response.json({ success: true, data: { action, updated: targets.length, parentId, results: action === 'purge' ? [] : targets.map(serializeObject) } });
  458. }
  459. if (operation === 'saveSpecial') {
  460. const objectId = String(input.objectId || '');
  461. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  462. const specName = String(payload.specName || '').trim();
  463. const specDir = String(payload.specDir || '').trim();
  464. const pid = Number(input.pid == null ? payload.pid || 0 : input.pid);
  465. if (!specName || specName.length > 100) fail(400, '专题名称长度应为 1 至 100 位');
  466. if (!specDir || specDir.length > 100) fail(400, '专题目录长度应为 1 至 100 位');
  467. if (!Number.isInteger(pid) || pid < 0) fail(400, '父专题编号无效');
  468. let companyId = pointerId(context.company);
  469. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  470. if (!companyId) fail(400, '专题必须指定帐套');
  471. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  472. const fields = await schemaFor('Special');
  473. let target;
  474. let currentSpecId = 0;
  475. if (objectId) {
  476. const query = new Parse.Query('Special'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  477. companyId = pointerId(target.get('company')) || companyId; currentSpecId = Number(target.get('specId')) || 0;
  478. } else target = new Parse.Object('Special');
  479. if (pid > 0) {
  480. const parent = await Psql.oneOrNone('SELECT "specId" FROM "Special" WHERE "company"=$1 AND "specId"=$2 LIMIT 1', [companyId, pid]);
  481. if (!parent) fail(404, '父专题不存在或不属于当前帐套');
  482. if (currentSpecId) {
  483. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "specId","pid",ARRAY["specId"::text] AS path FROM "Special" WHERE "company"=$1 AND "specId"=$2 UNION ALL SELECT s."specId",s."pid",chain.path||s."specId"::text FROM "Special" s JOIN chain ON s."specId"=chain."pid" WHERE s."company"=$1 AND NOT s."specId"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "specId"=$3 LIMIT 1', [companyId, pid, currentSpecId]);
  484. if (cycle) fail(409, '不能把专题移动到自身或其下级专题');
  485. }
  486. }
  487. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "Special" WHERE "company"=$1 AND "objectId"<>$2 AND (LOWER(TRIM(COALESCE("specName",\'\')))=LOWER($3) OR LOWER(TRIM(COALESCE("specDir",\'\')))=LOWER($4)) LIMIT 1', [companyId, objectId, specName, specDir]);
  488. if (duplicate) fail(409, '专题名称或目录不能重复');
  489. for (const [name, value] of Object.entries(payload)) {
  490. if (!fields[name] || isSystemField('Special', name)) continue;
  491. if (!GENERIC_WRITE_TYPES.has(fields[name].type)) fail(400, '字段不允许编辑: ' + name);
  492. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  493. }
  494. target.set('specName', specName); target.set('specDir', specDir); target.set('pid', pid); target.set('company', company); target.set('editDate', new Date());
  495. if (!objectId) { target.set('sourceKey', 'cloud:admin-special:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('openType', true); target.set('cdate', new Date()); target.set('cuser', String(context.current.get('username') || '')); }
  496. try { await target.save(null, { useMasterKey: true }); }
  497. catch (error) { fail(422, '专题初始写入失败: ' + String(error && error.message || error)); }
  498. try {
  499. if (!objectId) {
  500. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-special-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("specId"),0)+1 AS id FROM "Special",lock_row WHERE "company"=$1 AND COALESCE("specId",0)>0), next_order AS MATERIALIZED (SELECT COALESCE(MAX("orderId"),0)+1 AS id FROM "Special",lock_row WHERE "company"=$1 AND COALESCE("pid",0)=$3 AND "objectId"<>$2) UPDATE "Special" SET "specId"=next_id.id,"orderId"=next_order.id,"sourceKey"=\'[["SpecID",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id,next_order WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id, pid]);
  501. currentSpecId = Number(rows[0] && rows[0].id) || 0;
  502. if (!currentSpecId) throw new Error('无法分配专题编号');
  503. }
  504. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '专题结构写入失败: ' + String(error && error.message || error)); }
  505. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-special' : 'create-special', 'Special', target.id);
  506. return response.json({ success: true, data: serializeObject(target) });
  507. }
  508. if (operation === 'specialBatch') {
  509. const action = String(input.action || '');
  510. if (action === 'merge') fail(501, 'migration_blocked: CommonModel.specialId 仅存在于 Parse Schema、PostgreSQL 物理列缺失,且商品主表未迁移,无法安全合并专题关系');
  511. if (action !== 'move') fail(400, '不支持的专题批量操作');
  512. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  513. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  514. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个专题');
  515. const fields = await schemaFor('Special');
  516. const query = new Parse.Query('Special'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  517. const targets = await query.find({ useMasterKey: true });
  518. if (targets.length !== objectIds.length) fail(404, '部分专题不存在或不属于当前帐套');
  519. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  520. if (companyIds.length !== 1) fail(400, '批量操作的专题必须属于同一帐套');
  521. const companyId = companyIds[0];
  522. const specIds = targets.map((target) => Number(target.get('specId')) || 0);
  523. const pid = Number(input.pid);
  524. if (!Number.isInteger(pid) || pid < 0) fail(400, '目标父专题编号无效');
  525. if (pid > 0) {
  526. const parent = await Psql.oneOrNone('SELECT "specId" FROM "Special" WHERE "company"=$1 AND "specId"=$2 LIMIT 1', [companyId, pid]);
  527. if (!parent) fail(404, '目标父专题不存在或不属于当前帐套');
  528. for (const specId of specIds) {
  529. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "specId","pid",ARRAY["specId"::text] AS path FROM "Special" WHERE "company"=$1 AND "specId"=$2 UNION ALL SELECT s."specId",s."pid",chain.path||s."specId"::text FROM "Special" s JOIN chain ON s."specId"=chain."pid" WHERE s."company"=$1 AND NOT s."specId"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "specId"=$3 LIMIT 1', [companyId, pid, specId]);
  530. if (cycle) fail(409, '不能把专题移动到自身或其下级专题');
  531. }
  532. }
  533. for (const target of targets) { target.set('pid', pid); target.set('editDate', new Date()); }
  534. await Parse.Object.saveAll(targets, { useMasterKey: true });
  535. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'special-move', 'Special', target.id);
  536. return response.json({ success: true, data: { action, updated: targets.length, pid, results: targets.map(serializeObject) } });
  537. }
  538. if (operation === 'saveModelMetadata' || operation === 'saveModelFieldMetadata') {
  539. const className = operation === 'saveModelMetadata' ? 'Model' : 'ModelField';
  540. const objectId = String(input.objectId || '');
  541. if (!objectId) fail(501, 'migration_blocked: 新增模型或字段需要同步创建 PostgreSQL 物理表/列及旧模板文件,托管云函数中未开放此 DDL 流程');
  542. const fields = await schemaFor(className);
  543. const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  544. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  545. const allowed = className === 'Model'
  546. ? new Set(['modelName','itemName','itemUnit','itemIcon','description','islotsize','contentTemplate','thumbnail'])
  547. : new Set(['fieldAlias','fieldTips','description','isNotNull','isSearchForm','content','isShow','isView','showList','showWidth','isCopy','islotsize','isChain']);
  548. if (className === 'Model') {
  549. const modelName = String(payload.modelName == null ? target.get('modelName') || '' : payload.modelName).trim();
  550. if (!modelName || modelName.length > 100) fail(400, '模型名称长度应为 1 至 100 位');
  551. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "Model" WHERE "company"=$1 AND "objectId"<>$2 AND LOWER(TRIM(COALESCE("modelName",\'\')))=LOWER($3) LIMIT 1', [pointerId(target.get('company')), objectId, modelName]);
  552. if (duplicate) fail(409, '模型名称已存在');
  553. target.set('modelName', modelName);
  554. } else {
  555. const fieldAlias = String(payload.fieldAlias == null ? target.get('fieldAlias') || '' : payload.fieldAlias).trim();
  556. if (!fieldAlias || fieldAlias.length > 100) fail(400, '字段别名长度应为 1 至 100 位');
  557. target.set('fieldAlias', fieldAlias);
  558. }
  559. for (const [name, value] of Object.entries(payload)) {
  560. if (!allowed.has(name) || !fields[name]) continue;
  561. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  562. }
  563. await target.save(null, { useMasterKey: true }); await audit(context, className === 'Model' ? 'update-model-metadata' : 'update-model-field-metadata', className, objectId);
  564. return response.json({ success: true, data: serializeObject(target) });
  565. }
  566. if (operation === 'modelFieldOrder') {
  567. const items = Array.isArray(input.items) ? input.items : [];
  568. if (!items.length || items.length > 100) fail(400, '每次请提交 1 至 100 个字段顺序');
  569. const objectIds = items.map((item) => String(item && item.objectId || '').trim());
  570. const orderIds = items.map((item) => Number(item && item.orderId));
  571. if (objectIds.some((id) => !id) || new Set(objectIds).size !== objectIds.length || orderIds.some((id) => !Number.isInteger(id) || id < 0) || new Set(orderIds).size !== orderIds.length) fail(400, '字段或顺序参数无效/重复');
  572. const fields = await schemaFor('ModelField');
  573. const query = new Parse.Query('ModelField'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  574. const targets = await query.find({ useMasterKey: true });
  575. if (targets.length !== objectIds.length) fail(404, '部分模型字段不存在或不属于当前帐套');
  576. const modelIds = [...new Set(targets.map((target) => Number(target.get('modelId')) || 0))];
  577. if (modelIds.length !== 1) fail(400, '只能对同一模型的字段排序');
  578. const targetMap = new Map(targets.map((target) => [target.id, target]));
  579. for (const item of items) targetMap.get(String(item.objectId)).set('orderId', Number(item.orderId));
  580. await Parse.Object.saveAll(targets, { useMasterKey: true });
  581. for (const target of targets) await audit(context, 'order-model-field', 'ModelField', target.id);
  582. return response.json({ success: true, data: { updated: targets.length, modelId: modelIds[0], results: targets.map(serializeObject) } });
  583. }
  584. if (operation === 'saveGuestbook') {
  585. const objectId = String(input.objectId || '');
  586. if (!objectId) fail(400, '普通留言新增必须走前台留言云函数;后台只能通过专用回复流程新增');
  587. const fields = await schemaFor('Guestbook');
  588. const query = new Parse.Query('Guestbook'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  589. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  590. const title = String(payload.title == null ? target.get('title') || '' : payload.title).trim();
  591. const content = String(payload.tcontent == null ? target.get('tcontent') || '' : payload.tcontent);
  592. if (!title || title.length > 200) fail(400, '留言标题长度应为 1 至 200 位');
  593. if (content.length > 200000) fail(400, '留言内容过长');
  594. target.set('title', title); target.set('tcontent', content);
  595. await target.save(null, { useMasterKey: true }); await audit(context, 'update-guestbook', 'Guestbook', objectId);
  596. return response.json({ success: true, data: serializeObject(target) });
  597. }
  598. if (operation === 'guestbookReply') {
  599. const parentObjectId = String(input.parentObjectId || '');
  600. const title = String(input.title || '').trim() || '[管理员回复]';
  601. const content = String(input.content || '');
  602. if (!parentObjectId) fail(400, '缺少原留言');
  603. if (title.length > 200 || !content.trim() || content.length > 200000) fail(400, '回复标题或内容无效');
  604. const fields = await schemaFor('Guestbook');
  605. const query = new Parse.Query('Guestbook'); applyTenant(query, fields, context, input.companyId); const parent = await query.get(parentObjectId, { useMasterKey: true });
  606. const company = parent.get('company') || context.company; const companyId = pointerId(company); const parentGid = Number(parent.get('gid')) || 0; const cateid = Number(parent.get('cateid')) || 0;
  607. if (!companyId || !parentGid) fail(409, '原留言缺少帐套或旧系统编号');
  608. const reply = new Parse.Object('Guestbook');
  609. reply.set('sourceKey', 'cloud:admin-guestbook-reply:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); reply.set('company', company); reply.set('parentid', parentGid); reply.set('cateid', cateid); reply.set('userid', Number(context.current.get('legacyUserId')) || 0); reply.set('title', title); reply.set('tcontent', content); reply.set('status', 99); reply.set('gdate', new Date()); reply.set('ip', 'admin-cloud');
  610. try { await reply.save(null, { useMasterKey: true }); }
  611. catch (error) { fail(422, '管理员回复初始写入失败: ' + String(error && error.message || error)); }
  612. try {
  613. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-guestbook-gid:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("gid"),0)+1 AS id FROM "Guestbook",lock_row WHERE "company"=$1 AND COALESCE("gid",0)>0) UPDATE "Guestbook" SET "gid"=next_id.id,"sourceKey"=\'[["Gid",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, reply.id]);
  614. if (!Number(rows[0] && rows[0].id)) throw new Error('无法分配回复编号');
  615. } catch (error) { await reply.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '管理员回复结构写入失败: ' + String(error && error.message || error)); }
  616. await reply.fetch({ useMasterKey: true }); await audit({ ...context, company }, 'reply-guestbook', 'Guestbook', reply.id);
  617. return response.json({ success: true, data: serializeObject(reply) });
  618. }
  619. if (operation === 'guestbookBatch') {
  620. const action = String(input.action || '');
  621. if (!['audit','unaudit','recycle','recover','purge'].includes(action)) fail(400, '不支持的留言批量操作');
  622. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  623. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  624. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条留言');
  625. const fields = await schemaFor('Guestbook');
  626. const query = new Parse.Query('Guestbook'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  627. const targets = await query.find({ useMasterKey: true });
  628. if (targets.length !== objectIds.length) fail(404, '部分留言不存在或不属于当前帐套');
  629. if (action === 'purge') {
  630. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))]; const gids = targets.map((target) => Number(target.get('gid')) || 0);
  631. if (companyIds.length !== 1 || gids.some((gid) => gid < 1)) fail(409, '留言缺少有效帐套或编号');
  632. const children = await Psql.one('SELECT COUNT(*)::int AS count FROM "Guestbook" WHERE "company"=$1 AND "parentid"=ANY($2::numeric[]) AND NOT ("gid"=ANY($2::numeric[]))', [companyIds[0], gids]);
  633. if (Number(children.count) > 0) fail(409, '留言仍有回复,不能永久删除');
  634. await Parse.Object.destroyAll(targets, { useMasterKey: true });
  635. } else {
  636. const status = action === 'recycle' ? -2 : action === 'unaudit' ? 0 : 99;
  637. for (const target of targets) target.set('status', status);
  638. await Parse.Object.saveAll(targets, { useMasterKey: true });
  639. }
  640. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'guestbook-' + action, 'Guestbook', target.id);
  641. return response.json({ success: true, data: { action, updated: targets.length, results: action === 'purge' ? [] : targets.map(serializeObject) } });
  642. }
  643. if (operation === 'saveGuestCategory') {
  644. const objectId = String(input.objectId || '');
  645. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  646. const catename = String(payload.catename || '').trim();
  647. const parentId = Number(input.parentId == null ? payload.parentId || 0 : input.parentId);
  648. let gtype = Number(input.gtype == null ? payload.gtype || 0 : input.gtype);
  649. if (!catename || catename.length > 100) fail(400, '分类名称长度应为 1 至 100 位');
  650. if (!Number.isInteger(parentId) || parentId < 0 || ![0,1].includes(gtype)) fail(400, '分类类型或父分类编号无效');
  651. let companyId = pointerId(context.company);
  652. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  653. if (!companyId) fail(400, '分类必须指定帐套');
  654. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  655. const fields = await schemaFor('Guestcate');
  656. let target;
  657. let currentCateId = 0;
  658. if (objectId) {
  659. const query = new Parse.Query('Guestcate'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  660. companyId = pointerId(target.get('company')) || companyId; currentCateId = Number(target.get('cateid')) || 0; gtype = Number(target.get('gtype')) || 0;
  661. } else target = new Parse.Object('Guestcate');
  662. if (gtype === 0 && parentId !== 0) fail(400, '留言分类只能建立为顶级分类');
  663. if (parentId > 0) {
  664. const parent = await Psql.oneOrNone('SELECT "cateid" FROM "Guestcate" WHERE "company"=$1 AND "cateid"=$2 AND COALESCE("gtype",0)=$3 LIMIT 1', [companyId, parentId, gtype]);
  665. if (!parent) fail(404, '父分类不存在、类型不一致或不属于当前帐套');
  666. if (currentCateId) {
  667. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "cateid","parentId",ARRAY["cateid"::text] AS path FROM "Guestcate" WHERE "company"=$1 AND "cateid"=$2 UNION ALL SELECT c."cateid",c."parentId",chain.path||c."cateid"::text FROM "Guestcate" c JOIN chain ON c."cateid"=chain."parentId" WHERE c."company"=$1 AND NOT c."cateid"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "cateid"=$3 LIMIT 1', [companyId, parentId, currentCateId]);
  668. if (cycle) fail(409, '不能把分类移动到自身或其下级分类');
  669. }
  670. }
  671. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "Guestcate" WHERE "company"=$1 AND "objectId"<>$2 AND COALESCE("gtype",0)=$3 AND COALESCE("parentId",0)=$4 AND LOWER(TRIM(COALESCE("catename",\'\')))=LOWER($5) LIMIT 1', [companyId, objectId, gtype, parentId, catename]);
  672. if (duplicate) fail(409, '同一父分类下的分类名称不能重复');
  673. const allowed = new Set(['catename','desc','status','needLog','isShowUnaudit','postAuth','zipImgSize','barImage','barOwner','permibit','sendScore','replyScore','barInfo','isPlat']);
  674. for (const [name, value] of Object.entries(payload)) {
  675. if (!allowed.has(name) || !fields[name]) continue;
  676. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  677. }
  678. target.set('catename', catename); target.set('parentId', parentId); target.set('gtype', gtype); target.set('company', company);
  679. if (!objectId) { target.set('sourceKey', 'cloud:admin-guestcate:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); if (fields.status && payload.status == null) target.set('status', 1); }
  680. try { await target.save(null, { useMasterKey: true }); }
  681. catch (error) { fail(422, '分类初始写入失败: ' + String(error && error.message || error)); }
  682. try {
  683. if (!objectId) {
  684. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-guestcate-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("cateid"),0)+1 AS id FROM "Guestcate",lock_row WHERE "company"=$1 AND COALESCE("cateid",0)>0), next_order AS MATERIALIZED (SELECT COALESCE(MAX("orderId"),0)+1 AS id FROM "Guestcate",lock_row WHERE "company"=$1 AND COALESCE("gtype",0)=$3 AND COALESCE("parentId",0)=$4 AND "objectId"<>$2) UPDATE "Guestcate" SET "cateid"=next_id.id,"orderId"=next_order.id,"sourceKey"=\'[["Cateid",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id,next_order WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id, gtype, parentId]);
  685. currentCateId = Number(rows[0] && rows[0].id) || 0;
  686. if (!currentCateId) throw new Error('无法分配分类编号');
  687. }
  688. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '分类结构写入失败: ' + String(error && error.message || error)); }
  689. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-guest-category' : 'create-guest-category', 'Guestcate', target.id);
  690. return response.json({ success: true, data: serializeObject(target) });
  691. }
  692. if (operation === 'guestCategoryBatch') {
  693. const action = String(input.action || '');
  694. if (!['delete','recommend','unrecommend'].includes(action)) fail(400, '不支持的分类批量操作');
  695. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  696. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  697. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个分类');
  698. const fields = await schemaFor('Guestcate');
  699. const query = new Parse.Query('Guestcate'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  700. const targets = await query.find({ useMasterKey: true });
  701. if (targets.length !== objectIds.length) fail(404, '部分分类不存在或不属于当前帐套');
  702. if (action === 'delete') {
  703. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))]; const cateids = targets.map((target) => Number(target.get('cateid')) || 0);
  704. if (companyIds.length !== 1 || cateids.some((id) => id < 1)) fail(409, '分类缺少有效帐套或编号');
  705. const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "Guestcate" WHERE "company"=$1 AND "parentId"=ANY($2::numeric[]) AND NOT ("cateid"=ANY($2::numeric[]))) AS children,(SELECT COUNT(*)::int FROM "Guestbook" WHERE "company"=$1 AND "cateid"=ANY($2::numeric[])) AS messages,(SELECT COUNT(*)::int FROM "GuestBar" WHERE "company"=$1 AND "cateId"=ANY($2::numeric[])) AS posts', [companyIds[0], cateids]);
  706. if (Number(refs.children) || Number(refs.messages) || Number(refs.posts)) fail(409, '分类仍被下级分类、留言或帖子引用,不能删除');
  707. await Parse.Object.destroyAll(targets, { useMasterKey: true });
  708. } else {
  709. for (const target of targets) { if (Number(target.get('gtype')) !== 1) fail(400, '只有贴吧分类支持推荐'); target.set('barInfo', action === 'recommend' ? 'Recommend' : ''); }
  710. await Parse.Object.saveAll(targets, { useMasterKey: true });
  711. }
  712. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'guest-category-' + action, 'Guestcate', target.id);
  713. return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  714. }
  715. if (operation === 'barAuthorization') {
  716. fail(501, 'migration_blocked: 目标 Schema 缺少旧 ZL_Guest_BarAuth 用户版块权限关系(Uid、BarID、Look、Send、Reply),无法安全读取或保存逐用户浏览、发帖和回复权限');
  717. }
  718. if (operation === 'barMedal') {
  719. fail(501, 'migration_blocked: 目标 Schema 缺少旧 ZL_Guest_Medals 勋章及用户帖子授予关系,无法安全授予或撤销帖子勋章');
  720. }
  721. if (operation === 'saveDictionaryCategory') {
  722. const objectId = String(input.objectId || '');
  723. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  724. const categoryName = String(payload.categoryname || '').trim();
  725. const isUsed = payload.isused == null ? true : payload.isused === true || payload.isused === 'true';
  726. if (!categoryName || categoryName.length > 50) fail(400, '字典分类名称长度应为 1 至 50 位');
  727. let companyId = pointerId(context.company);
  728. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  729. if (!companyId) fail(400, '字典分类必须指定帐套');
  730. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  731. const fields = await schemaFor('Datadiccategory');
  732. let target;
  733. if (objectId) {
  734. const query = new Parse.Query('Datadiccategory'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  735. companyId = pointerId(target.get('company')) || companyId;
  736. } else target = new Parse.Object('Datadiccategory');
  737. const duplicateQuery = new Parse.Query('Datadiccategory'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000);
  738. const duplicates = await duplicateQuery.find({ useMasterKey: true });
  739. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('categoryname') || '').trim().toLowerCase() === categoryName.toLowerCase())) fail(409, '同一帐套的字典分类名称不能重复');
  740. target.set('categoryname', categoryName); target.set('isused', isUsed); target.set('company', company);
  741. if (objectId) {
  742. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '字典分类写入失败: ' + String(error && error.message || error)); }
  743. } else {
  744. let lastError;
  745. for (let attempt = 0; attempt < 5; attempt++) {
  746. const allCategories = new Parse.Query('Datadiccategory'); allCategories.limit(1000);
  747. const allItems = new Parse.Query('Datadic'); allItems.limit(1000);
  748. const [categoryRows, itemRows] = await Promise.all([allCategories.find({ useMasterKey: true }), allItems.find({ useMasterKey: true })]);
  749. const nextId = Math.max(0, ...categoryRows.map((entry) => Number(entry.get('diccateid')) || 0), ...itemRows.map((entry) => Number(entry.get('diccate')) || 0)) + 1;
  750. target.set('diccateid', nextId); target.set('sourceKey', '[["Diccateid",' + nextId + ']]');
  751. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  752. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  753. }
  754. if (lastError || !target.id) fail(422, '字典分类原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  755. }
  756. await audit({ ...context, company }, objectId ? 'update-dictionary-category' : 'create-dictionary-category', 'Datadiccategory', target.id);
  757. return response.json({ success: true, data: serializeObject(target) });
  758. }
  759. if (operation === 'saveDictionaryItem') {
  760. const objectId = String(input.objectId || '');
  761. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  762. const itemName = String(payload.dicname || '').trim();
  763. const categoryId = Number(input.categoryId == null ? payload.diccate || 0 : input.categoryId);
  764. const isUsed = payload.isused == null ? true : payload.isused === true || payload.isused === 'true';
  765. if (!itemName || itemName.length > 50) fail(400, '字典项名称长度应为 1 至 50 位');
  766. if (!Number.isInteger(categoryId) || categoryId < 1) fail(400, '请选择有效字典分类');
  767. let companyId = pointerId(context.company);
  768. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  769. if (!companyId) fail(400, '字典项必须指定帐套');
  770. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  771. const fields = await schemaFor('Datadic');
  772. let target;
  773. if (objectId) {
  774. const query = new Parse.Query('Datadic'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  775. companyId = pointerId(target.get('company')) || companyId;
  776. } else target = new Parse.Object('Datadic');
  777. const categoryFields = await schemaFor('Datadiccategory'); const categoryQuery = new Parse.Query('Datadiccategory'); applyTenant(categoryQuery, categoryFields, context, input.companyId); categoryQuery.equalTo('diccateid', categoryId);
  778. const category = await categoryQuery.first({ useMasterKey: true });
  779. if (!category || pointerId(category.get('company')) !== companyId) fail(404, '字典分类不存在或不属于当前帐套');
  780. const duplicateQuery = new Parse.Query('Datadic'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.equalTo('diccate', categoryId); duplicateQuery.limit(1000);
  781. const duplicates = await duplicateQuery.find({ useMasterKey: true });
  782. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('dicname') || '').trim().toLowerCase() === itemName.toLowerCase())) fail(409, '同一字典分类中的字典项名称不能重复');
  783. target.set('dicname', itemName); target.set('diccate', categoryId); target.set('isused', isUsed); target.set('company', company);
  784. if (objectId) {
  785. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '字典项写入失败: ' + String(error && error.message || error)); }
  786. } else {
  787. let lastError;
  788. for (let attempt = 0; attempt < 5; attempt++) {
  789. const allItems = new Parse.Query('Datadic'); allItems.limit(1000); const itemRows = await allItems.find({ useMasterKey: true });
  790. const nextId = Math.max(0, ...itemRows.map((entry) => Number(entry.get('dicid')) || 0)) + 1;
  791. target.set('dicid', nextId); target.set('sourceKey', '[["Dicid",' + nextId + ']]');
  792. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  793. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  794. }
  795. if (lastError || !target.id) fail(422, '字典项原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  796. }
  797. await audit({ ...context, company }, objectId ? 'update-dictionary-item' : 'create-dictionary-item', 'Datadic', target.id);
  798. return response.json({ success: true, data: serializeObject(target) });
  799. }
  800. if (operation === 'dictionaryCategories') {
  801. const fields = await schemaFor('Datadiccategory'); const query = new Parse.Query('Datadiccategory'); applyTenant(query, fields, context, input.companyId);
  802. if (input.enabledOnly === true) query.equalTo('isused', true);
  803. query.ascending('diccateid'); query.limit(1000);
  804. const results = await query.find({ useMasterKey: true });
  805. return response.json({ success: true, data: { results: results.map(serializeObject) } });
  806. }
  807. if (operation === 'dictionaryBatch') {
  808. const className = String(input.className || ''); const action = String(input.action || '');
  809. if (!['Datadiccategory','Datadic'].includes(className) || !['enable','disable','delete'].includes(action)) fail(400, '不支持的字典批量操作');
  810. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  811. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  812. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条字典记录');
  813. const fields = await schemaFor(className); const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  814. const targets = await query.find({ useMasterKey: true });
  815. if (targets.length !== objectIds.length) fail(404, '部分字典记录不存在或不属于当前帐套');
  816. if (action === 'delete' && className === 'Datadiccategory') {
  817. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))]; const categoryIds = targets.map((target) => Number(target.get('diccateid')) || 0);
  818. if (companyIds.length !== 1 || categoryIds.some((id) => id < 1)) fail(409, '字典分类缺少有效帐套或编号');
  819. const itemFields = await schemaFor('Datadic'); const refs = new Parse.Query('Datadic'); applyTenant(refs, itemFields, context, companyIds[0]); refs.containedIn('diccate', categoryIds);
  820. if (await refs.count({ useMasterKey: true })) fail(409, '字典分类仍有字典项,不能删除');
  821. }
  822. if (action === 'delete') await Parse.Object.destroyAll(targets, { useMasterKey: true });
  823. else { for (const target of targets) target.set('isused', action === 'enable'); await Parse.Object.saveAll(targets, { useMasterKey: true }); }
  824. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'dictionary-' + action, className, target.id);
  825. return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  826. }
  827. if (operation === 'saveGradeCategory') {
  828. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  829. const cateName = String(payload.cateName || '').trim(); const remark = String(payload.remark || '').trim();
  830. const aliases = String(payload.gradeField || '').split(/\r?\n|\|/).map((value) => value.trim()).filter(Boolean); const gradeField = aliases.join('|');
  831. if (!cateName || cateName.length > 50) fail(400, '多级字典分类名称长度应为 1 至 50 位');
  832. if (remark.length > 255) fail(400, '多级字典分类备注不能超过 255 位');
  833. if (aliases.length < 2 || gradeField.length > 500) fail(400, '层级别名至少填写 2 级,且总长度不能超过 500 位');
  834. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '多级字典分类必须指定帐套');
  835. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('GradeCate'); let target;
  836. if (objectId) { const query = new Parse.Query('GradeCate'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true }); companyId = pointerId(target.get('company')) || companyId; }
  837. else target = new Parse.Object('GradeCate');
  838. const duplicateQuery = new Parse.Query('GradeCate'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  839. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('cateName') || '').trim().toLowerCase() === cateName.toLowerCase())) fail(409, '同一帐套的多级字典分类名称不能重复');
  840. target.set('cateName', cateName); target.set('remark', remark); target.set('gradeField', gradeField); target.set('company', company);
  841. if (objectId) { try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '多级字典分类写入失败: ' + String(error && error.message || error)); } }
  842. else {
  843. let lastError;
  844. for (let attempt = 0; attempt < 5; attempt++) {
  845. const categories = new Parse.Query('GradeCate'); categories.limit(1000); const options = new Parse.Query('Grade'); options.limit(1000);
  846. const [categoryRows, optionRows] = await Promise.all([categories.find({ useMasterKey: true }), options.find({ useMasterKey: true })]);
  847. const nextId = Math.max(0, ...categoryRows.map((entry) => Number(entry.get('cateId')) || 0), ...optionRows.map((entry) => Number(entry.get('cate')) || 0)) + 1;
  848. target.set('cateId', nextId); target.set('sourceKey', '[["CateID",' + nextId + ']]');
  849. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  850. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  851. }
  852. if (lastError || !target.id) fail(422, '多级字典分类原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  853. }
  854. await audit({ ...context, company }, objectId ? 'update-grade-category' : 'create-grade-category', 'GradeCate', target.id);
  855. return response.json({ success: true, data: serializeObject(target) });
  856. }
  857. if (operation === 'saveGradeOption') {
  858. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; const gradeName = String(payload.gradeName || '').trim();
  859. if (!gradeName || gradeName.length > 50) fail(400, '多级字典选项名称长度应为 1 至 50 位');
  860. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '多级字典选项必须指定帐套');
  861. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('Grade'); let target; let categoryId; let parentId; let level;
  862. if (objectId) {
  863. const query = new Parse.Query('Grade'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true }); companyId = pointerId(target.get('company')) || companyId;
  864. categoryId = Number(target.get('cate')) || 0; parentId = Number(target.get('parentId')) || 0; level = Number(target.get('grade')) || 0;
  865. } else { target = new Parse.Object('Grade'); categoryId = Number(input.categoryId == null ? payload.cate || 0 : input.categoryId); parentId = Number(input.parentId == null ? payload.parentId || 0 : input.parentId); level = 1; }
  866. if (!Number.isInteger(categoryId) || categoryId < 1 || !Number.isInteger(parentId) || parentId < 0) fail(400, '多级字典分类或父选项编号无效');
  867. const categoryFields = await schemaFor('GradeCate'); const categoryQuery = new Parse.Query('GradeCate'); applyTenant(categoryQuery, categoryFields, context, input.companyId); categoryQuery.equalTo('cateId', categoryId); const category = await categoryQuery.first({ useMasterKey: true });
  868. if (!category || pointerId(category.get('company')) !== companyId) fail(404, '多级字典分类不存在或不属于当前帐套');
  869. const aliases = String(category.get('gradeField') || '').split('|').map((value) => value.trim()).filter(Boolean);
  870. if (!objectId && parentId > 0) { const parentQuery = new Parse.Query('Grade'); applyTenant(parentQuery, fields, context, input.companyId); parentQuery.equalTo('gradeId', parentId); const parent = await parentQuery.first({ useMasterKey: true }); if (!parent || Number(parent.get('cate')) !== categoryId || pointerId(parent.get('company')) !== companyId) fail(404, '父选项不存在、分类不一致或不属于当前帐套'); level = Number(parent.get('grade')) + 1; }
  871. if (!Number.isInteger(level) || level < 1 || level > aliases.length) fail(409, '当前层级已超过分类定义的层级别名');
  872. const duplicateQuery = new Parse.Query('Grade'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.equalTo('cate', categoryId); duplicateQuery.equalTo('parentId', parentId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  873. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('gradeName') || '').trim().toLowerCase() === gradeName.toLowerCase())) fail(409, '同一父级下的多级字典选项名称不能重复');
  874. target.set('gradeName', gradeName); target.set('cate', categoryId); target.set('parentId', parentId); target.set('grade', level); target.set('company', company);
  875. if (objectId) { try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '多级字典选项写入失败: ' + String(error && error.message || error)); } }
  876. else {
  877. let lastError;
  878. for (let attempt = 0; attempt < 5; attempt++) {
  879. const allOptions = new Parse.Query('Grade'); allOptions.limit(1000); const optionRows = await allOptions.find({ useMasterKey: true }); const nextId = Math.max(0, ...optionRows.map((entry) => Number(entry.get('gradeId')) || 0)) + 1;
  880. target.set('gradeId', nextId); target.set('sourceKey', '[["GradeID",' + nextId + ']]');
  881. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  882. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  883. }
  884. if (lastError || !target.id) fail(422, '多级字典选项原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  885. }
  886. await audit({ ...context, company }, objectId ? 'update-grade-option' : 'create-grade-option', 'Grade', target.id);
  887. return response.json({ success: true, data: serializeObject(target) });
  888. }
  889. if (operation === 'gradeCategories') {
  890. const fields = await schemaFor('GradeCate'); const query = new Parse.Query('GradeCate'); applyTenant(query, fields, context, input.companyId); query.ascending('cateId'); query.limit(1000); const results = await query.find({ useMasterKey: true });
  891. return response.json({ success: true, data: { results: results.map(serializeObject) } });
  892. }
  893. if (operation === 'gradeOptions') {
  894. const categoryId = Number(input.categoryId || 0); const parentId = input.parentId == null || input.parentId === '' ? -1 : Number(input.parentId); if (!Number.isInteger(categoryId) || categoryId < 1 || !Number.isInteger(parentId) || parentId < -1) fail(400, '多级字典筛选条件无效');
  895. const fields = await schemaFor('Grade'); const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const query = new Parse.Query('Grade'); applyTenant(query, fields, context, input.companyId); query.equalTo('cate', categoryId); if (parentId >= 0) query.equalTo('parentId', parentId);
  896. const search = String(input.search || '').trim(); if (search) query.matches('gradeName', escapeRegex(search), 'i'); const total = await query.count({ useMasterKey: true }); query.ascending('gradeId'); query.skip((page - 1) * pageSize); query.limit(pageSize); const results = await query.find({ useMasterKey: true });
  897. return response.json({ success: true, data: { className: 'Grade', page, pageSize, total, results: results.map(serializeObject) } });
  898. }
  899. if (operation === 'gradeBatch') {
  900. const className = String(input.className || ''); if (!['GradeCate','Grade'].includes(className) || String(input.action || '') !== 'delete') fail(400, '不支持的多级字典批量操作');
  901. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条多级字典记录');
  902. const fields = await schemaFor(className); const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分多级字典记录不存在或不属于当前帐套');
  903. if (className === 'GradeCate') { const ids = targets.map((target) => Number(target.get('cateId')) || 0); const optionFields = await schemaFor('Grade'); const refs = new Parse.Query('Grade'); applyTenant(refs, optionFields, context, input.companyId); refs.containedIn('cate', ids); if (await refs.count({ useMasterKey: true })) fail(409, '多级字典分类仍有选项,不能删除'); }
  904. else { const ids = targets.map((target) => Number(target.get('gradeId')) || 0); const refs = new Parse.Query('Grade'); applyTenant(refs, fields, context, input.companyId); refs.containedIn('parentId', ids); if (await refs.count({ useMasterKey: true })) fail(409, '多级字典选项仍有下级选项,不能删除'); }
  905. await Parse.Object.destroyAll(targets, { useMasterKey: true }); for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'grade-delete', className, target.id);
  906. return response.json({ success: true, data: { action: 'delete', updated: targets.length, results: [] } });
  907. }
  908. if (operation === 'saveCurrency') {
  909. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  910. const title = String(payload.title || '').trim(); const currencyName = String(payload.currencyName || '').trim().toUpperCase(); const currencySymbol = String(payload.currencySymbol || '').trim(); const exchange = Number(payload.currentExchange); const remark = String(payload.remark || '').trim();
  911. if (!title || title.length > 50) fail(400, '货币名称长度应为 1 至 50 位');
  912. if (!/^[A-Z][A-Z0-9]{1,9}$/.test(currencyName)) fail(400, '货币代码应为 2 至 10 位大写字母或数字');
  913. if (!currencySymbol || currencySymbol.length > 16) fail(400, '货币符号长度应为 1 至 16 位');
  914. if (!Number.isFinite(exchange) || exchange <= 0 || exchange > 1000000000) fail(400, '当前汇率必须是大于 0 的有效数字');
  915. if (remark.length > 255) fail(400, '货币备注不能超过 255 位');
  916. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '货币必须指定帐套');
  917. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('Currency'); let target;
  918. if (!objectId) fail(501, 'migration_blocked: Currency.id 与 Parse 对象保留 id 冲突,且 PostgreSQL 物理表缺少可写旧 ID 列,不能安全新增货币');
  919. { const query = new Parse.Query('Currency'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true }); companyId = pointerId(target.get('company')) || companyId; }
  920. const duplicateQuery = new Parse.Query('Currency'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  921. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('title') || '').trim().toLowerCase() === title.toLowerCase())) fail(409, '同一帐套的货币名称不能重复');
  922. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('currencyName') || '').trim().toUpperCase() === currencyName)) fail(409, '同一帐套的货币代码不能重复');
  923. target.set('title', title); target.set('currencyName', currencyName); target.set('currencySymbol', currencySymbol); target.set('currentExchange', exchange); target.set('remark', remark); target.set('company', company);
  924. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '货币写入失败: ' + String(error && error.message || error)); }
  925. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-currency' : 'create-currency', 'Currency', target.id); return response.json({ success: true, data: serializeObject(target) });
  926. }
  927. if (operation === 'currencyBatch') {
  928. if (String(input.className || '') !== 'Currency' || String(input.action || '') !== 'delete') fail(400, '不支持的货币批量操作'); const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条货币记录');
  929. const fields = await schemaFor('Currency'); const query = new Parse.Query('Currency'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分货币记录不存在或不属于当前帐套'); await Parse.Object.destroyAll(targets, { useMasterKey: true }); for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'currency-delete', 'Currency', target.id); return response.json({ success: true, data: { action: 'delete', updated: targets.length, results: [] } });
  930. }
  931. if (operation === 'saveHoliday') {
  932. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  933. if (!objectId) fail(501, 'migration_blocked: SysHoliday.id 与 Parse 对象保留 id 冲突,且 PostgreSQL 物理表缺少可写旧 ID 列,不能安全新增节假日');
  934. const name = String(payload.name || '').trim(); const htype = String(payload.htype || '').trim(); const hdate = String(payload.hdate || '').trim();
  935. const hdateStart = Number(payload.hdateStart); const hdateEnd = Number(payload.hdateEnd); const zstatus = Number(payload.zstatus);
  936. const strings = { ztype: String(payload.ztype || '').trim(), himage: String(payload.himage || '').trim(), remind: String(payload.remind || '').trim(), heffect: String(payload.heffect || '').trim(), hcontent: String(payload.hcontent || '').trim() };
  937. if (!name || name.length > 100) fail(400, '节假日名称长度应为 1 至 100 位');
  938. if (!['公历','农历'].includes(htype)) fail(400, '节假日类型只能是公历或农历');
  939. if (!/^(0[1-9]|1[0-2])月(0[1-9]|[12][0-9]|3[01])日$/.test(hdate)) fail(400, '节假日日期必须使用 MM月DD日 格式');
  940. if (!Number.isInteger(hdateStart) || hdateStart < 0 || hdateStart > 365 || !Number.isInteger(hdateEnd) || hdateEnd < 0 || hdateEnd > 365) fail(400, '提前与延后影响天数必须是 0 至 365 的整数');
  941. if (![0,99].includes(zstatus)) fail(400, '节假日状态只能是停用或启用');
  942. if (strings.ztype.length > 100 || strings.himage.length > 500 || strings.remind.length > 1000 || strings.heffect.length > 500 || strings.hcontent.length > 4000) fail(400, '节假日文本字段超过允许长度');
  943. const fields = await schemaFor('SysHoliday'); const query = new Parse.Query('SysHoliday'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  944. const duplicateQuery = new Parse.Query('SysHoliday'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  945. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('name') || '').trim().toLowerCase() === name.toLowerCase() && String(entry.get('htype') || '') === htype && String(entry.get('hdate') || '') === hdate)) fail(409, '同一帐套的节假日名称、类型和日期不能完全重复');
  946. target.set('name', name); target.set('htype', htype); target.set('hdate', hdate); target.set('hdateStart', hdateStart); target.set('hdateEnd', hdateEnd); target.set('zstatus', zstatus);
  947. for (const [field, value] of Object.entries(strings)) target.set(field, value);
  948. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '节假日写入失败: ' + String(error && error.message || error)); }
  949. await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-holiday', 'SysHoliday', target.id); return response.json({ success: true, data: serializeObject(target) });
  950. }
  951. if (operation === 'holidayBatch') {
  952. if (String(input.className || '') !== 'SysHoliday' || String(input.action || '') !== 'delete') fail(400, '不支持的节假日批量操作'); const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条节假日记录');
  953. const fields = await schemaFor('SysHoliday'); const query = new Parse.Query('SysHoliday'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分节假日记录不存在或不属于当前帐套'); await Parse.Object.destroyAll(targets, { useMasterKey: true }); for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'holiday-delete', 'SysHoliday', target.id); return response.json({ success: true, data: { action: 'delete', updated: targets.length, results: [] } });
  954. }
  955. if (operation === 'searchNavigations') {
  956. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const type = Number(input.type == null ? 1 : input.type); const state = Number(input.state == null ? -100 : input.state); const elite = Number(input.elite == null ? -100 : input.elite);
  957. if (![1,2].includes(type) || ![-100,1,2].includes(state) || ![-100,0,1].includes(elite)) fail(400, '快捷入口筛选条件无效');
  958. const fields = await schemaFor('Search'); const query = new Parse.Query('Search'); applyTenant(query, fields, context, input.companyId); query.limit(1000); const search = String(input.search || '').trim().toLowerCase();
  959. let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => Number(entry.get('type')) === type && (state === -100 || Number(entry.get('state')) === state) && (elite === -100 || (elite === 1 ? Number(entry.get('eliteLevel')) > 0 : Number(entry.get('eliteLevel')) === 0)) && (!search || String(entry.get('name') || '').toLowerCase().includes(search) || String(entry.get('fileUrl') || '').toLowerCase().includes(search)));
  960. results.sort((left, right) => Number(left.get('orderId') || 0) - Number(right.get('orderId') || 0) || Number(left.get('id') || 0) - Number(right.get('id') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize);
  961. return response.json({ success: true, data: { className: 'Search', page, pageSize, total, results: results.map(serializeObject) } });
  962. }
  963. if (operation === 'saveSearchNavigation') {
  964. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  965. if (!objectId) fail(501, 'migration_blocked: Search.id 与 Parse 对象保留 id 冲突,且 PostgreSQL 物理表缺少可写旧 ID 列,不能安全新增快捷入口');
  966. const name = String(payload.name || '').trim(); const fileUrl = String(payload.fileUrl || '').trim(); const ico = String(payload.ico || '').trim(); const bkcolor = String(payload.bkcolor || '').trim(); const userGroup = String(payload.userGroup || '').trim();
  967. const openType = Number(payload.openType); const mobile = Number(payload.mobile); const size = Number(payload.size); const eliteLevel = Number(payload.eliteLevel);
  968. if (!name || name.length > 100) fail(400, '快捷入口名称长度应为 1 至 100 位');
  969. if (!fileUrl || fileUrl.length > 500 || !fileUrl.startsWith('/') || fileUrl.startsWith('//') || /^[a-z]+:/i.test(fileUrl)) fail(400, '快捷入口地址必须是 1 至 500 位的站内路径');
  970. if (ico.length > 100 || (bkcolor && !/^#[0-9a-f]{6}$/i.test(bkcolor))) fail(400, '图标或背景颜色格式无效');
  971. if (![0,1].includes(openType) || ![0,1].includes(mobile) || !Number.isInteger(size) || size < 1 || size > 4 || !Number.isInteger(eliteLevel) || eliteLevel < 0 || eliteLevel > 10) fail(400, '快捷入口展示参数无效');
  972. if (userGroup && !/^\d+(,\d+)*$/.test(userGroup)) fail(400, '用户组必须使用逗号分隔的正整数 ID');
  973. const fields = await schemaFor('Search'); const query = new Parse.Query('Search'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  974. target.set('name', name); target.set('fileUrl', fileUrl); target.set('ico', ico); target.set('openType', openType); target.set('mobile', mobile); target.set('size', size); target.set('bkcolor', bkcolor); target.set('userGroup', userGroup); target.set('eliteLevel', eliteLevel);
  975. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '快捷入口写入失败: ' + String(error && error.message || error)); }
  976. await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-search-navigation', 'Search', target.id); return response.json({ success: true, data: serializeObject(target) });
  977. }
  978. if (operation === 'searchNavigationBatch') {
  979. if (String(input.className || '') !== 'Search') fail(400, '只能处理快捷入口'); const action = String(input.action || '');
  980. if (action === 'starturl') fail(501, 'migration_blocked: 目标云函数架构没有旧 SiteConfig.SiteOption.Admin_StartUrl 持久层,不能伪造全局后台起始页');
  981. if (!['enable','disable','elite','unelite','delete','order'].includes(action)) fail(400, '不支持的快捷入口批量操作');
  982. let requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; let orders = [];
  983. if (action === 'order') { orders = Array.isArray(input.orders) ? input.orders.map((entry) => ({ objectId: String(entry && entry.objectId || '').trim(), orderId: Number(entry && entry.orderId) })) : []; if (!orders.length || orders.length > 100 || orders.some((entry) => !entry.objectId || !Number.isInteger(entry.orderId) || entry.orderId < 1 || entry.orderId > 1000000)) fail(400, '排序必须包含 1 至 100 条有效入口及正整数顺序'); requestedIds = orders.map((entry) => entry.objectId); }
  984. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100 || (action === 'order' && objectIds.length !== orders.length)) fail(400, '每次请选择 1 至 100 条唯一快捷入口');
  985. const fields = await schemaFor('Search'); const query = new Parse.Query('Search'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分快捷入口不存在或不属于当前帐套');
  986. if (action === 'delete') await Parse.Object.destroyAll(targets, { useMasterKey: true });
  987. else { const orderMap = new Map(orders.map((entry) => [entry.objectId, entry.orderId])); for (const target of targets) { if (action === 'enable') target.set('state', 1); else if (action === 'disable') target.set('state', 2); else if (action === 'elite') target.set('eliteLevel', 1); else if (action === 'unelite') target.set('eliteLevel', 0); else target.set('orderId', orderMap.get(target.id)); } await Parse.Object.saveAll(targets, { useMasterKey: true }); }
  988. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'search-navigation-' + action, 'Search', target.id); return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  989. }
  990. if (operation === 'adZones') {
  991. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(1000, Math.max(1, Number(input.pageSize) || 20)); const status = Number(input.status == null ? -100 : input.status); const type = String(input.type || '').trim(); const search = String(input.search || '').trim().toLowerCase();
  992. if (![-100,0,99].includes(status) || type.length > 50 || search.length > 100) fail(400, '广告位筛选条件无效');
  993. const fields = await schemaFor('AdZone'); const query = new Parse.Query('AdZone'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true });
  994. results = results.filter((entry) => (status === -100 || Number(entry.get('zstatus')) === status) && (!type || String(entry.get('ztype') || '') === type) && (!search || [entry.get('name'),entry.get('remind'),entry.get('ztype')].some((value) => String(value || '').toLowerCase().includes(search))));
  995. results.sort((left, right) => Number(left.get('id') || 0) - Number(right.get('id') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize);
  996. return response.json({ success: true, data: { className: 'AdZone', page, pageSize, total, results: results.map(serializeObject) } });
  997. }
  998. if (operation === 'adInfos') {
  999. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const status = Number(input.status == null ? -100 : input.status); const zoneId = String(input.zoneId || '').trim(); const search = String(input.search || '').trim().toLowerCase();
  1000. if (![-100,0,99].includes(status) || (zoneId && !/^\d+$/.test(zoneId)) || search.length > 100) fail(400, '广告内容筛选条件无效');
  1001. const fields = await schemaFor('AdInfo'); const query = new Parse.Query('AdInfo'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true });
  1002. results = results.filter((entry) => (status === -100 || Number(entry.get('zstatus')) === status) && (!zoneId || String(entry.get('zoneId') || '') === zoneId) && (!search || [entry.get('name'),entry.get('linkUrl'),entry.get('text'),entry.get('remind')].some((value) => String(value || '').toLowerCase().includes(search))));
  1003. results.sort((left, right) => Number(left.get('id') || 0) - Number(right.get('id') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize);
  1004. return response.json({ success: true, data: { className: 'AdInfo', page, pageSize, total, results: results.map(serializeObject) } });
  1005. }
  1006. if (operation === 'saveAdZone') {
  1007. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1008. if (!objectId) fail(501, 'migration_blocked: AdZone.id 与 Parse 对象保留 id 冲突,且省略 id 创建不会生成旧广告位编号,不能安全新增广告位');
  1009. const name = String(payload.name || '').trim(); const remind = String(payload.remind || '').trim(); const ztype = String(payload.ztype || '').trim(); const showType = String(payload.showType || '').trim(); const zstatus = Number(payload.zstatus);
  1010. if (!name || name.length > 100 || remind.length > 2000 || !ztype || ztype.length > 50 || !showType || showType.length > 50 || ![0,99].includes(zstatus)) fail(400, '广告位名称、类型、展示方式、状态或备注无效');
  1011. const fields = await schemaFor('AdZone'); const query = new Parse.Query('AdZone'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  1012. target.set('name', name); target.set('remind', remind); target.set('ztype', ztype); target.set('showType', showType); target.set('zstatus', zstatus); const adminId = Number(context.current.get('legacyUserId')) || 0; if (adminId) target.set('cadmin', adminId);
  1013. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '广告位写入失败: ' + String(error && error.message || error)); }
  1014. await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-ad-zone', 'AdZone', target.id); return response.json({ success: true, data: serializeObject(target) });
  1015. }
  1016. if (operation === 'saveAdInfo') {
  1017. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1018. if (!objectId) fail(501, 'migration_blocked: AdInfo.id 与 Parse 对象保留 id 冲突,且省略 id 创建不会生成旧广告编号,不能安全新增广告内容');
  1019. const name = String(payload.name || '').trim(); const zoneId = String(input.zoneId == null ? payload.zoneId || '' : input.zoneId).trim(); const hasPriority = Object.prototype.hasOwnProperty.call(payload, 'priority'); const priority = hasPriority ? Number(payload.priority) : 0; const zstatus = Number(payload.zstatus);
  1020. const valueOfDate = (value) => value && typeof value === 'object' && value.iso ? value.iso : value; const sdate = new Date(valueOfDate(payload.sdate)); const edate = new Date(valueOfDate(payload.edate));
  1021. const strings = { linkUrl: String(payload.linkUrl || '').trim(), text: String(payload.text || ''), html: String(payload.html || ''), images: String(payload.images || '').trim(), image: String(payload.image || '').trim(), remind: String(payload.remind || '').trim(), style: String(payload.style || '') };
  1022. if (!name || name.length > 100 || !/^\d+$/.test(zoneId) || (hasPriority && (String(payload.priority).trim() === '' || !Number.isInteger(priority) || priority < 0 || priority > 1000000)) || ![0,99].includes(zstatus)) fail(400, '广告名称、广告位、权重或状态无效');
  1023. if (Number.isNaN(sdate.getTime()) || Number.isNaN(edate.getTime()) || edate < sdate) fail(400, '广告到期时间必须大于或等于开始时间');
  1024. if (strings.linkUrl.length > 2000 || strings.text.length > 20000 || strings.html.length > 200000 || strings.images.length > 10000 || strings.image.length > 2000 || strings.remind.length > 2000 || strings.style.length > 10000) fail(400, '广告内容字段超过允许长度');
  1025. const zoneFields = await schemaFor('AdZone'); const zoneQuery = new Parse.Query('AdZone'); applyTenant(zoneQuery, zoneFields, context, input.companyId); zoneQuery.limit(1000); const zones = await zoneQuery.find({ useMasterKey: true }); if (!zones.some((entry) => String(entry.get('id') || '') === zoneId)) fail(404, '目标广告位不存在或不属于当前帐套');
  1026. const fields = await schemaFor('AdInfo'); const query = new Parse.Query('AdInfo'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  1027. target.set('name', name); target.set('zoneId', zoneId); if (hasPriority) target.set('priority', String(priority)); target.set('zstatus', zstatus); target.set('sdate', sdate); target.set('edate', edate); for (const [field, value] of Object.entries(strings)) if (Object.prototype.hasOwnProperty.call(payload, field)) target.set(field, value);
  1028. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '广告内容写入失败: ' + String(error && error.message || error)); }
  1029. await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-ad-info', 'AdInfo', target.id); return response.json({ success: true, data: serializeObject(target) });
  1030. }
  1031. if (operation === 'adZoneBatch') {
  1032. if (String(input.className || '') !== 'AdZone') fail(400, '只能处理广告位'); const action = String(input.action || ''); if (!['active','pause','delete'].includes(action)) fail(400, '不支持的广告位批量操作');
  1033. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个广告位');
  1034. const fields = await schemaFor('AdZone'); const query = new Parse.Query('AdZone'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分广告位不存在或不属于当前帐套');
  1035. if (action === 'delete') { const zoneIds = new Set(targets.map((target) => String(target.get('id') || ''))); const infoFields = await schemaFor('AdInfo'); const refsQuery = new Parse.Query('AdInfo'); applyTenant(refsQuery, infoFields, context, input.companyId); refsQuery.limit(1000); const refs = await refsQuery.find({ useMasterKey: true }); if (refs.length >= 1000) fail(409, '广告内容数量超过安全核验上限,不能删除广告位'); if (refs.some((entry) => zoneIds.has(String(entry.get('zoneId') || '')))) fail(409, '广告位仍有关联广告内容,不能删除'); await Parse.Object.destroyAll(targets, { useMasterKey: true }); }
  1036. else { for (const target of targets) target.set('zstatus', action === 'active' ? 99 : 0); await Parse.Object.saveAll(targets, { useMasterKey: true }); }
  1037. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'ad-zone-' + action, 'AdZone', target.id); return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  1038. }
  1039. if (operation === 'adInfoBatch') {
  1040. if (String(input.className || '') !== 'AdInfo') fail(400, '只能处理广告内容'); const action = String(input.action || ''); if (!['audit','unaudit','delete'].includes(action)) fail(400, '不支持的广告内容批量操作');
  1041. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条广告内容');
  1042. const fields = await schemaFor('AdInfo'); const query = new Parse.Query('AdInfo'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分广告内容不存在或不属于当前帐套');
  1043. if (action === 'delete') await Parse.Object.destroyAll(targets, { useMasterKey: true }); else { for (const target of targets) target.set('zstatus', action === 'audit' ? 99 : 0); await Parse.Object.saveAll(targets, { useMasterKey: true }); }
  1044. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'ad-info-' + action, 'AdInfo', target.id); return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  1045. }
  1046. if (operation === 'adPreview') {
  1047. const objectId = String(input.zoneObjectId || ''); if (!objectId) fail(400, '缺少广告位 objectId'); const zoneFields = await schemaFor('AdZone'); const zoneQuery = new Parse.Query('AdZone'); applyTenant(zoneQuery, zoneFields, context, input.companyId); const zone = await zoneQuery.get(objectId, { useMasterKey: true }); const zoneId = String(zone.get('id') || '');
  1048. const infoFields = await schemaFor('AdInfo'); const infoQuery = new Parse.Query('AdInfo'); applyTenant(infoQuery, infoFields, context, input.companyId); infoQuery.limit(1000); const now = Date.now(); let results = await infoQuery.find({ useMasterKey: true }); results = results.filter((entry) => String(entry.get('zoneId') || '') === zoneId && Number(entry.get('zstatus')) === 99 && (!entry.get('sdate') || new Date(entry.get('sdate')).getTime() <= now) && (!entry.get('edate') || new Date(entry.get('edate')).getTime() >= now)); results.sort((left, right) => Number(right.get('priority') || 0) - Number(left.get('priority') || 0) || Number(left.get('id') || 0) - Number(right.get('id') || 0));
  1049. return response.json({ success: true, data: { zone: serializeObject(zone), total: results.length, results: results.map(serializeObject) } });
  1050. }
  1051. if (operation === 'saveExamClass') {
  1052. const objectId = String(input.objectId || '');
  1053. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1054. const className = String(payload.cClassName || '').trim();
  1055. const parentId = Number(input.parentId == null ? payload.cClassid || 0 : input.parentId);
  1056. const classType = Number(input.classType == null ? payload.cClassType || 1 : input.classType);
  1057. const orderId = Number(input.orderId == null ? payload.cOrderBy || 0 : input.orderId);
  1058. if (!className || className.length > 255) fail(400, '试题分类名称长度应为 1 至 255 位');
  1059. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父试题分类编号无效');
  1060. if (![1,2].includes(classType)) fail(400, '试题分类类型只能是答题类型或视频操作类型');
  1061. if (!Number.isInteger(orderId) || orderId < 0) fail(400, '试题分类排序必须是非负整数');
  1062. let companyId = pointerId(context.company);
  1063. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  1064. if (!companyId) fail(400, '试题分类必须指定帐套');
  1065. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1066. const fields = await schemaFor('ExamClass');
  1067. let target;
  1068. let currentId = 0;
  1069. if (objectId) {
  1070. const query = new Parse.Query('ExamClass'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  1071. companyId = pointerId(target.get('company')) || companyId; currentId = Number(target.get('cId')) || 0;
  1072. } else target = new Parse.Object('ExamClass');
  1073. if (parentId > 0) {
  1074. const parent = await Psql.oneOrNone('SELECT "cId" FROM "ExamClass" WHERE "company"=$1 AND "cId"=$2 LIMIT 1', [companyId, parentId]);
  1075. if (!parent) fail(404, '父试题分类不存在或不属于当前帐套');
  1076. if (currentId) {
  1077. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "cId","cClassid",ARRAY["cId"::text] AS path FROM "ExamClass" WHERE "company"=$1 AND "cId"=$2 UNION ALL SELECT c."cId",c."cClassid",chain.path||c."cId"::text FROM "ExamClass" c JOIN chain ON c."cId"=chain."cClassid" WHERE c."company"=$1 AND NOT c."cId"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "cId"=$3 LIMIT 1', [companyId, parentId, currentId]);
  1078. if (cycle) fail(409, '不能把试题分类移动到自身或其下级分类');
  1079. }
  1080. }
  1081. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "ExamClass" WHERE "company"=$1 AND "objectId"<>$2 AND LOWER(TRIM(COALESCE("cClassName",\'\')))=LOWER($3) LIMIT 1', [companyId, objectId, className]);
  1082. if (duplicate) fail(409, '同一帐套的试题分类名称不能重复');
  1083. target.set('cClassName', className); target.set('cClassid', parentId); target.set('cClassType', classType); target.set('company', company);
  1084. if (objectId) target.set('cOrderBy', orderId); else target.set('sourceKey', 'cloud:admin-exam-class:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10));
  1085. try { await target.save(null, { useMasterKey: true }); }
  1086. catch (error) { fail(422, '试题分类初始写入失败: ' + String(error && error.message || error)); }
  1087. try {
  1088. if (!objectId) {
  1089. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-exam-class-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("cId"),0)+1 AS id FROM "ExamClass",lock_row WHERE "company"=$1 AND COALESCE("cId",0)>0), next_order AS MATERIALIZED (SELECT COALESCE(MAX("cOrderBy"),0)+1 AS id FROM "ExamClass",lock_row WHERE "company"=$1 AND "objectId"<>$2) UPDATE "ExamClass" SET "cId"=next_id.id,"cOrderBy"=CASE WHEN $3>0 THEN $3 ELSE next_order.id END,"sourceKey"=\'[["C_id",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id,next_order WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id, orderId]);
  1090. currentId = Number(rows[0] && rows[0].id) || 0;
  1091. if (!currentId) throw new Error('无法分配试题分类编号');
  1092. }
  1093. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '试题分类结构写入失败: ' + String(error && error.message || error)); }
  1094. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-exam-class' : 'create-exam-class', 'ExamClass', target.id);
  1095. return response.json({ success: true, data: serializeObject(target) });
  1096. }
  1097. if (operation === 'examClassChildren') {
  1098. const parentId = Number(input.parentId || 0);
  1099. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父试题分类编号无效');
  1100. const fields = await schemaFor('ExamClass'); const query = new Parse.Query('ExamClass'); applyTenant(query, fields, context, input.companyId); query.equalTo('cClassid', parentId); query.ascending('cOrderBy'); query.limit(1000);
  1101. const results = await query.find({ useMasterKey: true });
  1102. return response.json({ success: true, data: { parentId, results: results.map(serializeObject) } });
  1103. }
  1104. if (operation === 'saveExamPoint') {
  1105. const objectId = String(input.objectId || '');
  1106. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1107. const pointName = String(payload.testPoint || '').trim();
  1108. const parentId = Number(input.parentId == null ? payload.tid || 0 : input.parentId);
  1109. const orderId = Number(input.orderId == null ? payload.orderBy || 0 : input.orderId);
  1110. if (!pointName || pointName.length > 50) fail(400, '考点名称长度应为 1 至 50 位');
  1111. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '上级考点编号无效');
  1112. if (!Number.isInteger(orderId) || orderId < 0) fail(400, '考点排序必须是非负整数');
  1113. let companyId = pointerId(context.company);
  1114. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  1115. if (!companyId) fail(400, '考点必须指定帐套');
  1116. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1117. const fields = await schemaFor('ExamPoint');
  1118. let target;
  1119. let currentId = 0;
  1120. if (objectId) {
  1121. const query = new Parse.Query('ExamPoint'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  1122. companyId = pointerId(target.get('company')) || companyId; currentId = Number(target.get('id')) || 0;
  1123. } else target = new Parse.Object('ExamPoint');
  1124. if (parentId > 0) {
  1125. const parent = await Psql.oneOrNone('SELECT "id" FROM "ExamPoint" WHERE "company"=$1 AND "id"=$2 LIMIT 1', [companyId, parentId]);
  1126. if (!parent) fail(404, '上级考点不存在或不属于当前帐套');
  1127. if (currentId) {
  1128. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "id","tid",ARRAY["id"::text] AS path FROM "ExamPoint" WHERE "company"=$1 AND "id"=$2 UNION ALL SELECT p."id",p."tid",chain.path||p."id"::text FROM "ExamPoint" p JOIN chain ON p."id"=chain."tid" WHERE p."company"=$1 AND NOT p."id"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "id"=$3 LIMIT 1', [companyId, parentId, currentId]);
  1129. if (cycle) fail(409, '不能把考点移动到自身或其下级考点');
  1130. }
  1131. }
  1132. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "ExamPoint" WHERE "company"=$1 AND "objectId"<>$2 AND LOWER(TRIM(COALESCE("testPoint",\'\')))=LOWER($3) LIMIT 1', [companyId, objectId, pointName]);
  1133. if (duplicate) fail(409, '同一帐套的考点名称不能重复');
  1134. target.set('testPoint', pointName); target.set('tid', parentId); target.set('company', company);
  1135. if (objectId) target.set('orderBy', orderId);
  1136. else { target.set('sourceKey', 'cloud:admin-exam-point:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('addUser', Number(context.current.get('legacyUserId')) || 0); target.set('addTime', new Date()); }
  1137. try { await target.save(null, { useMasterKey: true }); }
  1138. catch (error) { fail(422, '考点初始写入失败: ' + String(error && error.message || error)); }
  1139. try {
  1140. if (!objectId) {
  1141. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-exam-point-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("id"),0)+1 AS id FROM "ExamPoint",lock_row WHERE "company"=$1 AND COALESCE("id",0)>0), next_order AS MATERIALIZED (SELECT COALESCE(MAX("orderBy"),0)+1 AS id FROM "ExamPoint",lock_row WHERE "company"=$1 AND "objectId"<>$2) UPDATE "ExamPoint" SET "id"=next_id.id,"orderBy"=CASE WHEN $3>0 THEN $3 ELSE next_order.id END,"sourceKey"=\'[["ID",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id,next_order WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id, orderId]);
  1142. currentId = Number(rows[0] && rows[0].id) || 0;
  1143. if (!currentId) throw new Error('无法分配考点编号');
  1144. }
  1145. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '考点结构写入失败: ' + String(error && error.message || error)); }
  1146. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-exam-point' : 'create-exam-point', 'ExamPoint', target.id);
  1147. return response.json({ success: true, data: serializeObject(target) });
  1148. }
  1149. if (operation === 'saveKnowledge') {
  1150. const objectId = String(input.objectId || '');
  1151. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1152. const knowledgeName = String(payload.kName || '').trim();
  1153. const classId = Number(input.classId == null ? payload.kClassId || 0 : input.classId);
  1154. const parentId = Number(input.parentId == null ? payload.pid || 0 : input.parentId);
  1155. const orderId = Number(input.orderId == null ? payload.kOrderBy || 0 : input.orderId);
  1156. const status = Number(payload.status == null ? 1 : payload.status);
  1157. const grade = Number(payload.grade || 0);
  1158. const isSys = Number(payload.isSys || 0);
  1159. if (!knowledgeName || knowledgeName.length > 200) fail(400, '知识点名称长度应为 1 至 200 位');
  1160. if (!Number.isInteger(classId) || classId < 1) fail(400, '请选择有效试题分类');
  1161. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父知识点编号无效');
  1162. if (!Number.isInteger(orderId) || orderId < 0) fail(400, '知识点排序必须是非负整数');
  1163. if (![0,1].includes(status) || !Number.isInteger(grade) || grade < 0 || ![0,1].includes(isSys)) fail(400, '知识点状态、年级或系统标记无效');
  1164. let companyId = pointerId(context.company);
  1165. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  1166. if (!companyId) fail(400, '知识点必须指定帐套');
  1167. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1168. const subject = await Psql.oneOrNone('SELECT "cId" FROM "ExamClass" WHERE "company"=$1 AND "cId"=$2 LIMIT 1', [companyId, classId]);
  1169. if (!subject) fail(404, '试题分类不存在或不属于当前帐套');
  1170. const fields = await schemaFor('QuestionsKnowledge');
  1171. let target;
  1172. let currentId = 0;
  1173. if (objectId) {
  1174. const query = new Parse.Query('QuestionsKnowledge'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  1175. companyId = pointerId(target.get('company')) || companyId; currentId = Number(target.get('kId')) || 0;
  1176. } else target = new Parse.Object('QuestionsKnowledge');
  1177. if (parentId > 0) {
  1178. const parent = await Psql.oneOrNone('SELECT "kId" FROM "QuestionsKnowledge" WHERE "company"=$1 AND "kId"=$2 AND "kClassId"=$3 LIMIT 1', [companyId, parentId, classId]);
  1179. if (!parent) fail(404, '父知识点不存在、科目不一致或不属于当前帐套');
  1180. if (currentId) {
  1181. const cycle = await Psql.oneOrNone('WITH RECURSIVE chain AS (SELECT "kId","pid",ARRAY["kId"::text] AS path FROM "QuestionsKnowledge" WHERE "company"=$1 AND "kId"=$2 UNION ALL SELECT k."kId",k."pid",chain.path||k."kId"::text FROM "QuestionsKnowledge" k JOIN chain ON k."kId"=chain."pid" WHERE k."company"=$1 AND NOT k."kId"::text=ANY(chain.path)) SELECT 1 AS found FROM chain WHERE "kId"=$3 LIMIT 1', [companyId, parentId, currentId]);
  1182. if (cycle) fail(409, '不能把知识点移动到自身或其下级知识点');
  1183. }
  1184. }
  1185. const duplicate = await Psql.oneOrNone('SELECT "objectId" FROM "QuestionsKnowledge" WHERE "company"=$1 AND "objectId"<>$2 AND "kClassId"=$3 AND LOWER(TRIM(COALESCE("kName",\'\')))=LOWER($4) LIMIT 1', [companyId, objectId, classId, knowledgeName]);
  1186. if (duplicate) fail(409, '同一试题分类中的知识点名称不能重复');
  1187. target.set('kName', knowledgeName); target.set('kClassId', classId); target.set('pid', parentId); target.set('status', status); target.set('grade', grade); target.set('isSys', isSys); target.set('company', company);
  1188. if (objectId) target.set('kOrderBy', orderId);
  1189. else { target.set('sourceKey', 'cloud:admin-knowledge:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('cuser', Number(context.current.get('legacyUserId')) || 0); target.set('cdate', new Date()); }
  1190. try { await target.save(null, { useMasterKey: true }); }
  1191. catch (error) { fail(422, '知识点初始写入失败: ' + String(error && error.message || error)); }
  1192. try {
  1193. if (!objectId) {
  1194. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-knowledge-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("kId"),0)+1 AS id FROM "QuestionsKnowledge",lock_row WHERE "company"=$1 AND COALESCE("kId",0)>0), next_order AS MATERIALIZED (SELECT COALESCE(MAX("kOrderBy"),0)+1 AS id FROM "QuestionsKnowledge",lock_row WHERE "company"=$1 AND "kClassId"=$3 AND "pid"=$4 AND "objectId"<>$2) UPDATE "QuestionsKnowledge" SET "kId"=next_id.id,"kOrderBy"=CASE WHEN $5>0 THEN $5 ELSE next_order.id END,"sourceKey"=\'[["k_id",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id,next_order WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id, classId, parentId, orderId]);
  1195. currentId = Number(rows[0] && rows[0].id) || 0;
  1196. if (!currentId) throw new Error('无法分配知识点编号');
  1197. }
  1198. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '知识点结构写入失败: ' + String(error && error.message || error)); }
  1199. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-knowledge' : 'create-knowledge', 'QuestionsKnowledge', target.id);
  1200. return response.json({ success: true, data: serializeObject(target) });
  1201. }
  1202. if (operation === 'knowledgeChildren') {
  1203. const parentId = Number(input.parentId || 0); const classId = Number(input.classId || 0);
  1204. if (!Number.isInteger(parentId) || parentId < 0 || !Number.isInteger(classId) || classId < 1) fail(400, '知识点父级或试题分类编号无效');
  1205. const fields = await schemaFor('QuestionsKnowledge'); const query = new Parse.Query('QuestionsKnowledge'); applyTenant(query, fields, context, input.companyId); query.equalTo('kClassId', classId); query.equalTo('pid', parentId); query.ascending('kOrderBy'); query.limit(1000);
  1206. const results = await query.find({ useMasterKey: true });
  1207. return response.json({ success: true, data: { classId, parentId, results: results.map(serializeObject) } });
  1208. }
  1209. if (operation === 'saveExamTeacher') {
  1210. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1211. const teacherName = String(payload.tname || '').trim(); const classId = Number(input.classId == null ? payload.tclsss || 0 : input.classId);
  1212. if (!teacherName || teacherName.length > 50) fail(400, '教师姓名长度应为 1 至 50 位');
  1213. if (!Number.isInteger(classId) || classId < 0) fail(400, '任教试题分类编号无效');
  1214. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '教师必须指定帐套');
  1215. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1216. if (classId > 0) { const subject = await Psql.oneOrNone('SELECT "cId" FROM "ExamClass" WHERE "company"=$1 AND "cId"=$2 LIMIT 1', [companyId, classId]); if (!subject) fail(404, '任教试题分类不存在或不属于当前帐套'); }
  1217. const fields = await schemaFor('ExTeacher'); let target;
  1218. if (objectId) { const query = new Parse.Query('ExTeacher'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true }); companyId = pointerId(target.get('company')) || companyId; }
  1219. else target = new Parse.Object('ExTeacher');
  1220. const limits = { post: 50, teach: 50, fileUpload: 255, remark: 1000 };
  1221. for (const [name, limit] of Object.entries(limits)) { const value = String(payload[name] || '').trim(); if (value.length > limit) fail(400, name + ' 超出最大长度 ' + limit); target.set(name, value); }
  1222. target.set('tname', teacherName); target.set('tclsss', classId); target.set('company', company); target.set('addUser', Number(context.current.get('legacyUserId')) || 0);
  1223. if (!objectId) { target.set('sourceKey', 'cloud:admin-exam-teacher:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('creatTime', new Date()); }
  1224. try { await target.save(null, { useMasterKey: true }); }
  1225. catch (error) { fail(422, '教师初始写入失败: ' + String(error && error.message || error)); }
  1226. try {
  1227. if (!objectId) {
  1228. const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-exam-teacher-id:\'||$1))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("id"),0)+1 AS id FROM "ExTeacher",lock_row WHERE "company"=$1 AND COALESCE("id",0)>0) UPDATE "ExTeacher" SET "id"=next_id.id,"sourceKey"=\'[["ID",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id]);
  1229. if (!(Number(rows[0] && rows[0].id) || 0)) throw new Error('无法分配教师编号');
  1230. }
  1231. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '教师编号写入失败: ' + String(error && error.message || error)); }
  1232. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-exam-teacher' : 'create-exam-teacher', 'ExTeacher', target.id);
  1233. return response.json({ success: true, data: serializeObject(target) });
  1234. }
  1235. if (operation === 'barBatch') {
  1236. const action = String(input.action || '');
  1237. const actions = ['audit','unaudit','recycle','recover','move','top-global','top-section','top-undo','elite','elite-undo','bottom','bottom-undo'];
  1238. if (!actions.includes(action)) fail(400, '不支持的贴吧帖子批量操作');
  1239. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  1240. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  1241. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条帖子');
  1242. const fields = await schemaFor('GuestBar');
  1243. const query = new Parse.Query('GuestBar'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  1244. const targets = await query.find({ useMasterKey: true });
  1245. if (targets.length !== objectIds.length) fail(404, '部分帖子不存在或不属于当前帐套');
  1246. let cateId = null;
  1247. if (action === 'move') {
  1248. cateId = Number(input.cateId);
  1249. if (!Number.isInteger(cateId) || cateId < 1) fail(400, '目标贴吧分类编号无效');
  1250. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  1251. if (companyIds.length !== 1) fail(400, '批量移动的帖子必须属于同一帐套');
  1252. const category = await Psql.oneOrNone('SELECT "objectId" FROM "Guestcate" WHERE "company"=$1 AND "cateid"=$2 AND COALESCE("gtype",0)=1 LIMIT 1', [companyIds[0], cateId]);
  1253. if (!category) fail(404, '目标贴吧分类不存在或不属于当前帐套');
  1254. }
  1255. for (const target of targets) {
  1256. if (action === 'audit' || action === 'recover') target.set('status', 99);
  1257. else if (action === 'unaudit') target.set('status', 0);
  1258. else if (action === 'recycle') target.set('status', -2);
  1259. else if (action === 'move') target.set('cateId', cateId);
  1260. else if (action === 'top-global') target.set('orderFlag', 2);
  1261. else if (action === 'top-section') target.set('orderFlag', 1);
  1262. else if (action === 'bottom') target.set('orderFlag', -1);
  1263. else if (action === 'top-undo' || action === 'bottom-undo') target.set('orderFlag', 0);
  1264. else {
  1265. const flags = String(target.get('postFlag') || '').split(',').map((value) => value.trim()).filter(Boolean);
  1266. const next = new Set(flags);
  1267. if (action === 'elite') next.add('Recommend'); else next.delete('Recommend');
  1268. target.set('postFlag', next.size ? ',' + [...next].join(',') + ',' : '');
  1269. }
  1270. }
  1271. await Parse.Object.saveAll(targets, { useMasterKey: true });
  1272. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'bar-' + action, 'GuestBar', target.id);
  1273. return response.json({ success: true, data: { action, updated: targets.length, cateId, results: targets.map(serializeObject) } });
  1274. }
  1275. if (operation === 'contentBatch') {
  1276. const action = String(input.action || '');
  1277. if (!['status','recycle','recover','move'].includes(action)) fail(400, '不支持的内容批量操作');
  1278. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  1279. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  1280. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条内容');
  1281. const contentFields = await schemaFor('CommonModel');
  1282. const query = new Parse.Query('CommonModel'); applyTenant(query, contentFields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  1283. const targets = await query.find({ useMasterKey: true });
  1284. if (targets.length !== objectIds.length) fail(404, '部分内容不存在或不属于当前帐套');
  1285. let status = null;
  1286. let nodeId = null;
  1287. if (action === 'status') {
  1288. status = Number(input.status);
  1289. if (![-3,-1,0,99].includes(status)) fail(400, '不支持的内容状态');
  1290. } else if (action === 'recycle') status = -2;
  1291. else if (action === 'recover') status = 0;
  1292. else {
  1293. nodeId = Number(input.nodeId);
  1294. if (!Number.isInteger(nodeId) || nodeId < 1) fail(400, '请选择有效目标节点');
  1295. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  1296. if (companyIds.length !== 1) fail(400, '批量移动的内容必须属于同一帐套');
  1297. const node = await Psql.oneOrNone('SELECT "objectId" FROM "Node" WHERE "company"=$1 AND "nodeId"=$2 AND COALESCE("zstatus",99)<>-2 LIMIT 1', [companyIds[0], nodeId]);
  1298. if (!node) fail(404, '目标节点不存在或不属于当前帐套');
  1299. }
  1300. for (const target of targets) {
  1301. if (status !== null) target.set('status', status);
  1302. if (nodeId !== null) target.set('nodeId', nodeId);
  1303. }
  1304. await Parse.Object.saveAll(targets, { useMasterKey: true });
  1305. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'content-' + action, 'CommonModel', target.id);
  1306. return response.json({ success: true, data: { action, updated: targets.length, status, nodeId, results: targets.map(serializeObject) } });
  1307. }
  1308. const className = String(input.className || '');
  1309. assertClass(className);
  1310. const fields = await schemaFor(className);
  1311. const classWritable = !READ_ONLY_CLASSES.has(className);
  1312. if (operation === 'schema') {
  1313. const fieldList = Object.entries(fields).filter(([name]) => !HIDDEN_FIELDS.has(name) && !/(?:password|secret|sessiontoken|masterkey|privatekey)/i.test(name)).map(([name, field]) => ({ name, type: field.type, targetClass: field.targetClass, required: field.required === true, writable: classWritable && !isSystemField(className, name) && GENERIC_WRITE_TYPES.has(field.type) }));
  1314. return response.json({ success: true, data: { className, label: CLASS_LABELS[className] || className, fields: fieldList, writable: classWritable, creatable: classWritable && !['CommonModel','Model','ModelField','Guestbook','Currency','SysHoliday','Search','AdZone','AdInfo'].includes(className), supportsSoftDelete: Boolean(fields.isDeleted) } });
  1315. }
  1316. if (operation === 'list') {
  1317. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20));
  1318. let query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId);
  1319. const search = String(input.search || '').trim();
  1320. if (search) { const searchField = ['name','title','nodeName','specName','modelName','fieldName','fieldAlias','groupName','categoryname','dicname','cateName','gradeName','cClassName','testPoint','kName','tname','username','realName','mobile','sourceKey'].find((name) => fields[name] && fields[name].type === 'String'); if (searchField) query.matches(searchField, escapeRegex(search), 'i'); }
  1321. const sort = fields[input.sort] ? String(input.sort) : fields.updatedAt ? 'updatedAt' : 'createdAt'; if (input.order === 'asc') query.ascending(sort); else query.descending(sort);
  1322. const total = await query.count({ useMasterKey: true }); query.skip((page - 1) * pageSize); query.limit(pageSize);
  1323. const results = (await query.find({ useMasterKey: true })).filter(isVisible);
  1324. return response.json({ success: true, data: { className, page, pageSize, total, results: results.map(serializeObject) } });
  1325. }
  1326. const objectId = String(input.objectId || '');
  1327. if (operation === 'get') {
  1328. if (!objectId) fail(400, '缺少 objectId'); const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); const object = await query.get(objectId, { useMasterKey: true });
  1329. return response.json({ success: true, data: serializeObject(object) });
  1330. }
  1331. if (operation === 'save') {
  1332. if (!classWritable) fail(403, '该系统类不允许通用编辑');
  1333. if (className === '_User' && !objectId) fail(400, '新增用户必须走专用开户流程');
  1334. if (className === 'Group') fail(400, '用户组必须走专用保存流程');
  1335. if (className === 'Node') fail(400, '栏目必须走专用保存流程');
  1336. if (className === 'Special') fail(400, '专题必须走专用保存流程');
  1337. if (className === 'Model' || className === 'ModelField') fail(400, '模型结构必须走专用元数据流程');
  1338. if (className === 'Guestbook') fail(400, '留言必须走专用编辑或回复流程');
  1339. if (className === 'Guestcate') fail(400, '留言/贴吧分类必须走专用保存流程');
  1340. if (className === 'ExamClass') fail(400, '试题分类必须走专用保存流程');
  1341. if (className === 'ExamPoint') fail(400, '考点必须走专用保存流程');
  1342. if (className === 'QuestionsKnowledge') fail(400, '知识点必须走专用保存流程');
  1343. if (className === 'ExTeacher') fail(400, '考试教师必须走专用保存流程');
  1344. if (className === 'Datadiccategory' || className === 'Datadic') fail(400, '数据字典必须走专用保存流程');
  1345. if (className === 'GradeCate' || className === 'Grade') fail(400, '多级数据字典必须走专用保存流程');
  1346. if (className === 'Currency') fail(400, '货币必须走专用保存流程');
  1347. if (className === 'SysHoliday') fail(400, '节假日必须走专用保存流程');
  1348. if (className === 'Search') fail(400, '快捷入口必须走专用保存流程');
  1349. if (className === 'AdZone' || className === 'AdInfo') fail(400, '广告位与广告内容必须走专用保存流程');
  1350. if (className === 'CommonModel' && !objectId) fail(400, '内容新增必须同时写入模型附表,不能走通用保存');
  1351. let object;
  1352. if (objectId) { const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); object = await query.get(objectId, { useMasterKey: true }); } else object = new Parse.Object(className);
  1353. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1354. for (const [name, value] of Object.entries(payload)) { if (!fields[name] || isSystemField(className, name)) continue; if (!GENERIC_WRITE_TYPES.has(fields[name].type)) fail(400, '字段不允许通用编辑: ' + name); if (value === null) object.unset(name); else object.set(name, toParseValue(fields[name], value)); }
  1355. if (fields.company && context.company) object.set('company', context.company); if (fields.isDeleted && !objectId) object.set('isDeleted', false);
  1356. await object.save(null, { useMasterKey: true }); await audit(context, objectId ? 'update' : 'create', className, object.id);
  1357. return response.json({ success: true, data: serializeObject(object) });
  1358. }
  1359. if (operation === 'delete') {
  1360. if (!classWritable || !objectId) fail(400, '该记录不允许删除'); const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); const object = await query.get(objectId, { useMasterKey: true });
  1361. if (className === 'Model' || className === 'ModelField') fail(501, 'migration_blocked: 删除模型或字段需要同步删除 PostgreSQL 物理表/列并验证历史数据,托管云函数中未开放此 DDL 流程');
  1362. if (className === 'AdZone' || className === 'AdInfo') fail(400, '广告位与广告内容必须走专用批量删除流程');
  1363. if (className === 'Guestcate') { const cateid = Number(object.get('cateid')) || 0; const companyId = pointerId(object.get('company')); const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "Guestcate" WHERE "company"=$1 AND "parentId"=$2) AS children,(SELECT COUNT(*)::int FROM "Guestbook" WHERE "company"=$1 AND "cateid"=$2) AS messages,(SELECT COUNT(*)::int FROM "GuestBar" WHERE "company"=$1 AND "cateId"=$2) AS posts', [companyId, cateid]); if (Number(refs.children) || Number(refs.messages) || Number(refs.posts)) fail(409, '分类仍被下级分类、留言或帖子引用,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-guest-category', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1364. if (className === 'ExamClass') { const classId = Number(object.get('cId')) || 0; const companyId = pointerId(object.get('company')); const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "ExamClass" WHERE "company"=$1 AND "cClassid"=$2) AS children,(SELECT COUNT(*)::int FROM "ExamSysQuestions" WHERE "company"=$1 AND "pClass"=$2) AS questions', [companyId, classId]); if (Number(refs.children) || Number(refs.questions)) fail(409, '试题分类仍被下级分类或试题引用,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-exam-class', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1365. if (className === 'ExamPoint') { const pointId = Number(object.get('id')) || 0; const companyId = pointerId(object.get('company')); const children = await Psql.one('SELECT COUNT(*)::int AS count FROM "ExamPoint" WHERE "company"=$1 AND "tid"=$2', [companyId, pointId]); if (Number(children.count)) fail(409, '考点仍有下级考点,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-exam-point', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1366. if (className === 'QuestionsKnowledge') { const knowledgeId = Number(object.get('kId')) || 0; const companyId = pointerId(object.get('company')); const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "QuestionsKnowledge" WHERE "company"=$1 AND "pid"=$2) AS children,(SELECT COUNT(*)::int FROM "ExamSysQuestions" WHERE "company"=$1 AND "pKnowledge"=$2) AS questions', [companyId, knowledgeId]); if (Number(refs.children) || Number(refs.questions)) fail(409, '知识点仍被下级知识点或试题引用,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-knowledge', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1367. if (className === 'Datadiccategory' || className === 'Datadic') { if (className === 'Datadiccategory') { const categoryId = Number(object.get('diccateid')) || 0; const itemFields = await schemaFor('Datadic'); const refs = new Parse.Query('Datadic'); applyTenant(refs, itemFields, context, pointerId(object.get('company'))); refs.equalTo('diccate', categoryId); if (await refs.count({ useMasterKey: true })) fail(409, '字典分类仍有字典项,不能删除'); } await object.destroy({ useMasterKey: true }); await audit(context, 'delete-dictionary', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1368. if (className === 'GradeCate' || className === 'Grade') { const referenceFields = await schemaFor('Grade'); const refs = new Parse.Query('Grade'); applyTenant(refs, referenceFields, context, pointerId(object.get('company'))); if (className === 'GradeCate') refs.equalTo('cate', Number(object.get('cateId')) || 0); else refs.equalTo('parentId', Number(object.get('gradeId')) || 0); if (await refs.count({ useMasterKey: true })) fail(409, className === 'GradeCate' ? '多级字典分类仍有选项,不能删除' : '多级字典选项仍有下级选项,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-grade', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1369. if (className === '_User') assertCanManageUser(context, object, 'lock');
  1370. if (className === 'Group') { const groupId = Number(object.get('groupId')) || 0; const companyId = pointerId(object.get('company')); const users = await Psql.one('SELECT COUNT(*)::int AS count FROM "_User" WHERE "company"=$1 AND COALESCE("legacyGroupId",0)=$2 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE)', [companyId, groupId]); const children = await Psql.one('SELECT COUNT(*)::int AS count FROM "Group" WHERE "company"=$1 AND COALESCE("parentGroupId",0)=$2', [companyId, groupId]); if (Number(users.count) > 0) fail(409, '该用户组仍有用户,不能删除'); if (Number(children.count) > 0) fail(409, '该用户组仍有下级组,不能删除'); }
  1371. if (className === 'CommonModel') { object.set('status', -2); await object.save(null, { useMasterKey: true }); await audit(context, 'content-recycle', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: true, status: -2 } }); }
  1372. if (className === 'Node') { object.set('zstatus', -2); if (fields.editDate) object.set('editDate', new Date()); await object.save(null, { useMasterKey: true }); await audit(context, 'node-recycle', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: true, zstatus: -2 } }); }
  1373. if (className === 'Special') { const specId = Number(object.get('specId')) || 0; const companyId = pointerId(object.get('company')); const children = await Psql.one('SELECT COUNT(*)::int AS count FROM "Special" WHERE "company"=$1 AND COALESCE("pid",0)=$2', [companyId, specId]); if (Number(children.count) > 0) fail(409, '该专题仍有下级专题,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-special', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
  1374. if (className === 'Guestbook') { object.set('status', -2); await object.save(null, { useMasterKey: true }); await audit(context, 'guestbook-recycle', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: true, status: -2 } }); }
  1375. if (fields.isDeleted) { object.set('isDeleted', true); await object.save(null, { useMasterKey: true }); } else await object.destroy({ useMasterKey: true });
  1376. if (className === '_User') await revokeSessions([object]);
  1377. await audit(context, 'delete', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: Boolean(fields.isDeleted) } });
  1378. }
  1379. if (operation === 'resetPassword') {
  1380. if (className !== '_User' || !objectId || typeof input.newPassword !== 'string' || input.newPassword.length < 8) fail(400, '密码至少 8 位');
  1381. const query = new Parse.Query('_User'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); assertCanManageUser(context, target, 'reset-password'); target.setPassword(input.newPassword); if (fields.passwordResetRequired) target.set('passwordResetRequired', false); await target.save(null, { useMasterKey: true }); const revokedSessions = await revokeSessions([target]); await audit(context, 'reset-password', '_User', objectId); return response.json({ success: true, data: { objectId, revokedSessions } });
  1382. }
  1383. fail(400, '不支持的后台操作');
  1384. } catch (error) {
  1385. const status = Number(error.status || (error.code === 101 ? 404 : 500));
  1386. return response.status(status).json({ success: false, error: status >= 500 ? 'cloud_function_error' : 'request_rejected', message: error.message || '云函数执行失败' });
  1387. }
  1388. }
  1389. `;
  1390. function cmsReadCode(mode) {
  1391. return String.raw`
  1392. const MODE = ${JSON.stringify(mode)};
  1393. const HIDDEN = /(?:password|secret|sessiontoken|masterkey|privatekey|legacyPasswordHash|adminPassword)/i;
  1394. function inputOf(request) { const body = request.body || {}; return body.params && typeof body.params === 'object' ? body.params : body; }
  1395. function fail(status, message) { const error = new Error(message); error.status = status; throw error; }
  1396. function safe(value, depth = 0) { if (value == null || depth > 4) return value; if (Array.isArray(value)) return value.map((item) => safe(item, depth + 1)); if (value && typeof value.toJSON === 'function') return safe(value.toJSON(), depth + 1); if (typeof value === 'object') { const output = {}; for (const [key,item] of Object.entries(value)) if (!HIDDEN.test(key)) output[key] = safe(item, depth + 1); return output; } return value; }
  1397. async function auth(request) { const current = request.user || (typeof user !== 'undefined' ? user : null); if (!current) fail(401, '需要登录'); await current.fetch({ useMasterKey: true }); const roles = Array.isArray(current.get('roles')) ? current.get('roles').map(String) : []; const superAdmin = current.get('adminRoleKey') === 'super-admin' || roles.includes('super-admin'); if (!(current.get('isAdmin') === true || current.get('role') === 'admin' || roles.includes('admin') || superAdmin)) fail(403, '需要管理员权限'); const company = request.company || current.get('company') || null; if (!company && !superAdmin) fail(403, '管理员未分配帐套'); return { current, company, superAdmin }; }
  1398. async function schema(name) { try { return (await new Parse.Schema(name).get({ useMasterKey: true })).fields || {}; } catch (_) { return {}; } }
  1399. function tenant(query, fields, context) { if (fields.company && context.company) query.equalTo('company', context.company); }
  1400. function stripHtml(content) { return String(content == null ? '' : content).replace(/<!--[\s\S]*?-->/g, ' ').replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, ' ').replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, ' ').replace(/<[^>]+>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ').replace(/&amp;/gi, '&').replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&quot;/gi, '"').replace(/&#39;|&apos;/gi, "'").replace(/\s+/g, ' ').trim(); }
  1401. function escapeRegex(value) { return String(value).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'); }
  1402. async function handler(request, response) {
  1403. try {
  1404. const input = inputOf(request); const context = await auth(request); const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20));
  1405. if (MODE === 'content-normalizer') return response.json({ success: true, data: { content: stripHtml(input.content), mode: String(input.mode || 'strip') } });
  1406. if (MODE.startsWith('user-')) {
  1407. const userId = String(input.userId || ''); if (!userId) fail(400, '缺少 userId'); const fields = await schema('_User'); const query = new Parse.Query('_User'); tenant(query, fields, context); const target = await query.get(userId, { useMasterKey: true }); const data = safe(target);
  1408. if (MODE === 'user-extended') { delete data.legacyUserPlat; delete data.legacyWxUser; delete data.wechat; delete data.wxapp; return response.json({ success: true, data }); }
  1409. if (MODE === 'user-platform') return response.json({ success: true, data: { objectId: target.id, platform: safe(target.get('legacyUserPlat') || {}), company: safe(target.get('company')) } });
  1410. return response.json({ success: true, data: { objectId: target.id, wechat: safe(target.get('legacyWxUser') || target.get('wechat') || target.get('wxapp') || {}) } });
  1411. }
  1412. if (MODE === 'exam-classes' || MODE === 'guest-bar') {
  1413. const className = MODE === 'exam-classes' ? 'ExamClass' : 'GuestBar'; const fields = await schema(className); const query = new Parse.Query(className); tenant(query, fields, context); query.descending(fields.updatedAt ? 'updatedAt' : 'createdAt'); const total = await query.count({ useMasterKey: true }); query.skip((page - 1) * pageSize); query.limit(pageSize); const rows = await query.find({ useMasterKey: true }); return response.json({ success: true, data: { page, pageSize, total, results: rows.map(safe) } });
  1414. }
  1415. if (MODE === 'search') {
  1416. const keyword = stripHtml(input.keyword); if (!keyword) fail(400, '请输入搜索关键词'); const fields = await schema('CommonModel'); const candidates = ['title','inputer','sourceKey','synopsis','content'].filter((name) => fields[name] && fields[name].type === 'String'); if (!candidates.length) return response.json({ success: true, data: { page, pageSize, total: 0, results: [] } });
  1417. const pattern = escapeRegex(keyword); const queries = candidates.slice(0, 3).map((field) => { const query = new Parse.Query('CommonModel'); tenant(query, fields, context); query.matches(field, pattern, 'i'); return query; }); const query = queries.length === 1 ? queries[0] : Parse.Query.or(...queries); query.descending('updatedAt'); query.skip((page - 1) * pageSize); query.limit(pageSize); const rows = await query.find({ useMasterKey: true }); return response.json({ success: true, data: { page, pageSize, total: rows.length < pageSize ? (page - 1) * pageSize + rows.length : null, results: rows.map((row) => { const json = safe(row); if (json.content) json.content = stripHtml(json.content).slice(0, 260); return json; }) } });
  1418. }
  1419. fail(400, '不支持的 CMS 查询');
  1420. } catch (error) { const status = Number(error.status || (error.code === 101 ? 404 : 500)); return response.status(status).json({ success: false, error: status >= 500 ? 'cloud_function_error' : 'request_rejected', message: error.message || '云函数执行失败' }); }
  1421. }
  1422. `;
  1423. }
  1424. const appGatewayCode = String.raw`
  1425. const DEFAULT_COMPANY_ID = '7pIbDBJmKx';
  1426. const PUBLIC_READ = new Set(['content_list','content_get','content_uphis','node_list','node_get','app_update']);
  1427. const BLOCKED = {
  1428. mcode_send: '缺少新短信服务商凭据与验证码存储', user_login_mobile: '缺少新短信验证码服务', user_register_mobile: '缺少新短信验证码服务', user_sync2: '依赖微信容器授权与新版微信凭据',
  1429. cart_list: '目标 Schema 无购物车类', coupon_list: '目标 Schema 无优惠券实例类', coupon_usrgot_add: '目标 Schema 无用户优惠券类', coupon_usrgot_list: '目标 Schema 无用户优惠券类',
  1430. order_comment_add: '目标 Schema 无订单评价类', order_comment_list: '目标 Schema 无订单评价类', order_delivery: '目标 Schema 无订单与物流类', order_get: '目标 Schema 无订单类', order_list: '目标 Schema 无订单类', order_signfor: '目标 Schema 无订单类',
  1431. payment_cart: '目标 Schema 无订单与支付明细类', payment_cart_again: '目标 Schema 无订单与支付明细类', payment_success: '目标 Schema 无支付明细类',
  1432. invoice_add: '目标 Schema 无发票类', invoice_del: '目标 Schema 无发票类', invoice_get: '目标 Schema 无发票类', invoice_list: '目标 Schema 无发票类', invoice_upd: '目标 Schema 无发票类',
  1433. receaddr_add: '目标 Schema 无收货地址类', receaddr_del: '目标 Schema 无收货地址类', receaddr_get: '目标 Schema 无收货地址类', receaddr_list: '目标 Schema 无收货地址类', receaddr_upd: '目标 Schema 无收货地址类',
  1434. user_bank_add: '目标 Schema 无提现账户类', user_bank_del: '目标 Schema 无提现账户类', user_bank_get: '目标 Schema 无提现账户类', user_bank_list: '目标 Schema 无提现账户类', user_cash_add: '缺少提现事务账本', user_cash_list: '缺少提现事务账本',
  1435. user_coin_recharge: '缺少支付凭据与事务账本', user_exp_transfer: '缺少积分事务规则确认', user_money_recharge: '缺少支付凭据与事务账本', user_money_transfer: '缺少资金事务规则确认',
  1436. user_group_usr_supply: '目标 Schema 无会员续费订单类', user_group_usr_upgrade: '目标 Schema 无会员升级订单类', user_shop_order: '目标 Schema 无订单类', user_shop_sales: '目标 Schema 无销售明细类',
  1437. user_star_add: '目标 Schema 无收藏关系类', user_star_del: '目标 Schema 无收藏关系类', user_star_is: '目标 Schema 无收藏关系类', user_update_paypwd: '需要独立支付密码哈希服务',
  1438. user_update_pwd: '旧流程强制校验短信验证码,但新短信服务与验证码存储尚未提供', user_update_pwdall: '同时依赖登录密码与支付密码写入,目标系统缺少独立支付密码哈希服务',
  1439. vote_add: '目标 Schema 无可证明的投票记录类', vote_ask: '目标 Schema 无可证明的投票记录类', vote_question: '目标 Schema 无可证明的投票记录类',
  1440. product_list: '目标 Product 仅是 ZL_P_Product 附表,缺少 ZL_Commodities 商品主表', product_get: '目标 Product 仅是 ZL_P_Product 附表,缺少商品名称、价格、正文、所有者与主键关系', product_stock_list: '目标 Schema 无 ZL_Shop_Stock 库存流水类',
  1441. product_del: '缺少 ZL_Commodities 主表及其 UserID 所有权字段', product_stock_change: '缺少 ZL_Commodities 主表、当前库存与 ZL_Shop_Stock 流水类', product_sale_change: '缺少 ZL_Commodities 主表及 Sales/UserID 字段',
  1442. unit_record_update: '旧源码在调用前无条件 return;目标库也未迁移 Model 57 单元聚合副表',
  1443. e_get_21list_tj: '迁移数据未包含复习收入金额字段或可验证的计价规则',
  1444. pub_add: '旧前端依赖 Pub 7-13,但目标库只迁入 Pub 2-6,且缺少注销、供应商、商户邀请、退换货与结算副表', pub_list: '旧前端依赖 Pub 7-13,但目标库只迁入 Pub 2-6,无法恢复对应历史记录与审核范围',
  1445. user_rnauth_add: '实名认证需新的合规审核与敏感数据存储', user_rnauth_get: '实名认证需新的合规审核与敏感数据存储', user_rnauth_upd: '实名认证需新的合规审核与敏感数据存储',
  1446. product_add: '缺少 ZL_Commodities 商品主表,无法与 Product 附表进行事务新增', product_upd: '缺少 ZL_Commodities 商品主表,无法恢复主表与附表事务更新'
  1447. };
  1448. const SENSITIVE = /(?:password|pwd|secret|sessiontoken|masterkey|privatekey|legacyPasswordHash|adminPassword|payPassword)/i;
  1449. function inputOf(request) { const body = request.body || {}; return body.params && typeof body.params === 'object' ? body.params : body; }
  1450. function envelope(result, addon, page) { const value = { retcode: 0, retmsg: '', result }; if (addon !== undefined) value.addon = addon; if (page) value.page = page; return value; }
  1451. function reject(message) { return { retcode: -1, retmsg: message, result: null }; }
  1452. function fail(status, message) { const error = new Error(message); error.status = status; throw error; }
  1453. function safe(value, depth = 0) { if (value == null || depth > 4) return value; if (value instanceof Date) return value.toISOString(); if (Array.isArray(value)) return value.map((item) => safe(item, depth + 1)); if (value && typeof value.toJSON === 'function') return safe(value.toJSON(), depth + 1); if (typeof value === 'object') { const output = {}; for (const [key,item] of Object.entries(value)) if (!SENSITIVE.test(key)) output[key] = safe(item, depth + 1); return output; } return value; }
  1454. function number(value, fallback = 0) { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : fallback; }
  1455. function pageInput(input) { return { index: Math.max(1, number(input.cpage || input.page, 1)), size: Math.min(100, Math.max(1, number(input.psize || input.pageSize, 20))) }; }
  1456. function companyPointer() { return Parse.Object.createWithoutData('Company', DEFAULT_COMPANY_ID); }
  1457. async function fieldsOf(className) { return (await new Parse.Schema(className).get({ useMasterKey: true })).fields || {}; }
  1458. function tenant(query, fields) { if (fields.company) query.equalTo('company', companyPointer()); }
  1459. function isVisible(row) { const value = row && typeof row.get === 'function' ? row.get('isDeleted') : row && row.isDeleted; return ![true, 1, '1', 'true', 'True', 'TRUE'].includes(value); }
  1460. function legacyAliases(value, className) {
  1461. const row = safe(value); const maps = {
  1462. CommonModel: { GeneralID:'generalId', OrderID:'orderId', NodeID:'nodeId', ModelID:'modelId', ItemID:'itemId', TableName:'tableName', Title:'title', Inputer:'inputer', Hits:'hits', CreateTime:'createTime', Status:'status', TopImg:'topImg', Subtitle:'subtitle' },
  1463. Node: { NodeID:'nodeId', NodeName:'nodeName', NodeType:'nodeType', NodeDir:'nodeDir', NodeUrl:'nodeUrl', ParentID:'parentId', OrderID:'orderId', NodePic:'nodePicUrl', Description:'description', ConsumePoint:'consumePoint', ConsumeDeposit:'consumeDeposit', ConsumeType:'consumeType', ConsumeTime:'consumeTime', ConsumeCount:'consumeCount', AddPoint:'addPoint' },
  1464. App: { ID:'id' }
  1465. }; const map = maps[className] || {}; for (const [legacy,source] of Object.entries(map)) if (row[legacy] === undefined && row[source] !== undefined) row[legacy] = row[source]; return row;
  1466. }
  1467. async function currentUser(request, required = true) { const current = request.user || (typeof user !== 'undefined' ? user : null); if (!current) { if (required) fail(401, '登录状态已失效'); return null; } await current.fetch({ useMasterKey: true }); const company = current.get('company'); if (company && company.id !== DEFAULT_COMPANY_ID) fail(403, '用户不属于小树英语帐套'); return current; }
  1468. async function revokeUserSessions(target) { let count = 0; while (true) { const query = new Parse.Query('_Session'); query.equalTo('user', target); query.limit(1000); const sessions = await query.find({ useMasterKey:true }); if (!sessions.length) break; await Parse.Object.destroyAll(sessions,{useMasterKey:true}); count += sessions.length; if (sessions.length < 1000) break; } return count; }
  1469. function objectValue(source, key) { return source && typeof source.get === 'function' ? source.get(key) : source && source[key]; }
  1470. function legacyData(source) { const value = objectValue(source, 'legacyUserData'); return value && typeof value === 'object' && !Array.isArray(value) ? value : {}; }
  1471. function firstValue(...values) { return values.find((value) => value !== undefined && value !== null && value !== ''); }
  1472. function legacyUser(current, withToken = false) {
  1473. const data = legacyData(current); const username = String(firstValue(objectValue(current,'username'),data.UserName,'') || ''); const userId = number(firstValue(objectValue(current,'legacyUserId'),objectValue(current,'userid'),objectValue(current,'num'),data.UserID)); const groupId = number(firstValue(objectValue(current,'legacyGroupId'),data.GroupID)); const honeyName = String(firstValue(objectValue(current,'nickname'),objectValue(current,'nickName'),objectValue(current,'realName'),data.HoneyName,username) || ''); const avatar = String(firstValue(objectValue(current,'avatar'),data.salt,'') || ''); const mobile = String(firstValue(objectValue(current,'mobile'),objectValue(current,'phone'),'') || ''); const parentId = number(firstValue(data.ParentUserID,objectValue(current,'puid'))); const vip = number(firstValue(data.VIP,objectValue(current,'vip')));
  1474. const value = { objectId:String(objectValue(current,'objectId') || current.id || ''), userId, userName:username, honeyName, userFace:avatar, mobile, groupId, groupName:String(objectValue(current,'roleName') || ''), email:String(firstValue(objectValue(current,'email'),data.Email,'') || ''), puid:parentId, vip, regTime:firstValue(data.RegTime,objectValue(current,'createdAt')), birthday:firstValue(objectValue(current,'birthday'),data.birthday,''), wechat:firstValue(objectValue(current,'wechat'),data.wechat,''), seturl:String(firstValue(data.seturl,objectValue(current,'seturl'),'') || '') };
  1475. if (withToken) value.sessionToken = current.getSessionToken(); return value;
  1476. }
  1477. function legacyUserAddon(current) {
  1478. const data = legacyData(current); const state = objectValue(current,'isDisabled') === true ? 0 : number(firstValue(data.State,1),1); const result = { vip:number(data.VIP), state, State:state, regTime:firstValue(data.RegTime,objectValue(current,'createdAt')), purse:number(data.Purse), silverCoin:number(data.SilverCoin), userExp:number(data.UserExp), userPoint:number(data.UserPoint), boffExp:number(data.boffExp) }; result.VIP = result.vip; result.Purse = result.purse; result.SilverCoin = result.silverCoin; result.UserExp = result.userExp; result.UserPoint = result.userPoint; return result;
  1479. }
  1480. async function registerUser(input) {
  1481. const username = String(input.name || input.username || '').trim(); const password = String(input.passwd || input.password || ''); if (!username) fail(400,'账号不能为空'); if (password.length < 6 || password.length > 18) fail(400,'密码长度应为 6 至 18 位'); const inviteCode = String(input.code || input.inviCode || '').trim(); let parentId = 0; if (inviteCode) { const rows = await Psql.query('SELECT COALESCE("legacyUserId",("legacyUserData"->>\'UserID\')::numeric) AS id FROM "_User" WHERE "company"=$1 AND "username"=$2 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) LIMIT 1',[DEFAULT_COMPANY_ID,inviteCode]); parentId = number(rows[0] && rows[0].id); if (!parentId) fail(400,'邀请码不存在'); }
  1482. const company = await new Parse.Query('Company').get(DEFAULT_COMPANY_ID,{useMasterKey:true}); const created = new Parse.User(); created.setUsername(username); created.setPassword(password); created.set('company',company); created.set('type','user'); created.set('isDisabled',false); created.set('legacyGroupId',1); created.set('nickname',username); if (/^1\d{10}$/.test(username)) created.set('mobile',username); try { await created.signUp(); } catch (error) { if (number(error && error.code) === 202) fail(409,'此用户名已被使用'); throw error; }
  1483. const sessionToken = created.getSessionToken(); try { const regTime = new Date().toISOString(); const data = { UserID:0,UserName:username,HoneyName:username,GroupID:1,ParentUserID:parentId,VIP:0,RegTime:regTime,Purse:0,SilverCoin:0,UserExp:0,UserPoint:0,boffExp:0,State:1 }; const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-legacy-user-id\'))), next_id AS MATERIALIZED (SELECT COALESCE(MAX("legacyUserId"),0)+1 AS id FROM "_User",lock_row WHERE "company"=$1 AND COALESCE("legacyUserId",0)>0) UPDATE "_User" SET "legacyUserId"=next_id.id,"legacyGroupId"=1,"legacyUserData"=jsonb_set($3::jsonb,\'{UserID}\',to_jsonb(next_id.id),true),"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id',[DEFAULT_COMPANY_ID,created.id,JSON.stringify(data)]); const userId = number(rows[0] && rows[0].id); if (!userId) throw new Error('无法分配旧系统用户 ID'); await created.fetch({useMasterKey:true}); const result = legacyUser(created); result.sessionToken = sessionToken; return { result,addon:{ State:1,state:1,parentUserId:parentId } }; } catch (error) { await created.destroy({useMasterKey:true}).catch(() => undefined); throw error; }
  1484. }
  1485. async function updateUserProfile(input,current) {
  1486. const ownId = ownLegacyId(current); const requestedId = number(input.uid || ownId); if (requestedId !== ownId && !isAdminUser(current)) fail(403,'不允许修改其他用户资料'); const model = parseObject(input.mu,'用户资料'); const fields = await fieldsOf('_User'); const source = { ...model,...input }; delete source.mu; const mappings = { honeyName:'nickname',nickname:'nickname',trueName:'realName',realName:'realName',userFace:'avatar',avatar:'avatar',mobile:'mobile',Email:'email',email:'email',sex:'gender',gender:'gender',birthday:'birthday',seturl:'seturl' }; const legacyMappings = { honeyName:'HoneyName',nickname:'HoneyName',trueName:'TrueName',realName:'TrueName',userFace:'salt',avatar:'salt',mobile:'Mobile',Email:'Email',email:'Email',sex:'Sex',gender:'Sex',birthday:'birthday',seturl:'seturl',Position:'Position',position:'Position' }; const data = { ...legacyData(current) }; for (const [key,target] of Object.entries(mappings)) if (source[key] !== undefined && fields[target]) current.set(target,writeValue(source[key],fields[target])); for (const [key,target] of Object.entries(legacyMappings)) if (source[key] !== undefined) data[target] = typeof source[key] === 'string' ? cleanText(source[key],target === 'salt' || target === 'seturl' ? 1000 : 200) : source[key];
  1487. const inviteCode = String(input.inviCode || '').trim(); if (inviteCode) { const existingParent = number(data.ParentUserID); const rows = await Psql.query('SELECT COALESCE("legacyUserId",("legacyUserData"->>\'UserID\')::numeric) AS id FROM "_User" WHERE "company"=$1 AND "username"=$2 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) LIMIT 1',[DEFAULT_COMPANY_ID,inviteCode]); const parentId = number(rows[0] && rows[0].id); if (!parentId) fail(400,'邀请码不存在'); if (parentId === ownId || await chainContains(parentId,ownId)) fail(400,'邀请关系不能形成循环'); if (existingParent && existingParent !== parentId) fail(409,'邀请人已完善,不能变更'); data.ParentUserID = parentId; }
  1488. current.set('legacyUserData',data); await current.save(null,{useMasterKey:true}); return { result:legacyUser(current),addon:legacyUserAddon(current) };
  1489. }
  1490. function legacyUserRow(source) {
  1491. const data = legacyData(source); const userId = number(firstValue(source.legacyUserId,source.userid,source.num,data.UserID)); const username = String(firstValue(source.username,data.UserName,'') || ''); const honeyName = String(firstValue(source.nickname,source.nickName,source.realName,data.HoneyName,username) || ''); const groupId = number(firstValue(source.legacyGroupId,data.GroupID)); const parentId = number(firstValue(data.ParentUserID,source.puid)); const avatar = String(firstValue(source.avatar,data.salt,'') || ''); const teamSize = number(firstValue(source.__teamSize,source.TeamSize)); const vip = number(firstValue(data.VIP,source.vip)); const regTime = firstValue(data.RegTime,source.createdAt); const row = { objectId:String(source.objectId || ''), userId, userName:username, honeyName, userFace:avatar, mobile:String(firstValue(source.mobile,source.phone,'') || ''), groupId, puid:parentId, vip, regTime, teamSize, email:String(firstValue(source.email,data.Email,'') || ''), realName:String(firstValue(source.realName,data.TrueName,'') || '') };
  1492. return { ...row, UserID:userId, UserName:username, HoneyName:honeyName, UserFace:avatar, GroupID:groupId, ParentUserID:parentId, VIP:vip, RegTime:regTime, TeamSize:teamSize, Email:row.email, TrueName:row.realName, UserExp:number(data.UserExp), boffExp:number(data.boffExp), salt:avatar };
  1493. }
  1494. async function findByLegacyId(className, fields, legacyId, aliases) { const field = aliases.find((name) => fields[name]); if (!field) return null; const companyClause = fields.company ? ' AND "company" = $2' : ''; const values = fields.company ? [String(legacyId),DEFAULT_COMPANY_ID] : [String(legacyId)]; const rows = await Psql.query('SELECT "objectId" FROM "' + className + '" WHERE CAST("' + field + '" AS text) = $1' + companyClause + ' LIMIT 1', values); return rows[0] ? new Parse.Query(className).get(rows[0].objectId,{useMasterKey:true}) : null; }
  1495. async function paged(className, input, configure) { const fields = await fieldsOf(className); const paging = pageInput(input); const query = new Parse.Query(className); tenant(query, fields); if (configure) configure(query, fields); const total = await query.count({ useMasterKey: true }); query.skip((paging.index - 1) * paging.size); query.limit(paging.size); query.descending(fields.updatedAt ? 'updatedAt' : 'createdAt'); const rows = (await query.find({ useMasterKey: true })).filter(isVisible); return { rows: rows.map(safe), page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } }; }
  1496. const CONTENT_ADDONS = {
  1497. 52: { className:'VocabularyWord', fields:['id','lj','sy','yb','yp'] },
  1498. 53: { className:'PracticeRecord', fields:['id','kcid','scid','xxcs','yhid','jrscb'] },
  1499. 54: { className:'CourseAppointment', fields:['id','pl','bxrq','dslx','dszt','fxpl','jffs','jssj','kcid','kssj','plxm','scsj','sdsd','szmd','szyh','yysj','yykcid'] },
  1500. 56: { className:'DailyStudyRecord', fields:['id','pl','con','djq','ygg','dqrq','dsid','fxrl','xxqs','szmdid','userId','learned'] },
  1501. 58: { className:'CourseBinding', fields:['id','yxx','cksl','kcid','syjd','yhid'] },
  1502. 59: { className:'LessonRecord', fields:['id','pf','jffs','jsmz','kcid','kclx','kcmc','kzsj','pjnr','pldp','xymz','yyds','plpjsj','szmdid'] },
  1503. 60: { className:'MemoryPracticeRecord', fields:['id','fxzt','kcid','plid','wcsj','yhid','kywrq','kywsj','xxjlid','orderId'] },
  1504. 61: { className:'AssessmentProfile', fields:['id','df','askid','wrong','userId','answerid','dontKnow','prevScore','totalScore'] }
  1505. };
  1506. const NODE_MODELS = { 28:58, 29:54, 32:53, 291:56, 296:59, 327:52, 388:60, 389:61 };
  1507. const PRIVATE_CONTENT_MODELS = new Set([53,54,56,58,59,60,61]);
  1508. const CONTENT_WRITE_AUTH = {
  1509. 53: { subjects:['yhid'], actors:[], tableName:'ZL_C_lxjl', nodeId:32 }, 54: { subjects:['szyh'], actors:['pl'], tableName:'ZL_C_order', nodeId:29 }, 56: { subjects:['userId'], actors:['pl'], tableName:'ZL_C_ss', nodeId:291 }, 58: { subjects:['yhid'], actors:[], tableName:'ZL_C_kcbd', nodeId:28 },
  1510. 59: { subjects:['xymz'], actors:['jsmz'], tableName:'ZL_C_skjl', nodeId:296 }, 60: { subjects:['yhid'], actors:['plid'], tableName:'ZL_C_kywjl', nodeId:388 }, 61: { subjects:['userId'], actors:[], tableName:'ZL_C_cespj', nodeId:389 }
  1511. };
  1512. function contentModel(input, nodeIds) { const explicit = number(input.modelId || input.modelid || input.ModelID); return explicit || (nodeIds.length === 1 ? NODE_MODELS[number(nodeIds[0])] || 0 : 0); }
  1513. function requestedContentModel(input) { const nodes = String(input.nodeid || input.nid || input.nodes || '').split(',').map(number).filter(Boolean); return contentModel(input, nodes); }
  1514. function legacyFilterPairs(input) {
  1515. const source = [input.myfield, input.myfield2].filter(Boolean).join('|'); if (!source) return [];
  1516. return source.split('|').map((part) => { const match = String(part).trim().match(/^([A-Za-z][A-Za-z0-9_.]*)=(.*)$/); if (!match) fail(400, '内容过滤条件格式错误'); return { name: match[1].replace(/^B\./i,''), value: match[2] }; });
  1517. }
  1518. function addonField(config, requested) { return config && config.fields.find((field) => field.toLowerCase() === String(requested).toLowerCase()); }
  1519. function contentQueryRequiresAuth(action, input) { return (action === 'content_list' || action === 'content_list_llk') && (PRIVATE_CONTENT_MODELS.has(requestedContentModel(input)) || legacyFilterPairs(input).length > 0); }
  1520. async function authorizeContentAccess(current, input) {
  1521. if (!PRIVATE_CONTENT_MODELS.has(requestedContentModel(input))) return; const pairs = legacyFilterPairs(input); await authorizeOwnerPairs(current, pairs.map((pair) => ({ name: pair.name.toLowerCase(), value: number(pair.value) })).filter((pair) => pair.value));
  1522. }
  1523. function isAdminUser(current) { const roles = Array.isArray(current.get('roles')) ? current.get('roles').map(String) : []; return current.get('isAdmin') === true || current.get('role') === 'admin' || roles.includes('admin'); }
  1524. async function authorizeOwnerPairs(current, pairs) {
  1525. if (isAdminUser(current)) return; const owners = pairs.filter((pair) => ['userid','yhid','xymz','jsmz','szyh'].includes(pair.name)); if (!owners.length) fail(403, '私有内容查询必须限定用户');
  1526. const ownId = number(current.get('legacyUserId') || current.get('userid') || current.get('num')); const subjects = owners.filter((pair) => ['userid','yhid','xymz'].includes(pair.name)); if (subjects.some((pair) => pair.value === ownId)) return;
  1527. const targets = subjects.length ? subjects : owners; const fields = await fieldsOf('_User'); for (const targetId of [...new Set(targets.map((pair) => pair.value))]) { if (targetId === ownId) continue; const target = await findByLegacyId('_User', fields, targetId, ['legacyUserId','userid','num']); const agent = target && target.get('agent'); if (!target || !agent || agent.id !== current.id) fail(403, '无权查看该学员的内容记录'); }
  1528. }
  1529. async function authorizeContentDetail(current, detail) { const pairs = ['userId','yhid','xymz','jsmz','szyh'].map((name) => ({ name: name.toLowerCase(), value: number(detail[name] ?? detail[name === 'userId' ? 'UserID' : name]) })).filter((pair) => pair.value); await authorizeOwnerPairs(current, pairs); }
  1530. function contentOrder(input, config) {
  1531. const raw = String(input.orders || '').trim(); if (!raw) return 'c."updatedAt" DESC'; if (/^NEWID\(\)$/i.test(raw)) return 'RANDOM()';
  1532. const match = raw.match(/^([A-Za-z][A-Za-z0-9_.]*)\s*=\s*(ASC|DESC)$/i); if (!match) return 'c."updatedAt" DESC'; const requested = match[1].replace(/^B\./i,''); const direction = match[2].toUpperCase();
  1533. const addon = addonField(config, requested); if (addon) return 'a."' + addon + '" ' + direction; const base = { id:'itemId', generalid:'generalId', createtime:'createTime', updatedat:'updatedAt', title:'title' }[requested.toLowerCase()]; return base ? 'c."' + base + '" ' + direction : 'c."updatedAt" DESC';
  1534. }
  1535. async function contentPage(input, publicOnly = false) {
  1536. const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID]; const clauses = ['c."company" = $1'];
  1537. if (input.objectId) { values.push(String(input.objectId)); clauses.push('c."objectId" = $' + values.length); }
  1538. if (input.generalId) { values.push(String(input.generalId)); clauses.push('CAST(c."generalId" AS text) = $' + values.length); }
  1539. const nodeIds = String(input.nodeid || input.nid || input.nodes || '').split(',').map((value) => String(number(value))).filter((value) => value !== '0');
  1540. if (nodeIds.length) { values.push(nodeIds); clauses.push('CAST(c."nodeId" AS text) = ANY($' + values.length + '::text[])'); }
  1541. const modelId = contentModel(input, nodeIds); const config = CONTENT_ADDONS[modelId] || null; if (modelId) { values.push(String(modelId)); clauses.push('CAST(c."modelId" AS text) = $' + values.length); }
  1542. if (publicOnly && !modelId) { values.push([...PRIVATE_CONTENT_MODELS].map(String)); clauses.push('CAST(c."modelId" AS text) <> ALL($' + values.length + '::text[])'); }
  1543. const filters = legacyFilterPairs(input); if (filters.length && !config) fail(501, '该内容模型的 addon 联表尚未映射');
  1544. for (const filter of filters) { const field = addonField(config, filter.name); if (!field) fail(501, 'addon 字段尚未映射: ' + filter.name); values.push(String(filter.value)); clauses.push('CAST(a."' + field + '" AS text) = $' + values.length); }
  1545. if (input.skey) { values.push('%' + String(input.skey).replace(/[%_]/g, '') + '%'); clauses.push('c."title" ILIKE $' + values.length); }
  1546. const join = config ? ' LEFT JOIN "' + config.className + '" a ON a."company" = $1 AND CAST(a."id" AS text) = CAST(c."itemId" AS text)' : ''; const where = clauses.join(' AND ');
  1547. const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "CommonModel" c' + join + ' WHERE ' + where, values); const rowValues = values.concat([paging.size, (paging.index - 1) * paging.size]);
  1548. const select = config ? 'c.*, row_to_json(a) AS "__addon"' : 'c.*'; const rows = await Psql.query('SELECT ' + select + ' FROM "CommonModel" c' + join + ' WHERE ' + where + ' ORDER BY ' + contentOrder(input, config) + ' LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2), rowValues);
  1549. const normalized = rows.filter(isVisible).map((source) => { const addon = source.__addon || {}; const row = { ...source, ...addon }; delete row.__addon; if (source.objectId) row.objectId = source.objectId; return legacyAliases(row, 'CommonModel'); }); const total = number(countRow.total);
  1550. return { rows: normalized, page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
  1551. }
  1552. async function sqlPage(className, input, filters = []) {
  1553. if (!['App','Node'].includes(className)) fail(400, '不允许查询该类'); const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID]; const clauses = ['"company" = $1'];
  1554. for (const filter of filters) { values.push(String(filter.value)); clauses.push('CAST("' + filter.field + '" AS text) = $' + values.length); }
  1555. const where = clauses.join(' AND '); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "' + className + '" WHERE ' + where, values); const rowValues = values.concat([paging.size, (paging.index - 1) * paging.size]);
  1556. const rows = await Psql.query('SELECT * FROM "' + className + '" WHERE ' + where + ' ORDER BY "updatedAt" DESC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2), rowValues); const total = number(countRow.total);
  1557. return { rows: rows.filter(isVisible).map((row) => legacyAliases(row, className)), page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
  1558. }
  1559. async function nodePage(input) {
  1560. const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID]; const clauses = ['"company"=$1']; if (input.pid !== undefined && input.pid !== '') { values.push(String(number(input.pid))); clauses.push('CAST("parentId" AS text)=$' + values.length); } const where = clauses.join(' AND '); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "Node" WHERE ' + where,values); const rows = await Psql.query('SELECT * FROM "Node" WHERE ' + where + ' ORDER BY CASE WHEN CAST("orderId" AS text) ~ \'^-?[0-9]+$\' THEN CAST("orderId" AS numeric) ELSE 0 END ASC, CASE WHEN CAST("nodeId" AS text) ~ \'^-?[0-9]+$\' THEN CAST("nodeId" AS numeric) ELSE 0 END ASC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2),values.concat([paging.size,(paging.index - 1) * paging.size])); const total = number(countRow.total); return { rows:rows.filter(isVisible).map((row) => legacyAliases(row,'Node')),page:{itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size} };
  1561. }
  1562. async function nodeUnitPage(input,current) {
  1563. const uid = await authorizeRequestedUser(current,input.userId || input.uid); const paging = pageInput(input); const parentId = number(input.pid); if (!parentId) fail(400,'缺少课程栏目 ID'); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "Node" WHERE "company"=$1 AND CAST("parentId" AS text)=$2',[DEFAULT_COMPANY_ID,String(parentId)]); const rows = await Psql.query('SELECT n.*,COALESCE(w.total,0)::int AS "total",COALESCE(l.learned,0)::int AS "yx_word" FROM "Node" n LEFT JOIN LATERAL (SELECT COUNT(*)::int AS total FROM "CommonModel" c WHERE c."company"=$1 AND CAST(c."modelId" AS text)=\'52\' AND CAST(c."nodeId" AS text)=CAST(n."nodeId" AS text)) w ON TRUE LEFT JOIN LATERAL (SELECT COUNT(DISTINCT CAST(p."scid" AS text))::int AS learned FROM "PracticeRecord" p JOIN "CommonModel" c ON c."company"=$1 AND CAST(c."modelId" AS text)=\'52\' AND CAST(c."generalId" AS text)=CAST(p."scid" AS text) AND CAST(c."nodeId" AS text)=CAST(n."nodeId" AS text) WHERE p."company"=$1 AND CAST(p."yhid" AS text)=$3 AND COALESCE(CAST(p."xxcs" AS numeric),0)>0) l ON TRUE WHERE n."company"=$1 AND CAST(n."parentId" AS text)=$2 ORDER BY CASE WHEN CAST(n."orderId" AS text) ~ \'^-?[0-9]+$\' THEN CAST(n."orderId" AS numeric) ELSE 0 END ASC,CASE WHEN CAST(n."nodeId" AS text) ~ \'^-?[0-9]+$\' THEN CAST(n."nodeId" AS numeric) ELSE 0 END ASC LIMIT $4 OFFSET $5',[DEFAULT_COMPANY_ID,String(parentId),String(uid),paging.size,(paging.index - 1) * paging.size]); const total = number(countRow.total); return { rows:rows.map((source) => { const row = legacyAliases(source,'Node'); row.total = number(source.total); row.yx_word = number(source.yx_word); row.process = row.total ? Math.round(row.yx_word / row.total * 100) : 0; return row; }),page:{itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size} };
  1564. }
  1565. function legacyAppRow(source) { if (!source) return null; const row = legacyAliases(source,'App'); row.ver = number(firstValue(row.index,String(row.version || '').replace(/\D/g,''))); row.nver = String(row.version || ''); row.intro = String(firstValue(row.changelog,row.desc,'') || ''); row.path = String(firstValue(row.downUrl,row.apkUrl,'') || ''); row.size = null; row.sizeUnavailable = true; return row; }
  1566. function parseArray(value) { if (Array.isArray(value)) return value; if (typeof value !== 'string' || !value.trim()) return []; try { const parsed = JSON.parse(value); return Array.isArray(parsed) ? parsed : []; } catch (_) { return []; } }
  1567. function largePageInput(input) { return { index: Math.max(1, number(input.cpage || input.page, 1)), size: Math.min(500, Math.max(1, number(input.psize || input.pageSize, 20))) }; }
  1568. function ownLegacyId(current) { return number(current && (current.get('legacyUserId') || current.get('userid') || current.get('num'))); }
  1569. async function legacyUserObject(legacyId) { const fields = await fieldsOf('_User'); return findByLegacyId('_User', fields, legacyId, ['legacyUserId','userid','num']); }
  1570. async function chainContains(startId, expectedAncestorId) {
  1571. let cursor = number(startId); const expected = number(expectedAncestorId); const visited = new Set();
  1572. for (let depth = 0; cursor && depth < 64 && !visited.has(cursor); depth += 1) { if (cursor === expected) return true; visited.add(cursor); const item = await legacyUserObject(cursor); if (!item) return false; cursor = number(legacyData(item).ParentUserID); }
  1573. return false;
  1574. }
  1575. async function authorizeTeamUser(current, requestedId) {
  1576. const ownId = ownLegacyId(current); const targetId = number(requestedId || ownId); if (!targetId) fail(400, '缺少用户 ID'); if (isAdminUser(current) || targetId === ownId) return targetId;
  1577. if (await chainContains(targetId, ownId)) return targetId; if (await chainContains(ownId, targetId)) return targetId; fail(403, '无权查看该团队成员');
  1578. }
  1579. function userSelect(alias = 'u') { return alias + '."objectId",' + alias + '."username",' + alias + '."email",' + alias + '."mobile",' + alias + '."phone",' + alias + '."avatar",' + alias + '."nickname",' + alias + '."nickName",' + alias + '."realName",' + alias + '."legacyUserId",' + alias + '."legacyGroupId",' + alias + '."legacyUserData",' + alias + '."createdAt"'; }
  1580. async function teamUserPage(input, current) {
  1581. const paging = pageInput(input); const parentId = number(input.puid || ownLegacyId(current)); if (!parentId && !isAdminUser(current)) fail(400, '团队列表必须指定上级用户'); if (parentId) await authorizeTeamUser(current,parentId);
  1582. const values = [DEFAULT_COMPANY_ID]; const clauses = ['u."company" = $1','(u."isDeleted" IS NULL OR u."isDeleted" = FALSE)']; if (parentId) { values.push(String(parentId)); clauses.push('COALESCE(u."legacyUserData"->>\'ParentUserID\',\'0\') = $' + values.length); }
  1583. const groups = String(input.gids || '').split(',').map(number).filter((value) => value > 0); if (groups.length) { values.push(groups.map(String)); clauses.push('COALESCE(CAST(u."legacyGroupId" AS text),u."legacyUserData"->>\'GroupID\',\'0\') = ANY($' + values.length + '::text[])'); }
  1584. const where = clauses.join(' AND '); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "_User" u WHERE ' + where, values); const rowValues = values.concat([paging.size,(paging.index - 1) * paging.size]); const order = groups.length ? 'CASE WHEN COALESCE(u."legacyUserData"->>\'UserExp\',\'0\') ~ \'^-?[0-9]+(?:\\.[0-9]+)?$\' THEN (u."legacyUserData"->>\'UserExp\')::numeric ELSE 0 END DESC,' : '';
  1585. const rows = await Psql.query('SELECT ' + userSelect('u') + ',(SELECT COUNT(*)::int FROM "_User" child WHERE child."company" = $1 AND COALESCE(child."legacyUserData"->>\'ParentUserID\',\'0\') = COALESCE(CAST(u."legacyUserId" AS text),u."legacyUserData"->>\'UserID\',\'0\')) AS "__teamSize" FROM "_User" u WHERE ' + where + ' ORDER BY ' + order + ' CASE WHEN COALESCE(CAST(u."legacyUserId" AS text),u."legacyUserData"->>\'UserID\',\'0\') ~ \'^[0-9]+$\' THEN COALESCE(CAST(u."legacyUserId" AS text),u."legacyUserData"->>\'UserID\',\'0\')::numeric ELSE 0 END DESC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2), rowValues); const total = number(countRow.total);
  1586. return { rows:rows.map(legacyUserRow), page:{ itemCount:total, pageCount:Math.ceil(total / paging.size), pageIndex:paging.index, pageSize:paging.size } };
  1587. }
  1588. async function teamStats(input,current) {
  1589. const parentId = await authorizeTeamUser(current,input.uid); const rows = await Psql.query('SELECT COALESCE("legacyUserData"->>\'VIP\',\'0\') AS vip,COUNT(*)::int AS total FROM "_User" WHERE "company"=$1 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) AND COALESCE("legacyUserData"->>\'ParentUserID\',\'0\')=$2 GROUP BY COALESCE("legacyUserData"->>\'VIP\',\'0\')', [DEFAULT_COMPANY_ID,String(parentId)]); const result = { childs:0,v0:0,v1:0,v2:0,v3:0,v4:0,v5:0 }; for (const row of rows) { const total = number(row.total); result.childs += total; const key = 'v' + Math.max(0,Math.min(5,number(row.vip))); result[key] += total; } return result;
  1590. }
  1591. async function coachStudentPage(input,current) {
  1592. const coachId = ownLegacyId(current); if (!coachId) fail(400,'陪练账号缺少旧系统用户 ID'); const paging = pageInput(input); const baseValues = [DEFAULT_COMPANY_ID,String(coachId)]; const base = 'FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company"=$1 AND CAST(a."id" AS text)=CAST(c."itemId" AS text) WHERE c."company"=$1 AND CAST(c."modelId" AS text)=\'54\' AND CAST(c."status" AS text)=\'99\' AND CAST(a."pl" AS text)=$2 AND COALESCE(CAST(a."szyh" AS text),\'\')<>\'\''; const countRow = await Psql.one('SELECT COUNT(DISTINCT CAST(a."szyh" AS text))::int AS total ' + base,baseValues); const rows = await Psql.query('WITH students AS (SELECT CAST(a."szyh" AS text) AS uid,MAX(CAST(a."id" AS text)) AS appointment_id ' + base + ' GROUP BY CAST(a."szyh" AS text) ORDER BY MAX(c."updatedAt") DESC LIMIT $3 OFFSET $4) SELECT ' + userSelect('u') + ',students.uid AS "__studentId",students.appointment_id AS "__appointmentId" FROM students LEFT JOIN "_User" u ON u."company"=$1 AND CAST(u."legacyUserId" AS text)=students.uid',baseValues.concat([paging.size,(paging.index - 1) * paging.size])); const normalized = rows.map((row) => { const value = legacyUserRow(row); const studentId = number(row.__studentId || value.UserID); return { ...value, userId:studentId, UserID:studentId, szyh:studentId, ID:number(row.__appointmentId), honeyname:value.HoneyName, honeyName:value.HoneyName }; }); const total = number(countRow.total); return { rows:normalized,page:{ itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size } };
  1593. }
  1594. const POINT_HISTORY_CLASSES = { 1:'UserExpDomP',2:'UserSIcon',3:'UserExpHis',4:'UserUserPoint',5:'UserDummyPoint',6:'UserCredit' };
  1595. function legacyPointRow(source) { const row = safe(source); row.ExpHisID = firstValue(row.expHisId,row.objectId); row.UserID = number(row.userId); row.HisTime = firstValue(row.hisTime,row.createdAt); row.Score = number(row.score); row.Detail = String(firstValue(row.detail,row.remark,'') || ''); row.Remark = String(row.remark || ''); row.score_before = number(row.scoreBefore); return row; }
  1596. async function pointHistoryPage(input,current) {
  1597. const stype = number(input.stype); const className = POINT_HISTORY_CLASSES[stype]; if (!className) fail(400,'虚拟币类型必须为 1-6'); const uid = await authorizeRequestedUser(current,input.uid); const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID,String(uid)]; const where = '"company"=$1 AND CAST("userId" AS text)=$2'; const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "' + className + '" WHERE ' + where,values); const rows = await Psql.query('SELECT * FROM "' + className + '" WHERE ' + where + ' ORDER BY COALESCE("hisTime","updatedAt","createdAt") DESC LIMIT $3 OFFSET $4',values.concat([paging.size,(paging.index - 1) * paging.size])); const total = number(countRow.total); return { rows:rows.filter(isVisible).map(legacyPointRow),page:{ itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size },addon:stype === 1 ? { purse_fee:null,purseFeeRuleUnavailable:true } : {} };
  1598. }
  1599. async function createGuestbook(input,current) {
  1600. const model = parseObject(input.model,'留言'); const uid = ownLegacyId(current); if (!uid) fail(400,'当前用户缺少旧系统用户 ID'); const requestedUid = number(firstValue(model.UserID,model.userid,input.UserID,input.userid,uid)); if (requestedUid !== uid && !isAdminUser(current)) fail(403,'不允许代替其他用户提交留言'); const name = cleanText(firstValue(input.name,model.Name,model.name,''),80); const title = cleanText(firstValue(model.Title,model.title,input.Title,input.title,name ? name + ' 反馈的意见' : '用户反馈'),200); const content = String(firstValue(model.TContent,model.tcontent,input.TContent,input.tcontent,input.content,'') || '').trim(); if (!content) fail(400,'请填写反馈内容'); if (content.length > 800) fail(400,'反馈内容不得超过 800 字'); const gid = Math.floor(100000000000000 + Math.random() * 800000000000000); const item = new Parse.Object('Guestbook'); item.set('company',current.get('company')); item.set('sourceKey','cloud:guestbook_add:' + uid + ':' + gid); item.set('gid',gid); item.set('gdate',new Date()); item.set('userid',requestedUid); item.set('title',title); item.set('tcontent',content); item.set('cateid',number(firstValue(model.Cateid,model.cateid,input.Cateid,input.cateid),22)); item.set('parentid',0); item.set('status',0); await item.save(null,{useMasterKey:true}); const result = safe(item); return { ...result,GID:gid,UserID:requestedUid,Title:title,TContent:content,Cateid:number(result.cateid),Status:0 };
  1601. }
  1602. async function authorizeRequestedUser(current, requestedId) {
  1603. const targetId = number(requestedId || ownLegacyId(current)); if (!targetId) fail(400, '缺少用户 ID'); if (isAdminUser(current) || targetId === ownLegacyId(current)) return targetId;
  1604. const fields = await fieldsOf('_User'); const target = await findByLegacyId('_User', fields, targetId, ['legacyUserId','userid','num']); const agent = target && target.get('agent'); if (!target || !agent || agent.id !== current.id) fail(403, '无权查看该学员的业务记录'); return targetId;
  1605. }
  1606. async function authorizeBusinessRow(current, row, subjectFields, actorFields = []) {
  1607. if (isAdminUser(current)) return; const ownId = ownLegacyId(current); const allIds = subjectFields.concat(actorFields).map((name) => number(row[name] ?? row[name.toLowerCase()] ?? row[name.toUpperCase()])).filter(Boolean); if (allIds.includes(ownId)) return;
  1608. const subjectIds = subjectFields.map((name) => number(row[name] ?? row[name.toLowerCase()] ?? row[name.toUpperCase()])).filter(Boolean); if (!subjectIds.length) fail(403, '业务记录缺少可验证的所属用户'); const fields = await fieldsOf('_User'); for (const targetId of [...new Set(subjectIds)]) { const target = await findByLegacyId('_User', fields, targetId, ['legacyUserId','userid','num']); const agent = target && target.get('agent'); if (target && agent && agent.id === current.id) return; } fail(403, '无权查看该业务记录');
  1609. }
  1610. function normalizeWordRow(source) { const addon = source.__addon || {}; const merged = { ...source, ...addon }; delete merged.__addon; return legacyAliases(merged, 'CommonModel'); }
  1611. async function orderDetailRow(inputId, current, authorize = true) {
  1612. const id = String(inputId || ''); if (!id) fail(400, '缺少预约 ID'); const rows = await Psql.query('SELECT c.*, row_to_json(a) AS "__addon", n."nodeName" AS "__courseTitle" FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company" = $1 AND CAST(a."id" AS text) = CAST(c."itemId" AS text) LEFT JOIN "Node" n ON n."company" = $1 AND CAST(n."nodeId" AS text) = CAST(a."kcid" AS text) WHERE c."company" = $1 AND CAST(c."modelId" AS text) = \'54\' AND CAST(c."generalId" AS text) = $2 LIMIT 1', [DEFAULT_COMPANY_ID, id]);
  1613. let source = rows[0]; if (!source && /^[A-Za-z0-9_-]{10,40}$/.test(id)) { const direct = await Psql.query('SELECT a.*, n."nodeName" AS "__courseTitle" FROM "CourseAppointment" a LEFT JOIN "Node" n ON n."company" = $1 AND CAST(n."nodeId" AS text) = CAST(a."kcid" AS text) WHERE a."company" = $1 AND a."objectId" = $2 LIMIT 1', [DEFAULT_COMPANY_ID, id]); if (direct[0]) source = { ...direct[0], generalId: id, GeneralID: id, title: direct[0].title || '课程预约' }; }
  1614. if (!source) return null; const addon = source.__addon || {}; const courseTitle = source.__courseTitle || source.subtitle || ''; delete source.__addon; delete source.__courseTitle; const row = legacyAliases({ ...source, ...addon }, 'CommonModel'); row.kcmc = row.kcmc || courseTitle; row.yykcmc = row.yykcmc || courseTitle; row.HoneyName = row.HoneyName || String(row.Title || '').split('(')[0]; if (authorize) await authorizeBusinessRow(current, row, ['szyh'], ['pl']); return row;
  1615. }
  1616. async function recordDetailData(input, current) {
  1617. const id = String(input.id || input.gid || ''); if (!id) fail(400, '缺少学习记录 ID'); const rows = await Psql.query('SELECT c.*, row_to_json(d) AS "__addon" FROM "CommonModel" c JOIN "DailyStudyRecord" d ON d."company" = $1 AND CAST(d."id" AS text) = CAST(c."itemId" AS text) WHERE c."company" = $1 AND CAST(c."modelId" AS text) = \'56\' AND CAST(c."generalId" AS text) = $2 LIMIT 1', [DEFAULT_COMPANY_ID, id]);
  1618. if (!rows.length) return null; const source = rows[0]; const recordAddon = source.__addon || {}; delete source.__addon; const record = legacyAliases({ ...source, ...recordAddon }, 'CommonModel'); await authorizeBusinessRow(current, record, ['userId'], ['pl']); const storedWords = parseArray(recordAddon.xxqs); const ids = [...new Set(storedWords.map((item) => String(item && (item.GeneralID ?? item.generalId ?? item.id) || '')).filter(Boolean))]; let wordRows = [];
  1619. if (ids.length) wordRows = await Psql.query('SELECT c.*, row_to_json(v) AS "__addon" FROM "CommonModel" c LEFT JOIN "VocabularyWord" v ON v."company" = $1 AND CAST(v."id" AS text) = CAST(c."itemId" AS text) WHERE c."company" = $1 AND CAST(c."modelId" AS text) = \'52\' AND CAST(c."generalId" AS text) = ANY($2::text[])', [DEFAULT_COMPANY_ID, ids]);
  1620. const details = new Map(wordRows.map((row) => { const normalized = normalizeWordRow(row); return [String(normalized.GeneralID || normalized.generalId), normalized]; })); const words = storedWords.map((item) => { const raw = item && typeof item === 'object' ? safe(item) : {}; const wordId = String(raw.GeneralID ?? raw.generalId ?? raw.id ?? ''); const detail = details.get(wordId) || legacyAliases({ generalId: wordId, title: raw.Title || raw.title || '' }, 'CommonModel'); return { ...detail, ...raw, GeneralID: number(wordId, wordId), Title: raw.Title || raw.title || detail.Title || detail.title || '', detail: [detail] }; });
  1621. const order = recordAddon.dsid ? await orderDetailRow(recordAddon.dsid, current, false) : null; return { words, addon: order ? [order] : [], record };
  1622. }
  1623. async function newWordPage(input, current) {
  1624. const uid = await authorizeRequestedUser(current, input.uid); const paging = largePageInput(input); const values = [DEFAULT_COMPANY_ID, String(uid)]; const where = 'p."company" = $1 AND CAST(p."yhid" AS text) = $2 AND LOWER(CAST(p."jrscb" AS text)) IN (\'1\',\'true\')'; const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "PracticeRecord" p WHERE ' + where, values); const rows = await Psql.query('SELECT p.*, pc."generalId" AS "__practiceGeneralId", c.*, row_to_json(v) AS "__addon" FROM "PracticeRecord" p JOIN "CommonModel" c ON c."company" = $1 AND CAST(c."modelId" AS text) = \'52\' AND CAST(c."generalId" AS text) = CAST(p."scid" AS text) LEFT JOIN "VocabularyWord" v ON v."company" = $1 AND CAST(v."id" AS text) = CAST(c."itemId" AS text) LEFT JOIN "CommonModel" pc ON pc."company" = $1 AND CAST(pc."modelId" AS text) = \'53\' AND CAST(pc."itemId" AS text) = CAST(p."id" AS text) WHERE ' + where + ' ORDER BY p."updatedAt" DESC LIMIT $3 OFFSET $4', values.concat([paging.size, (paging.index - 1) * paging.size]));
  1625. const result = rows.map((source) => { const practice = { id: source.id, kcid: source.kcid, scid: source.scid, xxcs: source.xxcs, yhid: source.yhid, jrscb: source.jrscb }; const detail = normalizeWordRow(source); return { ...practice, GeneralID: number(source.__practiceGeneralId || source.id), Title: detail.Title || detail.title || '', detail: [detail] }; }); const total = number(countRow.total); return { rows: result, page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
  1626. }
  1627. async function courseWordPage(input, current) {
  1628. const uid = await authorizeRequestedUser(current, input.uid); const nodes = String(input.nids || input.nid || '').split(',').map((value) => String(number(value))).filter((value) => value !== '0'); if (!nodes.length) fail(400, '缺少词库单元 ID'); const paging = { index: Math.max(1, number(input.cpage || input.page, 1)), size: Math.min(10000, Math.max(1, number(input.psize || input.pageSize, 1000))) }; const values = [DEFAULT_COMPANY_ID, String(uid), nodes]; const where = 'c."company" = $1 AND CAST(c."modelId" AS text) = \'52\' AND CAST(c."nodeId" AS text) = ANY($3::text[])'; const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "CommonModel" c WHERE ' + where, values); const rows = await Psql.query('SELECT c.*, row_to_json(v) AS "__addon", p."xxcs" AS "__learned", p."jrscb" AS "__newWord" FROM "CommonModel" c LEFT JOIN "VocabularyWord" v ON v."company" = $1 AND CAST(v."id" AS text) = CAST(c."itemId" AS text) LEFT JOIN LATERAL (SELECT pr."xxcs", pr."jrscb" FROM "PracticeRecord" pr WHERE pr."company" = $1 AND CAST(pr."yhid" AS text) = $2 AND CAST(pr."scid" AS text) = CAST(c."generalId" AS text) ORDER BY pr."updatedAt" DESC LIMIT 1) p ON TRUE WHERE ' + where + ' ORDER BY c."orderId" ASC, c."generalId" ASC LIMIT $4 OFFSET $5', values.concat([paging.size, (paging.index - 1) * paging.size])); const result = rows.map((source) => { const learned = number(source.__learned); const newWord = number(source.__newWord); delete source.__learned; delete source.__newWord; const word = normalizeWordRow(source); return { ...word, detail: word, gldy: word.GeneralID, w_learned: learned, ifnew: newWord }; }); const total = number(countRow.total); return { rows: result, page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
  1629. }
  1630. async function updateLearningWords(input, current) {
  1631. const uid = await authorizeRequestedUser(current, input.uid); const wordIds = [...new Set(String(input.wordsId || input.wordIds || '').split(',').map((value) => String(number(value))).filter((value) => value !== '0'))]; if (!wordIds.length) fail(400, '请选择单词'); if (wordIds.length > 100) fail(400, '单次最多操作 100 个单词'); const saveLearning = number(input.save) === 1; const hasNewWordFlag = input.ifnew !== undefined && input.ifnew !== ''; const newWordFlag = hasNewWordFlag ? (number(input.ifnew) === 1 ? '1' : '0') : null; if (!saveLearning && !hasNewWordFlag) fail(400, '缺少学习或生词操作类型'); const kcid = number(input.kcid);
  1632. const validRows = await Psql.query('SELECT CAST("generalId" AS text) AS id FROM "CommonModel" WHERE "company" = $1 AND CAST("modelId" AS text) = \'52\' AND CAST("generalId" AS text) = ANY($2::text[])', [DEFAULT_COMPANY_ID, wordIds]); const validIds = new Set(validRows.map((row) => String(row.id))); const invalid = wordIds.filter((id) => !validIds.has(id)); if (invalid.length) fail(400, '包含不存在的词库 ID: ' + invalid.join(','));
  1633. const existingRows = await Psql.query('SELECT "objectId", CAST("scid" AS text) AS "scid" FROM "PracticeRecord" WHERE "company" = $1 AND CAST("yhid" AS text) = $2 AND CAST("scid" AS text) = ANY($3::text[])', [DEFAULT_COMPANY_ID, String(uid), wordIds]); const existing = await Promise.all(existingRows.map((row) => new Parse.Query('PracticeRecord').get(row.objectId, { useMasterKey: true }))); const byWord = new Map(existing.map((item) => [String(item.get('scid')), item])); const changed = []; let created = 0;
  1634. for (const wordId of wordIds) { let item = byWord.get(wordId); if (!item) { if (!kcid) fail(400, '首次记录单词时缺少课程 ID'); item = new Parse.Object('PracticeRecord'); item.set('company', current.get('company')); item.set('sourceKey', 'cloud:e_add_words:' + uid + ':' + wordId); item.set('yhid', uid); item.set('scid', number(wordId)); item.set('kcid', String(kcid)); item.set('xxcs', 0); item.set('jrscb', '0'); created += 1; } else if (kcid && !item.get('kcid')) item.set('kcid', String(kcid)); if (saveLearning) item.set('xxcs', number(item.get('xxcs')) + 1); if (newWordFlag !== null) item.set('jrscb', newWordFlag); changed.push(item); }
  1635. const saved = await Parse.Object.saveAll(changed, { useMasterKey: true }); return { affected: saved.length, created, learnedIncremented: saveLearning ? saved.length : 0, newWordState: newWordFlag === null ? undefined : number(newWordFlag), objectIds: saved.map((item) => item.id) };
  1636. }
  1637. function parseObject(value, label) { if (value && typeof value === 'object' && !Array.isArray(value)) return value; if (typeof value !== 'string' || !value.trim()) return {}; try { const parsed = JSON.parse(value); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed; } catch (_) {} fail(400, label + '格式错误'); }
  1638. function cleanText(value, max) { return String(value == null ? '' : value).trim().slice(0, max); }
  1639. async function validateStudyWords(raw) { const words = parseArray(raw); if (words.length > 500) fail(400, '单次学习记录最多 500 个单词'); const normalized = words.map((item) => ({ GeneralID: number(item && (item.GeneralID ?? item.generalId ?? item.id)), Title: cleanText(item && (item.Title ?? item.title), 200), check: number(item && item.check) })).filter((item) => item.GeneralID); if (!normalized.length && words.length) fail(400, '学习记录中的单词 ID 无效'); if (normalized.length) { const ids = [...new Set(normalized.map((item) => String(item.GeneralID)))]; const rows = await Psql.query('SELECT CAST("generalId" AS text) AS id FROM "CommonModel" WHERE "company" = $1 AND CAST("modelId" AS text) = \'52\' AND CAST("generalId" AS text) = ANY($2::text[])', [DEFAULT_COMPANY_ID, ids]); if (new Set(rows.map((row) => String(row.id))).size !== ids.length) fail(400, '学习记录包含不存在的词库 ID'); } return normalized; }
  1640. async function upsertStudyRecord(input, current) {
  1641. const uid = await authorizeRequestedUser(current, input.uid); const orderId = String(input.orderId || input.id || '').trim(); if (!orderId) fail(400, '缺少预约 ID'); const order = await orderDetailRow(orderId, current); if (!order) fail(404, '预约记录不存在'); const orderOwner = number(order.szyh); if (orderOwner && orderOwner !== uid) fail(403, '预约记录与学员不匹配'); const addon = parseObject(input.addon, '学习记录'); const wordsProvided = addon.xxqs !== undefined; const words = wordsProvided ? await validateStudyWords(addon.xxqs) : null; const inputer = cleanText(input.inputer || current.get('nickname') || current.get('realName') || current.get('username'), 100); const title = cleanText(input.title || inputer, 200) || '学习记录';
  1642. const rows = await Psql.query('SELECT c."objectId" AS "commonObjectId", c."generalId", d."objectId" AS "recordObjectId" FROM "CommonModel" c JOIN "DailyStudyRecord" d ON d."company" = $1 AND CAST(d."id" AS text) = CAST(c."itemId" AS text) WHERE c."company" = $1 AND CAST(c."modelId" AS text) = \'56\' AND CAST(d."dsid" AS text) = $2 AND CAST(d."userId" AS text) = $3 ORDER BY c."updatedAt" DESC LIMIT 1', [DEFAULT_COMPANY_ID, orderId, String(uid)]); const found = rows[0] || null; let record; let common; let created = false;
  1643. if (found) { record = await new Parse.Query('DailyStudyRecord').get(found.recordObjectId, { useMasterKey: true }); common = await new Parse.Query('CommonModel').get(found.commonObjectId, { useMasterKey: true }); }
  1644. const applyFields = (target) => { const actorId = ownLegacyId(current); target.set('userId', uid); target.set('dsid', orderId); target.set('pl', actorId && actorId !== uid ? String(actorId) : '0'); if (addon.con !== undefined) target.set('con', cleanText(addon.con, 1000)); if (addon.dqrq !== undefined) { const date = cleanText(addon.dqrq, 20); if (!/^\d{8}$/.test(date)) fail(400, '学习日期必须为 yyyymmdd'); target.set('dqrq', date); } if (addon.szmdid !== undefined) target.set('szmdid', cleanText(addon.szmdid, 100)); if (addon.fxrl !== undefined) target.set('fxrl', cleanText(addon.fxrl, 1000)); if (wordsProvided) { const learned = words.length; target.set('xxqs', JSON.stringify(words)); target.set('learned', learned); target.set('ygg', words.filter((item) => item.check === 1).length); target.set('djq', words.filter((item) => item.check === 2).length); } else { for (const name of ['learned','ygg','djq']) if (addon[name] !== undefined) target.set(name, Math.max(0, number(addon[name]))); } };
  1645. if (record) { applyFields(record); common.set('title', title); common.set('inputer', inputer); common.set('hits', number(record.get('learned'))); await Parse.Object.saveAll([record, common], { useMasterKey: true }); return { GeneralID: number(found.generalId), generalId: number(found.generalId), objectId: common.id, recordObjectId: record.id, created: false }; }
  1646. created = true; const baseId = Math.floor(100000000000000 + Math.random() * 800000000000000); const recordId = baseId; const generalId = baseId + 1; record = new Parse.Object('DailyStudyRecord'); record.set('company', current.get('company')); record.set('sourceKey', 'cloud:stu_record:' + uid + ':' + orderId); applyFields(record); await record.save(null, { useMasterKey: true }); try { await Psql.none('UPDATE "DailyStudyRecord" SET "id" = $1 WHERE "objectId" = $2', [recordId, record.id]); common = new Parse.Object('CommonModel'); common.set('company', current.get('company')); common.set('sourceKey', 'cloud:stu_record:' + uid + ':' + orderId); common.set('generalId', generalId); common.set('itemId', recordId); common.set('modelId', 56); common.set('nodeId', 291); common.set('tableName', 'ZL_C_ss'); common.set('title', title); common.set('inputer', inputer); common.set('hits', number(record.get('learned'))); common.set('status', 99); await common.save(null, { useMasterKey: true }); } catch (error) { if (common && common.id) await common.destroy({ useMasterKey: true }).catch(() => undefined); await record.destroy({ useMasterKey: true }).catch(() => undefined); throw error; } return { GeneralID: generalId, generalId, objectId: common.id, recordObjectId: record.id, created };
  1647. }
  1648. function reviewSchedule() {
  1649. const shifted = new Date(Date.now() + 8 * 60 * 60 * 1000); const today = new Date(Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth(), shifted.getUTCDate())); const pad = (value) => String(value).padStart(2, '0');
  1650. return [1,2,3,5,7,9,11,14,17,21,30,40,50,60,90].map((offset) => { const day = new Date(today.getTime() + offset * 86400000); return day.getUTCFullYear() + pad(day.getUTCMonth() + 1) + pad(day.getUTCDate()); }).join(',');
  1651. }
  1652. async function createStudyContent(input, current) {
  1653. const content = parseObject(input.content, '内容'); const addon = parseObject(input.addon, '附表内容'); const modelId = number(content.ModelID ?? content.modelId); if (modelId !== 56) fail(400, 'content_add_zt 只支持每日学习记录 Model 56');
  1654. const uid = await authorizeRequestedUser(current, addon.UserID ?? addon.userId); const words = addon.xxqs === undefined ? [] : await validateStudyWords(addon.xxqs); const actorId = ownLegacyId(current); const recordId = Math.floor(100000000000000 + Math.random() * 800000000000000); const generalId = recordId + 1; let record; let common;
  1655. record = new Parse.Object('DailyStudyRecord'); record.set('company', current.get('company')); record.set('sourceKey', 'cloud:content_add_zt:' + uid + ':' + generalId); record.set('userId', uid); record.set('pl', actorId && actorId !== uid ? String(actorId) : '0'); record.set('fxrl', reviewSchedule()); record.set('xxqs', JSON.stringify(words)); record.set('learned', words.length || Math.max(0, number(addon.learned))); record.set('ygg', words.length ? words.filter((item) => item.check === 1).length : Math.max(0, number(addon.ygg))); record.set('djq', words.length ? words.filter((item) => item.check === 2).length : Math.max(0, number(addon.djq)));
  1656. if (addon.con !== undefined) record.set('con', cleanText(addon.con, 1000)); if (addon.dqrq !== undefined) { const date = cleanText(addon.dqrq, 20); if (!/^\d{8}$/.test(date)) fail(400, '学习日期必须为 yyyymmdd'); record.set('dqrq', date); } if (addon.dsid !== undefined) record.set('dsid', cleanText(addon.dsid, 100)); if (addon.szmdid !== undefined) record.set('szmdid', cleanText(addon.szmdid, 100));
  1657. await record.save(null, { useMasterKey: true }); try { await Psql.none('UPDATE "DailyStudyRecord" SET "id" = $1 WHERE "objectId" = $2', [recordId, record.id]); common = new Parse.Object('CommonModel'); common.set('company', current.get('company')); common.set('sourceKey', 'cloud:content_add_zt:' + uid + ':' + generalId); common.set('generalId', generalId); common.set('itemId', recordId); common.set('modelId', 56); common.set('nodeId', number(content.nodeId ?? content.NodeID, 291) || 291); common.set('tableName', 'ZL_C_ss'); common.set('title', cleanText(content.title ?? content.Title, 200) || cleanText(current.get('nickname') || current.get('username'), 200) || '学习记录'); common.set('inputer', cleanText(content.inputer ?? content.Inputer ?? current.get('username'), 100)); common.set('hits', number(content.Hits ?? content.hits, record.get('learned'))); common.set('status', number(content.Status ?? content.status, 99)); await common.save(null, { useMasterKey: true }); } catch (error) { if (common && common.id) await common.destroy({ useMasterKey: true }).catch(() => undefined); await record.destroy({ useMasterKey: true }).catch(() => undefined); throw error; }
  1658. return String(generalId);
  1659. }
  1660. function writeAddonField(config, requested) { const normalized = String(requested).replace(/[^A-Za-z0-9]/g, '').toLowerCase(); return config && config.fields.find((field) => field.replace(/[^A-Za-z0-9]/g, '').toLowerCase() === normalized); }
  1661. function writeValue(value, definition) {
  1662. if (!definition) return value; if (definition.type === 'Number') { const parsed = Number(value); if (!Number.isFinite(parsed)) fail(400, '数值字段格式错误'); return parsed; }
  1663. if (definition.type === 'Boolean') return [true,1,'1','true','True','TRUE'].includes(value); if (definition.type === 'Date') { const date = new Date(value); if (Number.isNaN(date.getTime())) fail(400, '日期字段格式错误'); return date; }
  1664. if (definition.type === 'String') return typeof value === 'string' ? value.slice(0, 50000) : JSON.stringify(value).slice(0, 50000); fail(400, '不支持写入字段类型 ' + definition.type);
  1665. }
  1666. function snapshotFields(object, fields) { const snapshot = {}; for (const field of fields) snapshot[field] = Object.prototype.hasOwnProperty.call(object.attributes || {}, field) ? { exists:true, value:object.get(field) } : { exists:false }; return snapshot; }
  1667. function restoreFields(object, snapshot) { for (const [field,state] of Object.entries(snapshot)) { if (state.exists) object.set(field, state.value); else object.unset(field); } }
  1668. async function updateContentPair(input, current) {
  1669. const content = parseObject(input.content, '内容'); const addonInput = parseObject(input.addon, '附表内容'); const generalId = String(content.GeneralID ?? content.generalId ?? input.id ?? input.generalId ?? '').trim(); if (!generalId) fail(400, '缺少内容 GeneralID');
  1670. const resolved = await resolveContent({ id: generalId }, true); const common = resolved.object; if (!common) fail(404, '指定内容不存在'); const modelId = number(common.get('modelId')); const config = CONTENT_ADDONS[modelId]; const auth = CONTENT_WRITE_AUTH[modelId]; if (!config || !auth) fail(501, '目标 Schema 未迁移内容模型 ' + modelId); if (modelId === 59 && number(common.get('nodeId')) !== 296) fail(501, 'Model 59 的非课次节点缺少独立目标 Schema');
  1671. const addonRows = await Psql.query('SELECT "objectId" FROM "' + config.className + '" WHERE "company" = $1 AND CAST("id" AS text) = $2 LIMIT 1', [DEFAULT_COMPANY_ID, String(common.get('itemId'))]); const addon = addonRows[0] ? await new Parse.Query(config.className).get(addonRows[0].objectId, { useMasterKey: true }) : null; if (!addon) fail(404, '内容附表不存在'); const existing = safe(addon); await authorizeBusinessRow(current, existing, auth.subjects, auth.actors);
  1672. const addonSchema = await fieldsOf(config.className); const addonChanged = []; const addonSnapshot = {}; for (const [requested,value] of Object.entries(addonInput)) { if (String(requested).toLowerCase() === 'id') continue; const field = writeAddonField(config, requested); if (!field || !addonSchema[field] || ['id','company','sourceKey'].includes(field)) fail(400, '不允许更新附表字段 ' + requested); if (auth.subjects.concat(auth.actors).includes(field) && String(existing[field] ?? '') !== String(value ?? '')) fail(403, '不允许变更内容所属用户'); if (!addonSnapshot[field]) Object.assign(addonSnapshot, snapshotFields(addon, [field])); addon.set(field, writeValue(value, addonSchema[field])); addonChanged.push(field); }
  1673. const commonSnapshot = snapshotFields(common, ['upDateTime','title','template','createTime']); const commonChanged = ['upDateTime']; common.set('upDateTime', new Date()); const title = content.Title ?? content.title; if (title !== undefined && String(title).trim()) { common.set('title', cleanText(title, 200)); commonChanged.push('title'); } const template = content.Template ?? content.template; if (template !== undefined && template !== null) { common.set('template', String(template) === '-100' ? '' : cleanText(template, 500)); commonChanged.push('template'); } const createTime = content.CreateTime ?? content.createTime; if (createTime) { const date = new Date(createTime); if (Number.isNaN(date.getTime()) || date.getUTCFullYear() <= 1970) fail(400, '内容创建时间格式错误'); common.set('createTime', date); commonChanged.push('createTime'); }
  1674. if (!addonChanged.length && commonChanged.length === 1) fail(400, '没有可更新的内容字段'); try { await Parse.Object.saveAll([addon, common], { useMasterKey: true }); } catch (error) { restoreFields(addon, addonSnapshot); restoreFields(common, commonSnapshot); await Parse.Object.saveAll([addon, common], { useMasterKey: true }).catch(() => undefined); throw error; } return String(common.get('generalId'));
  1675. }
  1676. async function createContentPair(input, current) {
  1677. const content = parseObject(input.content, '内容'); const addonInput = parseObject(input.addon, '附表内容'); const modelId = number(content.ModelID ?? content.modelId); const config = CONTENT_ADDONS[modelId]; const auth = CONTENT_WRITE_AUTH[modelId]; if (!config || !auth) fail(501, '目标 Schema 未迁移内容模型 ' + modelId); const nodeId = number(content.NodeID ?? content.nodeId, auth.nodeId); if (modelId === 59 && nodeId !== 296) fail(501, 'Model 59 的非课次节点缺少独立目标 Schema');
  1678. const ownerField = auth.subjects[0]; const ownerRequested = Object.entries(addonInput).find(([key]) => writeAddonField(config, key) === ownerField); const ownerId = number(ownerRequested && ownerRequested[1]); if (!ownerId) fail(400, '附表缺少所属用户字段 ' + ownerField); await authorizeRequestedUser(current, ownerId); const actorId = ownLegacyId(current); const schema = await fieldsOf(config.className); const recordId = Math.floor(100000000000000 + Math.random() * 800000000000000); const generalId = recordId + 1; let addon; let common;
  1679. addon = new Parse.Object(config.className); addon.set('company', current.get('company')); addon.set('sourceKey', 'cloud:content_add:' + ownerId + ':' + generalId); for (const [requested,value] of Object.entries(addonInput)) { if (String(requested).toLowerCase() === 'id') continue; const field = writeAddonField(config, requested); if (!field || !schema[field] || ['id','company','sourceKey'].includes(field)) fail(400, '不允许写入附表字段 ' + requested); if (auth.subjects.includes(field) && number(value) !== ownerId) fail(403, '不允许变更内容所属用户'); if (auth.actors.includes(field) && number(value) && !isAdminUser(current) && number(value) !== actorId) fail(403, '不允许冒用其他业务操作人'); addon.set(field, writeValue(value, schema[field])); }
  1680. if (modelId === 56 && addonInput.xxqs !== undefined) { const words = await validateStudyWords(addonInput.xxqs); addon.set('xxqs', JSON.stringify(words)); addon.set('learned', words.length); addon.set('ygg', words.filter((item) => item.check === 1).length); addon.set('djq', words.filter((item) => item.check === 2).length); }
  1681. await addon.save(null, { useMasterKey: true }); try { await Psql.none('UPDATE "' + config.className + '" SET "id" = $1 WHERE "objectId" = $2', [recordId, addon.id]); common = new Parse.Object('CommonModel'); common.set('company', current.get('company')); common.set('sourceKey', 'cloud:content_add:' + ownerId + ':' + generalId); common.set('generalId', generalId); common.set('itemId', recordId); common.set('modelId', modelId); common.set('nodeId', nodeId || auth.nodeId); common.set('tableName', auth.tableName); common.set('title', cleanText(content.Title ?? content.title, 200) || cleanText(current.get('nickname') || current.get('username'), 200) || '内容记录'); common.set('inputer', cleanText(content.Inputer ?? content.inputer ?? current.get('username'), 100)); common.set('hits', number(content.Hits ?? content.hits)); common.set('status', number(content.Status ?? content.status, 99)); if (content.Template ?? content.template) common.set('template', cleanText(content.Template ?? content.template, 500)); await common.save(null, { useMasterKey: true }); } catch (error) { if (common && common.id) await common.destroy({ useMasterKey: true }).catch(() => undefined); await addon.destroy({ useMasterKey: true }).catch(() => undefined); throw error; }
  1682. return String(generalId);
  1683. }
  1684. function randomObjectId() { const chars = '0123456789abcdef'; let value = ''; for (let index = 0; index < 20; index += 1) value += chars[Math.floor(Math.random() * chars.length)]; return value; }
  1685. function periodConfig(type) { return ({ 1:{ field:'Purse', ledger:'UserExpDomP', point:0.5 }, 2:{ field:'SilverCoin', ledger:'UserSIcon', point:1 }, 3:{ field:'UserExp', ledger:'UserExpHis', point:0 }, 4:{ field:'UserPoint', ledger:'UserUserPoint', point:0 } })[number(type)] || null; }
  1686. async function deductOrderPeriod(student, uid, type, orderId, detail) {
  1687. const config = periodConfig(type); if (!config) fail(400, '不支持的课时类型'); const periodKey = 'cloud:e_order_update:' + orderId + ':period'; const pointKey = 'cloud:e_order_update:' + orderId + ':point'; const sql = 'WITH locked AS (SELECT "objectId", COALESCE(("legacyUserData"->>$2)::numeric,0) AS before, COALESCE(("legacyUserData"->>\'UserPoint\')::numeric,0) AS point_before FROM "_User" WHERE "objectId"=$1 FOR UPDATE), claim AS (INSERT INTO "' + config.ledger + '" ("objectId","createdAt","updatedAt","company","sourceKey","score","scoreBefore","userId","hisTime","operator","scoreType","detail","remark","operatorIp","type1","type2","type3","attach","extend") SELECT $5,NOW(),NOW(),$7,$3,-1,locked.before,$8,NOW(),2,$9,$10,\'API\',\'\',\'0\',\'\',\'\',\'\',\'\' FROM locked WHERE locked.before >= 1 ON CONFLICT ("sourceKey") DO NOTHING RETURNING "objectId"), updated AS (UPDATE "_User" u SET "legacyUserData"=CASE WHEN $11::numeric > 0 THEN jsonb_set(jsonb_set(COALESCE(u."legacyUserData",\'{}\'::jsonb),ARRAY[$2]::text[],to_jsonb((locked.before-1)::numeric),true),ARRAY[\'UserPoint\']::text[],to_jsonb(GREATEST(locked.point_before-$11::numeric,0)),true) ELSE jsonb_set(COALESCE(u."legacyUserData",\'{}\'::jsonb),ARRAY[$2]::text[],to_jsonb((locked.before-1)::numeric),true) END, "updatedAt"=NOW() FROM locked,claim WHERE u."objectId"=locked."objectId" RETURNING u."objectId"), point_log AS (INSERT INTO "UserUserPoint" ("objectId","createdAt","updatedAt","company","sourceKey","score","scoreBefore","userId","hisTime","operator","scoreType","detail","remark","operatorIp","type1","type2","type3","attach","extend") SELECT $6,NOW(),NOW(),$7,$4,-$11,GREATEST(locked.point_before-$11::numeric,0),$8,NOW(),2,$9,$10,\'API\',\'\',\'0\',\'\',\'\',\'\',\'\' FROM locked,claim WHERE $11::numeric > 0 ON CONFLICT ("sourceKey") DO NOTHING RETURNING "objectId") SELECT (SELECT COUNT(*)::int FROM claim) AS claimed,(SELECT before FROM locked) AS before,(SELECT point_before FROM locked) AS point_before'; const rows = await Psql.query(sql, [student.id,config.field,periodKey,pointKey,randomObjectId(),randomObjectId(),DEFAULT_COMPANY_ID,uid,number(type),detail,config.point]); const row = rows[0] || {}; if (row.before === undefined) fail(404, '学员不存在'); if (number(row.before) < 1 && !number(row.claimed)) fail(409, '课时不足'); return { claimed:number(row.claimed) === 1, config, periodKey, pointKey };
  1688. }
  1689. async function rollbackOrderPeriod(studentId, config, periodKey, pointKey) {
  1690. const sql = 'WITH period_deleted AS (DELETE FROM "' + config.ledger + '" WHERE "sourceKey"=$2 RETURNING 1), point_deleted AS (DELETE FROM "UserUserPoint" WHERE "sourceKey"=$3 RETURNING 1), updated AS (UPDATE "_User" u SET "legacyUserData"=CASE WHEN $5::numeric > 0 THEN jsonb_set(jsonb_set(COALESCE(u."legacyUserData",\'{}\'::jsonb),ARRAY[$4]::text[],to_jsonb((COALESCE((u."legacyUserData"->>$4)::numeric,0)+1)::numeric),true),ARRAY[\'UserPoint\']::text[],to_jsonb((COALESCE((u."legacyUserData"->>\'UserPoint\')::numeric,0)+$5::numeric)),true) ELSE jsonb_set(COALESCE(u."legacyUserData",\'{}\'::jsonb),ARRAY[$4]::text[],to_jsonb((COALESCE((u."legacyUserData"->>$4)::numeric,0)+1)::numeric),true) END,"updatedAt"=NOW() WHERE u."objectId"=$1 AND EXISTS(SELECT 1 FROM period_deleted) RETURNING 1) SELECT (SELECT COUNT(*)::int FROM updated) AS restored'; await Psql.query(sql, [studentId,periodKey,pointKey,config.field,config.point]);
  1691. }
  1692. async function memoryReviewsForOrder(orderId, order, current) {
  1693. const rows = await Psql.query('SELECT d.*,c."generalId" AS "recordGeneralId" FROM "DailyStudyRecord" d JOIN "CommonModel" c ON c."company"=$1 AND CAST(c."modelId" AS text)=\'56\' AND CAST(c."itemId" AS text)=CAST(d."id" AS text) WHERE d."company"=$1 AND CAST(d."userId" AS text)=$2 AND CAST(d."dsid" AS text)=$3 ORDER BY d."updatedAt" DESC LIMIT 1', [DEFAULT_COMPANY_ID,String(number(order.szyh)),String(orderId)]); const study = rows[0]; if (!study) return { created:[], count:0 }; const dates = [...new Set(String(study.fxrl || '').split(',').filter((date) => /^\d{8}$/.test(date)))].slice(0, 15); const created = [];
  1694. try { for (const date of dates) { const key = 'cloud:e_order_update:' + orderId + ':review:' + date; const existingRecordRows = await Psql.query('SELECT "objectId","id" FROM "MemoryPracticeRecord" WHERE "company"=$1 AND "sourceKey"=$2 LIMIT 1', [DEFAULT_COMPANY_ID,key]); let record = existingRecordRows[0] ? await new Parse.Query('MemoryPracticeRecord').get(existingRecordRows[0].objectId,{useMasterKey:true}) : null; const existingCommonRows = await Psql.query('SELECT "objectId" FROM "CommonModel" WHERE "company"=$1 AND "sourceKey"=$2 LIMIT 1', [DEFAULT_COMPANY_ID,key]); if (record && existingCommonRows[0]) continue; const recordId = record ? number(record.get('id')) : Math.floor(100000000000000 + Math.random() * 800000000000000); if (!record) { record = new Parse.Object('MemoryPracticeRecord'); record.set('company',current.get('company')); record.set('sourceKey',key); record.set('yhid',number(order.szyh)); record.set('plid',number(order.fxpl || order.pl)); record.set('orderId',number(orderId)); record.set('xxjlid',number(study.recordGeneralId)); record.set('kcid',number(order.kcid)); const iso = date.slice(0,4)+'-'+date.slice(4,6)+'-'+date.slice(6,8); record.set('kywrq',iso); record.set('kywsj',iso+' '+cleanText(order.sdsd,20)); await record.save(null,{useMasterKey:true}); await Psql.none('UPDATE "MemoryPracticeRecord" SET "id"=$1 WHERE "objectId"=$2',[recordId,record.id]); created.push({ record, common:null }); } if (!existingCommonRows[0]) { const common = new Parse.Object('CommonModel'); common.set('company',current.get('company')); common.set('sourceKey',key); common.set('generalId',recordId+1); common.set('itemId',recordId); common.set('modelId',60); common.set('nodeId',388); common.set('tableName','ZL_C_gywjl'); common.set('title',cleanText(order.HoneyName || order.Title,120)+'@21天抗遗忘@'+date.slice(0,4)+'-'+date.slice(4,6)+'-'+date.slice(6,8)); common.set('inputer',cleanText(current.get('nickname') || current.get('username'),100)); common.set('hits',0); common.set('status',99); await common.save(null,{useMasterKey:true}); const tracked = created.find((item) => item.record.id === record.id); if (tracked) tracked.common = common; else created.push({ record:null, common }); } } return { created, count:dates.length }; } catch (error) { for (const pair of created.reverse()) { if (pair.common) await pair.common.destroy({useMasterKey:true}).catch(() => undefined); if (pair.record) await pair.record.destroy({useMasterKey:true}).catch(() => undefined); } throw error; }
  1695. }
  1696. async function appointmentObject(orderId) { const rows = await Psql.query('SELECT a."objectId" FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company"=$1 AND CAST(a."id" AS text)=CAST(c."itemId" AS text) WHERE c."company"=$1 AND CAST(c."modelId" AS text)=\'54\' AND CAST(c."generalId" AS text)=$2 LIMIT 1',[DEFAULT_COMPANY_ID,String(orderId)]); if (rows[0]) return new Parse.Query('CourseAppointment').get(rows[0].objectId,{useMasterKey:true}); if (/^[A-Za-z0-9_-]{10,40}$/.test(String(orderId))) return new Parse.Query('CourseAppointment').get(String(orderId),{useMasterKey:true}); return null; }
  1697. async function updateOrderStatus(input, current) {
  1698. const content = parseObject(input.content,'预约更新内容'); const orderId = String(content.GeneralID ?? content.generalId ?? input.orderId ?? input.id ?? '').trim(); if (!orderId) fail(400,'缺少预约 ID'); const status = number(input.status,-1); if (![10,11,20,30].includes(status)) fail(400,'不支持的预约状态'); const order = await orderDetailRow(orderId,current,false); if (!order) fail(404,'预约记录不存在'); const actorId = ownLegacyId(current); const studentId = number(order.szyh); const coachId = number(order.pl); const requiredActor = status === 20 ? studentId : coachId; if (!isAdminUser(current) && actorId !== requiredActor) fail(403,status === 20 ? '仅预约学员可以确认评价' : '仅预约陪练可以更新课程状态'); const previous = number(order.dszt); const allowed = ({10:[0,10],11:[10,11],20:[11,20],30:[11,20,30]})[status]; if (!allowed.includes(previous)) fail(409,'预约状态不能从 '+previous+' 更新为 '+status); if (previous === status) return { GeneralID:orderId,previousStatus:previous,status,unchanged:true };
  1699. const appointment = await appointmentObject(orderId); if (!appointment) fail(404,'预约附表不存在'); let reviews = {created:[],count:0}; let period = null; let student = null; try { if (status === 11) { reviews = await memoryReviewsForOrder(orderId,order,current); const fields = await fieldsOf('_User'); student = await findByLegacyId('_User',fields,studentId,['legacyUserId','userid','num']); if (!student) fail(404,'预约学员不存在'); period = await deductOrderPeriod(student,studentId,number(order.dslx),orderId,new Date().toISOString().slice(0,16).replace('T',' ')+'学习结束,订单:'+orderId); }
  1700. appointment.set('dszt',String(status)); const now = cleanText(content.UpDateTime ?? content.updateTime,30) || new Date().toISOString().slice(0,16).replace('T',' '); if (status === 10) appointment.set('kssj',now); if (status === 11) appointment.set('jssj',now); await appointment.save(null,{useMasterKey:true}); return { GeneralID:orderId,previousStatus:previous,status,unchanged:false,reviewCount:reviews.count,periodDeducted:Boolean(period && period.claimed) }; }
  1701. catch (error) { if (period && period.claimed && student) await rollbackOrderPeriod(student.id,period.config,period.periodKey,period.pointKey).catch(() => undefined); for (const pair of reviews.created.reverse()) { if (pair.common) await pair.common.destroy({useMasterKey:true}).catch(() => undefined); if (pair.record) await pair.record.destroy({useMasterKey:true}).catch(() => undefined); } throw error; }
  1702. }
  1703. async function orderStatistics(input, current) {
  1704. const uid = await authorizeRequestedUser(current, input.uid); let target = current; if (uid !== ownLegacyId(current)) { const fields = await fieldsOf('_User'); target = await findByLegacyId('_User', fields, uid, ['legacyUserId','userid','num']); } if (!target) fail(404, '用户不存在'); const groupId = number(target.get('legacyGroupId') || target.get('groupId')); let t30 = 0; let t60 = 0; let tTiyan = 0; let total = 0; let commission = 0; let duration = 0;
  1705. if (groupId === 3) { const row = await Psql.one('SELECT COUNT(*) FILTER (WHERE CAST("kclx" AS text) = \'1\')::int AS t30, COUNT(*) FILTER (WHERE CAST("kclx" AS text) = \'2\')::int AS t60, COUNT(*) FILTER (WHERE CAST("kclx" AS text) = \'3\')::int AS tiyan, COUNT(*)::int AS total FROM "LessonRecord" WHERE "company" = $1 AND CAST("jsmz" AS text) = $2', [DEFAULT_COMPANY_ID, String(uid)]); t30 = number(row.t30); t60 = number(row.t60); tTiyan = number(row.tiyan); total = number(row.total); commission = t30 * 20 + t60 * 40 + tTiyan * 40; duration = t30 * 0.5 + t60 + tTiyan; }
  1706. else if (groupId === 1) { const row = await Psql.one('SELECT COUNT(*) FILTER (WHERE CAST("dslx" AS text) = \'1\')::int AS t30, COUNT(*) FILTER (WHERE CAST("dslx" AS text) = \'2\')::int AS t60, COUNT(*) FILTER (WHERE CAST("dslx" AS text) = \'3\')::int AS tiyan FROM "CourseAppointment" WHERE "company" = $1 AND CAST("szyh" AS text) = $2 AND CAST("dszt" AS text) ~ \'^[0-9]+$\' AND CAST("dszt" AS numeric) > 10', [DEFAULT_COMPANY_ID, String(uid)]); const practice = await Psql.one('SELECT COUNT(*)::int AS total FROM "PracticeRecord" WHERE "company" = $1 AND CAST("yhid" AS text) = $2', [DEFAULT_COMPANY_ID, String(uid)]); t30 = number(row.t30); t60 = number(row.t60); tTiyan = number(row.tiyan); total = number(practice.total); duration = t30 * 0.5 + t60 + tTiyan; }
  1707. return { t30:String(t30), t60:String(t60), t_tiyan:String(tTiyan), t_shichang:String(duration), t_total:String(total), t_yongji:String(commission) };
  1708. }
  1709. function learnedDate(row) { const raw = String(row.dqrq || '').trim(); return /^\d{8}$/.test(raw) ? raw.slice(0,4) + '-' + raw.slice(4,6) + '-' + raw.slice(6,8) : String(row.kywsj || '').slice(0,10); }
  1710. async function memoryPage(input, current) {
  1711. const uid = await authorizeRequestedUser(current, input.uid); const paging = largePageInput(input); const income = number(input.shouru) === 1; const values = [DEFAULT_COMPANY_ID, String(uid)]; const clauses = ['c."company" = $1', 'CAST(c."modelId" AS text) = \'60\'', 'CAST(m."' + (income ? 'plid' : 'yhid') + '" AS text) = $2']; if (input.status !== undefined && input.status !== '') { values.push(String(number(input.status))); clauses.push('CAST(m."fxzt" AS text) = $' + values.length); } const where = clauses.join(' AND '); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "CommonModel" c JOIN "MemoryPracticeRecord" m ON m."company" = $1 AND CAST(m."id" AS text) = CAST(c."itemId" AS text) WHERE ' + where, values); const rowValues = values.concat([paging.size, (paging.index - 1) * paging.size]);
  1712. const rows = await Psql.query('SELECT c.*, row_to_json(m) AS "__addon", d."learned", d."dqrq", n."nodeName" AS "kc_title" FROM "CommonModel" c JOIN "MemoryPracticeRecord" m ON m."company" = $1 AND CAST(m."id" AS text) = CAST(c."itemId" AS text) LEFT JOIN "CommonModel" dc ON dc."company" = $1 AND CAST(dc."modelId" AS text) = \'56\' AND CAST(dc."generalId" AS text) = CAST(m."xxjlid" AS text) LEFT JOIN "DailyStudyRecord" d ON d."company" = $1 AND CAST(d."id" AS text) = CAST(dc."itemId" AS text) LEFT JOIN "Node" n ON n."company" = $1 AND CAST(n."nodeId" AS text) = CAST(m."kcid" AS text) WHERE ' + where + ' ORDER BY m."kywsj" DESC, c."updatedAt" DESC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2), rowValues); const result = rows.map((source) => { const addon = source.__addon || {}; delete source.__addon; const row = legacyAliases({ ...source, ...addon }, 'CommonModel'); row.learned_date = learnedDate(row); if (income) { row.money = 0; row.incomeRuleUnavailable = true; } return row; }); const total = number(countRow.total); return { rows: result, page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
  1713. }
  1714. async function resolveContent(input, requireOne = false) { const fields = await fieldsOf('CommonModel'); const id = String(input.id || input.gid || input.generalId || ''); if (!id) { const query = new Parse.Query('CommonModel'); tenant(query, fields); if (requireOne) fail(400, '缺少内容 ID'); return { query, fields }; } if (!/^\d+$/.test(id) && /^[A-Za-z0-9_-]{10,40}$/.test(id)) { const byObjectId = new Parse.Query('CommonModel'); tenant(byObjectId, fields); try { return { object: await byObjectId.get(id, { useMasterKey: true }), fields }; } catch (_) {} } const rows = await Psql.query('SELECT "objectId" FROM "CommonModel" WHERE "company" = $1 AND CAST("generalId" AS text) = $2 LIMIT 1', [DEFAULT_COMPANY_ID, id]); if (!rows[0]) return { object:null, fields }; return { object:await new Parse.Query('CommonModel').get(rows[0].objectId, { useMasterKey: true }), fields }; }
  1715. async function handler(request, response) {
  1716. try {
  1717. const input = inputOf(request); const action = String(input.action || ''); if (!action) return response.status(400).json(reject('缺少 action'));
  1718. if (action === 'migration_status') return response.json(envelope({ implemented: ['app_update','user_login_passwd','user_register','user_info_name','user_get','user_list','user_dept','e_user_list','user_update','content_list','content_list_llk','content_get','content_uphis','content_add','content_add_zt','content_update','node_list','node_get','e_add_words','e_ck_list','e_get_21list','e_order_detail','e_order_tongji','e_order_update_v2','e_record_detail','e_words_list','stu_record_update_v2','user_point_list','guestbook_add'], blocked: BLOCKED }));
  1719. if (BLOCKED[action]) return response.status(501).json(reject('migration_blocked: ' + BLOCKED[action]));
  1720. if (action === 'user_login_passwd') {
  1721. const username = String(input.name || input.username || '').trim(); const password = String(input.passwd || input.password || ''); if (!username || !password) return response.status(400).json(reject('请输入账号和密码'));
  1722. try { const loggedIn = await Parse.User.logIn(username, password); if (loggedIn.get('isDisabled') === true || loggedIn.get('isDeleted') === true) { await revokeUserSessions(loggedIn).catch(() => undefined); return response.status(403).json(reject('账号已停用')); } if (loggedIn.get('passwordResetRequired') === true) return response.status(403).json(reject('旧系统账号必须先重置 Parse 密码')); return response.json(envelope(legacyUser(loggedIn, true), { State: 1 })); } catch (_) { return response.status(401).json(reject('账号或密码错误')); }
  1723. }
  1724. if (action === 'user_register') { const registered = await registerUser(input); return response.json(envelope(registered.result,registered.addon)); }
  1725. if (action === 'user_info_name') { const username = String(input.uname || input.name || '').trim(); if (!username) return response.status(400).json(reject('缺少用户名')); const rows = await Psql.query('SELECT "objectId" FROM "_User" WHERE "company" = $1 AND "username" = $2 LIMIT 1', [DEFAULT_COMPANY_ID, username]); const found = rows[0]; return found ? response.json(envelope({ objectId: found.objectId })) : response.status(404).json(reject('用户不存在')); }
  1726. const privateNodeProgress = action === 'node_list' && number(input.ifunit) === 1; const publicRead = PUBLIC_READ.has(action) && !contentQueryRequiresAuth(action, input) && !privateNodeProgress; const current = await currentUser(request, !publicRead); if (contentQueryRequiresAuth(action, input) && current) await authorizeContentAccess(current, input);
  1727. if (action === 'user_get') { const requestedId = number(input.uid || ownLegacyId(current)); let target = current; if (requestedId && requestedId !== ownLegacyId(current)) { await authorizeTeamUser(current,requestedId); target = await legacyUserObject(requestedId); if (!target) return response.status(404).json(reject('用户不存在')); } return response.json(envelope(legacyUser(target),legacyUserAddon(target))); }
  1728. if (action === 'user_list') { const result = await teamUserPage(input,current); return response.json(envelope(result.rows,undefined,result.page)); }
  1729. if (action === 'user_dept') return response.json(envelope(await teamStats(input,current)));
  1730. if (action === 'e_user_list') { const result = await coachStudentPage(input,current); return response.json(envelope(result.rows,undefined,result.page)); }
  1731. if (action === 'user_update') { const updated = await updateUserProfile(input,current); return response.json(envelope(updated.result,updated.addon)); }
  1732. if (action === 'app_update') { const result = await sqlPage('App', { page: 1, pageSize: 1 }); return response.json(envelope(legacyAppRow(result.rows[0]))); }
  1733. if (action === 'content_list' || action === 'content_list_llk') { const result = await contentPage(input, !current); return response.json(envelope(result.rows, undefined, result.page)); }
  1734. if (action === 'content_get') { const id = String(input.id || input.gid || input.generalId || ''); if (!id) return response.status(400).json(reject('缺少内容 ID')); const identity = /^\d+$/.test(id) ? { generalId: id } : { objectId: id }; const base = await contentPage({ page: 1, pageSize: 1, ...identity }); let detail = base.rows[0]; if (!detail) return response.status(404).json(reject('内容不存在')); const detailModel = number(detail.modelId || detail.ModelID); if (CONTENT_ADDONS[detailModel]) detail = (await contentPage({ page: 1, pageSize: 1, modelId: detailModel, ...identity })).rows[0] || detail; if (PRIVATE_CONTENT_MODELS.has(detailModel)) { if (!current) return response.status(401).json(reject('该内容详情需要登录')); await authorizeContentDetail(current, detail); } return response.json(envelope([detail])); }
  1735. if (action === 'content_uphis') { const id = String(input.id || input.gid || input.generalId || ''); if (!id) return response.status(400).json(reject('缺少内容 ID')); const identity = /^\d+$/.test(id) ? { generalId:id } : { objectId:id }; const base = await contentPage({ page:1,pageSize:1,...identity }); const detail = base.rows[0]; if (!detail) return response.status(404).json(reject('内容不存在')); const detailModel = number(detail.modelId || detail.ModelID); if (PRIVATE_CONTENT_MODELS.has(detailModel)) { if (!current) return response.status(401).json(reject('该内容详情需要登录')); await authorizeContentDetail(current,detail); } const updated = await Psql.one('UPDATE "CommonModel" SET "hits"=COALESCE("hits",0)+1,"updatedAt"=CURRENT_TIMESTAMP WHERE "company"=$1 AND CAST("objectId" AS text)=$2 RETURNING "hits"',[DEFAULT_COMPANY_ID,String(detail.objectId)]); return response.json(envelope({ hits:number(updated.hits) })); }
  1736. if (action === 'content_add') return response.json(envelope(await createContentPair(input, current)));
  1737. if (action === 'content_update') return response.json(envelope(await updateContentPair(input, current)));
  1738. if (action === 'node_list') { const result = privateNodeProgress ? await nodeUnitPage(input,current) : await nodePage(input); return response.json(envelope(result.rows, undefined, result.page)); }
  1739. if (action === 'node_get') { const result = await sqlPage('Node', { page: 1, pageSize: 1 }, [{ field: 'nodeId', value: number(input.id || input.nid) }]); return result.rows[0] ? response.json(envelope(result.rows[0])) : response.status(404).json(reject('栏目不存在')); }
  1740. const legacyId = ownLegacyId(current);
  1741. if (action === 'content_add_zt') return response.json(envelope(await createStudyContent(input, current)));
  1742. if (action === 'e_order_update_v2') return response.json(envelope(await updateOrderStatus(input,current)));
  1743. if (action === 'e_order_tongji') return response.json(envelope(await orderStatistics(input, current)));
  1744. if (action === 'stu_record_update_v2') return response.json(envelope(await upsertStudyRecord(input, current)));
  1745. if (action === 'e_add_words') return response.json(envelope(await updateLearningWords(input, current)));
  1746. if (action === 'e_ck_list') { const result = await courseWordPage(input, current); return response.json(envelope(result.rows, undefined, result.page)); }
  1747. if (action === 'e_get_21list') { const result = await memoryPage(input, current); return response.json(envelope(result.rows, undefined, result.page)); }
  1748. if (action === 'e_words_list') { const result = await newWordPage(input, current); return response.json(envelope(result.rows, undefined, result.page)); }
  1749. if (action === 'e_order_detail') { const found = await orderDetailRow(input.id, current); return found ? response.json(envelope([found])) : response.status(404).json(reject('预约记录不存在')); }
  1750. if (action === 'e_record_detail') { const found = await recordDetailData(input, current); return found ? response.json(envelope(found.words, found.addon)) : response.status(404).json(reject('学习记录不存在')); }
  1751. if (action === 'user_point_list') { const result = await pointHistoryPage(input,current); return response.json(envelope(result.rows,result.addon,result.page)); }
  1752. if (action === 'guestbook_add') return response.json(envelope(await createGuestbook(input,current)));
  1753. return response.status(501).json(reject('migration_blocked: 尚未完成动作映射 ' + action));
  1754. } catch (error) { const status = Number(error.status || (error.code === 101 ? 404 : 500)); const message = status === 501 ? 'migration_blocked: ' + error.message : status >= 500 ? '云函数执行失败' : error.message; return response.status(status).json(reject(message)); }
  1755. }
  1756. `;
  1757. const definitions = [
  1758. { name: 'xiaoshu.admin.gateway', desc: '小树陪练 Angular 管理后台统一数据网关(权限、帐套、CRUD、统计)', path: 'xiaoshu/admin/gateway', code: adminGatewayCode, params: [{ name: 'operation', type: 'String', required: true }] },
  1759. { name: 'cms.content-normalizer', desc: '替代 ZL_StripeHtmlTag/ZL_StripeTrimstr,保守输出纯文本', path: 'xiaoshu/cms/content-normalizer', code: cmsReadCode('content-normalizer'), params: [{ name: 'content', type: 'String', required: false }] },
  1760. { name: 'cms.users.extended', desc: '替代 ZL_EX_UserView,返回安全用户扩展资料', path: 'xiaoshu/cms/users/extended', code: cmsReadCode('user-extended'), params: [{ name: 'userId', type: 'String', required: true }] },
  1761. { name: 'cms.users.platform', desc: '替代 ZL_User_PlatView', path: 'xiaoshu/cms/users/platform', code: cmsReadCode('user-platform'), params: [{ name: 'userId', type: 'String', required: true }] },
  1762. { name: 'cms.users.wechat', desc: '替代 ZL_User_WXView,过滤令牌与密钥', path: 'xiaoshu/cms/users/wechat', code: cmsReadCode('user-wechat'), params: [{ name: 'userId', type: 'String', required: true }] },
  1763. { name: 'cms.exams.classes', desc: '替代 ZL_Exam_ClassView', path: 'xiaoshu/cms/exams/classes', code: cmsReadCode('exam-classes'), params: [{ name: 'page', type: 'Number', required: false, default: 1 }] },
  1764. { name: 'cms.guest.bar', desc: '替代 ZL_Guest_BarView', path: 'xiaoshu/cms/guest/bar', code: cmsReadCode('guest-bar'), params: [{ name: 'page', type: 'Number', required: false, default: 1 }] },
  1765. { name: 'cms.search', desc: '替代 ZL_SearchView,搜索规范化 CommonModel', path: 'xiaoshu/cms/search', code: cmsReadCode('search'), params: [{ name: 'keyword', type: 'String', required: true }] },
  1766. { name: 'xiaoshu.app.gateway', desc: '旧 WXAPP action 到 Parse 规范化类的兼容云函数;无法证明等价的动作返回 migration_blocked', path: 'xiaoshu/app/gateway', code: appGatewayCode, params: [{ name: 'action', type: 'String', required: true }] },
  1767. ];
  1768. function validateDefinition(definition) {
  1769. if (definition.path.startsWith('/')) throw new Error(`${definition.name}: 当前执行器的全局 path 不接受前导 /`);
  1770. const factory = new Function(`${definition.code}\nreturn typeof handler;`);
  1771. if (factory() !== 'function') throw new Error(`${definition.name}: 未定义 handler`);
  1772. }
  1773. async function parseRequest(path, init = {}) {
  1774. const response = await fetch(`${PARSE_URL}${path}`, {
  1775. ...init,
  1776. headers: {
  1777. 'X-Parse-Application-Id': APP_ID,
  1778. 'X-Parse-Master-Key': MASTER_KEY,
  1779. 'Content-Type': 'application/json',
  1780. ...(init.headers || {}),
  1781. },
  1782. });
  1783. const payload = await response.json();
  1784. if (!response.ok || payload.error) throw new Error(payload.error || `Parse 请求失败:${response.status}`);
  1785. return payload;
  1786. }
  1787. async function upsert(definition) {
  1788. const where = encodeURIComponent(JSON.stringify({ name: definition.name }));
  1789. const existing = await parseRequest(`/classes/Function?where=${where}&limit=1&keys=objectId`);
  1790. const body = {
  1791. name: definition.name,
  1792. desc: definition.desc,
  1793. type: 'standalone',
  1794. path: definition.path,
  1795. code: definition.code.trim(),
  1796. params: definition.params,
  1797. paramList: definition.params,
  1798. respType: 'json',
  1799. respJson: { success: true, data: {} },
  1800. enabled: true,
  1801. version: '1.1.2',
  1802. };
  1803. const objectId = existing.results?.[0]?.objectId;
  1804. if (objectId) {
  1805. await parseRequest(`/classes/Function/${objectId}`, { method: 'PUT', body: JSON.stringify(body) });
  1806. return { action: 'updated', objectId };
  1807. }
  1808. const created = await parseRequest('/classes/Function', { method: 'POST', body: JSON.stringify(body) });
  1809. return { action: 'created', objectId: created.objectId };
  1810. }
  1811. for (const definition of definitions) validateDefinition(definition);
  1812. if (validateOnly) {
  1813. console.log(`Validated ${definitions.length} cloud function definitions.`);
  1814. } else {
  1815. if (!MASTER_KEY) throw new Error('缺少 XIAOSHU_MASTER_KEY;不会把 masterKey 写入项目文件。');
  1816. for (const definition of definitions) {
  1817. const result = await upsert(definition);
  1818. console.log(`${result.action.padEnd(7)} ${definition.path} (${result.objectId})`);
  1819. }
  1820. }