func-authing-org-sync.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. const { ManagementClient } = require('authing-node-sdk')
  2. const managementClient = new ManagementClient({
  3. accessKeyId: '669b25e1731d50c59f5494d1',
  4. accessKeySecret: "4cfc095a72a67e22065c97e90054315c",
  5. host: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
  6. })
  7. // const pgp = require('pg-promise')();
  8. // const pgClient = () => {return pgp("postgresql://textbook:Edu2024textbask@oss-cn-beijing-internal.aliyuncs.com:5432/textbook");}
  9. import { pgClient } from '../../db/pg-instance'
  10. export function defineAuthingDepartSync(){
  11. Parse.Cloud.define("authingDepartSync", async (request) => {
  12. let result = await syncOrganizationsFromAuthing()
  13. return result
  14. });
  15. }
  16. /**
  17. * 同步全部组织架构 From Authing
  18. * @desc
  19. * https://docs.authing.cn/v3/reference/sdk/node/management/管理组织机构/list-organizations.html
  20. * @param {*} token
  21. * @returns
  22. */
  23. async function syncOrganizationsFromAuthing(){
  24. // 通过用户的 id_token 初始化之后获取用户信息
  25. let orgList = []
  26. try{
  27. let result = await managementClient.listOrganizations({
  28. page: 1,
  29. limit: 50,
  30. withPost: true,
  31. withCustomData: true
  32. });
  33. if(result?.data?.list?.length){
  34. orgList = orgList.concat(result?.data?.list)
  35. let departList = await getAllChildDepartments(orgList[0])
  36. // console.log(departList)
  37. console.log(departList?.length)
  38. // return
  39. let insertRes = await InsertAllDepartment(departList);
  40. console.log(insertRes)
  41. // 将所有不存在的部门,设置为isDeleted删除状态
  42. try{
  43. let deleteRes = await UpdateAllDeleteDepartment(departList);
  44. }catch(err){}
  45. return {code:200,count:departList?.length,message:`成功导入${departList?.length}条`}
  46. }
  47. }catch(err){
  48. console.error(err)
  49. }
  50. return
  51. // console.log(user)
  52. }
  53. module.exports.syncOrganizationsFromAuthing = syncOrganizationsFromAuthing
  54. async function UpdateAllDeleteDepartment(departList){
  55. let existsIdList = departList.map(depart=>depart?.departmentId)
  56. existsIdList = existsIdList.filter(item=>item)
  57. let sql = `
  58. UPDATE "Department" SET "isDeleted" = true
  59. WHERE "objectId" <> ALL ($1);
  60. `
  61. let result = await pgClient().any(sql,[existsIdList]);
  62. return result
  63. }
  64. async function InsertAllDepartment(departList){
  65. // {
  66. // departmentId: '66868df17adf199d1c77875d',
  67. // organizationCode: '1000000',
  68. // name: '河北人民出版社有限责任公司',
  69. // description: '',
  70. // code: '30000095',
  71. // hasChildren: false,
  72. // isVirtualNode: false,
  73. // i18n: { name: [Object] },
  74. // customData: {},
  75. // status: true
  76. // createdAt: '2024-07-04T11:56:33.813Z',
  77. // updatedAt: '2024-07-04T11:56:33.813Z',
  78. // },
  79. let rowData = []
  80. departList.forEach(depart=>{
  81. let objectId = depart?.departmentId
  82. if(!depart?.hasChildren){ // 最后一级,类型为单位
  83. depart.type = "单位"
  84. }
  85. let parentId = depart?.parent?.departmentId // 指针是正常的
  86. let branchName = depart?.branch?.name // 分值为当前单位最上级分支(表示应用下,分支最高级名称)
  87. rowData.push([
  88. // 1-5
  89. objectId, depart?.organizationCode, depart?.name, depart?.description, branchName,
  90. // 6-10
  91. parentId, depart?.code, depart?.createdAt || new Date(), depart?.updatedAt || new Date(), depart?.status,
  92. // 11
  93. depart?.type,depart?.hasChildren
  94. ])
  95. })
  96. let flattenedParams = rowData.flat();
  97. let syncDepartSQL = `
  98. INSERT INTO "Department" ("objectId", "organizationCode", "name", "description","branch","parent","code","createdAt","updatedAt","status","type","hasChildren")
  99. VALUES
  100. ${rowData.map((_, i) => `($${i * 12 + 1}, $${i * 12 + 2}, $${i * 12 + 3}, $${i * 12 + 4}, $${i * 12 + 5}, $${i * 12 + 6}, $${i * 12 + 7}, $${i * 12 + 8}, $${i * 12 + 9}, $${i * 12 + 10}, $${i * 12 + 11}, $${i * 12 + 12})`).join(',\n')}
  101. ON CONFLICT ("objectId") DO UPDATE
  102. SET
  103. "organizationCode" = EXCLUDED."organizationCode",
  104. "name" = EXCLUDED."name",
  105. "description" = EXCLUDED."description",
  106. "branch" = EXCLUDED."branch",
  107. "parent" = EXCLUDED."parent",
  108. "code" = EXCLUDED."code",
  109. "status" = EXCLUDED."status",
  110. "createdAt" = EXCLUDED."createdAt",
  111. "updatedAt" = EXCLUDED."updatedAt",
  112. "type" = EXCLUDED."type",
  113. "hasChildren" = EXCLUDED."hasChildren";
  114. `
  115. let result = await pgClient().any(syncDepartSQL,flattenedParams);
  116. return result
  117. }
  118. async function getAllChildDepartments(organization,depart,parentMap,level){
  119. // if(level>3) return []
  120. let newParentMap = JSON.parse(JSON.stringify(parentMap||{}))
  121. level = level || 1
  122. let currentDepart = depart || organization
  123. if(level==1) newParentMap["1"] = newParentMap["1"] || depart
  124. if(level==2) newParentMap["2"] = newParentMap["2"] || depart
  125. if(level==3) newParentMap["3"] = newParentMap["3"] || depart
  126. if(level==4) newParentMap["4"] = newParentMap["4"] || depart
  127. if(!currentDepart?.hasChildren) return []
  128. let departmentList = []
  129. let childDepartList
  130. // if(organization){
  131. try{
  132. childDepartList = await getDepartmentOfOrg(currentDepart?.organizationCode,currentDepart?.departmentId,currentDepart,newParentMap)
  133. // childDepartList?.forEach(item=>item.parent = currentDepart)
  134. }catch(err){console.error(err)}
  135. // }
  136. departmentList = departmentList.concat(childDepartList)
  137. // console.log("childDepartList",childDepartList)
  138. let pList = childDepartList?.map(item=>getAllChildDepartments(null,item,newParentMap,level+1))
  139. let resList = await Promise.all(pList);
  140. resList.forEach((list,index)=>{
  141. list = list?.map(item=>{
  142. return item
  143. })
  144. if(list?.length) departmentList = departmentList.concat(list)
  145. })
  146. return departmentList
  147. }
  148. async function getDepartmentOfOrg(organizationCode,departmentId,parent,parentMap){
  149. let newParent = JSON.parse(JSON.stringify(parent))
  150. let newParentMap = JSON.parse(JSON.stringify(parentMap))
  151. let result
  152. try{
  153. result = await managementClient.listChildrenDepartments({
  154. // 替换组织 Code 和部门 ID
  155. organizationCode: organizationCode,
  156. departmentId: departmentId,
  157. departmentIdType: 'department_id',
  158. withCustomData: true
  159. });
  160. }catch(err){}
  161. if(result?.data?.list?.length) {
  162. let list = result?.data?.list;
  163. list.forEach(item=>{
  164. item.branch = newParentMap?.["2"]
  165. item.parent = newParent
  166. })
  167. return result?.data?.list
  168. }
  169. return []
  170. }
  171. // const crypto = require('crypto');
  172. // function generateObjectId(inputString) {
  173. // const hash = crypto.createHash('sha256').update(inputString).digest('hex');
  174. // const objectId = hash;
  175. // return objectId;
  176. // }