OrganizeController.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. package jnpf.permission.controller;
  2. import cn.dev33.satoken.annotation.SaCheckPermission;
  3. import cn.dev33.satoken.annotation.SaMode;
  4. import io.swagger.v3.oas.annotations.Operation;
  5. import io.swagger.v3.oas.annotations.Parameter;
  6. import io.swagger.v3.oas.annotations.Parameters;
  7. import io.swagger.v3.oas.annotations.tags.Tag;
  8. import jakarta.validation.Valid;
  9. import jnpf.base.ActionResult;
  10. import jnpf.base.controller.SuperController;
  11. import jnpf.base.service.DictionaryDataService;
  12. import jnpf.base.service.SysconfigService;
  13. import jnpf.base.util.ExcelTool;
  14. import jnpf.base.vo.DownloadVO;
  15. import jnpf.base.vo.ListVO;
  16. import jnpf.base.vo.PageListVO;
  17. import jnpf.base.vo.PaginationVO;
  18. import jnpf.config.ConfigValueUtil;
  19. import jnpf.constant.FileTypeConstant;
  20. import jnpf.constant.MsgCode;
  21. import jnpf.constant.PermissionConst;
  22. import jnpf.emnus.OrgTypeEnum;
  23. import jnpf.exception.DataException;
  24. import jnpf.message.service.SynThirdDingTalkService;
  25. import jnpf.message.service.SynThirdQyService;
  26. import jnpf.message.util.SynThirdConsts;
  27. import jnpf.model.*;
  28. import jnpf.permission.constant.OrgColumnMap;
  29. import jnpf.permission.entity.OrganizeEntity;
  30. import jnpf.permission.entity.PositionEntity;
  31. import jnpf.permission.model.organize.*;
  32. import jnpf.permission.model.user.mod.UserIdModel;
  33. import jnpf.permission.service.OrganizeService;
  34. import jnpf.permission.service.PositionService;
  35. import jnpf.permission.service.UserService;
  36. import jnpf.util.*;
  37. import jnpf.util.treeutil.SumTree;
  38. import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
  39. import jnpf.workflow.service.TaskApi;
  40. import lombok.extern.slf4j.Slf4j;
  41. import org.springframework.beans.factory.annotation.Autowired;
  42. import org.springframework.web.bind.annotation.*;
  43. import java.io.IOException;
  44. import java.util.*;
  45. import java.util.stream.Collectors;
  46. /**
  47. * 组织机构
  48. * 组织架构:公司》部门》岗位》用户
  49. *
  50. * @author JNPF开发平台组
  51. * @version V3.1.0
  52. * @copyright 引迈信息技术有限公司
  53. * @date 2019年9月26日 上午9:18
  54. */
  55. @Tag(name = "组织管理", description = "Organize")
  56. @RestController
  57. @RequestMapping("/api/permission/Organize")
  58. @Slf4j
  59. public class OrganizeController extends SuperController<OrganizeService, OrganizeEntity> {
  60. @Autowired
  61. private OrganizeService organizeService;
  62. @Autowired
  63. private SynThirdQyService synThirdQyService;
  64. @Autowired
  65. private SynThirdDingTalkService synThirdDingTalkService;
  66. @Autowired
  67. private SysconfigService sysconfigApi;
  68. @Autowired
  69. private PositionService positionService;
  70. @Autowired
  71. private TaskApi taskApi;
  72. @Operation(summary = "获取组织列表")
  73. @SaCheckPermission(value = {"permission.organize", "permission.user", "permission.role",
  74. "integrationCenter.dingTalk", "integrationCenter.weCom"}, mode = SaMode.OR)
  75. @Parameters({
  76. @Parameter(name = "id", description = "主键", required = true)
  77. })
  78. @GetMapping("/AsyncList/{id}")
  79. public ActionResult<PageListVO<OrganizeListVO>> getList(@PathVariable("id") String id, OrganizePagination pagination) {
  80. pagination.setParentId(id);
  81. pagination.setDataType(1);
  82. if (StringUtil.isNotEmpty(pagination.getKeyword())) {
  83. pagination.setParentId(null);
  84. pagination.setDataType(null);
  85. }
  86. List<OrganizeEntity> list = organizeService.getList(pagination);
  87. Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
  88. List<OrganizeListVO> listVO = JsonUtil.getJsonToList(list, OrganizeListVO.class);
  89. for (OrganizeListVO item : listVO) {
  90. if (PermissionConst.DEPARTMENT.equals(item.getCategory())) {
  91. item.setIcon(PermissionConst.DEPARTMENT_ICON);
  92. } else {
  93. item.setIcon(PermissionConst.COMPANY_ICON);
  94. }
  95. if (StringUtil.isNotEmpty(item.getParentId()) && Objects.nonNull(allOrgsTreeName.get(item.getParentId()))) {
  96. item.setParentName(allOrgsTreeName.get(item.getParentId()).toString());
  97. }
  98. item.setHasChildren(true);
  99. String[] orgs = item.getOrganizeIdTree().split(",");
  100. item.setOrganizeIds(Arrays.asList(orgs));
  101. }
  102. ListVO<OrganizeListVO> vo = new ListVO<>();
  103. vo.setList(listVO);
  104. if (Objects.equals(pagination.getDataType(), 1)) {
  105. ActionResult.page(listVO, null);
  106. }
  107. PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
  108. return ActionResult.page(listVO, jsonToBean);
  109. }
  110. @Operation(summary = "新建组织")
  111. @Parameters({
  112. @Parameter(name = "organizeCrForm", description = "组织模型", required = true)
  113. })
  114. @SaCheckPermission(value = {"permission.organize"})
  115. @PostMapping
  116. public ActionResult create(@RequestBody @Valid OrganizeCrForm organizeCrForm) {
  117. OrganizeEntity entity = JsonUtil.getJsonToBean(organizeCrForm, OrganizeEntity.class);
  118. if (organizeService.isExistByFullName(entity, false, false)) {
  119. return ActionResult.fail(MsgCode.EXIST001.get());
  120. }
  121. if (organizeService.isExistByEnCode(entity.getEnCode(), null)) {
  122. return ActionResult.fail(MsgCode.EXIST002.get());
  123. }
  124. //验证层级
  125. if (!organizeService.checkLevel(entity)) {
  126. return ActionResult.fail(MsgCode.PS036.get(sysconfigApi.getSysInfo().getOrgLevel()));
  127. }
  128. organizeService.create(entity);
  129. ThreadPoolExecutorUtil.getExecutor().execute(() -> {
  130. try {
  131. //创建组织后判断是否需要同步到企业微信
  132. synThirdQyService.unifyDepartmentSysToQy(false, entity, "", SynThirdConsts.CREAT_DEP);
  133. //创建组织后判断是否需要同步到钉钉
  134. synThirdDingTalkService.unifyDepartmentSysToDing(false, entity, "", SynThirdConsts.CREAT_DEP);
  135. } catch (Exception e) {
  136. log.error("创建组织后同步失败到企业微信或钉钉失败,异常:{}", e.getMessage());
  137. }
  138. });
  139. return ActionResult.success(MsgCode.SU001.get());
  140. }
  141. @Operation(summary = "更新组织")
  142. @Parameters({
  143. @Parameter(name = "id", description = "主键值", required = true),
  144. @Parameter(name = "organizeUpForm", description = "组织模型", required = true)
  145. })
  146. @SaCheckPermission(value = {"permission.organize"})
  147. @PutMapping("/{id}")
  148. public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid OrganizeUpForm organizeUpForm) {
  149. List<OrganizeEntity> synList = new ArrayList<>();
  150. OrganizeEntity entity = JsonUtil.getJsonToBean(organizeUpForm, OrganizeEntity.class);
  151. entity.setId(id);
  152. OrganizeEntity info = organizeService.getInfo(id);
  153. if (info == null) {
  154. return ActionResult.fail(MsgCode.FA002.get());
  155. }
  156. OrganizeEntity parentInfo = organizeService.getInfo(organizeUpForm.getParentId());
  157. //不能放到自己下级组织内
  158. if (id.equals(entity.getParentId()) || (parentInfo != null && parentInfo.getOrganizeIdTree() != null && parentInfo.getOrganizeIdTree().contains(id))) {
  159. return ActionResult.fail(MsgCode.SYS146.get(MsgCode.PS003.get()));
  160. }
  161. //todo 验证流程是否逐级审批
  162. if (!Objects.equals(info.getParentId(), organizeUpForm.getParentId())) {
  163. List<String> stepList = taskApi.getStepList();
  164. if (stepList.contains(id)) {
  165. return ActionResult.fail(MsgCode.OA029.get());
  166. }
  167. }
  168. entity.setId(id);
  169. if (organizeService.isExistByFullName(entity, false, true)) {
  170. return ActionResult.fail(MsgCode.EXIST001.get());
  171. }
  172. if (organizeService.isExistByEnCode(entity.getEnCode(), id)) {
  173. return ActionResult.fail(MsgCode.EXIST002.get());
  174. }
  175. //验证层级
  176. if (!organizeService.checkLevel(entity)) {
  177. return ActionResult.fail(MsgCode.PS036.get(sysconfigApi.getSysInfo().getOrgLevel()));
  178. }
  179. //验证下级类型
  180. if (!Objects.equals(info.getCategory(), entity.getCategory())) {
  181. if (!organizeService.checkOrgType(entity)) {
  182. return ActionResult.fail(MsgCode.PS037.get());
  183. }
  184. }
  185. boolean flag = organizeService.update(id, entity);
  186. synList.add(entity);
  187. // 父级id或者组织名称变化则更新下级所有树形信息
  188. if (!Objects.equals(entity.getParentId(), info.getParentId()) || !Objects.equals(entity.getFullName(), info.getFullName())) {
  189. List<String> underOrganizations = organizeService.getUnderOrganizations(id, false);
  190. underOrganizations.forEach(t -> {
  191. OrganizeEntity info1 = organizeService.getInfo(t);
  192. if (StringUtil.isNotEmpty(info1.getOrganizeIdTree())) {
  193. organizeService.setOrgTreeIdAndName(info1);
  194. organizeService.update(info1.getId(), info1);
  195. synList.add(info1);
  196. }
  197. });
  198. }
  199. ThreadPoolExecutorUtil.getExecutor().execute(() -> {
  200. synList.forEach(t -> {
  201. try {
  202. //修改组织后判断是否需要同步到企业微信
  203. synThirdQyService.unifyDepartmentSysToQy(false, t, "",SynThirdConsts.UPDATE_DEP);
  204. //修改组织后判断是否需要同步到钉钉
  205. synThirdDingTalkService.unifyDepartmentSysToDing(false, t, "",SynThirdConsts.UPDATE_DEP);
  206. } catch (Exception e) {
  207. log.error("修改组织后同步失败到企业微信或钉钉失败,异常:{}", e.getMessage());
  208. }
  209. });
  210. });
  211. if (!flag) {
  212. return ActionResult.fail(MsgCode.FA002.get());
  213. }
  214. return ActionResult.success(MsgCode.SU004.get());
  215. }
  216. @Operation(summary = "获取组织信息")
  217. @Parameters({
  218. @Parameter(name = "id", description = "主键值", required = true)
  219. })
  220. @SaCheckPermission(value = {"permission.organize"})
  221. @GetMapping("/{id}")
  222. public ActionResult<OrganizeInfoVO> info(@PathVariable("id") String id) throws DataException {
  223. OrganizeEntity entity = organizeService.getInfo(id);
  224. OrganizeInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, OrganizeInfoVO.class);
  225. if (StringUtil.isNotEmpty(entity.getParentId())) {
  226. OrganizeEntity pInfo = organizeService.getInfo(entity.getParentId());
  227. if (pInfo != null) {
  228. vo.setParentName(pInfo.getFullName());
  229. vo.setParentCategory(pInfo.getCategory());
  230. }
  231. }
  232. if (StringUtil.isNotEmpty(entity.getOrganizeIdTree())) {
  233. String replace = entity.getOrganizeIdTree().replace(entity.getId(), "");
  234. if (StringUtil.isNotEmpty(replace) && !",".equals(replace)) {
  235. vo.setOrganizeIdTree(Arrays.asList(replace.split(",")));
  236. } else {
  237. vo.setOrganizeIdTree(Collections.singletonList("-1"));
  238. }
  239. }
  240. return ActionResult.success(vo);
  241. }
  242. @Operation(summary = "删除组织")
  243. @Parameters({
  244. @Parameter(name = "id", description = "主键值", required = true)
  245. })
  246. @SaCheckPermission(value = {"permission.organize"})
  247. @DeleteMapping("/{id}")
  248. public ActionResult<String> delete(@PathVariable("id") String orgId) {
  249. return organizeService.delete(orgId, true);
  250. }
  251. //+++++++++++++++++++++++++++++++++++其他接口+++++++++++++++++++++++++++++
  252. @Operation(summary = "获取组织列表")
  253. @Parameters({
  254. @Parameter(name = "id", description = "主键", required = true)
  255. })
  256. @GetMapping("/Selector")
  257. public ActionResult<PageListVO<OrganizeSelectorVO>> getList(OrganizePagination pagination) {
  258. pagination.setDataType(1);
  259. if (StringUtil.isNotEmpty(pagination.getKeyword())) {
  260. pagination.setParentId(null);
  261. pagination.setDataType(null);
  262. }
  263. List<OrganizeEntity> list = organizeService.getList(pagination);
  264. Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
  265. List<OrganizeSelectorVO> listVO = JsonUtil.getJsonToList(list, OrganizeSelectorVO.class);
  266. for (OrganizeSelectorVO item : listVO) {
  267. if (PermissionConst.DEPARTMENT.equals(item.getCategory())) {
  268. item.setIcon(PermissionConst.DEPARTMENT_ICON);
  269. } else {
  270. item.setIcon(PermissionConst.COMPANY_ICON);
  271. }
  272. if (StringUtil.isNotEmpty(pagination.getKeyword())) {
  273. item.setFullName(item.getOrgNameTree());
  274. } else {
  275. item.setHasChildren(true);
  276. }
  277. if (StringUtil.isNotEmpty(item.getParentId()) && Objects.nonNull(allOrgsTreeName.get(item.getParentId()))) {
  278. item.setParentName(allOrgsTreeName.get(item.getParentId()).toString());
  279. }
  280. String[] orgs = item.getOrganizeIdTree().split(",");
  281. item.setOrganizeIds(Arrays.asList(orgs));
  282. }
  283. PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
  284. return ActionResult.page(listVO, jsonToBean);
  285. }
  286. @Operation(summary = "自定义范围回显")
  287. @Parameters({
  288. @Parameter(name = "userIdModel", description = "参数模型")
  289. })
  290. @PostMapping("/SelectedList")
  291. public ActionResult<ListVO<OrganizeListVO>> SelectedList(@RequestBody UserIdModel userIdModel) {
  292. List<OrganizeListVO> list = organizeService.selectedList(userIdModel.getIds());
  293. ListVO<OrganizeListVO> listVO = new ListVO<>();
  294. listVO.setList(list);
  295. return ActionResult.success(listVO);
  296. }
  297. @Operation(summary = "自定义范围下拉")
  298. @Parameters({
  299. @Parameter(name = "userIdModel", description = "参数模型")
  300. })
  301. @PostMapping("/OrganizeCondition")
  302. public ActionResult<ListVO<OrganizeListVO>> OrganizeCondition(@RequestBody UserIdModel userIdModel) {
  303. List<OrganizeEntity> list = organizeService.OrganizeCondition(userIdModel.getIds());
  304. List<OrganizeModel> modelList = JsonUtil.getJsonToList(list, OrganizeModel.class);
  305. for (OrganizeModel item : modelList) {
  306. if (PermissionConst.DEPARTMENT.equals(item.getCategory())) {
  307. item.setIcon(PermissionConst.DEPARTMENT_ICON);
  308. } else {
  309. item.setIcon(PermissionConst.COMPANY_ICON);
  310. }
  311. }
  312. List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(modelList);
  313. List<OrganizeListVO> voList = JsonUtil.getJsonToList(trees, OrganizeListVO.class);
  314. for (OrganizeListVO item : voList) {
  315. item.setFullName(item.getOrgNameTree());
  316. }
  317. ListVO<OrganizeListVO> listVO = new ListVO<>();
  318. listVO.setList(voList);
  319. return ActionResult.success(listVO);
  320. }
  321. @Operation(summary = "组织异步带岗位")
  322. @Parameters({
  323. @Parameter(name = "id", description = "主键", required = true),
  324. @Parameter(name = "type", description = "类型:organize、position", required = true)
  325. })
  326. @GetMapping("/AsyncPosList")
  327. public ActionResult<PageListVO<OrganizePositonVO>> AsyncPosList(@RequestParam("id") String id, @RequestParam(name = "type") String type) {
  328. List<OrganizePositonVO> listVO = new ArrayList<>();
  329. //不是组织就是岗位
  330. type = StringUtil.isNotEmpty(type) && PermissionConst.ORGANIZE.equals(type) ? PermissionConst.ORGANIZE : PermissionConst.POSITION;
  331. Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
  332. if (PermissionConst.ORGANIZE.equals(type)) {
  333. OrganizeEntity info = organizeService.getInfo(id);
  334. //添加岗位
  335. if (!Objects.equals(id, "0")) {
  336. String dutyPosition = info.getDutyPosition();
  337. List<PositionEntity> posList = positionService.getListByOrgIdOneLevel(Collections.singletonList(id));
  338. List<OrganizePositonVO> posListVo = JsonUtil.getJsonToList(posList, OrganizePositonVO.class);
  339. posListVo.forEach(item -> {
  340. item.setType(PermissionConst.POSITION);
  341. item.setIcon(PermissionConst.POSITION_ICON);
  342. item.setHasChildren(true);
  343. item.setOrganize(String.valueOf(allOrgsTreeName.get(item.getOrganizeId())));
  344. item.setOrgNameTree(item.getOrganize() + "/" + item.getFullName());
  345. if (StringUtil.isNotEmpty(dutyPosition) && dutyPosition.equals(item.getId())) {
  346. item.setIsDutyPosition(1);
  347. }
  348. });
  349. listVO.addAll(posListVo);
  350. }
  351. //添加组织
  352. OrganizePagination pagination = new OrganizePagination();
  353. pagination.setDataType(1);
  354. pagination.setParentId(id);
  355. List<OrganizeEntity> orgList = organizeService.getList(pagination);
  356. List<OrganizePositonVO> listOrgVO = JsonUtil.getJsonToList(orgList, OrganizePositonVO.class);
  357. for (OrganizePositonVO item : listOrgVO) {
  358. item.setType(PermissionConst.ORGANIZE);
  359. if (PermissionConst.DEPARTMENT.equals(item.getCategory())) {
  360. item.setIcon(PermissionConst.DEPARTMENT_ICON);
  361. } else {
  362. item.setIcon(PermissionConst.COMPANY_ICON);
  363. }
  364. item.setHasChildren(true);
  365. }
  366. listVO.addAll(listOrgVO);
  367. } else {
  368. List<PositionEntity> posList = positionService.getByParentId(id);
  369. listVO.addAll(JsonUtil.getJsonToList(posList, OrganizePositonVO.class));
  370. for (OrganizePositonVO item : listVO) {
  371. item.setType(PermissionConst.POSITION);
  372. item.setIcon(PermissionConst.POSITION_ICON);
  373. item.setHasChildren(true);
  374. item.setOrganize(String.valueOf(allOrgsTreeName.get(item.getOrganizeId())));
  375. item.setOrgNameTree(item.getOrganize() + "/" + item.getFullName());
  376. }
  377. }
  378. return ActionResult.page(listVO, null);
  379. }
  380. // -------------------导入导出--------------------
  381. @Operation(summary = "模板下载")
  382. @SaCheckPermission("permission.organize")
  383. @GetMapping("/TemplateDownload")
  384. public ActionResult<DownloadVO> TemplateDownload() {
  385. OrgColumnMap columnMap = new OrgColumnMap();
  386. String excelName = columnMap.getExcelName();
  387. Map<String, String> keyMap = columnMap.getColumnByType(0);
  388. List<ExcelColumnAttr> models = columnMap.getFieldsModel(false, 0);
  389. List<Map<String, Object>> list = columnMap.getDefaultList();
  390. Map<String, String[]> optionMap = getOptionMap();
  391. ExcelModel excelModel = ExcelModel.builder().models(models).selectKey(new ArrayList<>(keyMap.keySet())).optionMap(optionMap).build();
  392. DownloadVO vo = ExcelTool.getImportTemplate(FileTypeConstant.TEMPORARY, excelName, keyMap, list, excelModel);
  393. return ActionResult.success(vo);
  394. }
  395. @Operation(summary = "上传导入Excel")
  396. @SaCheckPermission("permission.organize")
  397. @PostMapping("/Uploader")
  398. public ActionResult<Object> Uploader() {
  399. return ExcelTool.uploader();
  400. }
  401. @Operation(summary = "导入预览")
  402. @SaCheckPermission("permission.organize")
  403. @GetMapping("/ImportPreview")
  404. public ActionResult<Map<String, Object>> ImportPreview(String fileName) throws Exception {
  405. // 导入字段
  406. OrgColumnMap columnMap = new OrgColumnMap();
  407. Map<String, String> keyMap = columnMap.getColumnByType(0);
  408. Map<String, Object> headAndDataMap = ExcelTool.importPreview(FileTypeConstant.TEMPORARY, fileName, keyMap);
  409. return ActionResult.success(headAndDataMap);
  410. }
  411. @Operation(summary = "导出异常报告")
  412. @SaCheckPermission("permission.organize")
  413. @PostMapping("/ExportExceptionData")
  414. public ActionResult<DownloadVO> ExportExceptionData(@RequestBody ExcelImportForm visualImportModel) {
  415. List<Map<String, Object>> dataList = visualImportModel.getList();
  416. OrgColumnMap columnMap = new OrgColumnMap();
  417. String excelName = columnMap.getExcelName();
  418. Map<String, String> keyMap = columnMap.getColumnByType(0);
  419. List<ExcelColumnAttr> models = columnMap.getFieldsModel(true, 0);
  420. ExcelModel excelModel = ExcelModel.builder().optionMap(getOptionMap()).models(models).build();
  421. DownloadVO vo = ExcelTool.exportExceptionReport(FileTypeConstant.TEMPORARY, excelName, keyMap, dataList, excelModel);
  422. return ActionResult.success(vo);
  423. }
  424. @Operation(summary = "导入数据")
  425. @SaCheckPermission("permission.organize")
  426. @PostMapping("/ImportData")
  427. public ActionResult<ExcelImportVO> ImportData(@RequestBody ExcelImportForm visualImportModel) throws Exception {
  428. List<Map<String, Object>> listData = new ArrayList<>();
  429. List<Map<String, Object>> headerRow = new ArrayList<>();
  430. if (visualImportModel.isType()) {
  431. ActionResult result = ImportPreview(visualImportModel.getFileName());
  432. if (result == null) {
  433. throw new Exception(MsgCode.FA018.get());
  434. }
  435. if (result.getCode() != 200) {
  436. throw new Exception(result.getMsg());
  437. }
  438. if (result.getData() instanceof Map) {
  439. Map<String, Object> data = (Map<String, Object>) result.getData();
  440. listData = (List<Map<String, Object>>) data.get("dataRow");
  441. headerRow = (List<Map<String, Object>>) data.get("headerRow");
  442. }
  443. } else {
  444. listData = visualImportModel.getList();
  445. }
  446. List<OrganizeEntity> addList = new ArrayList<>();
  447. List<Map<String, Object>> failList = new ArrayList<>();
  448. // 对数据做校验
  449. this.validateImportData(listData, addList, failList);
  450. //正常数据插入
  451. for (OrganizeEntity each : addList) {
  452. organizeService.create(each);
  453. }
  454. ExcelImportVO importModel = new ExcelImportVO();
  455. importModel.setSnum(addList.size());
  456. importModel.setFnum(failList.size());
  457. importModel.setResultType(!failList.isEmpty() ? 1 : 0);
  458. importModel.setFailResult(failList);
  459. importModel.setHeaderRow(headerRow);
  460. return ActionResult.success(importModel);
  461. }
  462. @Operation(summary = "导出Excel")
  463. @SaCheckPermission("permission.organize")
  464. @GetMapping("/ExportData")
  465. public ActionResult ExportData(OrganizePagination pagination) throws IOException {
  466. //获取当前用户的所有可见组织
  467. pagination.setDataType(1);
  468. List<OrganizeEntity> list = organizeService.getList(pagination);
  469. List<OrganizeEntity> allOrg = organizeService.getList(false);
  470. Map<String, String> idNameMap = allOrg.stream().collect(Collectors.toMap(OrganizeEntity::getId,
  471. e -> e.getFullName() + "/" + e.getEnCode(), (existing, replacement) -> existing));
  472. List<Map<String, Object>> realList = JsonUtil.getJsonToListMap(JsonUtil.getObjectToString(list));
  473. for (Map<String, Object> item : realList) {
  474. if (item.get("parentId") != null && !"-1".equals(item.get("parentId").toString())) {
  475. item.put("parentId", idNameMap.get(item.get("parentId")));
  476. } else {
  477. item.put("parentId", "");
  478. }
  479. item.put("category", OrgTypeEnum.get(item.get("category").toString()).getName());
  480. }
  481. //获取字段
  482. OrgColumnMap columnMap = new OrgColumnMap();
  483. String excelName = columnMap.getExcelName();
  484. Map<String, String> keyMap = columnMap.getColumnByType(0);
  485. List<ExcelColumnAttr> models = columnMap.getFieldsModel(true, 0);
  486. ExcelModel excelModel = ExcelModel.builder().models(models).selectKey(new ArrayList<>(keyMap.keySet())).build();
  487. DownloadVO vo = ExcelTool.creatModelExcel(FileTypeConstant.TEMPORARY, excelName, keyMap, realList, excelModel);
  488. return ActionResult.success(vo);
  489. }
  490. /**
  491. * 字段验证
  492. *
  493. * @param listData
  494. * @param addList
  495. * @param failList
  496. */
  497. private void validateImportData(List<Map<String, Object>> listData, List<OrganizeEntity> addList, List<Map<String, Object>> failList) {
  498. OrgColumnMap columnMap = new OrgColumnMap();
  499. Map<String, String> keyMap = columnMap.getColumnByType(0);
  500. Integer orgLevel = sysconfigApi.getSysInfo().getOrgLevel();
  501. List<OrganizeEntity> allOrg = organizeService.getList(false);
  502. Map<String, String> nameCodeMap = allOrg.stream().collect(Collectors.toMap(t -> t.getFullName() + "/" + t.getEnCode(), OrganizeEntity::getId));
  503. for (int i = 0, len = listData.size(); i < len; i++) {
  504. Map<String, Object> eachMap = listData.get(i);
  505. Map<String, Object> realMap = JsonUtil.getJsonToBean(eachMap, Map.class);
  506. StringJoiner errInfo = new StringJoiner(",");
  507. //处理父级组织
  508. String parentId;
  509. String organizeIdTree = "";
  510. List<String> childType = new ArrayList<>();
  511. if (eachMap.get("parentId") != null) {
  512. parentId = nameCodeMap.get(eachMap.get("parentId").toString());
  513. if (StringUtil.isEmpty(parentId)) {
  514. errInfo.add("找不到上级组织");
  515. } else {
  516. OrganizeEntity parentOrg = allOrg.stream().filter(t -> t.getId().equals(parentId)).findFirst().orElse(null);
  517. if (parentOrg != null) {
  518. childType = OrgTypeEnum.get(parentOrg.getCategory()).getChildType();
  519. organizeIdTree = parentOrg.getOrganizeIdTree();
  520. } else {
  521. //库里不存在,从表格数据查询
  522. parentOrg = addList.stream().filter(t -> t.getId().equals(parentId)).findFirst().orElse(null);
  523. if (parentOrg != null) {
  524. childType = OrgTypeEnum.get(parentOrg.getCategory()).getChildType();
  525. organizeIdTree = parentOrg.getOrganizeIdTree() + "," + parentOrg.getId();
  526. }
  527. }
  528. //层级限制
  529. if (organizeIdTree.split(",").length > orgLevel) {
  530. errInfo.add(MsgCode.PS036.get(orgLevel));
  531. }
  532. }
  533. } else {
  534. parentId = "-1";
  535. childType = Arrays.asList(OrgTypeEnum.GROUP.getCode(), OrgTypeEnum.COMPANY.getCode(), OrgTypeEnum.AGENCY.getCode(),
  536. OrgTypeEnum.OFFICE.getCode(), OrgTypeEnum.UNIT.getCode());
  537. }
  538. if (errInfo.length() > 0) {
  539. eachMap.put("errorsInfo", errInfo.toString());
  540. failList.add(eachMap);
  541. continue;
  542. }
  543. realMap.put("parentId", parentId);
  544. realMap.put("organizeIdTree", organizeIdTree);
  545. for (String column : keyMap.keySet()) {
  546. Object valueObj = eachMap.get(column);
  547. String value = valueObj == null ? null : String.valueOf(valueObj);
  548. String columnName = keyMap.get(column);
  549. switch (column) {
  550. case "category":
  551. String category = "";
  552. if (eachMap.get("category") != null && StringUtil.isNotEmpty(eachMap.get("category").toString())) {
  553. category = OrgTypeEnum.getByName(eachMap.get("category").toString()).getCode();
  554. } else {
  555. errInfo.add(columnName + "不能为空");
  556. break;
  557. }
  558. //组织下级类型不支持
  559. if (!childType.contains(category)) {
  560. errInfo.add("组织类型异常,上级组织不允许添加该组织类型");
  561. break;
  562. }
  563. realMap.put("category", category);
  564. break;
  565. case "fullName":
  566. if (StringUtil.isEmpty(value)) {
  567. errInfo.add(columnName + "不能为空");
  568. break;
  569. }
  570. if (value.length() > 50) {
  571. errInfo.add(columnName + "值超出最多输入字符限制");
  572. break;
  573. }
  574. //库里判重
  575. long fullNameCount = allOrg.stream().filter(t -> t.getParentId().equals(parentId) && t.getFullName().equals(value)).count();
  576. if (fullNameCount > 0) {
  577. errInfo.add(columnName + "值已存在");
  578. break;
  579. }
  580. //表格内重复
  581. fullNameCount = addList.stream().filter(t -> t.getParentId().equals(parentId) && t.getFullName().equals(value)).count();
  582. if (fullNameCount > 0) {
  583. errInfo.add(columnName + "值已存在");
  584. break;
  585. }
  586. realMap.put("fullName", value);
  587. break;
  588. case "enCode":
  589. if (StringUtil.isEmpty(value)) {
  590. break;
  591. }
  592. if (value.length() > 50) {
  593. errInfo.add(columnName + "值超出最多输入字符限制");
  594. break;
  595. }
  596. if (!RegexUtils.checkEnCode(value)) {
  597. errInfo.add(columnName + "只能输入英文、数字和小数点且小数点不能放在首尾");
  598. break;
  599. }
  600. //库里重复
  601. long enCodeCount = allOrg.stream().filter(t -> t.getEnCode().equals(value)).count();
  602. if (enCodeCount > 0) {
  603. errInfo.add(columnName + "值已存在");
  604. break;
  605. }
  606. //表格内重复
  607. enCodeCount = addList.stream().filter(t -> value.equals(t.getEnCode())).count();
  608. if (enCodeCount > 0) {
  609. errInfo.add(columnName + "值已存在");
  610. break;
  611. }
  612. break;
  613. case "sortCode":
  614. if (StringUtil.isEmpty(value)) {
  615. realMap.put("sortCode", 0);
  616. break;
  617. }
  618. long numValue;
  619. try {
  620. numValue = Long.parseLong(value);
  621. } catch (Exception e) {
  622. errInfo.add(columnName + "值不正确");
  623. break;
  624. }
  625. if (numValue < 0) {
  626. errInfo.add(columnName + "值不能小于0");
  627. break;
  628. }
  629. if (numValue > 1000000) {
  630. errInfo.add(columnName + "值不能大于999999");
  631. break;
  632. }
  633. break;
  634. default:
  635. break;
  636. }
  637. }
  638. if (errInfo.length() == 0) {
  639. OrganizeEntity organizeEntity = JsonUtil.getJsonToBean(realMap, OrganizeEntity.class);
  640. organizeEntity.setCreatorTime(new Date());
  641. String uuid = RandomUtil.uuId();
  642. organizeEntity.setId(uuid);
  643. if (StringUtil.isNotEmpty(organizeEntity.getEnCode())) {
  644. nameCodeMap.put(organizeEntity.getFullName() + "/" + organizeEntity.getEnCode(), organizeEntity.getId());
  645. }
  646. addList.add(organizeEntity);
  647. } else {
  648. eachMap.put("errorsInfo", errInfo.toString());
  649. failList.add(eachMap);
  650. }
  651. }
  652. }
  653. /**
  654. * 获取下拉框
  655. *
  656. * @return
  657. */
  658. private Map<String, String[]> getOptionMap() {
  659. Map<String, String[]> optionMap = new HashMap<>();
  660. //类型
  661. String[] typeMap = Arrays.stream(OrgTypeEnum.values()).map(OrgTypeEnum::getName).toArray(String[]::new);
  662. optionMap.put("category", typeMap);
  663. return optionMap;
  664. }
  665. }