filing.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const rootId = '-1';
  10. const filingType = [
  11. { value: 1, name: '立项文件' },
  12. { value: 2, name: '招标投标、合同协议文件' },
  13. { value: 3, name: '勘察、设计文件' },
  14. { value: 4, name: '征地、拆迁、移民文件' },
  15. { value: 5, name: '项目管理文件' },
  16. { value: 6, name: '施工文件' },
  17. { value: 7, name: '信息系统开发文件' },
  18. { value: 8, name: '设备文件' },
  19. { value: 9, name: '监理文件' },
  20. { value: 10, name: '科研项目文件' },
  21. { value: 11, name: '生产技术准备、试运行文件' },
  22. { value: 12, name: '竣工验收文件' },
  23. ];
  24. const maxFilingType = 12;
  25. module.exports = app => {
  26. class Filing extends app.BaseService {
  27. /**
  28. * 构造函数
  29. *
  30. * @param {Object} ctx - egg全局变量
  31. * @param {String} tableName - 表名
  32. * @return {void}
  33. */
  34. constructor(ctx) {
  35. super(ctx);
  36. this.tableName = 'filing';
  37. }
  38. get allFilingType () {
  39. return filingType.map(x => { return x.value });
  40. }
  41. analysisFilingType(filing) {
  42. const copy = JSON.parse(JSON.stringify(filing));
  43. const curFilingType = copy.filter(f => {
  44. return f.is_fixed;
  45. });
  46. const checkChildren = function (parent) {
  47. parent.children = curFilingType.filter(x => { return x.tree_pid === parent.id; });
  48. if (parent.children.length > 1) parent.children.sort((x, y) => { return x.tree_order - y.tree_order; });
  49. for (const c of parent.children) {
  50. checkChildren(c);
  51. }
  52. };
  53. const topFiling = curFilingType.filter(x => { return x.tree_level === 1; });
  54. topFiling.sort((x, y) => { return x.tree_order - y.tree_order; });
  55. for (const tp of topFiling) {
  56. checkChildren(tp);
  57. }
  58. const result = [];
  59. const getFilingType = function(arr, prefix = '') {
  60. for (const a of arr) {
  61. if (a.children.length) {
  62. getFilingType(a.children, prefix ? prefix + '/' + a.name : a.name);
  63. } else {
  64. result.push({ value: a.filing_type, name: a.name, parentsName: prefix });
  65. }
  66. }
  67. };
  68. getFilingType(topFiling);
  69. return result;
  70. }
  71. async getFilingType(spid) {
  72. const filing = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);
  73. return this.analysisFilingType(filing);
  74. }
  75. async initFiling(spid, templateId, transaction) {
  76. const count = await this.count({ spid });
  77. if (count > 0) return;
  78. const templateFiling = await this.ctx.service.filingTemplate.getAllDataByCondition({
  79. where: { temp_id: templateId },
  80. orders: [['tree_level', 'asc']],
  81. });
  82. const insertData = [];
  83. for (const f of templateFiling) {
  84. f.newId = this.uuid.v4();
  85. const parent = f.tree_pid !== rootId ? templateFiling.find(x => { return x.id === f.tree_pid; }) : null;
  86. const newData = {
  87. id: f.newId, tree_pid: parent ? parent.newId : rootId, tree_level: f.tree_level, tree_order: f.tree_order,
  88. spid, add_user_id: this.ctx.session.sessionUser.accountId,
  89. create_uid: this.ctx.session.sessionUser.accountId, is_fixed: f.is_fixed,
  90. filing_type: f.filing_type, name: f.name, tips: f.tips, upload_tips: f.upload_tips, file_company: f.file_company,
  91. };
  92. insertData.push(newData);
  93. }
  94. if (transaction) {
  95. await transaction.insert(this.tableName, insertData);
  96. } else {
  97. await this.db.insert(this.tableName, insertData);
  98. }
  99. }
  100. _buildInitializedFiling(spid, sourceData, operatorUid) {
  101. const source = (sourceData || []).slice().sort((x, y) => {
  102. const levelDiff = Number(x.tree_level) - Number(y.tree_level);
  103. return levelDiff || Number(x.tree_order) - Number(y.tree_order);
  104. });
  105. const sourceNodeMap = {};
  106. const insertData = [];
  107. for (const node of source) {
  108. const sourceId = String(node.id || '');
  109. if (!sourceId || sourceNodeMap[sourceId]) throw '来源项目目录数据错误';
  110. const sourceParentId = String(node.tree_pid);
  111. const isRoot = sourceParentId === rootId;
  112. const parent = isRoot ? null : sourceNodeMap[sourceParentId];
  113. if (!isRoot && !parent) throw '来源项目目录结构不完整';
  114. const newNode = {
  115. id: this.uuid.v4(),
  116. spid,
  117. tree_pid: parent ? parent.id : rootId,
  118. tree_level: parent ? Number(parent.tree_level) + 1 : 1,
  119. tree_order: Number(node.tree_order),
  120. name: String(node.name || ''),
  121. filing_type: Number(node.filing_type),
  122. add_user_id: Number(operatorUid),
  123. create_uid: Number(operatorUid),
  124. is_fixed: Number(node.is_fixed) === 1 ? 1 : 0,
  125. is_deleted: 0,
  126. file_count: 0,
  127. tips: node.tips || '',
  128. upload_tips: node.upload_tips || '',
  129. file_company: node.file_company || '',
  130. is_rela: Number(node.is_rela) === 1 ? 1 : 0,
  131. };
  132. if (!newNode.name || !Number.isInteger(newNode.filing_type) || newNode.filing_type <= 0 ||
  133. !Number.isInteger(newNode.tree_order) || newNode.tree_order <= 0) {
  134. throw '来源项目目录数据错误';
  135. }
  136. sourceNodeMap[sourceId] = newNode;
  137. insertData.push(newNode);
  138. }
  139. return insertData;
  140. }
  141. /**
  142. * 首次初始化项目资料目录。
  143. *
  144. * 空白模式创建一个可继续编辑的根目录;模板和项目模式只复制目录字段,
  145. * 不复制文件与目录授权用户配置。
  146. *
  147. * @param {String} spid 目标子项目ID
  148. * @param {String} initType 初始化方式(blank/template/project)
  149. * @param {Array} sourceData 来源模板或项目的有效目录
  150. * @param {Number} operatorUid 初始化用户ID
  151. * @param {Object|null} templateData 选用的系统模板
  152. * @return {Object} 初始化结果
  153. */
  154. async initializeDirectory(spid, initType, sourceData, operatorUid, templateData = null) {
  155. let directorySource = sourceData || [];
  156. if (initType === 'blank') {
  157. directorySource = [{
  158. id: 'blank-root', tree_pid: rootId, tree_level: 1, tree_order: 1,
  159. name: '新建文件夹', filing_type: maxFilingType + 1, is_fixed: 1,
  160. tips: '', upload_tips: '', file_company: '', is_rela: 0,
  161. }];
  162. } else if (initType !== 'project' && initType !== 'template') {
  163. throw '初始化方式错误';
  164. }
  165. if (initType === 'template' && (!templateData || !templateData.id)) throw '系统模板数据错误';
  166. if (directorySource.length === 0) throw '来源数据没有可复制的资料目录';
  167. const insertData = this._buildInitializedFiling(spid, directorySource, operatorUid);
  168. const conn = await this.db.beginTransaction();
  169. try {
  170. await conn.query('SELECT id FROM ?? WHERE id = ? FOR UPDATE', [
  171. this.ctx.service.subProject.tableName, spid,
  172. ]);
  173. const activeCount = await conn.count(this.tableName, { spid, is_deleted: 0 });
  174. if (activeCount > 0) throw '当前项目已经存在资料目录,无需重复初始化';
  175. await conn.insert(this.tableName, insertData);
  176. if (initType === 'template') {
  177. await conn.update(this.ctx.service.subProject.tableName, {
  178. id: spid,
  179. filing_template_id: templateData.id,
  180. filing_template_name: templateData.name,
  181. });
  182. }
  183. await conn.commit();
  184. return { count: insertData.length };
  185. } catch (err) {
  186. await conn.rollback();
  187. throw err;
  188. }
  189. }
  190. _filterValidFiling(filing, filingType) {
  191. const validFiling = filing.filter(x => { return filingType.indexOf(x.filing_type) > -1;});
  192. const checkParent = function(child) {
  193. let parent = validFiling.find(x => { return x.id === child.tree_pid; });
  194. if (!parent) {
  195. parent = filing.find(x => { return x.id === child.tree_pid; });
  196. validFiling.push(parent);
  197. }
  198. if (parent.tree_level > 1) checkParent(parent);
  199. };
  200. for (const vf of validFiling) {
  201. if (vf.tree_level > 1 && vf.is_fixed) checkParent(vf);
  202. }
  203. return validFiling;
  204. }
  205. async getValidFiling(spid, filingType) {
  206. if (!filingType || filingType.length === 0) return [];
  207. const result = await this.getAllDataByCondition({ where: { spid, is_deleted: 0 } });
  208. if (filingType === 'all') return result;
  209. return this._filterValidFiling(result, filingType);
  210. }
  211. async getPosterityData(id){
  212. const result = [];
  213. let cur = await this.getAllDataByCondition({ where: { tree_pid: id } });
  214. let iLevel = 1;
  215. while (cur.length > 0 && iLevel < 6) {
  216. result.push(...cur);
  217. cur = await this.getAllDataByCondition({ where: { tree_pid: cur.map(x => { return x.id })} });
  218. iLevel += 1;
  219. }
  220. return result;
  221. }
  222. _checkFixed(data) {
  223. if (data.is_fixed) throw '固定分类,不可编辑';
  224. }
  225. async getNewName(spid, name = '新增文件类别') {
  226. const data = await this.db.query(`SELECT * FROM ${this.tableName} WHERE spid = '${spid}' AND name LIKE '${name}%'`);
  227. if (data.length === 0) return name;
  228. const _ = this._;
  229. const names = data.map(x => { return _.toInteger(x.name.replace(name, '')) });
  230. const filterNames = names.filter(x => { return x > 0 });
  231. const max = filterNames.reduce((pre, cur) => { return Math.max(pre, cur); }, 0);
  232. return max >= 0 ? name + (max + 1) : name;
  233. }
  234. async getNewFilingType(spid) {
  235. const max = await this.db.queryOne(`SELECT filing_type FROM ${this.tableName} WHERE spid = '${spid}' ORDER BY filing_type DESC`);
  236. return max && max.filing_type ? max.filing_type + 1 : maxFilingType + 1;
  237. }
  238. async add(data) {
  239. const parent = await this.getDataById(data.tree_pid);
  240. // 允许管理员添加顶层
  241. // if (!parent) throw '添加数据结构错误';
  242. if (parent && parent.file_count > 0) throw `分类【${parent.name}】下存在文件,不可添加子分类`;
  243. const sibling = await this.getAllDataByCondition({ where: { spid: this.ctx.subProject.id, tree_pid: parent ? parent.id : rootId }, orders: [['tree_order', 'asc']]});
  244. const preChild = data.tree_pre_id ? sibling.find(x => { return x.id === data.tree_pre_id; }) : null;
  245. const filing_type = parent ? parent.filing_type : await this.getNewFilingType(this.ctx.subProject.id);
  246. const conn = await this.db.beginTransaction();
  247. try {
  248. // 获取当前用户信息
  249. const sessionUser = this.ctx.session.sessionUser;
  250. // 获取当前项目信息
  251. const sessionProject = this.ctx.session.sessionProject;
  252. const tree_order = preChild ? preChild.tree_order + 1 : (sibling.length > 0 ? sibling[sibling.length - 1].tree_order + 1 : 1);
  253. const name = await this.getNewName(this.ctx.subProject.id);
  254. const insertData = {
  255. id: this.uuid.v4(), spid: this.ctx.subProject.id, add_user_id: sessionUser.accountId,
  256. create_uid: sessionUser.accountId,
  257. tree_pid: parent ? parent.id : rootId, tree_level: parent ? parent.tree_level + 1 : 1, tree_order,
  258. name, filing_type: filing_type, is_fixed: parent ? 0 : 1
  259. };
  260. const operate = await conn.insert(this.tableName, insertData);
  261. if (operate.affectedRows === 0) throw '新增文件夹失败';
  262. const updateData = [];
  263. if (preChild) {
  264. sibling.forEach(x => {
  265. if (x.tree_order >= tree_order) updateData.push({ id: x.id, tree_order: x.tree_order + 1 });
  266. });
  267. }
  268. if (updateData.length > 0) await conn.updateRows(this.tableName, updateData);
  269. await conn.commit();
  270. return { create: [insertData], update: updateData };
  271. } catch (error) {
  272. await conn.rollback();
  273. throw error;
  274. }
  275. }
  276. async save(data) {
  277. const filing = await this.getDataById(data.id);
  278. // this._checkFixed(filing);
  279. const result = await this.db.update(this.tableName, data);
  280. if (result.affectedRows > 0) {
  281. return data;
  282. } else {
  283. throw '更新数据失败';
  284. }
  285. }
  286. async del(data) {
  287. const filing = await this.getDataById(data.id);
  288. // this._checkFixed(filing);
  289. const posterity = await this.getPosterityData(data.id);
  290. const delData = posterity.map(x => {return { id: x.id, is_deleted: 1 }; });
  291. delData.push({ id: data.id, is_deleted: 1});
  292. const sibling = await this.getAllDataByCondition({ where: { tree_pid: filing.tree_pid, spid: delData.spid, is_deleted: 0 } });
  293. const updateData = [];
  294. sibling.forEach(x => {
  295. if (x.tree_order > filing.tree_order) updateData.push({ id: x.id, tree_order: x.tree_order - 1});
  296. });
  297. const conn = await this.db.beginTransaction();
  298. try {
  299. await conn.updateRows(this.tableName, delData);
  300. if (updateData.length > 0) conn.updateRows(this.tableName, updateData);
  301. await conn.update(this.ctx.service.file.tableName, { is_deleted: 1}, { where: {filing_id: delData.map(x => { return x.id; })} });
  302. await this.ctx.service.subProjectFilingPermission.removeFilingNodes(
  303. filing.spid, delData.map(x => x.id), conn
  304. );
  305. await conn.commit();
  306. return { delete: delData.map(x => { return x.id }), update: updateData };
  307. } catch(err) {
  308. await conn.rollback();
  309. throw err;
  310. }
  311. }
  312. async move(data) {
  313. const filing = await this.getDataById(data.id);
  314. if (!filing || filing.is_deleted) throw '移动的分类不存在,请刷新页面后重试';
  315. if (this.ctx.subProject && filing.spid !== this.ctx.subProject.id) throw '移动的分类不属于当前项目';
  316. if (Number(filing.is_fixed)) throw '固定分类不可移动';
  317. if (data.tree_pid === undefined || data.tree_pid === null || data.tree_pid === '') throw '请选择移动后的目录';
  318. const treePid = String(data.tree_pid);
  319. const treeOrder = Number(data.tree_order);
  320. if (!Number.isInteger(treeOrder) || treeOrder < 0) throw '移动后的目录顺序错误';
  321. const posterity = await this.getPosterityData(filing.id);
  322. const filingWithFiles = [filing, ...posterity].find(x => !x.is_deleted && Number(x.file_count) > 0);
  323. if (filingWithFiles) throw `分类【${filingWithFiles.name}】下存在文件,不可移动目录`;
  324. if (treePid === String(filing.id) || posterity.find(x => String(x.id) === treePid)) {
  325. throw '不能将目录移动到自身或其子目录下';
  326. }
  327. const parent = treePid === rootId ? null : await this.getDataById(treePid);
  328. if (treePid !== rootId && (!parent || parent.is_deleted || parent.spid !== filing.spid)) {
  329. throw '移动后的分类不存在,请刷新页面后重试';
  330. }
  331. if (parent && String(filing.tree_pid) !== treePid && Number(parent.file_count) > 0) {
  332. throw `分类【${parent.name}】下存在文件,不可添加子分类`;
  333. }
  334. const sibling = await this.getAllDataByCondition({ where: { spid: filing.spid, tree_pid: treePid, is_deleted: 0 } });
  335. const updateData = { id: filing.id, tree_order: treeOrder, tree_pid: treePid, tree_level: (parent ? parent.tree_level : 0) + 1 };
  336. if (data.name !== undefined) {
  337. const name = String(data.name).trim();
  338. if (!name) throw '目录名称不能为空';
  339. if (name.length > 100) throw '目录名称不能超过100个字符';
  340. updateData.name = name;
  341. }
  342. if (data.is_fixed !== undefined) {
  343. const isFixed = Number(data.is_fixed);
  344. if (isFixed !== 0 && isFixed !== 1) throw '固定目录状态错误';
  345. updateData.is_fixed = isFixed;
  346. }
  347. const posterityUpdateData = posterity.map(x => {
  348. return { id: x.id, tree_level: (parent ? parent.tree_level : 0) + 1 - filing.tree_level + x.tree_level };
  349. });
  350. const siblingUpdateData = [];
  351. if (treePid === String(filing.tree_pid)) {
  352. if (treeOrder < filing.tree_order) {
  353. sibling.forEach(x => {
  354. if (x.id === filing.id) return;
  355. if (x.tree_order < treeOrder) return;
  356. if (x.tree_order > filing.tree_order) return;
  357. siblingUpdateData.push({ id: x.id, tree_order: x.tree_order + 1 });
  358. });
  359. } else {
  360. sibling.forEach(x => {
  361. if (x.id === filing.id) return;
  362. if (x.tree_order < filing.tree_order) return;
  363. if (x.tree_order > treeOrder) return;
  364. siblingUpdateData.push({ id: x.id, tree_order: x.tree_order - 1 });
  365. });
  366. }
  367. } else {
  368. const orgSibling = await this.getAllDataByCondition({ where: { spid: filing.spid, tree_pid: filing.tree_pid, is_deleted: 0 } });
  369. orgSibling.forEach(x => {
  370. if (x.id === filing.id) return;
  371. if (x.tree_order < filing.tree_order) return;
  372. siblingUpdateData.push({ id: x.id, tree_order: x.tree_order - 1 });
  373. });
  374. sibling.forEach(x => {
  375. if (x.id === filing.id) return;
  376. if (x.tree_order < treeOrder) return;
  377. siblingUpdateData.push({ id: x.id, tree_order: x.tree_order + 1 });
  378. });
  379. }
  380. const conn = await this.db.beginTransaction();
  381. try {
  382. await conn.update(this.tableName, updateData);
  383. if (posterityUpdateData.length > 0) await conn.updateRows(this.tableName, posterityUpdateData);
  384. if (siblingUpdateData.length > 0) await conn.updateRows(this.tableName, siblingUpdateData);
  385. await conn.commit();
  386. } catch (err) {
  387. await conn.rollback();
  388. throw err;
  389. }
  390. return { update: [updateData, ...posterityUpdateData, ...siblingUpdateData] };
  391. }
  392. async editDirectory(data) {
  393. if (!data || !data.id) throw '请选择需要编辑的目录';
  394. const filing = await this.getDataById(data.id);
  395. if (!filing || filing.is_deleted) throw '编辑的分类不存在,请刷新页面后重试';
  396. if (this.ctx.subProject && filing.spid !== this.ctx.subProject.id) throw '编辑的分类不属于当前项目';
  397. const name = String(data.name || '').trim();
  398. if (!name) throw '目录名称不能为空';
  399. if (name.length > 100) throw '目录名称不能超过100个字符';
  400. const isFixed = Number(data.is_fixed);
  401. if (isFixed !== 0 && isFixed !== 1) throw '固定目录状态错误';
  402. if (data.tree_pid === undefined || data.tree_pid === null || data.tree_pid === '') throw '请选择目录';
  403. const treePid = String(data.tree_pid);
  404. if (treePid === String(filing.tree_pid)) {
  405. const updateData = { id: filing.id, name, is_fixed: isFixed };
  406. const result = await this.db.update(this.tableName, updateData);
  407. if (result.affectedRows === 0) throw '更新目录失败';
  408. return { update: [updateData] };
  409. }
  410. const parent = treePid === rootId ? null : await this.getDataById(treePid);
  411. if (treePid !== rootId && (!parent || parent.is_deleted || parent.spid !== filing.spid)) {
  412. throw '移动后的分类不存在,请刷新页面后重试';
  413. }
  414. const targetChildren = await this.getAllDataByCondition({
  415. where: { spid: filing.spid, tree_pid: treePid, is_deleted: 0 },
  416. orders: [['tree_order', 'asc']],
  417. });
  418. const lastChild = targetChildren.length > 0 ? targetChildren[targetChildren.length - 1] : null;
  419. const treeOrder = lastChild ? Number(lastChild.tree_order) + 1 : 1;
  420. return await this.move({
  421. id: filing.id, tree_pid: treePid, tree_order: treeOrder,
  422. name, is_fixed: isFixed,
  423. });
  424. }
  425. async multiUpdate(spid, data) {
  426. if (!data || data.length === 0) throw '提交数据格式错误';
  427. const sourceData = await this.getAllDataByCondition({ where: { spid } });
  428. const validFields = ['id', 'is_fixed', 'name', 'filing_type', 'tree_order', 'tips', 'upload_tips', 'file_company'];
  429. const updateData = [];
  430. for (const d of data) {
  431. if (!d.id) throw '提交数据格式错误';
  432. const sd = sourceData.find(x => { return x.id === d.id; });
  433. if (!sd) throw '提交数据格式错误';
  434. const nd = {};
  435. for (const prop in d) {
  436. if (validFields.indexOf(prop) < 0) continue;
  437. nd[prop] = d[prop];
  438. }
  439. updateData.push(nd);
  440. }
  441. await this.db.updateRows(this.tableName, updateData);
  442. return await this.getAllDataByCondition({ where: { spid } });
  443. }
  444. async sumFileCount(spid) {
  445. const result = await this.db.queryOne(`SELECT SUM(file_count) AS file_count FROM ${this.tableName} WHERE spid = '${spid}' and is_deleted = 0`);
  446. return result.file_count;
  447. }
  448. }
  449. return Filing;
  450. };