migrate-mobile-teaching.mjs 4.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env node
  2. import { readFileSync } from 'node:fs';
  3. import { randomBytes } from 'node:crypto';
  4. import { request as httpsRequest } from 'node:https';
  5. const sql=readFileSync(new URL('./sql/mobile-teaching.sql',import.meta.url),'utf8');
  6. if(!process.argv.includes('--apply')) {
  7. console.log('只读检查:教学写入迁移脚本已就绪。使用 --apply 执行;不修改历史教学或工资数据。');
  8. process.exit(0);
  9. }
  10. const master=process.env.XIAOSHU_MASTER_KEY;
  11. if(!master)throw new Error('缺少 XIAOSHU_MASTER_KEY');
  12. const parseUrl=(process.env.XIAOSHU_PARSE_URL||'https://server.xiaoshu.pro/parse').replace(/\/$/,'');
  13. const appId=process.env.XIAOSHU_PARSE_APP_ID||'7pIbDBJmKx_main';
  14. async function request(path,options={}) {
  15. const res=await fetch(parseUrl+path,{...options,headers:{'Content-Type':'application/json','X-Parse-Application-Id':appId,'X-Parse-Master-Key':master}});
  16. const data=await res.json();if(!res.ok||data.error)throw new Error(data.error||data.message||data.retmsg||`HTTP ${res.status}`);return data;
  17. }
  18. function invokeMigration(url,token) {
  19. return new Promise((resolve,reject)=>{const body=JSON.stringify({token,params:{}}),req=httpsRequest(url,{method:'POST',headers:{'Content-Type':'application/json','Content-Length':Buffer.byteLength(body)}},(res)=>{let raw='';res.setEncoding('utf8');res.on('data',(chunk)=>raw+=chunk);res.on('end',()=>{try{resolve({ok:Number(res.statusCode)>=200&&Number(res.statusCode)<300,data:JSON.parse(raw)})}catch(error){reject(error)}});});req.on('error',reject);req.write(body);req.end();});
  20. }
  21. for(const name of ['SurveyItem','SurveyLog']) {
  22. const schema=await request('/schemas/'+name),fields=Object.fromEntries(Object.entries({operatorId:{type:'String'},learnerLegacyId:{type:'Number'},sourceStudyId:{type:'String'}}).filter(([key])=>!schema.fields[key]));
  23. if(Object.keys(fields).length)await request('/schemas/'+name,{method:'PUT',body:JSON.stringify({fields})});
  24. }
  25. const company=(await request('/classes/Company?limit=1&keys=objectId')).results?.[0];
  26. if(!company)throw new Error('未找到帐套');
  27. const suffix=Date.now()+'_'+randomBytes(5).toString('hex'),path='xiaoshu/system/mobile-teaching-'+suffix;
  28. let userId='',functionId='';
  29. try {
  30. const sessions=await request('/classes/_Session?include=user&limit=200&order=-updatedAt');
  31. const selected=sessions.results.find(s=>s.sessionToken&&s.user?.isAdmin&&!s.user?.isDisabled&&new Date(s.expiresAt.iso)>new Date());
  32. if(!selected)throw new Error('没有可用管理员会话');
  33. const account={objectId:selected.user.objectId,sessionToken:selected.sessionToken};const authorizedId=account.objectId;
  34. const code=`async function handler(request,response){try{const current=request.user;if(!current)return response.status(401).json({success:false});await current.fetch({useMasterKey:true});if(current.id!==${JSON.stringify(authorizedId)})return response.status(403).json({success:false});await Psql.none(${JSON.stringify(sql)});const counts=await Psql.query('SELECT COUNT(*)::int AS commands FROM "MobileTeachingCommand"');return response.json({success:true,counts});}catch(error){return response.status(500).json({success:false,message:String(error.message||error)});}}`;
  35. const fn=await request('/classes/Function',{method:'POST',body:JSON.stringify({name:path,path,code,type:'standalone',desc:'教学写入一次性数据库迁移',enabled:true,params:[],paramList:[],respType:'json'})});functionId=fn.objectId;
  36. const res=await invokeMigration(parseUrl.replace(/\/parse$/,'/api/functions/')+path,account.sessionToken);
  37. if(!res.ok||!res.data.success)throw new Error(res.data.message||'迁移失败');console.log(JSON.stringify(res.data,null,2));
  38. } finally {
  39. // Cleanup failures are reported, including IDs, so no temporary privileged surface is silently left behind.
  40. const failures=[];
  41. if(functionId)try{await request('/classes/Function/'+functionId,{method:'DELETE'});}catch{failures.push('临时函数 '+functionId);}
  42. if(userId)try{await request('/users/'+userId,{method:'DELETE'});}catch{failures.push('临时管理员 '+userId);}
  43. if(failures.length)throw new Error('需要清理:'+failures.join('、'));
  44. }