deploy-admin-functions.mjs 285 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  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: '广告内容管理', FontPicShape: '字体图形素材', FontPicShapeType: '字体图形分类', DesignAsk: '问卷调查', DesignQuestion: '问卷题目', DesignAnswer: '问卷答卷', ServiceSeat: '客服席位', Temp: '客服欢迎语', 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','DesignAnswer']);
  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. FontPicShape: new Set(['id','shape','typeId','userId','userName','sourceKey','createTime','updateTime']),
  48. FontPicShapeType: new Set(['id','sourceKey','createTime','updateTime']),
  49. DesignAsk: new Set(['id','cdate','cuser','adminId','sourceKey']),
  50. DesignQuestion: new Set(['id','askId','cdate','cuser','orderId','sourceKey']),
  51. DesignAnswer: new Set(['id','askId','ip','cdate','userId','sourceKey']),
  52. ServiceSeat: new Set(['sId','sAdminId','sRemrk','sDateTime','sourceKey']),
  53. Temp: new Set(['id','useType','str3','str5','str6','describe','cdate','userId','sourceKey'])
  54. };
  55. function inputOf(request) {
  56. const body = request.body || {};
  57. return body.params && typeof body.params === 'object' ? body.params : body;
  58. }
  59. function fail(status, message) { const error = new Error(message); error.status = status; throw error; }
  60. function pointerId(value) { return value && (value.id || value.objectId || (value.__type === 'Pointer' && value.objectId)); }
  61. function escapeRegex(value) { return String(value).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'); }
  62. function safeValue(value, depth = 0) {
  63. if (value == null || depth > 4) return value;
  64. if (Array.isArray(value)) return value.map((item) => safeValue(item, depth + 1));
  65. if (value instanceof Date) return value.toISOString();
  66. 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) };
  67. if (value && typeof value.toJSON === 'function') return safeValue(value.toJSON(), depth + 1);
  68. if (typeof value === 'object') {
  69. const output = {};
  70. for (const [key, item] of Object.entries(value)) {
  71. if (HIDDEN_FIELDS.has(key) || /(?:password|secret|token|masterkey|privatekey|mch_key|^ak$|^sk$)/i.test(key)) continue;
  72. output[key] = safeValue(item, depth + 1);
  73. }
  74. return output;
  75. }
  76. return value;
  77. }
  78. 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); }
  79. async function requireAdmin(request) {
  80. const current = request.user || (typeof user !== 'undefined' ? user : null);
  81. if (!current) fail(401, '管理员会话已失效');
  82. await current.fetch({ useMasterKey: true });
  83. if (current.get('isDisabled') === true || current.get('isDeleted') === true) fail(403, '管理员账号已停用');
  84. const roles = Array.isArray(current.get('roles')) ? current.get('roles').map(String) : [];
  85. const role = String(current.get('role') || '');
  86. const roleKey = String(current.get('adminRoleKey') || '');
  87. const isSuperAdmin = roleKey === 'super-admin' || roles.includes('super-admin');
  88. const isAdmin = current.get('isAdmin') === true || role === 'admin' || roles.includes('admin') || isSuperAdmin;
  89. if (!isAdmin) fail(403, '当前账号未被授权为后台管理员');
  90. const company = request.company || current.get('company') || null;
  91. if (!company && !isSuperAdmin) fail(403, '管理员账号尚未分配帐套');
  92. return { current, roles, isSuperAdmin, company };
  93. }
  94. function isAdminAccount(target) {
  95. const roles = Array.isArray(target.get('roles')) ? target.get('roles').map(String) : [];
  96. return target.get('isAdmin') === true || target.get('role') === 'admin' || roles.includes('admin') || target.get('adminRoleKey') === 'super-admin' || roles.includes('super-admin');
  97. }
  98. function assertCanManageUser(context, target, action) {
  99. if (action === 'lock' && target.id === context.current.id) fail(400, '不能停用当前登录账号');
  100. if (isAdminAccount(target) && target.id !== context.current.id && !context.isSuperAdmin) fail(403, '只有超级管理员可以管理其他管理员账号');
  101. }
  102. async function revokeSessions(targets) {
  103. let revoked = 0;
  104. while (targets.length) {
  105. const query = new Parse.Query('_Session'); query.containedIn('user', targets); query.limit(1000);
  106. const sessions = await query.find({ useMasterKey: true });
  107. if (!sessions.length) break;
  108. await Parse.Object.destroyAll(sessions, { useMasterKey: true }); revoked += sessions.length;
  109. if (sessions.length < 1000) break;
  110. }
  111. return revoked;
  112. }
  113. function assertClass(className) {
  114. if (!ALLOWED_CLASSES.has(className)) fail(400, '不允许访问该数据类');
  115. }
  116. function isSystemField(className, name) { return SYSTEM_FIELDS.has(name) || Boolean(CLASS_SYSTEM_FIELDS[className] && CLASS_SYSTEM_FIELDS[className].has(name)); }
  117. async function schemaFor(className) {
  118. assertClass(className);
  119. const schema = await new Parse.Schema(className).get({ useMasterKey: true });
  120. return schema && schema.fields ? schema.fields : {};
  121. }
  122. function applyTenant(query, fields, context, requestedCompanyId) {
  123. if (!fields.company) return;
  124. if (context.isSuperAdmin && requestedCompanyId) {
  125. query.equalTo('company', Parse.Object.createWithoutData('Company', String(requestedCompanyId)));
  126. } else if (context.company) {
  127. query.equalTo('company', context.company);
  128. }
  129. }
  130. function serializeObject(object) { return safeValue(object.toJSON()); }
  131. function toParseValue(field, value) {
  132. if (value == null || value === '') return value;
  133. if (field.type === 'Pointer') {
  134. const objectId = pointerId(value) || value;
  135. return Parse.Object.createWithoutData(field.targetClass, String(objectId));
  136. }
  137. if (field.type === 'Date') {
  138. const date = new Date(value.iso || value);
  139. if (Number.isNaN(date.getTime())) fail(400, '日期字段格式无效');
  140. return date;
  141. }
  142. if (field.type === 'Number') {
  143. const number = Number(value);
  144. if (!Number.isFinite(number)) fail(400, '数字字段格式无效');
  145. return number;
  146. }
  147. if (field.type === 'Boolean') return value === true || value === 'true';
  148. if (field.type === 'Array') { if (!Array.isArray(value)) fail(400, '数组字段格式无效'); return value; }
  149. if (field.type === 'Object') { if (!value || typeof value !== 'object' || Array.isArray(value)) fail(400, '对象字段格式无效'); return value; }
  150. if (!GENERIC_WRITE_TYPES.has(field.type)) fail(400, '该字段类型不允许通用编辑: ' + field.type);
  151. return value;
  152. }
  153. async function countClass(className, context) {
  154. const fields = await schemaFor(className);
  155. const query = new Parse.Query(className);
  156. applyTenant(query, fields, context);
  157. if (fields.isDeleted) query.notEqualTo('isDeleted', true);
  158. return query.count({ useMasterKey: true });
  159. }
  160. async function audit(context, action, className, objectId) {
  161. try {
  162. const log = new Parse.Object('SysLog');
  163. const schema = await new Parse.Schema('SysLog').get({ useMasterKey: true });
  164. const fields = schema.fields || {};
  165. if (fields.company && context.company) log.set('company', context.company);
  166. if (fields.userId) log.set('userId', context.current.id);
  167. if (fields.userName) log.set('userName', String(context.current.get('username') || ''));
  168. if (fields.remind) log.set('remind', '[AngularAdmin] ' + action + ' ' + className + '/' + objectId);
  169. if (fields.logType) log.set('logType', 'angular-admin');
  170. await log.save(null, { useMasterKey: true });
  171. } catch (_) { /* 审计表字段来自旧系统,失败不能覆盖主操作结果。 */ }
  172. }
  173. async function handler(request, response) {
  174. try {
  175. const input = inputOf(request);
  176. const operation = String(input.operation || 'meta');
  177. const context = await requireAdmin(request);
  178. if (operation === 'meta') {
  179. const functionQuery = new Parse.Query('Function');
  180. functionQuery.notEqualTo('enabled', false);
  181. const cloudFunctions = await functionQuery.count({ useMasterKey: true });
  182. return response.json({ success: true, data: {
  183. 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 },
  184. classes: ALLOWED_CLASSES.size, cloudFunctions
  185. }});
  186. }
  187. if (operation === 'dashboard') {
  188. const metrics = [
  189. ['_User','用户总数'],['CourseBinding','课程绑定'],['CourseAppointment','课程预约'],['PracticeRecord','练习记录'],['LessonRecord','上课记录'],['DailyStudyRecord','每日学习'],['VocabularyWord','词库单词'],['CommonModel','内容记录']
  190. ];
  191. const counts = await Promise.all(metrics.map(async ([className, label]) => ({ className, label, count: await countClass(className, context), route: '/admin/resources/' + className })));
  192. const functionQuery = new Parse.Query('Function'); functionQuery.notEqualTo('enabled', false);
  193. let registeredRecords = 195452;
  194. try { const row = await Psql.oneOrNone('SELECT COUNT(*)::int AS count FROM cms.record_registry'); if (row) registeredRecords = Number(row.count); } catch (_) {}
  195. 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 }) } } });
  196. }
  197. if (operation === 'catalog') {
  198. const resources = [...ALLOWED_CLASSES].sort().map((className) => ({ className, label: CLASS_LABELS[className] || className, writable: !READ_ONLY_CLASSES.has(className), route: '/admin/resources/' + className }));
  199. return response.json({ success: true, data: { total: resources.length, resources } });
  200. }
  201. if (operation === 'apiCatalog') {
  202. const query = new Parse.Query('Function'); query.ascending('path'); query.limit(1000); const rows = await query.find({ useMasterKey: true });
  203. 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) }));
  204. return response.json({ success: true, data: { total: results.length, results } });
  205. }
  206. if (operation === 'legacyConfigBlocker') {
  207. const action = String(input.action || ''); const blockers = {
  208. APIInfo_Submit: '旧 API_ID/API_Key/API_AdminKey、IP 访问策略与目标 sessionToken/云函数权限模型不等价,且没有能对全部函数生效的站点配置层',
  209. APIInfo_SwaggerClose: '目标云函数引擎没有帐套级 Swagger 实时调试关闭开关',
  210. APIInfo_SwaggerOpen: '目标云函数引擎没有帐套级 Swagger 实时调试开启开关',
  211. LicenceFile_API: '目标 Schema 缺少许可、隐私、协议与版权文档存储,云函数也不能写旧 wwwroot/Config 文件',
  212. close_system: '云函数运行时不存在可通过 app_offline.htm 关闭的单体 ASP.NET 进程',
  213. Hotkey: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,旧 XML 配置文件也不在云函数运行时',
  214. HotkeyAdd: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,无法生成可全局生效的快捷键',
  215. HotkeyAdd_Submit: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,不能伪造保存成功',
  216. Hotkey_API: '目标 Schema 没有 KeyboardConfig/Hotkey 持久化模型,启停、删除、重载和脚本匹配无可操作对象',
  217. Prize: '目标 Schema 没有 PrizeConfig/PrizeTask 配置模型及签到、任务规则数据',
  218. Prize_Submit: '目标 Schema 没有 PrizeConfig/PrizeTask 配置模型,无法持久化奖励积分、重复周期和过期规则'
  219. };
  220. if (!Object.prototype.hasOwnProperty.call(blockers, action)) fail(400, '不支持的旧配置动作'); fail(501, 'migration_blocked: ' + blockers[action]);
  221. }
  222. if (operation === 'createUser') {
  223. const username = String(input.username || '').trim();
  224. const password = typeof input.password === 'string' ? input.password : '';
  225. const displayName = String(input.displayName || '').trim();
  226. const mobile = String(input.mobile || '').trim();
  227. const inviteUsername = String(input.inviteUsername || '').trim();
  228. if (username.length < 3 || username.length > 64) fail(400, '账号长度应为 3 至 64 位');
  229. if (password.length < 8 || password.length > 72) fail(400, '密码长度应为 8 至 72 位');
  230. if (displayName.length > 100) fail(400, '显示名不能超过 100 位');
  231. if (mobile.length > 32) fail(400, '手机号不能超过 32 位');
  232. let companyId = pointerId(context.company);
  233. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  234. if (!companyId) fail(400, '开户必须指定帐套');
  235. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  236. const userFields = await schemaFor('_User');
  237. if (!userFields.company) fail(500, '用户表缺少帐套字段');
  238. 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]);
  239. if (duplicate) fail(409, '此用户名已被使用');
  240. let parentId = 0;
  241. if (inviteUsername) {
  242. 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]);
  243. parentId = Number(inviter && inviter.id) || 0;
  244. if (!parentId) fail(400, '邀请账号不存在');
  245. }
  246. const created = new Parse.User();
  247. created.setUsername(username); created.setPassword(password); created.set('company', company);
  248. if (userFields.type) created.set('type', 'user');
  249. if (userFields.isDisabled) created.set('isDisabled', false);
  250. if (userFields.isDeleted) created.set('isDeleted', false);
  251. if (userFields.legacyGroupId) created.set('legacyGroupId', 1);
  252. if (userFields.nickname) created.set('nickname', displayName || username);
  253. if (mobile && userFields.mobile) created.set('mobile', mobile);
  254. if (userFields.isAdmin) created.set('isAdmin', false);
  255. if (userFields.roles) created.set('roles', []);
  256. try { await created.signUp(null, { useMasterKey: true }); }
  257. catch (error) { if (Number(error && error.code) === 202) fail(409, '此用户名已被使用'); throw error; }
  258. try {
  259. const regTime = new Date().toISOString();
  260. 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 };
  261. 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)]);
  262. const legacyUserId = Number(rows[0] && rows[0].id) || 0;
  263. if (!legacyUserId) throw new Error('无法分配旧系统用户 ID');
  264. await created.fetch({ useMasterKey: true });
  265. await audit({ ...context, company }, 'create-user', '_User', created.id);
  266. return response.json({ success: true, data: { ...serializeObject(created), userId: legacyUserId, groupId: 1 } });
  267. } catch (error) {
  268. await created.destroy({ useMasterKey: true }).catch(() => undefined);
  269. throw error;
  270. }
  271. }
  272. if (operation === 'userBatch') {
  273. const action = String(input.action || '');
  274. if (!['lock','unlock','move'].includes(action)) fail(400, '不支持的用户批量操作');
  275. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  276. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  277. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个用户');
  278. const userFields = await schemaFor('_User');
  279. const query = new Parse.Query('_User'); applyTenant(query, userFields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  280. const targets = await query.find({ useMasterKey: true });
  281. if (targets.length !== objectIds.length) fail(404, '部分用户不存在或不属于当前帐套');
  282. for (const target of targets) assertCanManageUser(context, target, action);
  283. let group = null;
  284. let groupId = 0;
  285. if (action === 'move') {
  286. groupId = Number(input.groupId);
  287. if (!Number.isInteger(groupId) || groupId < 1) fail(400, '请选择有效用户组');
  288. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  289. if (companyIds.length !== 1) fail(400, '批量移动的用户必须属于同一帐套');
  290. const groupRow = await Psql.oneOrNone('SELECT "objectId" FROM "Group" WHERE "company"=$1 AND "groupId"=$2 LIMIT 1', [companyIds[0], groupId]);
  291. if (!groupRow) fail(404, '目标用户组不存在或不属于当前帐套');
  292. group = await new Parse.Query('Group').get(String(groupRow.objectId), { useMasterKey: true });
  293. }
  294. const now = new Date();
  295. for (const target of targets) {
  296. const legacyData = { ...(target.get('legacyUserData') || {}) };
  297. if (action === 'move') {
  298. target.set('legacyGroupId', groupId); legacyData.GroupID = groupId;
  299. } else {
  300. const disabled = action === 'lock'; target.set('isDisabled', disabled); legacyData.State = disabled ? 0 : 1;
  301. if (userFields.statusAction) target.set('statusAction', disabled ? 'admin-lock' : 'admin-unlock');
  302. if (userFields.statusReason) target.set('statusReason', String(input.reason || '').trim().slice(0, 200));
  303. if (userFields.statusUpdatedAt) target.set('statusUpdatedAt', now);
  304. if (userFields.statusUpdatedBy) target.set('statusUpdatedBy', context.current.id);
  305. }
  306. target.set('legacyUserData', legacyData);
  307. }
  308. await Parse.Object.saveAll(targets, { useMasterKey: true });
  309. const revokedSessions = action === 'lock' ? await revokeSessions(targets) : 0;
  310. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'user-' + action, '_User', target.id);
  311. return response.json({ success: true, data: { action, updated: targets.length, revokedSessions, group: group ? serializeObject(group) : null, results: targets.map(serializeObject) } });
  312. }
  313. if (operation === 'saveGroup') {
  314. const objectId = String(input.objectId || '');
  315. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  316. const groupName = String(payload.groupName || '').trim();
  317. const description = String(payload.description || groupName).trim();
  318. const parentGroupId = payload.parentGroupId === undefined || payload.parentGroupId === '' ? 0 : Number(payload.parentGroupId);
  319. if (!groupName || groupName.length > 100) fail(400, '用户组名称为必填项且不能超过 100 位');
  320. if (description.length > 500) fail(400, '用户组说明不能超过 500 位');
  321. if (!Number.isInteger(parentGroupId) || parentGroupId < 0) fail(400, '父用户组编号无效');
  322. let companyId = pointerId(context.company);
  323. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  324. if (!companyId) fail(400, '用户组必须指定帐套');
  325. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  326. const groupFields = await schemaFor('Group');
  327. let target;
  328. let currentGroupId = 0;
  329. if (objectId) {
  330. const query = new Parse.Query('Group'); applyTenant(query, groupFields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  331. currentGroupId = Number(target.get('groupId')) || 0;
  332. } else target = new Parse.Object('Group');
  333. 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]);
  334. if (duplicate) fail(409, '当前帐套已存在同名用户组');
  335. if (parentGroupId) {
  336. let cursor = parentGroupId; const visited = new Set();
  337. while (cursor) {
  338. if (cursor === currentGroupId || visited.has(cursor)) fail(400, '父用户组不能形成循环');
  339. visited.add(cursor);
  340. const parent = await Psql.oneOrNone('SELECT "parentGroupId" AS parent_id FROM "Group" WHERE "company"=$1 AND "groupId"=$2 LIMIT 1', [companyId, cursor]);
  341. if (!parent) fail(404, '父用户组不存在或不属于当前帐套');
  342. cursor = Number(parent.parent_id) || 0;
  343. if (visited.size > 100) fail(400, '用户组层级过深');
  344. }
  345. }
  346. target.set('company', company); target.set('groupName', groupName); target.set('description', description); target.set('parentGroupId', parentGroupId);
  347. const stringFields = ['otherName','enroll','signImg'];
  348. const numberFields = ['orderId','companyGroup','vipgroup','rebateRate','credit','vipnum','upPoint','upSicon','favCount','consumeType','ccountPerDay','upGradeMoney'];
  349. for (const name of stringFields) if (payload[name] !== undefined && groupFields[name]) target.set(name, String(payload[name] || '').trim());
  350. 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); }
  351. if (payload.regSelect !== undefined && groupFields.regSelect) target.set('regSelect', payload.regSelect === true || payload.regSelect === 'true');
  352. if (!objectId && groupFields.sourceKey) target.set('sourceKey', 'cloud:admin-group:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10));
  353. await target.save(null, { useMasterKey: true });
  354. if (!objectId) {
  355. try {
  356. 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]);
  357. currentGroupId = Number(rows[0] && rows[0].id) || 0;
  358. if (!currentGroupId) throw new Error('无法分配用户组编号');
  359. } catch (error) { await target.destroy({ useMasterKey: true }).catch(() => undefined); throw error; }
  360. }
  361. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-group' : 'create-group', 'Group', target.id);
  362. return response.json({ success: true, data: serializeObject(target) });
  363. }
  364. if (operation === 'saveNode') {
  365. const objectId = String(input.objectId || '');
  366. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  367. const nodeName = String(payload.nodeName || '').trim();
  368. const nodeDir = String(payload.nodeDir || '').trim();
  369. const parentId = Number(input.parentId == null ? payload.parentId || 0 : input.parentId);
  370. if (!nodeName || nodeName.length > 100) fail(400, '栏目名称长度应为 1 至 100 位');
  371. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父节点编号无效');
  372. let companyId = pointerId(context.company);
  373. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  374. if (!companyId) fail(400, '栏目必须指定帐套');
  375. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  376. const fields = await schemaFor('Node');
  377. let target;
  378. let currentNodeId = 0;
  379. if (objectId) {
  380. const query = new Parse.Query('Node'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  381. companyId = pointerId(target.get('company')) || companyId;
  382. currentNodeId = Number(target.get('nodeId')) || 0;
  383. } else target = new Parse.Object('Node');
  384. let parentDepth = 0;
  385. if (parentId > 0) {
  386. 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]);
  387. if (!parent) fail(404, '父节点不存在、已回收或不属于当前帐套');
  388. parentDepth = Number(parent.depth) || 0;
  389. if (currentNodeId) {
  390. 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]);
  391. if (cycle) fail(409, '不能把栏目移动到自身或其下级栏目');
  392. }
  393. }
  394. 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]);
  395. if (duplicate) fail(409, '同一父栏目下的栏目名称或目录名不能重复');
  396. for (const [name, value] of Object.entries(payload)) {
  397. if (!fields[name] || isSystemField('Node', name)) continue;
  398. if (!GENERIC_WRITE_TYPES.has(fields[name].type)) fail(400, '字段不允许编辑: ' + name);
  399. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  400. }
  401. target.set('nodeName', nodeName); target.set('nodeDir', nodeDir); target.set('parentId', parentId); target.set('depth', parentDepth + 1); target.set('company', company);
  402. if (!objectId) {
  403. target.set('sourceKey', 'cloud:admin-node:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10));
  404. target.set('zstatus', 99); target.set('child', 0); target.set('cdate', new Date());
  405. if (fields.cuser) target.set('cuser', Number(context.current.get('legacyUserId')) || 0);
  406. if (fields.cuname) target.set('cuname', String(context.current.get('username') || ''));
  407. }
  408. if (fields.editDate) target.set('editDate', new Date());
  409. try { await target.save(null, { useMasterKey: true }); }
  410. catch (error) { fail(422, '栏目初始写入失败: ' + String(error && error.message || error)); }
  411. try {
  412. if (!objectId) {
  413. 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]);
  414. currentNodeId = Number(rows[0] && rows[0].id) || 0;
  415. if (!currentNodeId) throw new Error('无法分配栏目编号');
  416. }
  417. 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]);
  418. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '栏目结构写入失败: ' + String(error && error.message || error)); }
  419. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-node' : 'create-node', 'Node', target.id);
  420. return response.json({ success: true, data: serializeObject(target) });
  421. }
  422. if (operation === 'nodeBatch') {
  423. const action = String(input.action || '');
  424. if (!['recycle','recover','move','purge'].includes(action)) fail(400, '不支持的栏目批量操作');
  425. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  426. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  427. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个栏目');
  428. const fields = await schemaFor('Node');
  429. const query = new Parse.Query('Node'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  430. const targets = await query.find({ useMasterKey: true });
  431. if (targets.length !== objectIds.length) fail(404, '部分栏目不存在或不属于当前帐套');
  432. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  433. if (companyIds.length !== 1) fail(400, '批量操作的栏目必须属于同一帐套');
  434. const companyId = companyIds[0];
  435. const nodeIds = targets.map((target) => Number(target.get('nodeId')) || 0);
  436. if (nodeIds.some((nodeId) => nodeId < 1)) fail(409, '栏目缺少有效旧系统编号');
  437. let parentId = null;
  438. let parentDepth = 0;
  439. if (action === 'move') {
  440. parentId = Number(input.parentId);
  441. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '目标父节点编号无效');
  442. if (parentId > 0) {
  443. 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]);
  444. if (!parent) fail(404, '目标父节点不存在、已回收或不属于当前帐套');
  445. parentDepth = Number(parent.depth) || 0;
  446. for (const nodeId of nodeIds) {
  447. 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]);
  448. if (cycle) fail(409, '不能把栏目移动到自身或其下级栏目');
  449. }
  450. }
  451. for (const target of targets) { target.set('parentId', parentId); target.set('depth', parentDepth + 1); if (fields.editDate) target.set('editDate', new Date()); }
  452. await Parse.Object.saveAll(targets, { useMasterKey: true });
  453. 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]);
  454. } else if (action === 'purge') {
  455. 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]);
  456. if (Number(refs.contents) || Number(refs.children) || Number(refs.auth) || Number(refs.templates)) fail(409, '栏目仍被内容、下级栏目、权限或模板引用,不能永久删除');
  457. await Parse.Object.destroyAll(targets, { useMasterKey: true });
  458. } else {
  459. const status = action === 'recycle' ? -2 : 99;
  460. for (const target of targets) { target.set('zstatus', status); if (fields.editDate) target.set('editDate', new Date()); }
  461. await Parse.Object.saveAll(targets, { useMasterKey: true });
  462. }
  463. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'node-' + action, 'Node', target.id);
  464. return response.json({ success: true, data: { action, updated: targets.length, parentId, results: action === 'purge' ? [] : targets.map(serializeObject) } });
  465. }
  466. if (operation === 'saveSpecial') {
  467. const objectId = String(input.objectId || '');
  468. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  469. const specName = String(payload.specName || '').trim();
  470. const specDir = String(payload.specDir || '').trim();
  471. const pid = Number(input.pid == null ? payload.pid || 0 : input.pid);
  472. if (!specName || specName.length > 100) fail(400, '专题名称长度应为 1 至 100 位');
  473. if (!specDir || specDir.length > 100) fail(400, '专题目录长度应为 1 至 100 位');
  474. if (!Number.isInteger(pid) || pid < 0) fail(400, '父专题编号无效');
  475. let companyId = pointerId(context.company);
  476. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  477. if (!companyId) fail(400, '专题必须指定帐套');
  478. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  479. const fields = await schemaFor('Special');
  480. let target;
  481. let currentSpecId = 0;
  482. if (objectId) {
  483. const query = new Parse.Query('Special'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  484. companyId = pointerId(target.get('company')) || companyId; currentSpecId = Number(target.get('specId')) || 0;
  485. } else target = new Parse.Object('Special');
  486. if (pid > 0) {
  487. const parent = await Psql.oneOrNone('SELECT "specId" FROM "Special" WHERE "company"=$1 AND "specId"=$2 LIMIT 1', [companyId, pid]);
  488. if (!parent) fail(404, '父专题不存在或不属于当前帐套');
  489. if (currentSpecId) {
  490. 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]);
  491. if (cycle) fail(409, '不能把专题移动到自身或其下级专题');
  492. }
  493. }
  494. 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]);
  495. if (duplicate) fail(409, '专题名称或目录不能重复');
  496. for (const [name, value] of Object.entries(payload)) {
  497. if (!fields[name] || isSystemField('Special', name)) continue;
  498. if (!GENERIC_WRITE_TYPES.has(fields[name].type)) fail(400, '字段不允许编辑: ' + name);
  499. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  500. }
  501. target.set('specName', specName); target.set('specDir', specDir); target.set('pid', pid); target.set('company', company); target.set('editDate', new Date());
  502. 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') || '')); }
  503. try { await target.save(null, { useMasterKey: true }); }
  504. catch (error) { fail(422, '专题初始写入失败: ' + String(error && error.message || error)); }
  505. try {
  506. if (!objectId) {
  507. 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]);
  508. currentSpecId = Number(rows[0] && rows[0].id) || 0;
  509. if (!currentSpecId) throw new Error('无法分配专题编号');
  510. }
  511. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '专题结构写入失败: ' + String(error && error.message || error)); }
  512. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-special' : 'create-special', 'Special', target.id);
  513. return response.json({ success: true, data: serializeObject(target) });
  514. }
  515. if (operation === 'specialBatch') {
  516. const action = String(input.action || '');
  517. if (action === 'merge') fail(501, 'migration_blocked: CommonModel.specialId 仅存在于 Parse Schema、PostgreSQL 物理列缺失,且商品主表未迁移,无法安全合并专题关系');
  518. if (action !== 'move') fail(400, '不支持的专题批量操作');
  519. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  520. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  521. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个专题');
  522. const fields = await schemaFor('Special');
  523. const query = new Parse.Query('Special'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  524. const targets = await query.find({ useMasterKey: true });
  525. if (targets.length !== objectIds.length) fail(404, '部分专题不存在或不属于当前帐套');
  526. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  527. if (companyIds.length !== 1) fail(400, '批量操作的专题必须属于同一帐套');
  528. const companyId = companyIds[0];
  529. const specIds = targets.map((target) => Number(target.get('specId')) || 0);
  530. const pid = Number(input.pid);
  531. if (!Number.isInteger(pid) || pid < 0) fail(400, '目标父专题编号无效');
  532. if (pid > 0) {
  533. const parent = await Psql.oneOrNone('SELECT "specId" FROM "Special" WHERE "company"=$1 AND "specId"=$2 LIMIT 1', [companyId, pid]);
  534. if (!parent) fail(404, '目标父专题不存在或不属于当前帐套');
  535. for (const specId of specIds) {
  536. 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]);
  537. if (cycle) fail(409, '不能把专题移动到自身或其下级专题');
  538. }
  539. }
  540. for (const target of targets) { target.set('pid', pid); target.set('editDate', new Date()); }
  541. await Parse.Object.saveAll(targets, { useMasterKey: true });
  542. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'special-move', 'Special', target.id);
  543. return response.json({ success: true, data: { action, updated: targets.length, pid, results: targets.map(serializeObject) } });
  544. }
  545. if (operation === 'saveModelMetadata' || operation === 'saveModelFieldMetadata') {
  546. const className = operation === 'saveModelMetadata' ? 'Model' : 'ModelField';
  547. const objectId = String(input.objectId || '');
  548. if (!objectId) fail(501, 'migration_blocked: 新增模型或字段需要同步创建 PostgreSQL 物理表/列及旧模板文件,托管云函数中未开放此 DDL 流程');
  549. const fields = await schemaFor(className);
  550. const query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  551. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  552. const allowed = className === 'Model'
  553. ? new Set(['modelName','itemName','itemUnit','itemIcon','description','islotsize','contentTemplate','thumbnail'])
  554. : new Set(['fieldAlias','fieldTips','description','isNotNull','isSearchForm','content','isShow','isView','showList','showWidth','isCopy','islotsize','isChain']);
  555. if (className === 'Model') {
  556. const modelName = String(payload.modelName == null ? target.get('modelName') || '' : payload.modelName).trim();
  557. if (!modelName || modelName.length > 100) fail(400, '模型名称长度应为 1 至 100 位');
  558. 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]);
  559. if (duplicate) fail(409, '模型名称已存在');
  560. target.set('modelName', modelName);
  561. } else {
  562. const fieldAlias = String(payload.fieldAlias == null ? target.get('fieldAlias') || '' : payload.fieldAlias).trim();
  563. if (!fieldAlias || fieldAlias.length > 100) fail(400, '字段别名长度应为 1 至 100 位');
  564. target.set('fieldAlias', fieldAlias);
  565. }
  566. for (const [name, value] of Object.entries(payload)) {
  567. if (!allowed.has(name) || !fields[name]) continue;
  568. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  569. }
  570. await target.save(null, { useMasterKey: true }); await audit(context, className === 'Model' ? 'update-model-metadata' : 'update-model-field-metadata', className, objectId);
  571. return response.json({ success: true, data: serializeObject(target) });
  572. }
  573. if (operation === 'modelFieldOrder') {
  574. const items = Array.isArray(input.items) ? input.items : [];
  575. if (!items.length || items.length > 100) fail(400, '每次请提交 1 至 100 个字段顺序');
  576. const objectIds = items.map((item) => String(item && item.objectId || '').trim());
  577. const orderIds = items.map((item) => Number(item && item.orderId));
  578. 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, '字段或顺序参数无效/重复');
  579. const fields = await schemaFor('ModelField');
  580. const query = new Parse.Query('ModelField'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  581. const targets = await query.find({ useMasterKey: true });
  582. if (targets.length !== objectIds.length) fail(404, '部分模型字段不存在或不属于当前帐套');
  583. const modelIds = [...new Set(targets.map((target) => Number(target.get('modelId')) || 0))];
  584. if (modelIds.length !== 1) fail(400, '只能对同一模型的字段排序');
  585. const targetMap = new Map(targets.map((target) => [target.id, target]));
  586. for (const item of items) targetMap.get(String(item.objectId)).set('orderId', Number(item.orderId));
  587. await Parse.Object.saveAll(targets, { useMasterKey: true });
  588. for (const target of targets) await audit(context, 'order-model-field', 'ModelField', target.id);
  589. return response.json({ success: true, data: { updated: targets.length, modelId: modelIds[0], results: targets.map(serializeObject) } });
  590. }
  591. if (operation === 'saveGuestbook') {
  592. const objectId = String(input.objectId || '');
  593. if (!objectId) fail(400, '普通留言新增必须走前台留言云函数;后台只能通过专用回复流程新增');
  594. const fields = await schemaFor('Guestbook');
  595. const query = new Parse.Query('Guestbook'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  596. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  597. const title = String(payload.title == null ? target.get('title') || '' : payload.title).trim();
  598. const content = String(payload.tcontent == null ? target.get('tcontent') || '' : payload.tcontent);
  599. if (!title || title.length > 200) fail(400, '留言标题长度应为 1 至 200 位');
  600. if (content.length > 200000) fail(400, '留言内容过长');
  601. target.set('title', title); target.set('tcontent', content);
  602. await target.save(null, { useMasterKey: true }); await audit(context, 'update-guestbook', 'Guestbook', objectId);
  603. return response.json({ success: true, data: serializeObject(target) });
  604. }
  605. if (operation === 'guestbookReply') {
  606. const parentObjectId = String(input.parentObjectId || '');
  607. const title = String(input.title || '').trim() || '[管理员回复]';
  608. const content = String(input.content || '');
  609. if (!parentObjectId) fail(400, '缺少原留言');
  610. if (title.length > 200 || !content.trim() || content.length > 200000) fail(400, '回复标题或内容无效');
  611. const fields = await schemaFor('Guestbook');
  612. const query = new Parse.Query('Guestbook'); applyTenant(query, fields, context, input.companyId); const parent = await query.get(parentObjectId, { useMasterKey: true });
  613. 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;
  614. if (!companyId || !parentGid) fail(409, '原留言缺少帐套或旧系统编号');
  615. const reply = new Parse.Object('Guestbook');
  616. 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');
  617. try { await reply.save(null, { useMasterKey: true }); }
  618. catch (error) { fail(422, '管理员回复初始写入失败: ' + String(error && error.message || error)); }
  619. try {
  620. 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]);
  621. if (!Number(rows[0] && rows[0].id)) throw new Error('无法分配回复编号');
  622. } catch (error) { await reply.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '管理员回复结构写入失败: ' + String(error && error.message || error)); }
  623. await reply.fetch({ useMasterKey: true }); await audit({ ...context, company }, 'reply-guestbook', 'Guestbook', reply.id);
  624. return response.json({ success: true, data: serializeObject(reply) });
  625. }
  626. if (operation === 'guestbookBatch') {
  627. const action = String(input.action || '');
  628. if (!['audit','unaudit','recycle','recover','purge'].includes(action)) fail(400, '不支持的留言批量操作');
  629. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  630. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  631. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条留言');
  632. const fields = await schemaFor('Guestbook');
  633. const query = new Parse.Query('Guestbook'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  634. const targets = await query.find({ useMasterKey: true });
  635. if (targets.length !== objectIds.length) fail(404, '部分留言不存在或不属于当前帐套');
  636. if (action === 'purge') {
  637. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))]; const gids = targets.map((target) => Number(target.get('gid')) || 0);
  638. if (companyIds.length !== 1 || gids.some((gid) => gid < 1)) fail(409, '留言缺少有效帐套或编号');
  639. 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]);
  640. if (Number(children.count) > 0) fail(409, '留言仍有回复,不能永久删除');
  641. await Parse.Object.destroyAll(targets, { useMasterKey: true });
  642. } else {
  643. const status = action === 'recycle' ? -2 : action === 'unaudit' ? 0 : 99;
  644. for (const target of targets) target.set('status', status);
  645. await Parse.Object.saveAll(targets, { useMasterKey: true });
  646. }
  647. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'guestbook-' + action, 'Guestbook', target.id);
  648. return response.json({ success: true, data: { action, updated: targets.length, results: action === 'purge' ? [] : targets.map(serializeObject) } });
  649. }
  650. if (operation === 'saveGuestCategory') {
  651. const objectId = String(input.objectId || '');
  652. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  653. const catename = String(payload.catename || '').trim();
  654. const parentId = Number(input.parentId == null ? payload.parentId || 0 : input.parentId);
  655. let gtype = Number(input.gtype == null ? payload.gtype || 0 : input.gtype);
  656. if (!catename || catename.length > 100) fail(400, '分类名称长度应为 1 至 100 位');
  657. if (!Number.isInteger(parentId) || parentId < 0 || ![0,1].includes(gtype)) fail(400, '分类类型或父分类编号无效');
  658. let companyId = pointerId(context.company);
  659. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  660. if (!companyId) fail(400, '分类必须指定帐套');
  661. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  662. const fields = await schemaFor('Guestcate');
  663. let target;
  664. let currentCateId = 0;
  665. if (objectId) {
  666. const query = new Parse.Query('Guestcate'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  667. companyId = pointerId(target.get('company')) || companyId; currentCateId = Number(target.get('cateid')) || 0; gtype = Number(target.get('gtype')) || 0;
  668. } else target = new Parse.Object('Guestcate');
  669. if (gtype === 0 && parentId !== 0) fail(400, '留言分类只能建立为顶级分类');
  670. if (parentId > 0) {
  671. 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]);
  672. if (!parent) fail(404, '父分类不存在、类型不一致或不属于当前帐套');
  673. if (currentCateId) {
  674. 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]);
  675. if (cycle) fail(409, '不能把分类移动到自身或其下级分类');
  676. }
  677. }
  678. 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]);
  679. if (duplicate) fail(409, '同一父分类下的分类名称不能重复');
  680. const allowed = new Set(['catename','desc','status','needLog','isShowUnaudit','postAuth','zipImgSize','barImage','barOwner','permibit','sendScore','replyScore','barInfo','isPlat']);
  681. for (const [name, value] of Object.entries(payload)) {
  682. if (!allowed.has(name) || !fields[name]) continue;
  683. if (value === null) target.unset(name); else target.set(name, toParseValue(fields[name], value));
  684. }
  685. target.set('catename', catename); target.set('parentId', parentId); target.set('gtype', gtype); target.set('company', company);
  686. 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); }
  687. try { await target.save(null, { useMasterKey: true }); }
  688. catch (error) { fail(422, '分类初始写入失败: ' + String(error && error.message || error)); }
  689. try {
  690. if (!objectId) {
  691. 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]);
  692. currentCateId = Number(rows[0] && rows[0].id) || 0;
  693. if (!currentCateId) throw new Error('无法分配分类编号');
  694. }
  695. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '分类结构写入失败: ' + String(error && error.message || error)); }
  696. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-guest-category' : 'create-guest-category', 'Guestcate', target.id);
  697. return response.json({ success: true, data: serializeObject(target) });
  698. }
  699. if (operation === 'guestCategoryBatch') {
  700. const action = String(input.action || '');
  701. if (!['delete','recommend','unrecommend'].includes(action)) fail(400, '不支持的分类批量操作');
  702. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  703. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  704. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个分类');
  705. const fields = await schemaFor('Guestcate');
  706. const query = new Parse.Query('Guestcate'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  707. const targets = await query.find({ useMasterKey: true });
  708. if (targets.length !== objectIds.length) fail(404, '部分分类不存在或不属于当前帐套');
  709. if (action === 'delete') {
  710. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))]; const cateids = targets.map((target) => Number(target.get('cateid')) || 0);
  711. if (companyIds.length !== 1 || cateids.some((id) => id < 1)) fail(409, '分类缺少有效帐套或编号');
  712. 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]);
  713. if (Number(refs.children) || Number(refs.messages) || Number(refs.posts)) fail(409, '分类仍被下级分类、留言或帖子引用,不能删除');
  714. await Parse.Object.destroyAll(targets, { useMasterKey: true });
  715. } else {
  716. for (const target of targets) { if (Number(target.get('gtype')) !== 1) fail(400, '只有贴吧分类支持推荐'); target.set('barInfo', action === 'recommend' ? 'Recommend' : ''); }
  717. await Parse.Object.saveAll(targets, { useMasterKey: true });
  718. }
  719. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'guest-category-' + action, 'Guestcate', target.id);
  720. return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  721. }
  722. if (operation === 'barAuthorization') {
  723. fail(501, 'migration_blocked: 目标 Schema 缺少旧 ZL_Guest_BarAuth 用户版块权限关系(Uid、BarID、Look、Send、Reply),无法安全读取或保存逐用户浏览、发帖和回复权限');
  724. }
  725. if (operation === 'barMedal') {
  726. fail(501, 'migration_blocked: 目标 Schema 缺少旧 ZL_Guest_Medals 勋章及用户帖子授予关系,无法安全授予或撤销帖子勋章');
  727. }
  728. if (operation === 'saveDictionaryCategory') {
  729. const objectId = String(input.objectId || '');
  730. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  731. const categoryName = String(payload.categoryname || '').trim();
  732. const isUsed = payload.isused == null ? true : payload.isused === true || payload.isused === 'true';
  733. if (!categoryName || categoryName.length > 50) fail(400, '字典分类名称长度应为 1 至 50 位');
  734. let companyId = pointerId(context.company);
  735. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  736. if (!companyId) fail(400, '字典分类必须指定帐套');
  737. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  738. const fields = await schemaFor('Datadiccategory');
  739. let target;
  740. if (objectId) {
  741. const query = new Parse.Query('Datadiccategory'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  742. companyId = pointerId(target.get('company')) || companyId;
  743. } else target = new Parse.Object('Datadiccategory');
  744. const duplicateQuery = new Parse.Query('Datadiccategory'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000);
  745. const duplicates = await duplicateQuery.find({ useMasterKey: true });
  746. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('categoryname') || '').trim().toLowerCase() === categoryName.toLowerCase())) fail(409, '同一帐套的字典分类名称不能重复');
  747. target.set('categoryname', categoryName); target.set('isused', isUsed); target.set('company', company);
  748. if (objectId) {
  749. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '字典分类写入失败: ' + String(error && error.message || error)); }
  750. } else {
  751. let lastError;
  752. for (let attempt = 0; attempt < 5; attempt++) {
  753. const allCategories = new Parse.Query('Datadiccategory'); allCategories.limit(1000);
  754. const allItems = new Parse.Query('Datadic'); allItems.limit(1000);
  755. const [categoryRows, itemRows] = await Promise.all([allCategories.find({ useMasterKey: true }), allItems.find({ useMasterKey: true })]);
  756. const nextId = Math.max(0, ...categoryRows.map((entry) => Number(entry.get('diccateid')) || 0), ...itemRows.map((entry) => Number(entry.get('diccate')) || 0)) + 1;
  757. target.set('diccateid', nextId); target.set('sourceKey', '[["Diccateid",' + nextId + ']]');
  758. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  759. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  760. }
  761. if (lastError || !target.id) fail(422, '字典分类原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  762. }
  763. await audit({ ...context, company }, objectId ? 'update-dictionary-category' : 'create-dictionary-category', 'Datadiccategory', target.id);
  764. return response.json({ success: true, data: serializeObject(target) });
  765. }
  766. if (operation === 'saveDictionaryItem') {
  767. const objectId = String(input.objectId || '');
  768. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  769. const itemName = String(payload.dicname || '').trim();
  770. const categoryId = Number(input.categoryId == null ? payload.diccate || 0 : input.categoryId);
  771. const isUsed = payload.isused == null ? true : payload.isused === true || payload.isused === 'true';
  772. if (!itemName || itemName.length > 50) fail(400, '字典项名称长度应为 1 至 50 位');
  773. if (!Number.isInteger(categoryId) || categoryId < 1) fail(400, '请选择有效字典分类');
  774. let companyId = pointerId(context.company);
  775. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  776. if (!companyId) fail(400, '字典项必须指定帐套');
  777. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  778. const fields = await schemaFor('Datadic');
  779. let target;
  780. if (objectId) {
  781. const query = new Parse.Query('Datadic'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  782. companyId = pointerId(target.get('company')) || companyId;
  783. } else target = new Parse.Object('Datadic');
  784. const categoryFields = await schemaFor('Datadiccategory'); const categoryQuery = new Parse.Query('Datadiccategory'); applyTenant(categoryQuery, categoryFields, context, input.companyId); categoryQuery.equalTo('diccateid', categoryId);
  785. const category = await categoryQuery.first({ useMasterKey: true });
  786. if (!category || pointerId(category.get('company')) !== companyId) fail(404, '字典分类不存在或不属于当前帐套');
  787. const duplicateQuery = new Parse.Query('Datadic'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.equalTo('diccate', categoryId); duplicateQuery.limit(1000);
  788. const duplicates = await duplicateQuery.find({ useMasterKey: true });
  789. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('dicname') || '').trim().toLowerCase() === itemName.toLowerCase())) fail(409, '同一字典分类中的字典项名称不能重复');
  790. target.set('dicname', itemName); target.set('diccate', categoryId); target.set('isused', isUsed); target.set('company', company);
  791. if (objectId) {
  792. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '字典项写入失败: ' + String(error && error.message || error)); }
  793. } else {
  794. let lastError;
  795. for (let attempt = 0; attempt < 5; attempt++) {
  796. const allItems = new Parse.Query('Datadic'); allItems.limit(1000); const itemRows = await allItems.find({ useMasterKey: true });
  797. const nextId = Math.max(0, ...itemRows.map((entry) => Number(entry.get('dicid')) || 0)) + 1;
  798. target.set('dicid', nextId); target.set('sourceKey', '[["Dicid",' + nextId + ']]');
  799. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  800. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  801. }
  802. if (lastError || !target.id) fail(422, '字典项原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  803. }
  804. await audit({ ...context, company }, objectId ? 'update-dictionary-item' : 'create-dictionary-item', 'Datadic', target.id);
  805. return response.json({ success: true, data: serializeObject(target) });
  806. }
  807. if (operation === 'dictionaryCategories') {
  808. const fields = await schemaFor('Datadiccategory'); const query = new Parse.Query('Datadiccategory'); applyTenant(query, fields, context, input.companyId);
  809. if (input.enabledOnly === true) query.equalTo('isused', true);
  810. query.ascending('diccateid'); query.limit(1000);
  811. const results = await query.find({ useMasterKey: true });
  812. return response.json({ success: true, data: { results: results.map(serializeObject) } });
  813. }
  814. if (operation === 'dictionaryBatch') {
  815. const className = String(input.className || ''); const action = String(input.action || '');
  816. if (!['Datadiccategory','Datadic'].includes(className) || !['enable','disable','delete'].includes(action)) fail(400, '不支持的字典批量操作');
  817. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  818. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  819. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条字典记录');
  820. 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);
  821. const targets = await query.find({ useMasterKey: true });
  822. if (targets.length !== objectIds.length) fail(404, '部分字典记录不存在或不属于当前帐套');
  823. if (action === 'delete' && className === 'Datadiccategory') {
  824. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))]; const categoryIds = targets.map((target) => Number(target.get('diccateid')) || 0);
  825. if (companyIds.length !== 1 || categoryIds.some((id) => id < 1)) fail(409, '字典分类缺少有效帐套或编号');
  826. const itemFields = await schemaFor('Datadic'); const refs = new Parse.Query('Datadic'); applyTenant(refs, itemFields, context, companyIds[0]); refs.containedIn('diccate', categoryIds);
  827. if (await refs.count({ useMasterKey: true })) fail(409, '字典分类仍有字典项,不能删除');
  828. }
  829. if (action === 'delete') await Parse.Object.destroyAll(targets, { useMasterKey: true });
  830. else { for (const target of targets) target.set('isused', action === 'enable'); await Parse.Object.saveAll(targets, { useMasterKey: true }); }
  831. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'dictionary-' + action, className, target.id);
  832. return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  833. }
  834. if (operation === 'saveGradeCategory') {
  835. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  836. const cateName = String(payload.cateName || '').trim(); const remark = String(payload.remark || '').trim();
  837. const aliases = String(payload.gradeField || '').split(/\r?\n|\|/).map((value) => value.trim()).filter(Boolean); const gradeField = aliases.join('|');
  838. if (!cateName || cateName.length > 50) fail(400, '多级字典分类名称长度应为 1 至 50 位');
  839. if (remark.length > 255) fail(400, '多级字典分类备注不能超过 255 位');
  840. if (aliases.length < 2 || gradeField.length > 500) fail(400, '层级别名至少填写 2 级,且总长度不能超过 500 位');
  841. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '多级字典分类必须指定帐套');
  842. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('GradeCate'); let target;
  843. 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; }
  844. else target = new Parse.Object('GradeCate');
  845. const duplicateQuery = new Parse.Query('GradeCate'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  846. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('cateName') || '').trim().toLowerCase() === cateName.toLowerCase())) fail(409, '同一帐套的多级字典分类名称不能重复');
  847. target.set('cateName', cateName); target.set('remark', remark); target.set('gradeField', gradeField); target.set('company', company);
  848. if (objectId) { try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '多级字典分类写入失败: ' + String(error && error.message || error)); } }
  849. else {
  850. let lastError;
  851. for (let attempt = 0; attempt < 5; attempt++) {
  852. const categories = new Parse.Query('GradeCate'); categories.limit(1000); const options = new Parse.Query('Grade'); options.limit(1000);
  853. const [categoryRows, optionRows] = await Promise.all([categories.find({ useMasterKey: true }), options.find({ useMasterKey: true })]);
  854. const nextId = Math.max(0, ...categoryRows.map((entry) => Number(entry.get('cateId')) || 0), ...optionRows.map((entry) => Number(entry.get('cate')) || 0)) + 1;
  855. target.set('cateId', nextId); target.set('sourceKey', '[["CateID",' + nextId + ']]');
  856. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  857. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  858. }
  859. if (lastError || !target.id) fail(422, '多级字典分类原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  860. }
  861. await audit({ ...context, company }, objectId ? 'update-grade-category' : 'create-grade-category', 'GradeCate', target.id);
  862. return response.json({ success: true, data: serializeObject(target) });
  863. }
  864. if (operation === 'saveGradeOption') {
  865. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; const gradeName = String(payload.gradeName || '').trim();
  866. if (!gradeName || gradeName.length > 50) fail(400, '多级字典选项名称长度应为 1 至 50 位');
  867. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '多级字典选项必须指定帐套');
  868. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('Grade'); let target; let categoryId; let parentId; let level;
  869. if (objectId) {
  870. 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;
  871. categoryId = Number(target.get('cate')) || 0; parentId = Number(target.get('parentId')) || 0; level = Number(target.get('grade')) || 0;
  872. } 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; }
  873. if (!Number.isInteger(categoryId) || categoryId < 1 || !Number.isInteger(parentId) || parentId < 0) fail(400, '多级字典分类或父选项编号无效');
  874. 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 });
  875. if (!category || pointerId(category.get('company')) !== companyId) fail(404, '多级字典分类不存在或不属于当前帐套');
  876. const aliases = String(category.get('gradeField') || '').split('|').map((value) => value.trim()).filter(Boolean);
  877. 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; }
  878. if (!Number.isInteger(level) || level < 1 || level > aliases.length) fail(409, '当前层级已超过分类定义的层级别名');
  879. 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 });
  880. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('gradeName') || '').trim().toLowerCase() === gradeName.toLowerCase())) fail(409, '同一父级下的多级字典选项名称不能重复');
  881. target.set('gradeName', gradeName); target.set('cate', categoryId); target.set('parentId', parentId); target.set('grade', level); target.set('company', company);
  882. if (objectId) { try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '多级字典选项写入失败: ' + String(error && error.message || error)); } }
  883. else {
  884. let lastError;
  885. for (let attempt = 0; attempt < 5; attempt++) {
  886. 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;
  887. target.set('gradeId', nextId); target.set('sourceKey', '[["GradeID",' + nextId + ']]');
  888. try { await target.save(null, { useMasterKey: true }); lastError = null; break; }
  889. catch (error) { lastError = error; if (!(Number(error && error.code) === 137 || /duplicate|unique/i.test(String(error && error.message || '')))) break; }
  890. }
  891. if (lastError || !target.id) fail(422, '多级字典选项原子编号写入失败: ' + String(lastError && lastError.message || lastError || '无法分配编号'));
  892. }
  893. await audit({ ...context, company }, objectId ? 'update-grade-option' : 'create-grade-option', 'Grade', target.id);
  894. return response.json({ success: true, data: serializeObject(target) });
  895. }
  896. if (operation === 'gradeCategories') {
  897. 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 });
  898. return response.json({ success: true, data: { results: results.map(serializeObject) } });
  899. }
  900. if (operation === 'gradeOptions') {
  901. 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, '多级字典筛选条件无效');
  902. 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);
  903. 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 });
  904. return response.json({ success: true, data: { className: 'Grade', page, pageSize, total, results: results.map(serializeObject) } });
  905. }
  906. if (operation === 'gradeBatch') {
  907. const className = String(input.className || ''); if (!['GradeCate','Grade'].includes(className) || String(input.action || '') !== 'delete') fail(400, '不支持的多级字典批量操作');
  908. 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 条多级字典记录');
  909. 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, '部分多级字典记录不存在或不属于当前帐套');
  910. 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, '多级字典分类仍有选项,不能删除'); }
  911. 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, '多级字典选项仍有下级选项,不能删除'); }
  912. 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);
  913. return response.json({ success: true, data: { action: 'delete', updated: targets.length, results: [] } });
  914. }
  915. if (operation === 'saveCurrency') {
  916. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  917. 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();
  918. if (!title || title.length > 50) fail(400, '货币名称长度应为 1 至 50 位');
  919. if (!/^[A-Z][A-Z0-9]{1,9}$/.test(currencyName)) fail(400, '货币代码应为 2 至 10 位大写字母或数字');
  920. if (!currencySymbol || currencySymbol.length > 16) fail(400, '货币符号长度应为 1 至 16 位');
  921. if (!Number.isFinite(exchange) || exchange <= 0 || exchange > 1000000000) fail(400, '当前汇率必须是大于 0 的有效数字');
  922. if (remark.length > 255) fail(400, '货币备注不能超过 255 位');
  923. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '货币必须指定帐套');
  924. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('Currency'); let target;
  925. if (!objectId) fail(501, 'migration_blocked: Currency.id 与 Parse 对象保留 id 冲突,且 PostgreSQL 物理表缺少可写旧 ID 列,不能安全新增货币');
  926. { 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; }
  927. const duplicateQuery = new Parse.Query('Currency'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  928. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('title') || '').trim().toLowerCase() === title.toLowerCase())) fail(409, '同一帐套的货币名称不能重复');
  929. if (duplicates.some((entry) => entry.id !== objectId && String(entry.get('currencyName') || '').trim().toUpperCase() === currencyName)) fail(409, '同一帐套的货币代码不能重复');
  930. target.set('title', title); target.set('currencyName', currencyName); target.set('currencySymbol', currencySymbol); target.set('currentExchange', exchange); target.set('remark', remark); target.set('company', company);
  931. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '货币写入失败: ' + String(error && error.message || error)); }
  932. 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) });
  933. }
  934. if (operation === 'currencyBatch') {
  935. 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 条货币记录');
  936. 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: [] } });
  937. }
  938. if (operation === 'saveHoliday') {
  939. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  940. if (!objectId) fail(501, 'migration_blocked: SysHoliday.id 与 Parse 对象保留 id 冲突,且 PostgreSQL 物理表缺少可写旧 ID 列,不能安全新增节假日');
  941. const name = String(payload.name || '').trim(); const htype = String(payload.htype || '').trim(); const hdate = String(payload.hdate || '').trim();
  942. const hdateStart = Number(payload.hdateStart); const hdateEnd = Number(payload.hdateEnd); const zstatus = Number(payload.zstatus);
  943. 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() };
  944. if (!name || name.length > 100) fail(400, '节假日名称长度应为 1 至 100 位');
  945. if (!['公历','农历'].includes(htype)) fail(400, '节假日类型只能是公历或农历');
  946. if (!/^(0[1-9]|1[0-2])月(0[1-9]|[12][0-9]|3[01])日$/.test(hdate)) fail(400, '节假日日期必须使用 MM月DD日 格式');
  947. if (!Number.isInteger(hdateStart) || hdateStart < 0 || hdateStart > 365 || !Number.isInteger(hdateEnd) || hdateEnd < 0 || hdateEnd > 365) fail(400, '提前与延后影响天数必须是 0 至 365 的整数');
  948. if (![0,99].includes(zstatus)) fail(400, '节假日状态只能是停用或启用');
  949. if (strings.ztype.length > 100 || strings.himage.length > 500 || strings.remind.length > 1000 || strings.heffect.length > 500 || strings.hcontent.length > 4000) fail(400, '节假日文本字段超过允许长度');
  950. 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 });
  951. const duplicateQuery = new Parse.Query('SysHoliday'); applyTenant(duplicateQuery, fields, context, input.companyId); duplicateQuery.limit(1000); const duplicates = await duplicateQuery.find({ useMasterKey: true });
  952. 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, '同一帐套的节假日名称、类型和日期不能完全重复');
  953. target.set('name', name); target.set('htype', htype); target.set('hdate', hdate); target.set('hdateStart', hdateStart); target.set('hdateEnd', hdateEnd); target.set('zstatus', zstatus);
  954. for (const [field, value] of Object.entries(strings)) target.set(field, value);
  955. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '节假日写入失败: ' + String(error && error.message || error)); }
  956. 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) });
  957. }
  958. if (operation === 'holidayBatch') {
  959. 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 条节假日记录');
  960. 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: [] } });
  961. }
  962. if (operation === 'searchNavigations') {
  963. 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);
  964. if (![1,2].includes(type) || ![-100,1,2].includes(state) || ![-100,0,1].includes(elite)) fail(400, '快捷入口筛选条件无效');
  965. 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();
  966. 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)));
  967. 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);
  968. return response.json({ success: true, data: { className: 'Search', page, pageSize, total, results: results.map(serializeObject) } });
  969. }
  970. if (operation === 'saveSearchNavigation') {
  971. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  972. if (!objectId) fail(501, 'migration_blocked: Search.id 与 Parse 对象保留 id 冲突,且 PostgreSQL 物理表缺少可写旧 ID 列,不能安全新增快捷入口');
  973. 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();
  974. const openType = Number(payload.openType); const mobile = Number(payload.mobile); const size = Number(payload.size); const eliteLevel = Number(payload.eliteLevel);
  975. if (!name || name.length > 100) fail(400, '快捷入口名称长度应为 1 至 100 位');
  976. if (!fileUrl || fileUrl.length > 500 || !fileUrl.startsWith('/') || fileUrl.startsWith('//') || /^[a-z]+:/i.test(fileUrl)) fail(400, '快捷入口地址必须是 1 至 500 位的站内路径');
  977. if (ico.length > 100 || (bkcolor && !/^#[0-9a-f]{6}$/i.test(bkcolor))) fail(400, '图标或背景颜色格式无效');
  978. 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, '快捷入口展示参数无效');
  979. if (userGroup && !/^\d+(,\d+)*$/.test(userGroup)) fail(400, '用户组必须使用逗号分隔的正整数 ID');
  980. 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 });
  981. 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);
  982. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '快捷入口写入失败: ' + String(error && error.message || error)); }
  983. 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) });
  984. }
  985. if (operation === 'searchNavigationBatch') {
  986. if (String(input.className || '') !== 'Search') fail(400, '只能处理快捷入口'); const action = String(input.action || '');
  987. if (action === 'starturl') fail(501, 'migration_blocked: 目标云函数架构没有旧 SiteConfig.SiteOption.Admin_StartUrl 持久层,不能伪造全局后台起始页');
  988. if (!['enable','disable','elite','unelite','delete','order'].includes(action)) fail(400, '不支持的快捷入口批量操作');
  989. let requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]; let orders = [];
  990. 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); }
  991. 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 条唯一快捷入口');
  992. 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, '部分快捷入口不存在或不属于当前帐套');
  993. if (action === 'delete') await Parse.Object.destroyAll(targets, { useMasterKey: true });
  994. 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 }); }
  995. 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) } });
  996. }
  997. if (operation === 'adZones') {
  998. 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();
  999. if (![-100,0,99].includes(status) || type.length > 50 || search.length > 100) fail(400, '广告位筛选条件无效');
  1000. 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 });
  1001. 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))));
  1002. 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);
  1003. return response.json({ success: true, data: { className: 'AdZone', page, pageSize, total, results: results.map(serializeObject) } });
  1004. }
  1005. if (operation === 'adInfos') {
  1006. 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();
  1007. if (![-100,0,99].includes(status) || (zoneId && !/^\d+$/.test(zoneId)) || search.length > 100) fail(400, '广告内容筛选条件无效');
  1008. 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 });
  1009. 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))));
  1010. 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);
  1011. return response.json({ success: true, data: { className: 'AdInfo', page, pageSize, total, results: results.map(serializeObject) } });
  1012. }
  1013. if (operation === 'saveAdZone') {
  1014. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1015. if (!objectId) fail(501, 'migration_blocked: AdZone.id 与 Parse 对象保留 id 冲突,且省略 id 创建不会生成旧广告位编号,不能安全新增广告位');
  1016. 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);
  1017. if (!name || name.length > 100 || remind.length > 2000 || !ztype || ztype.length > 50 || !showType || showType.length > 50 || ![0,99].includes(zstatus)) fail(400, '广告位名称、类型、展示方式、状态或备注无效');
  1018. 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 });
  1019. 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);
  1020. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '广告位写入失败: ' + String(error && error.message || error)); }
  1021. 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) });
  1022. }
  1023. if (operation === 'saveAdInfo') {
  1024. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1025. if (!objectId) fail(501, 'migration_blocked: AdInfo.id 与 Parse 对象保留 id 冲突,且省略 id 创建不会生成旧广告编号,不能安全新增广告内容');
  1026. 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);
  1027. 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));
  1028. 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 || '') };
  1029. 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, '广告名称、广告位、权重或状态无效');
  1030. if (Number.isNaN(sdate.getTime()) || Number.isNaN(edate.getTime()) || edate < sdate) fail(400, '广告到期时间必须大于或等于开始时间');
  1031. 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, '广告内容字段超过允许长度');
  1032. 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, '目标广告位不存在或不属于当前帐套');
  1033. 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 });
  1034. 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);
  1035. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '广告内容写入失败: ' + String(error && error.message || error)); }
  1036. 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) });
  1037. }
  1038. if (operation === 'adZoneBatch') {
  1039. if (String(input.className || '') !== 'AdZone') fail(400, '只能处理广告位'); const action = String(input.action || ''); if (!['active','pause','delete'].includes(action)) fail(400, '不支持的广告位批量操作');
  1040. 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 个广告位');
  1041. 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, '部分广告位不存在或不属于当前帐套');
  1042. 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 }); }
  1043. else { for (const target of targets) target.set('zstatus', action === 'active' ? 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-zone-' + action, 'AdZone', target.id); return response.json({ success: true, data: { action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  1045. }
  1046. if (operation === 'adInfoBatch') {
  1047. if (String(input.className || '') !== 'AdInfo') fail(400, '只能处理广告内容'); const action = String(input.action || ''); if (!['audit','unaudit','delete'].includes(action)) fail(400, '不支持的广告内容批量操作');
  1048. 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 条广告内容');
  1049. 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, '部分广告内容不存在或不属于当前帐套');
  1050. 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 }); }
  1051. 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) } });
  1052. }
  1053. if (operation === 'adPreview') {
  1054. 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') || '');
  1055. 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));
  1056. return response.json({ success: true, data: { zone: serializeObject(zone), total: results.length, results: results.map(serializeObject) } });
  1057. }
  1058. if (operation === 'fontShapeTypes') {
  1059. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(1000, Math.max(1, Number(input.pageSize) || 20)); const search = String(input.search || '').trim().toLowerCase(); if (search.length > 100) fail(400, '图形分类搜索词过长');
  1060. const fields = await schemaFor('FontPicShapeType'); const query = new Parse.Query('FontPicShapeType'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => !search || [entry.get('name'),entry.get('remarks')].some((value) => String(value || '').toLowerCase().includes(search))); 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);
  1061. return response.json({ success: true, data: { className: 'FontPicShapeType', page, pageSize, total, results: results.map(serializeObject) } });
  1062. }
  1063. if (operation === 'fontShapes') {
  1064. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const typeId = Number(input.typeId || 0); const search = String(input.search || '').trim().toLowerCase(); if (!Number.isInteger(typeId) || typeId < 0 || search.length > 100) fail(400, '图形素材筛选条件无效');
  1065. const fields = await schemaFor('FontPicShape'); const query = new Parse.Query('FontPicShape'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => (!typeId || Number(entry.get('typeId')) === typeId) && (!search || [entry.get('name'),entry.get('remarks'),entry.get('userName')].some((value) => String(value || '').toLowerCase().includes(search)))); 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);
  1066. return response.json({ success: true, data: { className: 'FontPicShape', page, pageSize, total, results: results.map(serializeObject) } });
  1067. }
  1068. if (operation === 'saveFontShapeType') {
  1069. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; if (!objectId) fail(501, 'migration_blocked: FontPicShapeType.id 与 Parse 保留 id 冲突,且省略 id 创建不会生成旧分类编号,不能安全新增图形分类');
  1070. const name = String(payload.name || '').trim(); const remarks = String(payload.remarks || '').trim(); if (!name || name.length > 100 || remarks.length > 2000) fail(400, '图形分类名称或备注无效');
  1071. const fields = await schemaFor('FontPicShapeType'); const query = new Parse.Query('FontPicShapeType'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); target.set('name', name); target.set('remarks', remarks); target.set('updateTime', new Date());
  1072. try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '图形分类写入失败: ' + String(error && error.message || error)); } await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-font-shape-type', 'FontPicShapeType', target.id); return response.json({ success: true, data: serializeObject(target) });
  1073. }
  1074. if (operation === 'saveFontShape') {
  1075. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; if (!objectId) fail(501, 'migration_blocked: FontPicShape.id 与 Parse 保留 id 冲突,且省略 id 创建不会生成旧素材编号,不能安全新增图形素材');
  1076. if (input.file) fail(501, 'migration_blocked: 当前 Parse Server 的 SDK 与 /files REST 接口均错误调用 MongoDB 文件适配器,而本项目使用 PostgreSQL;修复服务端文件存储配置前不能替换图形文件');
  1077. const name = String(payload.name || '').trim(); const remarks = String(payload.remarks || '').trim(); const typeId = Number(input.typeId == null ? payload.typeId || 0 : input.typeId); if (!name || name.length > 100 || remarks.length > 2000 || !Number.isInteger(typeId) || typeId < 1) fail(400, '图形素材名称、分类或备注无效');
  1078. const typeFields = await schemaFor('FontPicShapeType'); const typeQuery = new Parse.Query('FontPicShapeType'); applyTenant(typeQuery, typeFields, context, input.companyId); typeQuery.limit(1000); const types = await typeQuery.find({ useMasterKey: true }); if (!types.some((entry) => Number(entry.get('id')) === typeId)) fail(404, '目标图形分类不存在或不属于当前帐套');
  1079. const fields = await schemaFor('FontPicShape'); const query = new Parse.Query('FontPicShape'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true });
  1080. target.set('name', name); target.set('typeId', typeId); target.set('remarks', remarks); target.set('updateTime', new Date()); try { await target.save(null, { useMasterKey: true }); } catch (error) { fail(422, '图形素材写入失败: ' + String(error && error.message || error)); } await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-font-shape', 'FontPicShape', target.id); return response.json({ success: true, data: serializeObject(target) });
  1081. }
  1082. if (operation === 'fontShapeTypeBatch') {
  1083. if (String(input.className || '') !== 'FontPicShapeType' || 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 个图形分类');
  1084. const fields = await schemaFor('FontPicShapeType'); const query = new Parse.Query('FontPicShapeType'); 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, '部分图形分类不存在或不属于当前帐套'); const typeIds = new Set(targets.map((entry) => Number(entry.get('id'))).filter((value) => value > 0));
  1085. if (typeIds.size) { const shapeFields = await schemaFor('FontPicShape'); const refsQuery = new Parse.Query('FontPicShape'); applyTenant(refsQuery, shapeFields, context, input.companyId); refsQuery.limit(1000); const refs = await refsQuery.find({ useMasterKey: true }); if (refs.length >= 1000) fail(409, '图形素材数量超过安全核验上限,不能删除分类'); if (refs.some((entry) => typeIds.has(Number(entry.get('typeId'))))) fail(409, '图形分类仍有素材引用,不能删除'); }
  1086. await Parse.Object.destroyAll(targets, { useMasterKey: true }); for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'delete-font-shape-type', 'FontPicShapeType', target.id); return response.json({ success: true, data: { action: 'delete', updated: targets.length, results: [] } });
  1087. }
  1088. if (operation === 'fontShapeBatch') {
  1089. if (String(input.className || '') !== 'FontPicShape' || 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 个图形素材');
  1090. const fields = await schemaFor('FontPicShape'); const query = new Parse.Query('FontPicShape'); 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 }, 'delete-font-shape', 'FontPicShape', target.id); return response.json({ success: true, data: { action: 'delete', updated: targets.length, results: [] } });
  1091. }
  1092. if (operation === 'legacyFontPicBlocker') {
  1093. const action = String(input.action || ''); const blockers = { Index: '目标 Schema 缺少旧 FontPic 成品字体图主表与历史数据', FontPicInfo: '目标 Schema 缺少旧 FontPic 成品字体图详情数据', FontPicInfo_Submit: '目标 Schema 缺少旧 FontPic 成品字体图持久化模型', FontPic_API: '目标 Schema 缺少旧 FontPic 成品字体图可删除记录', Draft: '目标 Schema 缺少旧 FontPicDraft 草稿表与历史数据', DraftInfo: '目标 Schema 缺少旧 FontPicDraft 草稿详情数据', DraftInfo_Submit: '目标 Schema 缺少旧 FontPicDraft 草稿持久化模型', Draft_API: '目标 Schema 缺少旧 FontPicDraft 可删除记录' }; if (!Object.prototype.hasOwnProperty.call(blockers, action)) fail(400, '不支持的旧字体图动作'); fail(501, 'migration_blocked: ' + blockers[action]);
  1094. }
  1095. if (operation === 'surveys') {
  1096. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const search = String(input.search || '').trim().toLowerCase(); const status = Number(input.status == null ? -100 : input.status); if (search.length > 100 || ![-100,0,99].includes(status)) fail(400, '问卷筛选条件无效');
  1097. const fields = await schemaFor('DesignAsk'); const query = new Parse.Query('DesignAsk'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => (status === -100 || Number(entry.get('zstatus')) === status) && (!search || [entry.get('title'),entry.get('category'),entry.get('remind')].some((value) => String(value || '').toLowerCase().includes(search)))); 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); return response.json({ success: true, data: { className: 'DesignAsk', page, pageSize, total, results: results.map(serializeObject) } });
  1098. }
  1099. if (operation === 'surveyQuestions') {
  1100. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const askId = Number(input.askId || 0); const search = String(input.search || '').trim().toLowerCase(); if (!Number.isInteger(askId) || askId < 1 || search.length > 100) fail(400, '问卷题目筛选条件无效');
  1101. const askFields = await schemaFor('DesignAsk'); const askQuery = new Parse.Query('DesignAsk'); applyTenant(askQuery, askFields, context, input.companyId); askQuery.limit(1000); const asks = await askQuery.find({ useMasterKey: true }); if (!asks.some((entry) => Number(entry.get('id')) === askId)) fail(404, '问卷不存在或不属于当前帐套');
  1102. const fields = await schemaFor('DesignQuestion'); const query = new Parse.Query('DesignQuestion'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => Number(entry.get('askId')) === askId && (!search || [entry.get('qtitle'),entry.get('qcontent'),entry.get('qoption')].some((value) => String(value || '').toLowerCase().includes(search)))); 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); return response.json({ success: true, data: { className: 'DesignQuestion', askId, page, pageSize, total, results: results.map(serializeObject) } });
  1103. }
  1104. if (operation === 'surveyResults') {
  1105. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const askId = Number(input.askId || 0); if (!Number.isInteger(askId) || askId < 1) fail(400, '问卷答卷筛选条件无效');
  1106. const askFields = await schemaFor('DesignAsk'); const askQuery = new Parse.Query('DesignAsk'); applyTenant(askQuery, askFields, context, input.companyId); askQuery.limit(1000); const asks = await askQuery.find({ useMasterKey: true }); if (!asks.some((entry) => Number(entry.get('id')) === askId)) fail(404, '问卷不存在或不属于当前帐套');
  1107. const fields = await schemaFor('DesignAnswer'); const query = new Parse.Query('DesignAnswer'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => Number(entry.get('askId')) === askId); results.sort((left, right) => Number(right.get('id') || 0) - Number(left.get('id') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize); return response.json({ success: true, data: { className: 'DesignAnswer', askId, page, pageSize, total, results: results.map(serializeObject) } });
  1108. }
  1109. if (operation === 'saveSurvey') {
  1110. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; if (!objectId) fail(501, 'migration_blocked: DesignAsk.id 与 Parse 保留 id 冲突,sourceKey 创建探测不能还原旧问卷编号,不能安全新增问卷');
  1111. const title = String(payload.title || '').trim(); const category = String(payload.category || '').trim(); const remind = String(payload.remind || '').trim(); const preViewImg = String(payload.preViewImg || '').trim(); const startRaw = payload.startDate && typeof payload.startDate === 'object' ? payload.startDate.iso : payload.startDate; const endRaw = payload.endDate && typeof payload.endDate === 'object' ? payload.endDate.iso : payload.endDate; const startDate = new Date(String(startRaw || '')); const endDate = new Date(String(endRaw || '')); const ztype = Number(payload.ztype || 0); const ipinterval = Number(payload.ipinterval || 0); const zstatus = Number(payload.zstatus == null ? 0 : payload.zstatus); const flags = { isIplimit: Number(payload.isIplimit || 0), isNeedLogin: Number(payload.isNeedLogin || 0), isShowResult: Number(payload.isShowResult || 0), isEnableVcode: Number(payload.isEnableVcode || 0) };
  1112. if (!title || title.length > 200 || category.length > 100 || remind.length > 10000 || preViewImg.length > 2000 || Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime()) || endDate < startDate || endDate.getTime() < Date.now() || !Number.isInteger(ztype) || ztype < 0 || !Number.isFinite(ipinterval) || ipinterval < 0 || ![0,99].includes(zstatus) || Object.values(flags).some((value) => ![0,1].includes(value))) fail(400, '问卷标题、时间、状态或访问设置无效');
  1113. const fields = await schemaFor('DesignAsk'); const query = new Parse.Query('DesignAsk'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); target.set('title', title); target.set('category', category); target.set('remind', remind); target.set('preViewImg', preViewImg); target.set('startDate', startDate); target.set('endDate', endDate); target.set('ztype', ztype); target.set('ipinterval', ipinterval); target.set('zstatus', zstatus); for (const [name,value] of Object.entries(flags)) target.set(name, value); await target.save(null, { useMasterKey: true }); await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-survey', 'DesignAsk', target.id); return response.json({ success: true, data: serializeObject(target) });
  1114. }
  1115. if (operation === 'saveSurveyQuestion') {
  1116. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; if (!objectId) fail(501, 'migration_blocked: DesignQuestion.id 与 Parse 保留 id 冲突,sourceKey 创建探测不能还原旧题目编号,不能安全新增问卷题目');
  1117. const qtitle = String(payload.qtitle || '').trim(); const qcontent = String(payload.qcontent || '').trim(); const qtype = String(payload.qtype || '').trim().toLowerCase(); const qoption = String(payload.qoption || '').trim(); const qflag = String(payload.qflag || '').trim(); const required = payload.required === true || payload.required === 1 || payload.required === '1' || payload.required === 'true' ? 1 : 0; if (!qtitle || qtitle.length > 1000 || qcontent.length > 20000 || !/^[a-z][a-z0-9_-]{0,30}$/.test(qtype) || qoption.length > 20000 || qflag.length > 5000) fail(400, '问卷题目内容或类型无效');
  1118. if (['radio','checkbox'].includes(qtype)) { let options; try { options = JSON.parse(qoption); } catch { fail(400, '单选/多选题选项必须是有效 JSON 数组'); } if (!Array.isArray(options) || !options.length || options.length > 100 || options.some((item) => !item || typeof item !== 'object' || !String(item.text || '').trim() || String(item.text || '').length > 500 || String(item.value || '').length > 500)) fail(400, '单选/多选题选项格式无效'); }
  1119. if (qflag) { let flag; try { flag = JSON.parse(qflag); } catch { fail(400, '题目扩展设置必须是有效 JSON'); } if (!flag || typeof flag !== 'object' || Array.isArray(flag)) fail(400, '题目扩展设置必须是 JSON 对象'); }
  1120. const fields = await schemaFor('DesignQuestion'); const query = new Parse.Query('DesignQuestion'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); const askId = Number(target.get('askId') || 0); const askFields = await schemaFor('DesignAsk'); const askQuery = new Parse.Query('DesignAsk'); applyTenant(askQuery, askFields, context, input.companyId); askQuery.limit(1000); const asks = await askQuery.find({ useMasterKey: true }); if (!asks.some((entry) => Number(entry.get('id')) === askId)) fail(409, '题目所属问卷已不存在,不能继续编辑');
  1121. target.set('qtitle', qtitle); target.set('qcontent', qcontent); target.set('qtype', qtype); target.set('qoption', qoption); target.set('qflag', qflag || '{}'); target.set('required', required); await target.save(null, { useMasterKey: true }); await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-survey-question', 'DesignQuestion', target.id); return response.json({ success: true, data: serializeObject(target) });
  1122. }
  1123. if (operation === 'surveyBatch') {
  1124. const className = String(input.className || ''); const action = String(input.action || ''); const allowed = className === 'DesignAsk' ? ['start','stop','delete'] : className === 'DesignQuestion' ? ['delete','sort'] : className === 'DesignAnswer' ? ['delete'] : []; if (!allowed.includes(action)) 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 条问卷记录');
  1125. 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, '部分问卷记录不存在或不属于当前帐套');
  1126. if (action === 'delete') await Parse.Object.destroyAll(targets, { useMasterKey: true }); else if (className === 'DesignAsk') { for (const target of targets) target.set('zstatus', action === 'start' ? 99 : 0); await Parse.Object.saveAll(targets, { useMasterKey: true }); } else { const orders = Array.isArray(input.orders) ? input.orders : []; const orderMap = new Map(orders.map((item) => [String(item && item.objectId || ''), Number(item && item.orderId)])); if (orderMap.size !== objectIds.length || [...orderMap.values()].some((value) => !Number.isInteger(value) || value < 1 || value > 1000000)) fail(400, '题目排序数据无效'); for (const target of targets) target.set('orderId', orderMap.get(target.id)); await Parse.Object.saveAll(targets, { useMasterKey: true }); }
  1127. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'survey-' + className + '-' + action, className, target.id); return response.json({ success: true, data: { className, action, updated: targets.length, results: action === 'delete' ? [] : targets.map(serializeObject) } });
  1128. }
  1129. if (operation === 'surveyResultChart') {
  1130. const askId = Number(input.askId || 0); if (!Number.isInteger(askId) || askId < 1) fail(400, '缺少有效问卷编号'); const askFields = await schemaFor('DesignAsk'); const askQuery = new Parse.Query('DesignAsk'); applyTenant(askQuery, askFields, context, input.companyId); askQuery.limit(1000); const asks = await askQuery.find({ useMasterKey: true }); const survey = asks.find((entry) => Number(entry.get('id')) === askId); if (!survey) fail(404, '问卷不存在或不属于当前帐套');
  1131. const questionFields = await schemaFor('DesignQuestion'); const questionQuery = new Parse.Query('DesignQuestion'); applyTenant(questionQuery, questionFields, context, input.companyId); questionQuery.limit(1000); const questions = (await questionQuery.find({ useMasterKey: true })).filter((entry) => Number(entry.get('askId')) === askId); const answerFields = await schemaFor('DesignAnswer'); const answerQuery = new Parse.Query('DesignAnswer'); applyTenant(answerQuery, answerFields, context, input.companyId); answerQuery.limit(1000); const answers = (await answerQuery.find({ useMasterKey: true })).filter((entry) => Number(entry.get('askId')) === askId); const counts = new Map(); let invalidAnswers = 0;
  1132. for (const entry of answers) { let details; try { details = JSON.parse(String(entry.get('answer') || '')); } catch { invalidAnswers++; continue; } if (!Array.isArray(details)) { invalidAnswers++; continue; } for (const detail of details) { const qid = String(detail && detail.qid || ''); let values = detail && detail.answer; if (!Array.isArray(values)) values = values == null || values === '' ? [] : [values]; for (const value of values) { const key = qid + '\u0000' + String(value); counts.set(key, (counts.get(key) || 0) + 1); } } }
  1133. const chart = questions.sort((left, right) => Number(left.get('orderId') || 0) - Number(right.get('orderId') || 0) || Number(left.get('id') || 0) - Number(right.get('id') || 0)).map((question) => { let options = []; try { const parsed = JSON.parse(String(question.get('qoption') || '[]')); if (Array.isArray(parsed)) options = parsed; } catch {} const qid = String(question.get('id') || ''); const known = new Set(options.map((option) => String(option && option.value || ''))); let otherCount = 0; for (const [key,value] of counts) if (key.startsWith(qid + '\u0000') && !known.has(key.slice(qid.length + 1))) otherCount += value; return { id: qid, title: String(question.get('qtitle') || ''), type: String(question.get('qtype') || ''), options: options.map((option) => ({ text: String(option && option.text || ''), value: String(option && option.value || ''), count: counts.get(qid + '\u0000' + String(option && option.value || '')) || 0 })), otherCount }; }); return response.json({ success: true, data: { survey: serializeObject(survey), responseCount: answers.length, invalidAnswers, questions: chart } });
  1134. }
  1135. if (operation === 'serviceSeats') {
  1136. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const search = String(input.search || '').trim().toLowerCase(); if (search.length > 100) fail(400, '客服席位搜索词过长'); const fields = await schemaFor('ServiceSeat'); const query = new Parse.Query('ServiceSeat'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => !search || [entry.get('sName'),entry.get('sRemrk')].some((value) => String(value || '').toLowerCase().includes(search))); results.sort((left, right) => Number(left.get('sIndex') || 0) - Number(right.get('sIndex') || 0) || Number(left.get('sId') || 0) - Number(right.get('sId') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize); return response.json({ success: true, data: { className: 'ServiceSeat', page, pageSize, total, results: results.map(serializeObject) } });
  1137. }
  1138. if (operation === 'saveServiceSeat') {
  1139. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; const name = String(payload.sName || '').trim(); const faceImg = String(payload.sFaceImg || '').trim(); const username = String(input.username || payload.sRemrk || '').trim(); const isDefault = Number(payload.sDefault || 0); const index = Number(payload.sIndex || 0); if (!name || name.length > 100 || faceImg.length > 2000 || !/^[A-Za-z0-9_@.\-\u4e00-\u9fff]{2,64}$/.test(username) || ![0,1].includes(isDefault) || !Number.isInteger(index) || index < 0 || index > 1000000) fail(400, '客服名称、绑定账号、默认状态或排序无效'); let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '客服席位必须指定帐套'); const userRow = await Psql.oneOrNone('SELECT "objectId",COALESCE("legacyUserId",CASE WHEN COALESCE("legacyUserData"->>\'UserID\',\'\') ~ \'^[0-9]+$\' THEN ("legacyUserData"->>\'UserID\')::numeric END) AS legacy_id FROM "_User" WHERE "company"=$1 AND LOWER("username")=LOWER($2) AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) AND ("isDisabled" IS NULL OR "isDisabled"=FALSE) LIMIT 1', [companyId, username]); const legacyUserId = Number(userRow && userRow.legacy_id) || 0; if (!legacyUserId) fail(501, 'migration_blocked: 绑定账号不存在或缺少旧用户 ID;旧系统会用固定密码 123456 自动开户,该不安全行为不予迁移,请先通过安全开户流程创建账号'); const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('ServiceSeat'); let target; let created = false; if (objectId) { const query = new Parse.Query('ServiceSeat'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true }); } else { target = new Parse.Object('ServiceSeat'); target.set('sourceKey', 'cloud:service-seat:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('company', company); target.set('sDateTime', new Date().toISOString()); created = true; }
  1140. target.set('sName', name); target.set('sFaceImg', faceImg); target.set('sRemrk', username); target.set('sAdminId', legacyUserId); target.set('sDefault', isDefault); target.set('sIndex', index); try { await target.save(null, { useMasterKey: true }); if (created) { const rows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-service-seat-id\'))),next_id AS MATERIALIZED (SELECT COALESCE(MAX("sId"),0)+1 AS id FROM "ServiceSeat",lock_row WHERE "company"=$1) UPDATE "ServiceSeat" SET "sId"=next_id.id,"sourceKey"=\'[["S_ID",\'||next_id.id||\']]\',"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id]); if (!Number(rows[0] && rows[0].id)) throw new Error('无法分配客服席位编号'); } if (isDefault === 1) { const otherQuery = new Parse.Query('ServiceSeat'); applyTenant(otherQuery, fields, context, companyId); otherQuery.notEqualTo('objectId', target.id); otherQuery.limit(1000); const others = await otherQuery.find({ useMasterKey: true }); for (const other of others) if (Number(other.get('sDefault')) === 1) other.set('sDefault', 0); if (others.length) await Parse.Object.saveAll(others, { useMasterKey: true }); } } catch (error) { if (created && target.id) await target.destroy({ useMasterKey: true }).catch(() => undefined); throw error; } await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-service-seat' : 'create-service-seat', 'ServiceSeat', target.id); return response.json({ success: true, data: serializeObject(target) });
  1141. }
  1142. if (operation === 'serviceCodes') {
  1143. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const search = String(input.search || '').trim().toLowerCase(); if (search.length > 100) fail(400, '欢迎语搜索词过长'); const fields = await schemaFor('Temp'); const query = new Parse.Query('Temp'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => Number(entry.get('useType')) === 12 && (!search || [entry.get('str1'),entry.get('str2'),entry.get('str4')].some((value) => String(value || '').toLowerCase().includes(search)))); 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); return response.json({ success: true, data: { className: 'Temp', page, pageSize, total, results: results.map(serializeObject) } });
  1144. }
  1145. if (operation === 'saveServiceCode') {
  1146. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; if (!objectId) fail(501, 'migration_blocked: Temp.id 与 Parse 保留 id 冲突,省略 id 创建不能生成旧欢迎语编号,不能安全新增欢迎语模板'); const name = String(payload.str1 || '').trim(); const content = String(payload.str2 || '').trim(); const theme = String(payload.str4 || '').trim(); if (!name || name.length > 100 || !content || content.length > 50000 || !/^[A-Za-z0-9_-]{1,50}$/.test(theme)) fail(400, '欢迎语名称、内容或主题无效'); const fields = await schemaFor('Temp'); const query = new Parse.Query('Temp'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); if (Number(target.get('useType')) !== 12) fail(409, '该临时模板不是客服欢迎语'); target.set('str1', name); target.set('str2', content); target.set('str4', theme); await target.save(null, { useMasterKey: true }); await target.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || context.company }, 'update-service-code', 'Temp', target.id); return response.json({ success: true, data: serializeObject(target) });
  1147. }
  1148. if (operation === 'serviceBatch') {
  1149. const className = String(input.className || ''); if (!['ServiceSeat','Temp'].includes(className) || 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 条客服记录'); 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 || (className === 'Temp' && targets.some((target) => Number(target.get('useType')) !== 12))) fail(404, '部分客服记录不存在、不属于当前帐套或不是欢迎语模板'); await Parse.Object.destroyAll(targets, { useMasterKey: true }); for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'delete-service-' + (className === 'ServiceSeat' ? 'seat' : 'code'), className, target.id); return response.json({ success: true, data: { className, action: 'delete', updated: targets.length, results: [] } });
  1150. }
  1151. if (operation === 'legacyServiceChatBlocker') {
  1152. const action = String(input.action || ''); const blockers = { MsgEx: '目标 Schema 缺少旧 ChatMsg 会话消息表与历史数据', MsgInfo: '目标 Schema 缺少旧 ChatMsg 单条消息详情数据', MsgList: '目标 Schema 缺少旧 ChatMsg 消息列表数据', chat_del: '目标 Schema 缺少旧 ChatMsg 可删除记录' }; if (!Object.prototype.hasOwnProperty.call(blockers, action)) fail(400, '不支持的旧客服消息动作'); fail(501, 'migration_blocked: ' + blockers[action]);
  1153. }
  1154. if (operation === 'saveExamClass') {
  1155. const objectId = String(input.objectId || '');
  1156. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1157. const className = String(payload.cClassName || '').trim();
  1158. const parentId = Number(input.parentId == null ? payload.cClassid || 0 : input.parentId);
  1159. const classType = Number(input.classType == null ? payload.cClassType || 1 : input.classType);
  1160. const orderId = Number(input.orderId == null ? payload.cOrderBy || 0 : input.orderId);
  1161. if (!className || className.length > 255) fail(400, '试题分类名称长度应为 1 至 255 位');
  1162. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父试题分类编号无效');
  1163. if (![1,2].includes(classType)) fail(400, '试题分类类型只能是答题类型或视频操作类型');
  1164. if (!Number.isInteger(orderId) || orderId < 0) fail(400, '试题分类排序必须是非负整数');
  1165. let companyId = pointerId(context.company);
  1166. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  1167. if (!companyId) fail(400, '试题分类必须指定帐套');
  1168. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1169. const fields = await schemaFor('ExamClass');
  1170. let target;
  1171. let currentId = 0;
  1172. if (objectId) {
  1173. const query = new Parse.Query('ExamClass'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  1174. companyId = pointerId(target.get('company')) || companyId; currentId = Number(target.get('cId')) || 0;
  1175. } else target = new Parse.Object('ExamClass');
  1176. if (parentId > 0) {
  1177. const parent = await Psql.oneOrNone('SELECT "cId" FROM "ExamClass" WHERE "company"=$1 AND "cId"=$2 LIMIT 1', [companyId, parentId]);
  1178. if (!parent) fail(404, '父试题分类不存在或不属于当前帐套');
  1179. if (currentId) {
  1180. 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]);
  1181. if (cycle) fail(409, '不能把试题分类移动到自身或其下级分类');
  1182. }
  1183. }
  1184. 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]);
  1185. if (duplicate) fail(409, '同一帐套的试题分类名称不能重复');
  1186. target.set('cClassName', className); target.set('cClassid', parentId); target.set('cClassType', classType); target.set('company', company);
  1187. if (objectId) target.set('cOrderBy', orderId); else target.set('sourceKey', 'cloud:admin-exam-class:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10));
  1188. try { await target.save(null, { useMasterKey: true }); }
  1189. catch (error) { fail(422, '试题分类初始写入失败: ' + String(error && error.message || error)); }
  1190. try {
  1191. if (!objectId) {
  1192. 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]);
  1193. currentId = Number(rows[0] && rows[0].id) || 0;
  1194. if (!currentId) throw new Error('无法分配试题分类编号');
  1195. }
  1196. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '试题分类结构写入失败: ' + String(error && error.message || error)); }
  1197. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-exam-class' : 'create-exam-class', 'ExamClass', target.id);
  1198. return response.json({ success: true, data: serializeObject(target) });
  1199. }
  1200. if (operation === 'examClassChildren') {
  1201. const parentId = Number(input.parentId || 0);
  1202. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父试题分类编号无效');
  1203. 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);
  1204. const results = await query.find({ useMasterKey: true });
  1205. return response.json({ success: true, data: { parentId, results: results.map(serializeObject) } });
  1206. }
  1207. if (operation === 'saveExamPoint') {
  1208. const objectId = String(input.objectId || '');
  1209. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1210. const pointName = String(payload.testPoint || '').trim();
  1211. const parentId = Number(input.parentId == null ? payload.tid || 0 : input.parentId);
  1212. const orderId = Number(input.orderId == null ? payload.orderBy || 0 : input.orderId);
  1213. if (!pointName || pointName.length > 50) fail(400, '考点名称长度应为 1 至 50 位');
  1214. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '上级考点编号无效');
  1215. if (!Number.isInteger(orderId) || orderId < 0) fail(400, '考点排序必须是非负整数');
  1216. let companyId = pointerId(context.company);
  1217. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  1218. if (!companyId) fail(400, '考点必须指定帐套');
  1219. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1220. const fields = await schemaFor('ExamPoint');
  1221. let target;
  1222. let currentId = 0;
  1223. if (objectId) {
  1224. const query = new Parse.Query('ExamPoint'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  1225. companyId = pointerId(target.get('company')) || companyId; currentId = Number(target.get('id')) || 0;
  1226. } else target = new Parse.Object('ExamPoint');
  1227. if (parentId > 0) {
  1228. const parent = await Psql.oneOrNone('SELECT "id" FROM "ExamPoint" WHERE "company"=$1 AND "id"=$2 LIMIT 1', [companyId, parentId]);
  1229. if (!parent) fail(404, '上级考点不存在或不属于当前帐套');
  1230. if (currentId) {
  1231. 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]);
  1232. if (cycle) fail(409, '不能把考点移动到自身或其下级考点');
  1233. }
  1234. }
  1235. 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]);
  1236. if (duplicate) fail(409, '同一帐套的考点名称不能重复');
  1237. target.set('testPoint', pointName); target.set('tid', parentId); target.set('company', company);
  1238. if (objectId) target.set('orderBy', orderId);
  1239. 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()); }
  1240. try { await target.save(null, { useMasterKey: true }); }
  1241. catch (error) { fail(422, '考点初始写入失败: ' + String(error && error.message || error)); }
  1242. try {
  1243. if (!objectId) {
  1244. 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]);
  1245. currentId = Number(rows[0] && rows[0].id) || 0;
  1246. if (!currentId) throw new Error('无法分配考点编号');
  1247. }
  1248. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '考点结构写入失败: ' + String(error && error.message || error)); }
  1249. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-exam-point' : 'create-exam-point', 'ExamPoint', target.id);
  1250. return response.json({ success: true, data: serializeObject(target) });
  1251. }
  1252. if (operation === 'saveKnowledge') {
  1253. const objectId = String(input.objectId || '');
  1254. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1255. const knowledgeName = String(payload.kName || '').trim();
  1256. const classId = Number(input.classId == null ? payload.kClassId || 0 : input.classId);
  1257. const parentId = Number(input.parentId == null ? payload.pid || 0 : input.parentId);
  1258. const orderId = Number(input.orderId == null ? payload.kOrderBy || 0 : input.orderId);
  1259. const status = Number(payload.status == null ? 1 : payload.status);
  1260. const grade = Number(payload.grade || 0);
  1261. const isSys = Number(payload.isSys || 0);
  1262. if (!knowledgeName || knowledgeName.length > 200) fail(400, '知识点名称长度应为 1 至 200 位');
  1263. if (!Number.isInteger(classId) || classId < 1) fail(400, '请选择有效试题分类');
  1264. if (!Number.isInteger(parentId) || parentId < 0) fail(400, '父知识点编号无效');
  1265. if (!Number.isInteger(orderId) || orderId < 0) fail(400, '知识点排序必须是非负整数');
  1266. if (![0,1].includes(status) || !Number.isInteger(grade) || grade < 0 || ![0,1].includes(isSys)) fail(400, '知识点状态、年级或系统标记无效');
  1267. let companyId = pointerId(context.company);
  1268. if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId);
  1269. if (!companyId) fail(400, '知识点必须指定帐套');
  1270. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1271. const subject = await Psql.oneOrNone('SELECT "cId" FROM "ExamClass" WHERE "company"=$1 AND "cId"=$2 LIMIT 1', [companyId, classId]);
  1272. if (!subject) fail(404, '试题分类不存在或不属于当前帐套');
  1273. const fields = await schemaFor('QuestionsKnowledge');
  1274. let target;
  1275. let currentId = 0;
  1276. if (objectId) {
  1277. const query = new Parse.Query('QuestionsKnowledge'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true });
  1278. companyId = pointerId(target.get('company')) || companyId; currentId = Number(target.get('kId')) || 0;
  1279. } else target = new Parse.Object('QuestionsKnowledge');
  1280. if (parentId > 0) {
  1281. const parent = await Psql.oneOrNone('SELECT "kId" FROM "QuestionsKnowledge" WHERE "company"=$1 AND "kId"=$2 AND "kClassId"=$3 LIMIT 1', [companyId, parentId, classId]);
  1282. if (!parent) fail(404, '父知识点不存在、科目不一致或不属于当前帐套');
  1283. if (currentId) {
  1284. 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]);
  1285. if (cycle) fail(409, '不能把知识点移动到自身或其下级知识点');
  1286. }
  1287. }
  1288. 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]);
  1289. if (duplicate) fail(409, '同一试题分类中的知识点名称不能重复');
  1290. 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);
  1291. if (objectId) target.set('kOrderBy', orderId);
  1292. 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()); }
  1293. try { await target.save(null, { useMasterKey: true }); }
  1294. catch (error) { fail(422, '知识点初始写入失败: ' + String(error && error.message || error)); }
  1295. try {
  1296. if (!objectId) {
  1297. 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]);
  1298. currentId = Number(rows[0] && rows[0].id) || 0;
  1299. if (!currentId) throw new Error('无法分配知识点编号');
  1300. }
  1301. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '知识点结构写入失败: ' + String(error && error.message || error)); }
  1302. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-knowledge' : 'create-knowledge', 'QuestionsKnowledge', target.id);
  1303. return response.json({ success: true, data: serializeObject(target) });
  1304. }
  1305. if (operation === 'knowledgeChildren') {
  1306. const parentId = Number(input.parentId || 0); const classId = Number(input.classId || 0);
  1307. if (!Number.isInteger(parentId) || parentId < 0 || !Number.isInteger(classId) || classId < 1) fail(400, '知识点父级或试题分类编号无效');
  1308. 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);
  1309. const results = await query.find({ useMasterKey: true });
  1310. return response.json({ success: true, data: { classId, parentId, results: results.map(serializeObject) } });
  1311. }
  1312. if (operation === 'saveExamTeacher') {
  1313. const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1314. const teacherName = String(payload.tname || '').trim(); const classId = Number(input.classId == null ? payload.tclsss || 0 : input.classId);
  1315. if (!teacherName || teacherName.length > 50) fail(400, '教师姓名长度应为 1 至 50 位');
  1316. if (!Number.isInteger(classId) || classId < 0) fail(400, '任教试题分类编号无效');
  1317. let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '教师必须指定帐套');
  1318. const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true });
  1319. 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, '任教试题分类不存在或不属于当前帐套'); }
  1320. const fields = await schemaFor('ExTeacher'); let target;
  1321. 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; }
  1322. else target = new Parse.Object('ExTeacher');
  1323. const limits = { post: 50, teach: 50, fileUpload: 255, remark: 1000 };
  1324. 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); }
  1325. target.set('tname', teacherName); target.set('tclsss', classId); target.set('company', company); target.set('addUser', Number(context.current.get('legacyUserId')) || 0);
  1326. if (!objectId) { target.set('sourceKey', 'cloud:admin-exam-teacher:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('creatTime', new Date()); }
  1327. try { await target.save(null, { useMasterKey: true }); }
  1328. catch (error) { fail(422, '教师初始写入失败: ' + String(error && error.message || error)); }
  1329. try {
  1330. if (!objectId) {
  1331. 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]);
  1332. if (!(Number(rows[0] && rows[0].id) || 0)) throw new Error('无法分配教师编号');
  1333. }
  1334. } catch (error) { if (!objectId) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '教师编号写入失败: ' + String(error && error.message || error)); }
  1335. await target.fetch({ useMasterKey: true }); await audit({ ...context, company }, objectId ? 'update-exam-teacher' : 'create-exam-teacher', 'ExTeacher', target.id);
  1336. return response.json({ success: true, data: serializeObject(target) });
  1337. }
  1338. if (operation === 'barBatch') {
  1339. const action = String(input.action || '');
  1340. const actions = ['audit','unaudit','recycle','recover','move','top-global','top-section','top-undo','elite','elite-undo','bottom','bottom-undo'];
  1341. if (!actions.includes(action)) fail(400, '不支持的贴吧帖子批量操作');
  1342. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  1343. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  1344. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条帖子');
  1345. const fields = await schemaFor('GuestBar');
  1346. const query = new Parse.Query('GuestBar'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  1347. const targets = await query.find({ useMasterKey: true });
  1348. if (targets.length !== objectIds.length) fail(404, '部分帖子不存在或不属于当前帐套');
  1349. let cateId = null;
  1350. if (action === 'move') {
  1351. cateId = Number(input.cateId);
  1352. if (!Number.isInteger(cateId) || cateId < 1) fail(400, '目标贴吧分类编号无效');
  1353. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  1354. if (companyIds.length !== 1) fail(400, '批量移动的帖子必须属于同一帐套');
  1355. 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]);
  1356. if (!category) fail(404, '目标贴吧分类不存在或不属于当前帐套');
  1357. }
  1358. for (const target of targets) {
  1359. if (action === 'audit' || action === 'recover') target.set('status', 99);
  1360. else if (action === 'unaudit') target.set('status', 0);
  1361. else if (action === 'recycle') target.set('status', -2);
  1362. else if (action === 'move') target.set('cateId', cateId);
  1363. else if (action === 'top-global') target.set('orderFlag', 2);
  1364. else if (action === 'top-section') target.set('orderFlag', 1);
  1365. else if (action === 'bottom') target.set('orderFlag', -1);
  1366. else if (action === 'top-undo' || action === 'bottom-undo') target.set('orderFlag', 0);
  1367. else {
  1368. const flags = String(target.get('postFlag') || '').split(',').map((value) => value.trim()).filter(Boolean);
  1369. const next = new Set(flags);
  1370. if (action === 'elite') next.add('Recommend'); else next.delete('Recommend');
  1371. target.set('postFlag', next.size ? ',' + [...next].join(',') + ',' : '');
  1372. }
  1373. }
  1374. await Parse.Object.saveAll(targets, { useMasterKey: true });
  1375. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'bar-' + action, 'GuestBar', target.id);
  1376. return response.json({ success: true, data: { action, updated: targets.length, cateId, results: targets.map(serializeObject) } });
  1377. }
  1378. if (operation === 'contentBatch') {
  1379. const action = String(input.action || '');
  1380. if (!['status','recycle','recover','move'].includes(action)) fail(400, '不支持的内容批量操作');
  1381. const requestedIds = Array.isArray(input.objectIds) ? input.objectIds : [input.objectId];
  1382. const objectIds = [...new Set(requestedIds.map((value) => String(value || '').trim()).filter(Boolean))];
  1383. if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 条内容');
  1384. const contentFields = await schemaFor('CommonModel');
  1385. const query = new Parse.Query('CommonModel'); applyTenant(query, contentFields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length);
  1386. const targets = await query.find({ useMasterKey: true });
  1387. if (targets.length !== objectIds.length) fail(404, '部分内容不存在或不属于当前帐套');
  1388. let status = null;
  1389. let nodeId = null;
  1390. if (action === 'status') {
  1391. status = Number(input.status);
  1392. if (![-3,-1,0,99].includes(status)) fail(400, '不支持的内容状态');
  1393. } else if (action === 'recycle') status = -2;
  1394. else if (action === 'recover') status = 0;
  1395. else {
  1396. nodeId = Number(input.nodeId);
  1397. if (!Number.isInteger(nodeId) || nodeId < 1) fail(400, '请选择有效目标节点');
  1398. const companyIds = [...new Set(targets.map((target) => pointerId(target.get('company'))).filter(Boolean))];
  1399. if (companyIds.length !== 1) fail(400, '批量移动的内容必须属于同一帐套');
  1400. 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]);
  1401. if (!node) fail(404, '目标节点不存在或不属于当前帐套');
  1402. }
  1403. for (const target of targets) {
  1404. if (status !== null) target.set('status', status);
  1405. if (nodeId !== null) target.set('nodeId', nodeId);
  1406. }
  1407. await Parse.Object.saveAll(targets, { useMasterKey: true });
  1408. for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'content-' + action, 'CommonModel', target.id);
  1409. return response.json({ success: true, data: { action, updated: targets.length, status, nodeId, results: targets.map(serializeObject) } });
  1410. }
  1411. const className = String(input.className || '');
  1412. assertClass(className);
  1413. const fields = await schemaFor(className);
  1414. const classWritable = !READ_ONLY_CLASSES.has(className);
  1415. if (operation === 'schema') {
  1416. 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) }));
  1417. 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','FontPicShape','FontPicShapeType','DesignAsk','DesignQuestion','Temp'].includes(className), supportsSoftDelete: Boolean(fields.isDeleted) } });
  1418. }
  1419. if (operation === 'list') {
  1420. const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20));
  1421. let query = new Parse.Query(className); applyTenant(query, fields, context, input.companyId);
  1422. const search = String(input.search || '').trim();
  1423. 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'); }
  1424. const sort = fields[input.sort] ? String(input.sort) : fields.updatedAt ? 'updatedAt' : 'createdAt'; if (input.order === 'asc') query.ascending(sort); else query.descending(sort);
  1425. const total = await query.count({ useMasterKey: true }); query.skip((page - 1) * pageSize); query.limit(pageSize);
  1426. const results = (await query.find({ useMasterKey: true })).filter(isVisible);
  1427. return response.json({ success: true, data: { className, page, pageSize, total, results: results.map(serializeObject) } });
  1428. }
  1429. const objectId = String(input.objectId || '');
  1430. if (operation === 'get') {
  1431. 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 });
  1432. return response.json({ success: true, data: serializeObject(object) });
  1433. }
  1434. if (operation === 'save') {
  1435. if (!classWritable) fail(403, '该系统类不允许通用编辑');
  1436. if (className === '_User' && !objectId) fail(400, '新增用户必须走专用开户流程');
  1437. if (className === 'Group') fail(400, '用户组必须走专用保存流程');
  1438. if (className === 'Node') fail(400, '栏目必须走专用保存流程');
  1439. if (className === 'Special') fail(400, '专题必须走专用保存流程');
  1440. if (className === 'Model' || className === 'ModelField') fail(400, '模型结构必须走专用元数据流程');
  1441. if (className === 'Guestbook') fail(400, '留言必须走专用编辑或回复流程');
  1442. if (className === 'Guestcate') fail(400, '留言/贴吧分类必须走专用保存流程');
  1443. if (className === 'ExamClass') fail(400, '试题分类必须走专用保存流程');
  1444. if (className === 'ExamPoint') fail(400, '考点必须走专用保存流程');
  1445. if (className === 'QuestionsKnowledge') fail(400, '知识点必须走专用保存流程');
  1446. if (className === 'ExTeacher') fail(400, '考试教师必须走专用保存流程');
  1447. if (className === 'Datadiccategory' || className === 'Datadic') fail(400, '数据字典必须走专用保存流程');
  1448. if (className === 'GradeCate' || className === 'Grade') fail(400, '多级数据字典必须走专用保存流程');
  1449. if (className === 'Currency') fail(400, '货币必须走专用保存流程');
  1450. if (className === 'SysHoliday') fail(400, '节假日必须走专用保存流程');
  1451. if (className === 'Search') fail(400, '快捷入口必须走专用保存流程');
  1452. if (className === 'AdZone' || className === 'AdInfo') fail(400, '广告位与广告内容必须走专用保存流程');
  1453. if (className === 'FontPicShape' || className === 'FontPicShapeType') fail(400, '字体图形素材与分类必须走专用保存流程');
  1454. if (className === 'DesignAsk' || className === 'DesignQuestion' || className === 'DesignAnswer') fail(400, '问卷、题目与答卷必须走专用流程');
  1455. if (className === 'ServiceSeat' || className === 'Temp') fail(400, '客服席位与欢迎语必须走专用保存流程');
  1456. if (className === 'CommonModel' && !objectId) fail(400, '内容新增必须同时写入模型附表,不能走通用保存');
  1457. let object;
  1458. 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);
  1459. const payload = input.fields && typeof input.fields === 'object' ? input.fields : {};
  1460. 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)); }
  1461. if (fields.company && context.company) object.set('company', context.company); if (fields.isDeleted && !objectId) object.set('isDeleted', false);
  1462. await object.save(null, { useMasterKey: true }); await audit(context, objectId ? 'update' : 'create', className, object.id);
  1463. return response.json({ success: true, data: serializeObject(object) });
  1464. }
  1465. if (operation === 'delete') {
  1466. 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 });
  1467. if (className === 'Model' || className === 'ModelField') fail(501, 'migration_blocked: 删除模型或字段需要同步删除 PostgreSQL 物理表/列并验证历史数据,托管云函数中未开放此 DDL 流程');
  1468. if (className === 'AdZone' || className === 'AdInfo') fail(400, '广告位与广告内容必须走专用批量删除流程');
  1469. if (className === 'FontPicShape' || className === 'FontPicShapeType') fail(400, '字体图形素材与分类必须走专用批量删除流程');
  1470. if (className === 'DesignAsk' || className === 'DesignQuestion' || className === 'DesignAnswer') fail(400, '问卷、题目与答卷必须走专用批量流程');
  1471. if (className === 'ServiceSeat' || className === 'Temp') fail(400, '客服席位与欢迎语必须走专用批量流程');
  1472. 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 } }); }
  1473. 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 } }); }
  1474. 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 } }); }
  1475. 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 } }); }
  1476. 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 } }); }
  1477. 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 } }); }
  1478. if (className === '_User') assertCanManageUser(context, object, 'lock');
  1479. 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, '该用户组仍有下级组,不能删除'); }
  1480. 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 } }); }
  1481. 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 } }); }
  1482. 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 } }); }
  1483. 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 } }); }
  1484. if (fields.isDeleted) { object.set('isDeleted', true); await object.save(null, { useMasterKey: true }); } else await object.destroy({ useMasterKey: true });
  1485. if (className === '_User') await revokeSessions([object]);
  1486. await audit(context, 'delete', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: Boolean(fields.isDeleted) } });
  1487. }
  1488. if (operation === 'resetPassword') {
  1489. if (className !== '_User' || !objectId || typeof input.newPassword !== 'string' || input.newPassword.length < 8) fail(400, '密码至少 8 位');
  1490. 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 } });
  1491. }
  1492. fail(400, '不支持的后台操作');
  1493. } catch (error) {
  1494. const status = Number(error.status || (error.code === 101 ? 404 : 500));
  1495. return response.status(status).json({ success: false, error: status >= 500 ? 'cloud_function_error' : 'request_rejected', message: error.message || '云函数执行失败' });
  1496. }
  1497. }
  1498. `;
  1499. function cmsReadCode(mode) {
  1500. return String.raw`
  1501. const MODE = ${JSON.stringify(mode)};
  1502. const HIDDEN = /(?:password|secret|sessiontoken|masterkey|privatekey|legacyPasswordHash|adminPassword)/i;
  1503. function inputOf(request) { const body = request.body || {}; return body.params && typeof body.params === 'object' ? body.params : body; }
  1504. function fail(status, message) { const error = new Error(message); error.status = status; throw error; }
  1505. 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; }
  1506. 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 }; }
  1507. async function schema(name) { try { return (await new Parse.Schema(name).get({ useMasterKey: true })).fields || {}; } catch (_) { return {}; } }
  1508. function tenant(query, fields, context) { if (fields.company && context.company) query.equalTo('company', context.company); }
  1509. 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(); }
  1510. function escapeRegex(value) { return String(value).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'); }
  1511. async function handler(request, response) {
  1512. try {
  1513. 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));
  1514. if (MODE === 'content-normalizer') return response.json({ success: true, data: { content: stripHtml(input.content), mode: String(input.mode || 'strip') } });
  1515. if (MODE.startsWith('user-')) {
  1516. 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);
  1517. if (MODE === 'user-extended') { delete data.legacyUserPlat; delete data.legacyWxUser; delete data.wechat; delete data.wxapp; return response.json({ success: true, data }); }
  1518. if (MODE === 'user-platform') return response.json({ success: true, data: { objectId: target.id, platform: safe(target.get('legacyUserPlat') || {}), company: safe(target.get('company')) } });
  1519. return response.json({ success: true, data: { objectId: target.id, wechat: safe(target.get('legacyWxUser') || target.get('wechat') || target.get('wxapp') || {}) } });
  1520. }
  1521. if (MODE === 'exam-classes' || MODE === 'guest-bar') {
  1522. 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) } });
  1523. }
  1524. if (MODE === 'search') {
  1525. 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: [] } });
  1526. 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; }) } });
  1527. }
  1528. fail(400, '不支持的 CMS 查询');
  1529. } 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 || '云函数执行失败' }); }
  1530. }
  1531. `;
  1532. }
  1533. const appGatewayCode = String.raw`
  1534. const DEFAULT_COMPANY_ID = '7pIbDBJmKx';
  1535. const PUBLIC_READ = new Set(['content_list','content_get','content_uphis','node_list','node_get','app_update']);
  1536. const BLOCKED = {
  1537. mcode_send: '缺少新短信服务商凭据与验证码存储', user_login_mobile: '缺少新短信验证码服务', user_register_mobile: '缺少新短信验证码服务', user_sync2: '依赖微信容器授权与新版微信凭据',
  1538. cart_list: '目标 Schema 无购物车类', coupon_list: '目标 Schema 无优惠券实例类', coupon_usrgot_add: '目标 Schema 无用户优惠券类', coupon_usrgot_list: '目标 Schema 无用户优惠券类',
  1539. order_comment_add: '目标 Schema 无订单评价类', order_comment_list: '目标 Schema 无订单评价类', order_delivery: '目标 Schema 无订单与物流类', order_get: '目标 Schema 无订单类', order_list: '目标 Schema 无订单类', order_signfor: '目标 Schema 无订单类',
  1540. payment_cart: '目标 Schema 无订单与支付明细类', payment_cart_again: '目标 Schema 无订单与支付明细类', payment_success: '目标 Schema 无支付明细类',
  1541. invoice_add: '目标 Schema 无发票类', invoice_del: '目标 Schema 无发票类', invoice_get: '目标 Schema 无发票类', invoice_list: '目标 Schema 无发票类', invoice_upd: '目标 Schema 无发票类',
  1542. receaddr_add: '目标 Schema 无收货地址类', receaddr_del: '目标 Schema 无收货地址类', receaddr_get: '目标 Schema 无收货地址类', receaddr_list: '目标 Schema 无收货地址类', receaddr_upd: '目标 Schema 无收货地址类',
  1543. user_bank_add: '目标 Schema 无提现账户类', user_bank_del: '目标 Schema 无提现账户类', user_bank_get: '目标 Schema 无提现账户类', user_bank_list: '目标 Schema 无提现账户类', user_cash_add: '缺少提现事务账本', user_cash_list: '缺少提现事务账本',
  1544. user_coin_recharge: '缺少支付凭据与事务账本', user_exp_transfer: '缺少积分事务规则确认', user_money_recharge: '缺少支付凭据与事务账本', user_money_transfer: '缺少资金事务规则确认',
  1545. user_group_usr_supply: '目标 Schema 无会员续费订单类', user_group_usr_upgrade: '目标 Schema 无会员升级订单类', user_shop_order: '目标 Schema 无订单类', user_shop_sales: '目标 Schema 无销售明细类',
  1546. user_star_add: '目标 Schema 无收藏关系类', user_star_del: '目标 Schema 无收藏关系类', user_star_is: '目标 Schema 无收藏关系类', user_update_paypwd: '需要独立支付密码哈希服务',
  1547. user_update_pwd: '旧流程强制校验短信验证码,但新短信服务与验证码存储尚未提供', user_update_pwdall: '同时依赖登录密码与支付密码写入,目标系统缺少独立支付密码哈希服务',
  1548. vote_add: '目标 Schema 无可证明的投票记录类', vote_ask: '目标 Schema 无可证明的投票记录类', vote_question: '目标 Schema 无可证明的投票记录类',
  1549. product_list: '目标 Product 仅是 ZL_P_Product 附表,缺少 ZL_Commodities 商品主表', product_get: '目标 Product 仅是 ZL_P_Product 附表,缺少商品名称、价格、正文、所有者与主键关系', product_stock_list: '目标 Schema 无 ZL_Shop_Stock 库存流水类',
  1550. product_del: '缺少 ZL_Commodities 主表及其 UserID 所有权字段', product_stock_change: '缺少 ZL_Commodities 主表、当前库存与 ZL_Shop_Stock 流水类', product_sale_change: '缺少 ZL_Commodities 主表及 Sales/UserID 字段',
  1551. unit_record_update: '旧源码在调用前无条件 return;目标库也未迁移 Model 57 单元聚合副表',
  1552. e_get_21list_tj: '迁移数据未包含复习收入金额字段或可验证的计价规则',
  1553. pub_add: '旧前端依赖 Pub 7-13,但目标库只迁入 Pub 2-6,且缺少注销、供应商、商户邀请、退换货与结算副表', pub_list: '旧前端依赖 Pub 7-13,但目标库只迁入 Pub 2-6,无法恢复对应历史记录与审核范围',
  1554. user_rnauth_add: '实名认证需新的合规审核与敏感数据存储', user_rnauth_get: '实名认证需新的合规审核与敏感数据存储', user_rnauth_upd: '实名认证需新的合规审核与敏感数据存储',
  1555. product_add: '缺少 ZL_Commodities 商品主表,无法与 Product 附表进行事务新增', product_upd: '缺少 ZL_Commodities 商品主表,无法恢复主表与附表事务更新'
  1556. };
  1557. const SENSITIVE = /(?:password|pwd|secret|sessiontoken|masterkey|privatekey|legacyPasswordHash|adminPassword|payPassword)/i;
  1558. function inputOf(request) { const body = request.body || {}; return body.params && typeof body.params === 'object' ? body.params : body; }
  1559. function envelope(result, addon, page) { const value = { retcode: 0, retmsg: '', result }; if (addon !== undefined) value.addon = addon; if (page) value.page = page; return value; }
  1560. function reject(message) { return { retcode: -1, retmsg: message, result: null }; }
  1561. function fail(status, message) { const error = new Error(message); error.status = status; throw error; }
  1562. 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; }
  1563. function number(value, fallback = 0) { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : fallback; }
  1564. 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))) }; }
  1565. function companyPointer() { return Parse.Object.createWithoutData('Company', DEFAULT_COMPANY_ID); }
  1566. async function fieldsOf(className) { return (await new Parse.Schema(className).get({ useMasterKey: true })).fields || {}; }
  1567. function tenant(query, fields) { if (fields.company) query.equalTo('company', companyPointer()); }
  1568. 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); }
  1569. function legacyAliases(value, className) {
  1570. const row = safe(value); const maps = {
  1571. 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' },
  1572. 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' },
  1573. App: { ID:'id' }
  1574. }; 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;
  1575. }
  1576. 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; }
  1577. 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; }
  1578. function objectValue(source, key) { return source && typeof source.get === 'function' ? source.get(key) : source && source[key]; }
  1579. function legacyData(source) { const value = objectValue(source, 'legacyUserData'); return value && typeof value === 'object' && !Array.isArray(value) ? value : {}; }
  1580. function firstValue(...values) { return values.find((value) => value !== undefined && value !== null && value !== ''); }
  1581. function legacyUser(current, withToken = false) {
  1582. 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')));
  1583. 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'),'') || '') };
  1584. if (withToken) value.sessionToken = current.getSessionToken(); return value;
  1585. }
  1586. function legacyUserAddon(current) {
  1587. 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;
  1588. }
  1589. async function registerUser(input) {
  1590. 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,'邀请码不存在'); }
  1591. 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; }
  1592. 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; }
  1593. }
  1594. async function updateUserProfile(input,current) {
  1595. 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];
  1596. 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; }
  1597. current.set('legacyUserData',data); await current.save(null,{useMasterKey:true}); return { result:legacyUser(current),addon:legacyUserAddon(current) };
  1598. }
  1599. function legacyUserRow(source) {
  1600. 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,'') || '') };
  1601. 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 };
  1602. }
  1603. 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; }
  1604. 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 } }; }
  1605. const CONTENT_ADDONS = {
  1606. 52: { className:'VocabularyWord', fields:['id','lj','sy','yb','yp'] },
  1607. 53: { className:'PracticeRecord', fields:['id','kcid','scid','xxcs','yhid','jrscb'] },
  1608. 54: { className:'CourseAppointment', fields:['id','pl','bxrq','dslx','dszt','fxpl','jffs','jssj','kcid','kssj','plxm','scsj','sdsd','szmd','szyh','yysj','yykcid'] },
  1609. 56: { className:'DailyStudyRecord', fields:['id','pl','con','djq','ygg','dqrq','dsid','fxrl','xxqs','szmdid','userId','learned'] },
  1610. 58: { className:'CourseBinding', fields:['id','yxx','cksl','kcid','syjd','yhid'] },
  1611. 59: { className:'LessonRecord', fields:['id','pf','jffs','jsmz','kcid','kclx','kcmc','kzsj','pjnr','pldp','xymz','yyds','plpjsj','szmdid'] },
  1612. 60: { className:'MemoryPracticeRecord', fields:['id','fxzt','kcid','plid','wcsj','yhid','kywrq','kywsj','xxjlid','orderId'] },
  1613. 61: { className:'AssessmentProfile', fields:['id','df','askid','wrong','userId','answerid','dontKnow','prevScore','totalScore'] }
  1614. };
  1615. const NODE_MODELS = { 28:58, 29:54, 32:53, 291:56, 296:59, 327:52, 388:60, 389:61 };
  1616. const PRIVATE_CONTENT_MODELS = new Set([53,54,56,58,59,60,61]);
  1617. const CONTENT_WRITE_AUTH = {
  1618. 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 },
  1619. 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 }
  1620. };
  1621. 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); }
  1622. function requestedContentModel(input) { const nodes = String(input.nodeid || input.nid || input.nodes || '').split(',').map(number).filter(Boolean); return contentModel(input, nodes); }
  1623. function legacyFilterPairs(input) {
  1624. const source = [input.myfield, input.myfield2].filter(Boolean).join('|'); if (!source) return [];
  1625. 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] }; });
  1626. }
  1627. function addonField(config, requested) { return config && config.fields.find((field) => field.toLowerCase() === String(requested).toLowerCase()); }
  1628. function contentQueryRequiresAuth(action, input) { return (action === 'content_list' || action === 'content_list_llk') && (PRIVATE_CONTENT_MODELS.has(requestedContentModel(input)) || legacyFilterPairs(input).length > 0); }
  1629. async function authorizeContentAccess(current, input) {
  1630. 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));
  1631. }
  1632. 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'); }
  1633. async function authorizeOwnerPairs(current, pairs) {
  1634. if (isAdminUser(current)) return; const owners = pairs.filter((pair) => ['userid','yhid','xymz','jsmz','szyh'].includes(pair.name)); if (!owners.length) fail(403, '私有内容查询必须限定用户');
  1635. 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;
  1636. 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, '无权查看该学员的内容记录'); }
  1637. }
  1638. 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); }
  1639. function contentOrder(input, config) {
  1640. const raw = String(input.orders || '').trim(); if (!raw) return 'c."updatedAt" DESC'; if (/^NEWID\(\)$/i.test(raw)) return 'RANDOM()';
  1641. 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();
  1642. 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';
  1643. }
  1644. async function contentPage(input, publicOnly = false) {
  1645. const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID]; const clauses = ['c."company" = $1'];
  1646. if (input.objectId) { values.push(String(input.objectId)); clauses.push('c."objectId" = $' + values.length); }
  1647. if (input.generalId) { values.push(String(input.generalId)); clauses.push('CAST(c."generalId" AS text) = $' + values.length); }
  1648. const nodeIds = String(input.nodeid || input.nid || input.nodes || '').split(',').map((value) => String(number(value))).filter((value) => value !== '0');
  1649. if (nodeIds.length) { values.push(nodeIds); clauses.push('CAST(c."nodeId" AS text) = ANY($' + values.length + '::text[])'); }
  1650. 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); }
  1651. if (publicOnly && !modelId) { values.push([...PRIVATE_CONTENT_MODELS].map(String)); clauses.push('CAST(c."modelId" AS text) <> ALL($' + values.length + '::text[])'); }
  1652. const filters = legacyFilterPairs(input); if (filters.length && !config) fail(501, '该内容模型的 addon 联表尚未映射');
  1653. 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); }
  1654. if (input.skey) { values.push('%' + String(input.skey).replace(/[%_]/g, '') + '%'); clauses.push('c."title" ILIKE $' + values.length); }
  1655. 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 ');
  1656. 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]);
  1657. 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);
  1658. 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);
  1659. return { rows: normalized, page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
  1660. }
  1661. async function sqlPage(className, input, filters = []) {
  1662. if (!['App','Node'].includes(className)) fail(400, '不允许查询该类'); const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID]; const clauses = ['"company" = $1'];
  1663. for (const filter of filters) { values.push(String(filter.value)); clauses.push('CAST("' + filter.field + '" AS text) = $' + values.length); }
  1664. 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]);
  1665. 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);
  1666. 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 } };
  1667. }
  1668. async function nodePage(input) {
  1669. 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} };
  1670. }
  1671. async function nodeUnitPage(input,current) {
  1672. 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} };
  1673. }
  1674. 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; }
  1675. 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 []; } }
  1676. 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))) }; }
  1677. function ownLegacyId(current) { return number(current && (current.get('legacyUserId') || current.get('userid') || current.get('num'))); }
  1678. async function legacyUserObject(legacyId) { const fields = await fieldsOf('_User'); return findByLegacyId('_User', fields, legacyId, ['legacyUserId','userid','num']); }
  1679. async function chainContains(startId, expectedAncestorId) {
  1680. let cursor = number(startId); const expected = number(expectedAncestorId); const visited = new Set();
  1681. 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); }
  1682. return false;
  1683. }
  1684. async function authorizeTeamUser(current, requestedId) {
  1685. const ownId = ownLegacyId(current); const targetId = number(requestedId || ownId); if (!targetId) fail(400, '缺少用户 ID'); if (isAdminUser(current) || targetId === ownId) return targetId;
  1686. if (await chainContains(targetId, ownId)) return targetId; if (await chainContains(ownId, targetId)) return targetId; fail(403, '无权查看该团队成员');
  1687. }
  1688. 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"'; }
  1689. async function teamUserPage(input, current) {
  1690. const paging = pageInput(input); const parentId = number(input.puid || ownLegacyId(current)); if (!parentId && !isAdminUser(current)) fail(400, '团队列表必须指定上级用户'); if (parentId) await authorizeTeamUser(current,parentId);
  1691. 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); }
  1692. 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[])'); }
  1693. 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,' : '';
  1694. 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);
  1695. return { rows:rows.map(legacyUserRow), page:{ itemCount:total, pageCount:Math.ceil(total / paging.size), pageIndex:paging.index, pageSize:paging.size } };
  1696. }
  1697. async function teamStats(input,current) {
  1698. 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;
  1699. }
  1700. async function coachStudentPage(input,current) {
  1701. 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 } };
  1702. }
  1703. const POINT_HISTORY_CLASSES = { 1:'UserExpDomP',2:'UserSIcon',3:'UserExpHis',4:'UserUserPoint',5:'UserDummyPoint',6:'UserCredit' };
  1704. 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; }
  1705. async function pointHistoryPage(input,current) {
  1706. 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 } : {} };
  1707. }
  1708. async function createGuestbook(input,current) {
  1709. 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 };
  1710. }
  1711. async function authorizeRequestedUser(current, requestedId) {
  1712. const targetId = number(requestedId || ownLegacyId(current)); if (!targetId) fail(400, '缺少用户 ID'); if (isAdminUser(current) || targetId === ownLegacyId(current)) return targetId;
  1713. 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;
  1714. }
  1715. async function authorizeBusinessRow(current, row, subjectFields, actorFields = []) {
  1716. 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;
  1717. 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, '无权查看该业务记录');
  1718. }
  1719. function normalizeWordRow(source) { const addon = source.__addon || {}; const merged = { ...source, ...addon }; delete merged.__addon; return legacyAliases(merged, 'CommonModel'); }
  1720. async function orderDetailRow(inputId, current, authorize = true) {
  1721. 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]);
  1722. 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 || '课程预约' }; }
  1723. 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;
  1724. }
  1725. async function recordDetailData(input, current) {
  1726. 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]);
  1727. 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 = [];
  1728. 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]);
  1729. 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] }; });
  1730. const order = recordAddon.dsid ? await orderDetailRow(recordAddon.dsid, current, false) : null; return { words, addon: order ? [order] : [], record };
  1731. }
  1732. async function newWordPage(input, current) {
  1733. 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]));
  1734. 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 } };
  1735. }
  1736. async function courseWordPage(input, current) {
  1737. 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 } };
  1738. }
  1739. async function updateLearningWords(input, current) {
  1740. 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);
  1741. 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(','));
  1742. 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;
  1743. 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); }
  1744. 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) };
  1745. }
  1746. 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 + '格式错误'); }
  1747. function cleanText(value, max) { return String(value == null ? '' : value).trim().slice(0, max); }
  1748. 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; }
  1749. async function upsertStudyRecord(input, current) {
  1750. 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) || '学习记录';
  1751. 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;
  1752. if (found) { record = await new Parse.Query('DailyStudyRecord').get(found.recordObjectId, { useMasterKey: true }); common = await new Parse.Query('CommonModel').get(found.commonObjectId, { useMasterKey: true }); }
  1753. 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]))); } };
  1754. 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 }; }
  1755. 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 };
  1756. }
  1757. function reviewSchedule() {
  1758. 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');
  1759. 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(',');
  1760. }
  1761. async function createStudyContent(input, current) {
  1762. 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');
  1763. 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;
  1764. 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)));
  1765. 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));
  1766. 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; }
  1767. return String(generalId);
  1768. }
  1769. 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); }
  1770. function writeValue(value, definition) {
  1771. if (!definition) return value; if (definition.type === 'Number') { const parsed = Number(value); if (!Number.isFinite(parsed)) fail(400, '数值字段格式错误'); return parsed; }
  1772. 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; }
  1773. if (definition.type === 'String') return typeof value === 'string' ? value.slice(0, 50000) : JSON.stringify(value).slice(0, 50000); fail(400, '不支持写入字段类型 ' + definition.type);
  1774. }
  1775. 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; }
  1776. function restoreFields(object, snapshot) { for (const [field,state] of Object.entries(snapshot)) { if (state.exists) object.set(field, state.value); else object.unset(field); } }
  1777. async function updateContentPair(input, current) {
  1778. 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');
  1779. 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');
  1780. 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);
  1781. 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); }
  1782. 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'); }
  1783. 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'));
  1784. }
  1785. async function createContentPair(input, current) {
  1786. 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');
  1787. 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;
  1788. 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])); }
  1789. 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); }
  1790. 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; }
  1791. return String(generalId);
  1792. }
  1793. 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; }
  1794. 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; }
  1795. async function deductOrderPeriod(student, uid, type, orderId, detail) {
  1796. 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 };
  1797. }
  1798. async function rollbackOrderPeriod(studentId, config, periodKey, pointKey) {
  1799. 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]);
  1800. }
  1801. async function memoryReviewsForOrder(orderId, order, current) {
  1802. 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 = [];
  1803. 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; }
  1804. }
  1805. 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; }
  1806. async function updateOrderStatus(input, current) {
  1807. 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 };
  1808. 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); }
  1809. 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) }; }
  1810. 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; }
  1811. }
  1812. async function orderStatistics(input, current) {
  1813. 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;
  1814. 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; }
  1815. 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; }
  1816. return { t30:String(t30), t60:String(t60), t_tiyan:String(tTiyan), t_shichang:String(duration), t_total:String(total), t_yongji:String(commission) };
  1817. }
  1818. 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); }
  1819. async function memoryPage(input, current) {
  1820. 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]);
  1821. 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 } };
  1822. }
  1823. 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 }; }
  1824. async function handler(request, response) {
  1825. try {
  1826. const input = inputOf(request); const action = String(input.action || ''); if (!action) return response.status(400).json(reject('缺少 action'));
  1827. 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 }));
  1828. if (BLOCKED[action]) return response.status(501).json(reject('migration_blocked: ' + BLOCKED[action]));
  1829. if (action === 'user_login_passwd') {
  1830. const username = String(input.name || input.username || '').trim(); const password = String(input.passwd || input.password || ''); if (!username || !password) return response.status(400).json(reject('请输入账号和密码'));
  1831. 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('账号或密码错误')); }
  1832. }
  1833. if (action === 'user_register') { const registered = await registerUser(input); return response.json(envelope(registered.result,registered.addon)); }
  1834. 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('用户不存在')); }
  1835. 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);
  1836. 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))); }
  1837. if (action === 'user_list') { const result = await teamUserPage(input,current); return response.json(envelope(result.rows,undefined,result.page)); }
  1838. if (action === 'user_dept') return response.json(envelope(await teamStats(input,current)));
  1839. if (action === 'e_user_list') { const result = await coachStudentPage(input,current); return response.json(envelope(result.rows,undefined,result.page)); }
  1840. if (action === 'user_update') { const updated = await updateUserProfile(input,current); return response.json(envelope(updated.result,updated.addon)); }
  1841. if (action === 'app_update') { const result = await sqlPage('App', { page: 1, pageSize: 1 }); return response.json(envelope(legacyAppRow(result.rows[0]))); }
  1842. if (action === 'content_list' || action === 'content_list_llk') { const result = await contentPage(input, !current); return response.json(envelope(result.rows, undefined, result.page)); }
  1843. 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])); }
  1844. 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) })); }
  1845. if (action === 'content_add') return response.json(envelope(await createContentPair(input, current)));
  1846. if (action === 'content_update') return response.json(envelope(await updateContentPair(input, current)));
  1847. if (action === 'node_list') { const result = privateNodeProgress ? await nodeUnitPage(input,current) : await nodePage(input); return response.json(envelope(result.rows, undefined, result.page)); }
  1848. 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('栏目不存在')); }
  1849. const legacyId = ownLegacyId(current);
  1850. if (action === 'content_add_zt') return response.json(envelope(await createStudyContent(input, current)));
  1851. if (action === 'e_order_update_v2') return response.json(envelope(await updateOrderStatus(input,current)));
  1852. if (action === 'e_order_tongji') return response.json(envelope(await orderStatistics(input, current)));
  1853. if (action === 'stu_record_update_v2') return response.json(envelope(await upsertStudyRecord(input, current)));
  1854. if (action === 'e_add_words') return response.json(envelope(await updateLearningWords(input, current)));
  1855. if (action === 'e_ck_list') { const result = await courseWordPage(input, current); return response.json(envelope(result.rows, undefined, result.page)); }
  1856. if (action === 'e_get_21list') { const result = await memoryPage(input, current); return response.json(envelope(result.rows, undefined, result.page)); }
  1857. if (action === 'e_words_list') { const result = await newWordPage(input, current); return response.json(envelope(result.rows, undefined, result.page)); }
  1858. if (action === 'e_order_detail') { const found = await orderDetailRow(input.id, current); return found ? response.json(envelope([found])) : response.status(404).json(reject('预约记录不存在')); }
  1859. 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('学习记录不存在')); }
  1860. if (action === 'user_point_list') { const result = await pointHistoryPage(input,current); return response.json(envelope(result.rows,result.addon,result.page)); }
  1861. if (action === 'guestbook_add') return response.json(envelope(await createGuestbook(input,current)));
  1862. return response.status(501).json(reject('migration_blocked: 尚未完成动作映射 ' + action));
  1863. } 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)); }
  1864. }
  1865. `;
  1866. const definitions = [
  1867. { name: 'xiaoshu.admin.gateway', desc: '小树陪练 Angular 管理后台统一数据网关(权限、帐套、CRUD、统计)', path: 'xiaoshu/admin/gateway', code: adminGatewayCode, params: [{ name: 'operation', type: 'String', required: true }] },
  1868. { 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 }] },
  1869. { name: 'cms.users.extended', desc: '替代 ZL_EX_UserView,返回安全用户扩展资料', path: 'xiaoshu/cms/users/extended', code: cmsReadCode('user-extended'), params: [{ name: 'userId', type: 'String', required: true }] },
  1870. { name: 'cms.users.platform', desc: '替代 ZL_User_PlatView', path: 'xiaoshu/cms/users/platform', code: cmsReadCode('user-platform'), params: [{ name: 'userId', type: 'String', required: true }] },
  1871. { name: 'cms.users.wechat', desc: '替代 ZL_User_WXView,过滤令牌与密钥', path: 'xiaoshu/cms/users/wechat', code: cmsReadCode('user-wechat'), params: [{ name: 'userId', type: 'String', required: true }] },
  1872. { 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 }] },
  1873. { 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 }] },
  1874. { name: 'cms.search', desc: '替代 ZL_SearchView,搜索规范化 CommonModel', path: 'xiaoshu/cms/search', code: cmsReadCode('search'), params: [{ name: 'keyword', type: 'String', required: true }] },
  1875. { name: 'xiaoshu.app.gateway', desc: '旧 WXAPP action 到 Parse 规范化类的兼容云函数;无法证明等价的动作返回 migration_blocked', path: 'xiaoshu/app/gateway', code: appGatewayCode, params: [{ name: 'action', type: 'String', required: true }] },
  1876. ];
  1877. function validateDefinition(definition) {
  1878. if (definition.path.startsWith('/')) throw new Error(`${definition.name}: 当前执行器的全局 path 不接受前导 /`);
  1879. const factory = new Function(`${definition.code}\nreturn typeof handler;`);
  1880. if (factory() !== 'function') throw new Error(`${definition.name}: 未定义 handler`);
  1881. }
  1882. async function parseRequest(path, init = {}) {
  1883. const response = await fetch(`${PARSE_URL}${path}`, {
  1884. ...init,
  1885. headers: {
  1886. 'X-Parse-Application-Id': APP_ID,
  1887. 'X-Parse-Master-Key': MASTER_KEY,
  1888. 'Content-Type': 'application/json',
  1889. ...(init.headers || {}),
  1890. },
  1891. });
  1892. const payload = await response.json();
  1893. if (!response.ok || payload.error) throw new Error(payload.error || `Parse 请求失败:${response.status}`);
  1894. return payload;
  1895. }
  1896. async function upsert(definition) {
  1897. const where = encodeURIComponent(JSON.stringify({ name: definition.name }));
  1898. const existing = await parseRequest(`/classes/Function?where=${where}&limit=1&keys=objectId`);
  1899. const body = {
  1900. name: definition.name,
  1901. desc: definition.desc,
  1902. type: 'standalone',
  1903. path: definition.path,
  1904. code: definition.code.trim(),
  1905. params: definition.params,
  1906. paramList: definition.params,
  1907. respType: 'json',
  1908. respJson: { success: true, data: {} },
  1909. enabled: true,
  1910. version: '1.1.2',
  1911. };
  1912. const objectId = existing.results?.[0]?.objectId;
  1913. if (objectId) {
  1914. await parseRequest(`/classes/Function/${objectId}`, { method: 'PUT', body: JSON.stringify(body) });
  1915. return { action: 'updated', objectId };
  1916. }
  1917. const created = await parseRequest('/classes/Function', { method: 'POST', body: JSON.stringify(body) });
  1918. return { action: 'created', objectId: created.objectId };
  1919. }
  1920. for (const definition of definitions) validateDefinition(definition);
  1921. if (validateOnly) {
  1922. console.log(`Validated ${definitions.length} cloud function definitions.`);
  1923. } else {
  1924. if (!MASTER_KEY) throw new Error('缺少 XIAOSHU_MASTER_KEY;不会把 masterKey 写入项目文件。');
  1925. for (const definition of definitions) {
  1926. const result = await upsert(definition);
  1927. console.log(`${result.action.padEnd(7)} ${definition.path} (${result.objectId})`);
  1928. }
  1929. }