sub_project.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const rootId = '-1';
  10. const imType = require('../const/tender').imType;
  11. const defaultFunRela = {
  12. banOver: true,
  13. hintOver: true,
  14. banMinusChangeBills: true,
  15. minusNoValue: true,
  16. lockPayExpr: false,
  17. showMinusCol: true,
  18. imType: imType.zl.value,
  19. needGcl: false,
  20. budgetZb: true,
  21. budgetCtrl: true,
  22. };
  23. const funSet = require('../const/fun_set');
  24. const defaultFunSet = funSet.defaultInfo;
  25. const pageShowConst = require('../const/sp_page_show').defaultSetting;
  26. const shenpiConst = require('../const/sp_shenpi');
  27. const defaultShenpi = shenpiConst.defaultInfo.shenpi;
  28. const arrayInfo = ['shenpi'];
  29. class DragTree {
  30. /**
  31. * 构造函数
  32. */
  33. constructor(setting) {
  34. // 无索引
  35. this.datas = [];
  36. // 以key为索引indexedDB
  37. this.items = {};
  38. // 以排序为索引
  39. this.nodes = [];
  40. // 根节点
  41. this.children = [];
  42. // 树设置
  43. this.setting = setting;
  44. if (!this.setting.itemsPre) this.setting.itemsPre = 'id_';
  45. }
  46. /**
  47. * 树结构根据显示排序
  48. */
  49. sortTreeNode(isResort) {
  50. const self = this;
  51. const addSortNodes = function (nodes) {
  52. if (!nodes) { return }
  53. for (let i = 0; i < nodes.length; i++) {
  54. self.nodes.push(nodes[i]);
  55. nodes[i].index = self.nodes.length - 1;
  56. if (!isResort) {
  57. nodes[i].children = self.getChildren(nodes[i]);
  58. } else {
  59. nodes[i].children.sort((a, b) => { return a[self.setting.order] - b[self.setting.order]; })
  60. }
  61. addSortNodes(nodes[i].children);
  62. }
  63. };
  64. this.nodes = [];
  65. if (!isResort) {
  66. this.children = this.getChildren();
  67. } else {
  68. this.children.sort((a, b) => { return a[self.setting.order] - b[self.setting.order]; });
  69. }
  70. addSortNodes(this.children);
  71. }
  72. /**
  73. * 加载数据(初始化), 并给数据添加部分树结构必须数据
  74. * @param datas
  75. */
  76. loadDatas(datas) {
  77. const self = this;
  78. // 清空旧数据
  79. this.items = {};
  80. this.nodes = [];
  81. this.datas = [];
  82. this.children = [];
  83. // 加载全部数据
  84. datas.sort(function (a, b) {
  85. return a[self.setting.level] - b[self.setting.level];
  86. });
  87. for (const data of datas) {
  88. const keyName = this.setting.itemsPre + data[this.setting.id];
  89. if (this.items[keyName]) continue;
  90. const item = JSON.parse(JSON.stringify(data));
  91. item.children = [];
  92. item.expanded = true;
  93. item.visible = true;
  94. if (item[this.setting.pid] === this.setting.rootId) {
  95. this.children.push(item);
  96. } else {
  97. const parent = this.getParent(item);
  98. if (!parent) continue;
  99. parent.children.push(item);
  100. }
  101. this.items[keyName] = item;
  102. this.datas.push(item);
  103. }
  104. this.children.sort((a, b) => { return a[self.setting.order] - b[self.setting.order]; });
  105. this.sortTreeNode(true);
  106. }
  107. getItemsByIndex(index) {
  108. return this.nodes[index];
  109. }
  110. getItems(id) {
  111. return this.items[this.setting.itemsPre + id];
  112. };
  113. getParent(node) {
  114. return this.getItems(node[this.setting.pid]);
  115. };
  116. getChildren(node) {
  117. const setting = this.setting;
  118. const pid = node ? node[setting.id] : setting.rootId;
  119. const children = this.datas.filter(function (x) {
  120. return x[setting.pid] === pid;
  121. });
  122. children.sort((a, b) => { return a[setting.order] - b[setting.order]; });
  123. return children;
  124. };
  125. isLastSibling(node) {
  126. const siblings = this.getChildren(this.getParent(node));
  127. return (siblings && siblings.length > 0) ? node[this.setting.order] === siblings[siblings.length - 1][this.setting.order] : false;
  128. };
  129. recursiveFun(children, fun) {
  130. if (!fun) return;
  131. if (!children || children.length === 0) return;
  132. for (const c of children) {
  133. this.recursiveFun(c.children, fun);
  134. fun(c);
  135. }
  136. }
  137. }
  138. module.exports = app => {
  139. class SubProject extends app.BaseService {
  140. /**
  141. * 构造函数
  142. *
  143. * @param {Object} ctx - egg全局变量
  144. * @param {String} tableName - 表名
  145. * @return {void}
  146. */
  147. constructor(ctx) {
  148. super(ctx);
  149. this.tableName = 'sub_project';
  150. // const fileType = [{ key: 'file', value: 1, name: '资料归集'}, { key: 'info_progress', value: 2, name: '项目概况-阶段进度'}]
  151. this.FileReferenceType = { file: 1, info_progress: 2};
  152. }
  153. /**
  154. * 数据规则
  155. *
  156. * @param {String} scene - 场景
  157. * @return {Object} - 返回数据规则
  158. */
  159. rule(scene) {
  160. let rule = {};
  161. switch (scene) {
  162. case 'fun':
  163. rule = {
  164. imType: {type: 'enum', values: [imType.tz.value, imType.zl.value, imType.bb.value, imType.bw.value], required: true},
  165. banOver: {type: 'bool', required: true,},
  166. hintOver: {type: 'bool', required: true,},
  167. banMinusChangeBills: {type: 'bool', required: true,},
  168. minusNoValue: {type: 'bool', required: true,},
  169. lockPayExpr: {type: 'bool', required: true,},
  170. showMinusCol: {type: 'bool', required: true,},
  171. };
  172. break;
  173. default:
  174. break;
  175. }
  176. return rule;
  177. }
  178. _filterEmptyFolder(data) {
  179. data.sort((a, b) => { return b.tree_level - a.tree_level});
  180. const result = [];
  181. for (const d of data) {
  182. if (!d.is_folder) result.push(d);
  183. if (result.find(x => { return x.tree_pid === d.id; })) result.push(d);
  184. }
  185. return result;
  186. }
  187. async getSubProject(pid, uid, admin, filterFolder = false) {
  188. let result = await this.getAllDataByCondition({ where: { project_id: pid, is_delete: 0 } });
  189. const permission = await this.ctx.service.subProjPermission.getUserPermission(pid, uid);
  190. result = result.filter(x => {
  191. if (x.is_folder) return !filterFolder;
  192. const pb = permission.find(y => { return x.id === y.spid});
  193. if (admin) {
  194. x.tp_cache = pb && pb.tp_cache ? JSON.parse(pb.tp_cache) : {};
  195. return true;
  196. }
  197. if (!pb) return false;
  198. x.user_permission = pb;
  199. x.tp_cache = pb.tp_cache ? JSON.parse(pb.tp_cache) : {};
  200. // 只要项目下添加了账号,就允许看到项目
  201. return true;
  202. // return x.user_permission.budget_permission.length > 0 || x.user_permission.file_permission.length > 0 || x.user_permission.manage_permission.length > 0;
  203. });
  204. return admin ? result : this._filterEmptyFolder(result);
  205. }
  206. async getSubProjectTreeNodes(pid, uid, admin, filterFolder = false) {
  207. const subProjects = await this.getSubProject(pid, uid, admin, filterFolder);
  208. const subProjectsTree = new DragTree({ id: 'id', pid: 'tree_pid', level: 'tree_level', order: 'tree_order', rootId: '-1' });
  209. subProjectsTree.loadDatas(subProjects);
  210. const result = subProjectsTree.nodes.map(x => {
  211. return {
  212. id: x.id, tree_pid: x.tree_pid, tree_level: x.tree_level, is_folder: x.is_folder, name: x.name,
  213. is_last_sibling: subProjectsTree.isLastSibling(x), has_children: x.children && x.children.length > 0,
  214. };
  215. });
  216. return result;
  217. }
  218. async getBudgetProject(pid, uid, admin) {
  219. let result = await this.getAllDataByCondition({ where: { project_id: pid, is_delete: 0 } });
  220. const adminPermission = this.ctx.service.subProjPermission.adminPermission;
  221. const permission = admin ? [] : await this.ctx.service.subProjPermission.getUserPermission(pid, uid);
  222. result = result.filter(x => {
  223. if (!x.is_folder && !x.budget_id) return false;
  224. if (x.is_folder) return true;
  225. if (admin) {
  226. x.permission = adminPermission.budget_permission;
  227. x.manage_permission = adminPermission.manage_permission;
  228. return true;
  229. } else {
  230. const pb = permission.find(y => { return x.id === y.spid});
  231. if (!pb) return false;
  232. x.permission = pb.budget_permission;
  233. x.manage_permission = pb.manage_permission;
  234. return x.permission.length > 0;
  235. }
  236. });
  237. return this._filterEmptyFolder(result);
  238. }
  239. async getFileProject(pid, uid, admin) {
  240. let result = await this.getAllDataByCondition({ where: { project_id: pid, is_delete: 0 } });
  241. const adminPermission = this.ctx.service.subProjPermission.adminPermission;
  242. const permission = await this.ctx.service.subProjPermission.getUserPermission(pid, uid);
  243. result = result.filter(x => {
  244. if (!x.is_folder && !x.management) return false;
  245. if (x.is_folder) return true;
  246. if (admin) {
  247. x.permission = adminPermission.file_permission;
  248. x.manage_permission = adminPermission.manage_permission;
  249. return true;
  250. } else {
  251. const pb = permission.find(y => { return x.id === y.spid});
  252. if (!pb) return false;
  253. x.permission = pb.file_permission;
  254. x.manage_permission = pb.manage_permission;
  255. return x.permission.length > 0;
  256. }
  257. });
  258. return this._filterEmptyFolder(result);
  259. }
  260. async getLastChild(tree_pid) {
  261. const result = await this.getAllDataByCondition({ where: { tree_pid, project_id: this.ctx.session.sessionProject.id }, orders: [['tree_order', 'desc']], limit: 1, offset: 0 });
  262. return result[0];
  263. }
  264. async getPosterityData(id){
  265. const result = [];
  266. let cur = await this.getAllDataByCondition({ where: { tree_pid: id, project_id: this.ctx.session.sessionProject.id } });
  267. let iLevel = 1;
  268. while (cur.length > 0 && iLevel < 6) {
  269. result.push(...cur);
  270. cur = await this.getAllDataByCondition({ where: { tree_pid: cur.map(x => { return x.id })} });
  271. iLevel += 1;
  272. }
  273. return result;
  274. }
  275. async getStepNode(node, step) {
  276. const tree_order = [];
  277. while(step) {
  278. tree_order.push(node.tree_order + step);
  279. if (step > 0) {
  280. step = step - 1;
  281. } else {
  282. step = step + 1;
  283. }
  284. }
  285. return await this.getAllDataByCondition({ where: { tree_pid: node.tree_pid, tree_order, project_id: this.ctx.session.sessionProject.id }, orders: [['tree_order', 'asc']]});
  286. }
  287. async addFolder(data) {
  288. const parent = await this.getDataById(data.tree_pid);
  289. if (parent && !parent.is_folder) throw '添加数据结构错误';
  290. const lastChild = await this.getLastChild(parent ? parent.id : rootId);
  291. const conn = await this.db.beginTransaction();
  292. try {
  293. // 获取当前用户信息
  294. const sessionUser = this.ctx.session.sessionUser;
  295. // 获取当前项目信息
  296. const sessionProject = this.ctx.session.sessionProject;
  297. const insertData = {
  298. id: this.uuid.v4(), project_id: sessionProject.id, user_id: sessionUser.accountId,
  299. tree_pid: data.tree_pid,
  300. tree_level: parent ? parent.tree_level + 1 : 1,
  301. tree_order: lastChild ? lastChild.tree_order + 1 : 1,
  302. name: data.name, is_folder: 1,
  303. };
  304. const operate = await conn.insert(this.tableName, insertData);
  305. if (operate.affectedRows === 0) throw '新增文件夹失败';
  306. await conn.commit();
  307. return await this.getSubProject(sessionProject.id, sessionUser.accountId, sessionUser.is_admin);
  308. } catch (error) {
  309. await conn.rollback();
  310. throw error;
  311. }
  312. }
  313. async addSubProject(data) {
  314. const parent = await this.getDataById(data.tree_pid);
  315. if (parent && !parent.is_folder) throw '添加数据结构错误';
  316. const lastChild = await this.getLastChild(parent ? parent.id : rootId);
  317. const conn = await this.db.beginTransaction();
  318. try {
  319. // 获取当前用户信息
  320. const sessionUser = this.ctx.session.sessionUser;
  321. // 获取当前项目信息
  322. const sessionProject = this.ctx.session.sessionProject;
  323. const insertData = {
  324. id: this.uuid.v4(), project_id: sessionProject.id, user_id: sessionUser.accountId,
  325. tree_pid: data.tree_pid,
  326. tree_level: parent ? parent.tree_level + 1 : 1,
  327. tree_order: lastChild ? lastChild.tree_order + 1 : 1,
  328. name: data.name, is_folder: 0,
  329. };
  330. const operate = await conn.insert(this.tableName, insertData);
  331. // todo 根据节点新增时的其他操作
  332. if (operate.affectedRows === 0) throw '新增文件夹失败';
  333. await conn.commit();
  334. return await this.getSubProject(sessionProject.id, sessionUser.accountId, sessionUser.is_admin);
  335. } catch (error) {
  336. await conn.rollback();
  337. throw error;
  338. }
  339. }
  340. async dragTo(data) {
  341. const dragNode = await this.getDataById(data.drag_id);
  342. const dropNode = await this.getDataById(data.drop_id);
  343. if (!dragNode || !dropNode || !dropNode.is_folder) throw '拖拽数据结构错误';
  344. const lastChild = await this.getLastChild(dropNode.id);
  345. const posterity = await this.getPosterityData(dragNode.id);
  346. const conn = await this.db.beginTransaction();
  347. try {
  348. const updateData = {
  349. id: dragNode.id, tree_pid: dropNode.id, tree_level: dropNode.tree_level + 1,
  350. tree_order: lastChild ? lastChild.tree_order + 1 : 1,
  351. };
  352. await conn.update(this.tableName, updateData);
  353. if (dragNode.tree_level !== dropNode.tree_level + 1 && posterity.length > 0) {
  354. const posterityUpdateData = posterity.map(x => {
  355. return { id: x.id, tree_level: dropNode.tree_level + 1 - dragNode.tree_level + x.tree_level }
  356. });
  357. await conn.updateRows(this.tableName, posterityUpdateData);
  358. }
  359. // 升级原来的后项的order
  360. await conn.query(`UPDATE ${this.tableName} SET tree_order = tree_order-1 WHERE tree_pid = ? AND tree_order > ?`, [dragNode.tree_pid, dragNode.tree_order]);
  361. await conn.commit();
  362. } catch (error) {
  363. await conn.rollback();
  364. throw error;
  365. }
  366. return await this.getSubProject(this.ctx.session.sessionProject.id, this.ctx.session.sessionUser.accountId, this.ctx.session.sessionUser.is_admin);
  367. }
  368. async _siblingMove(node, step) {
  369. const stepNode = await this.getStepNode(node, step);
  370. const conn = await this.db.beginTransaction();
  371. try {
  372. const updateData = [];
  373. updateData.push({ id: node.id, tree_order: node.tree_order + step });
  374. for (const sn of stepNode) {
  375. updateData.push({ id: node.id, tree_order: step > 0 ? sn.tree_order - 1 : sn.tree_order + 1 });
  376. }
  377. await conn.updateRows(this.tableName, updateData);
  378. await conn.commit();
  379. } catch (error) {
  380. await conn.rollback();
  381. throw error;
  382. }
  383. }
  384. async _siblingMoveForce(node, step) {
  385. const sibling = await this.getAllDataByCondition({ where: { tree_pid: node.tree_pid, project_id: this.ctx.session.sessionProject.id, is_delete: 0 }, orders: [['tree_order', 'asc']] });
  386. const nodeIndex = sibling.findIndex(x => { return x.id === node.id });
  387. if (nodeIndex + step < 0) throw '移动数据结构错误';
  388. if (nodeIndex + step > sibling.length - 1) throw '移动数据结构错误';
  389. const conn = await this.db.beginTransaction();
  390. try {
  391. const updateData = [];
  392. updateData.push({ id: node.id, tree_order: sibling[nodeIndex + step].tree_order });
  393. while(step) {
  394. const stepNode = sibling[nodeIndex + step];
  395. if (step > 0) {
  396. updateData.push({ id: stepNode.id, tree_order: sibling[nodeIndex + step - 1].tree_order });
  397. step = step - 1;
  398. } else {
  399. updateData.push({ id: stepNode.id, tree_order: sibling[nodeIndex + step + 1].tree_order});
  400. step = step + 1;
  401. }
  402. }
  403. await conn.updateRows(this.tableName, updateData);
  404. await conn.commit();
  405. } catch (error) {
  406. await conn.rollback();
  407. throw error;
  408. }
  409. }
  410. async _topMove(node) {
  411. const lastChild = await this.getLastChild(rootId);
  412. const posterity = await this.getPosterityData(node.id);
  413. const conn = await this.db.beginTransaction();
  414. try {
  415. const updateData = { id: node.id, tree_pid: rootId, tree_level: 1, tree_order: lastChild ? lastChild.tree_order + 1 : 1 };
  416. await conn.update(this.tableName, updateData);
  417. if (node.tree_level !== 1 && posterity.length > 0) {
  418. const posterityUpdateData = posterity.map(x => {
  419. return { id: x.id, tree_level: x.tree_level - node.tree_level + 1 }
  420. });
  421. await conn.updateRows(this.tableName, posterityUpdateData);
  422. }
  423. // 升级原来的后项的order
  424. await conn.query(`UPDATE ${this.tableName} SET tree_order = tree_order-1 WHERE tree_pid = ? AND tree_order > ?`, [node.tree_pid, node.tree_order]);
  425. await conn.commit();
  426. } catch (error) {
  427. await conn.rollback();
  428. throw error;
  429. }
  430. }
  431. async move(data) {
  432. const node = await this.getDataById(data.id);
  433. if (!node) throw '移动数据结构错误';
  434. switch(data.type) {
  435. case 'up': await this._siblingMoveForce(node, -1); break;
  436. case 'down': await this._siblingMoveForce(node, 1); break;
  437. case 'top': await this._topMove(node); break;
  438. default: throw '未知移动类型';
  439. }
  440. return await this.getSubProject(this.ctx.session.sessionProject.id, this.ctx.session.sessionUser.accountId, this.ctx.session.sessionUser.is_admin);
  441. }
  442. async del(id) {
  443. const node = await this.getDataById(id);
  444. if (!node) throw '删除的数据不存在';
  445. const posterity = await this.getPosterityData(node.id);
  446. const updateData = [
  447. { id: node.id, is_delete: 1 },
  448. ];
  449. posterity.forEach(x => {
  450. updateData.push({ id: x.id, is_delete: 1});
  451. });
  452. await this.db.updateRows(this.tableName, updateData);
  453. return await this.getSubProject(this.ctx.session.sessionProject.id, this.ctx.session.sessionUser.accountId, this.ctx.session.sessionUser.is_admin);
  454. }
  455. async save(data) {
  456. const result = await this.db.update(this.tableName, data);
  457. if (result.affectedRows > 0) {
  458. return data;
  459. } else {
  460. throw '更新数据失败';
  461. }
  462. }
  463. async setBudgetStd(data) {
  464. const subProject = await this.getDataById(data.id);
  465. const budgetStd = await this.ctx.service.budgetStd.getDataById(data.std_id);
  466. if (!budgetStd) throw '选择的概算标准不存在,请刷新页面重试';
  467. const conn = await this.db.beginTransaction();
  468. try {
  469. const budget_id = await this.ctx.service.budget.add(conn, {
  470. pid: subProject.project_id, user_id: subProject.user_id, rela_tender: subProject.rela_tender
  471. }, budgetStd);
  472. const updateData = { id: data.id, std_id: budgetStd.id, std_name: budgetStd.name, budget_id };
  473. await conn.update(this.tableName, updateData);
  474. await conn.commit();
  475. return updateData;
  476. } catch (error) {
  477. await conn.rollback();
  478. throw error;
  479. }
  480. }
  481. async setRelaTender(data) {
  482. const subProject = await this.getDataById(data.id);
  483. const orgRelaTenderId = subProject.rela_tender.split(',');
  484. const conn = await this.db.beginTransaction();
  485. try {
  486. await conn.update(this.tableName, data);
  487. await conn.update(this.ctx.service.budget.tableName, { id: subProject.budget_id, rela_tender: data.rela_tender });
  488. const relaTenderId = data.rela_tender.split(',');
  489. const removeTenderId = orgRelaTenderId.filter(x => { return relaTenderId.indexOf(x) < 0});
  490. const addTenderId = relaTenderId.filter(x => { return orgRelaTenderId.indexOf(x) < 0});
  491. if (removeTenderId.length > 0) await conn.update(this.ctx.service.tender.tableName, { spid: '' }, { where: { id: removeTenderId }});
  492. if (addTenderId.length > 0) await conn.update(this.ctx.service.tender.tableName, { spid: data.id }, { where: { id: addTenderId }});
  493. await conn.commit();
  494. return data;
  495. } catch (error) {
  496. await conn.rollback();
  497. throw error;
  498. }
  499. }
  500. async addRelaTender(transaction, spid, tid) {
  501. if (!transaction) throw '未定义事务';
  502. const subProject = await this.getDataById(spid);
  503. if (!subProject) throw '所属项目不存在';
  504. const rela = subProject.rela_tender.split(',');
  505. if (rela.indexOf(tid + '') >= 0) return;
  506. rela.push(tid + '');
  507. const rela_tender = rela.join(',');
  508. await transaction.update(this.tableName, { id: spid, rela_tender});
  509. await transaction.update(this.ctx.service.budget.tableName, { id: subProject.budget_id, rela_tender});
  510. }
  511. async removeRelaTender(transaction, spid, tid) {
  512. if (!transaction) throw '未定义事务';
  513. const subProject = await this.getDataById(spid);
  514. if (!subProject) throw '所属项目不存在';
  515. const rela = subProject.rela_tender.split(',');
  516. if (rela.indexOf(tid + '') < 0) return;
  517. const rela_tender = rela.filter(x => { return x === tid + ''}).join(',');
  518. await transaction.update(this.tableName, { id: spid, rela_tender});
  519. await transaction.update(this.ctx.service.budget.tableName, { id: subProject.budget_id, rela_tender});
  520. }
  521. async setManagement(data) {
  522. const subProject = await this.getDataById(data.id);
  523. if (subProject.management === data.management) return data;
  524. const users = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { project_id: subProject.project_id, company: data.management }});
  525. const orgMember = await this.ctx.service.subProjPermission.getAllDataByCondition({ where: { spid: subProject.id } });
  526. const dm = [], um = [], im = [];
  527. const template = await this.ctx.service.filingTemplateList.getDataById(data.filingTemplate);
  528. if (!template) throw '选择的文件类别不存在';
  529. const templateFiling = await this.ctx.service.filingTemplate.getAllDataByCondition({
  530. where: { temp_id: template.id, is_fixed: 1 },
  531. });
  532. const filing_type = this.ctx.service.filing.analysisFilingType(templateFiling).map(x => { return x.value; }).join(','), file_permission = '1,2';
  533. for (const u of users) {
  534. const nm = orgMember.find(x => { return u.id === x.uid; });
  535. if (nm) {
  536. if (!nm.file_permission) um.push({ id: nm.id, file_permission, filing_type });
  537. } else {
  538. im.push({ id: this.uuid.v4(), spid: subProject.id, pid: subProject.project_id, uid: u.id, file_permission, filing_type });
  539. }
  540. }
  541. const conn = await this.db.beginTransaction();
  542. try {
  543. await conn.update(this.tableName, { id: subProject.id, management: data.management, filing_template_id: template.id, filing_template_name: template.name });
  544. await this.ctx.service.filing.initFiling(subProject.id, data.filingTemplate, conn);
  545. if (dm.length > 0) await conn.delete(this.ctx.service.subProjPermission.tableName, { id: dm });
  546. if (um.length > 0) await conn.updateRows(this.ctx.service.subProjPermission.tableName, um);
  547. if (im.length > 0) await conn.insert(this.ctx.service.subProjPermission.tableName, im);
  548. await conn.commit();
  549. return data;
  550. } catch (error) {
  551. await conn.rollback();
  552. throw error;
  553. }
  554. }
  555. async refreshManagementPermission(data) {
  556. const subProject = await this.getDataById(data.id);
  557. const users = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { project_id: subProject.project_id, company: subProject.management }});
  558. const orgMember = await this.ctx.service.subProjPermission.getAllDataByCondition({ where: { spid: subProject.id } });
  559. const dm = [], um = [], im = [];
  560. const filing_type = this.ctx.service.filing.allFilingType.join(','), file_permission = '1,2';
  561. for (const u of users) {
  562. const nm = orgMember.find(x => { return u.id === x.uid; });
  563. if (nm) {
  564. if (!nm.file_permission) um.push({ id: nm.id, file_permission, filing_type });
  565. } else {
  566. im.push({ id: this.uuid.v4(), spid: subProject.id, pid: subProject.project_id, uid: u.id, file_permission, filing_type });
  567. }
  568. }
  569. const conn = await this.db.beginTransaction();
  570. try {
  571. if (dm.length > 0) await conn.delete(this.ctx.service.subProjPermission.tableName, { id: dm });
  572. if (um.length > 0) await conn.updateRows(this.ctx.service.subProjPermission.tableName, um);
  573. if (im.length > 0) await conn.insert(this.ctx.service.subProjPermission.tableName, im);
  574. await conn.commit();
  575. return { dm: dm.length, um: um.length, im: im.length };
  576. } catch (error) {
  577. await conn.rollback();
  578. throw error;
  579. }
  580. }
  581. // 合同管理获取项目列表
  582. async getSubProjectByContract(pid, uid, admin, filterFolder = false) {
  583. let result = await this.getAllDataByCondition({ where: { project_id: pid, is_delete: 0 } });
  584. if (admin) return this._filterEmptyFolder(result);
  585. const permission = await this.ctx.service.contractAudit.getAllDataByCondition({ where: { uid } });
  586. result = result.filter(x => {
  587. if (x.is_folder) return !filterFolder;
  588. const pb = permission.find(y => { return x.id === y.spid; });
  589. if (!pb) return false;
  590. return true;
  591. });
  592. return this._filterEmptyFolder(result);
  593. }
  594. async getSubProjectByTender(pid, tenders, filterFolder = false) {
  595. if (tenders.length === 0) return [];
  596. const spids = this._.uniq(this._.map(tenders, 'spid'));
  597. let result = await this.getAllDataByCondition({ where: { project_id: pid, is_delete: 0 } });
  598. result = result.filter(x => {
  599. if (x.is_folder) return !filterFolder;
  600. if (!x.rela_tender) return false;
  601. return this._.includes(spids, x.id);
  602. });
  603. return this._filterEmptyFolder(result);
  604. }
  605. // 合同管理获取项目列表
  606. // async getSubProjectByFinancial(pid, uid, admin, filterFolder = false) {
  607. // let result = await this.getAllDataByCondition({ where: { project_id: pid, is_delete: 0 } });
  608. // if (admin) return this._filterEmptyFolder(result);
  609. //
  610. // const permission = await this.ctx.service.financialAudit.getAllDataByCondition({ where: { uid } });
  611. // result = result.filter(x => {
  612. // if (x.is_folder) return !filterFolder;
  613. // const pb = permission.find(y => { return x.id === y.spid; });
  614. // if (!pb) return false;
  615. // return true;
  616. // });
  617. // return this._filterEmptyFolder(result);
  618. // }
  619. async getFileReference(subProject, file_type) {
  620. if (file_type) {
  621. return await this.db.query(`SELECT id, name FROM zh_file_reference_list WHERE file_type = ?`, [file_type]);
  622. } else {
  623. return await this.db.query(`SELECT id, name FROM zh_file_reference_list`);
  624. }
  625. };
  626. getPageShow(page_show) {
  627. const info = page_show ? JSON.parse(page_show) : {};
  628. for (const pi in pageShowConst) {
  629. info[pi] = info[pi] === undefined ? pageShowConst[pi] : parseInt(info[pi]);
  630. this.ctx.helper._.defaults(info[pi], pageShowConst[pi]);
  631. }
  632. return info;
  633. }
  634. getShenpi(shenpi) {
  635. const info = shenpi ? JSON.parse(shenpi) : {};
  636. for (const pi in defaultShenpi) {
  637. info[pi] = info[pi] === undefined ? defaultShenpi[pi] : parseInt(info[pi]);
  638. this.ctx.helper._.defaultsDeep(info[pi], defaultShenpi[pi]);
  639. }
  640. return info;
  641. }
  642. async updatePageshow(id, page_show = this.ctx.subProject.page_show, transaction = null) {
  643. const condition = { id, page_show: JSON.stringify(page_show) };
  644. const result = transaction ? await transaction.update(this.tableName, condition) : await this.db.update(this.tableName, condition);
  645. return result.affectedRows === 1;
  646. }
  647. /**
  648. * 功能设置
  649. * @param id
  650. * @returns {Promise<null>}
  651. */
  652. getFunRela(subProject) {
  653. const result = subProject.fun_rela ? JSON.parse(subProject.fun_rela) : {};
  654. this.ctx.helper._.defaults(result, defaultFunRela);
  655. return result;
  656. }
  657. async updateFunRela(id, data) {
  658. const result = await this.db.update(this.tableName, {
  659. id: id, fun_rela: JSON.stringify({
  660. banOver: data.banOver, hintOver: data.hintOver, banMinusChangeBills: data.banMinusChangeBills,
  661. imType: data.imType,
  662. needGcl: data.needGcl, budgetCtrl: data.budgetCtrl, budgetZb: data.budgetZb,
  663. minusNoValue: data.minusNoValue,
  664. lockPayExpr: data.lockPayExpr, showMinusCol: data.showMinusCol, ledgerAss: data.ledgerAss,
  665. }),
  666. });
  667. return result.affectedRows === 1;
  668. }
  669. getFunSet(fun_set = null) {
  670. const result = fun_set ? JSON.parse(fun_set) : {};
  671. this.ctx.helper._.defaults(result, defaultFunSet);
  672. return result;
  673. }
  674. async updateFunSet(id, funSet) {
  675. const result = await this.db.update(this.tableName, {
  676. id, fun_set: JSON.stringify(funSet),
  677. });
  678. return result.affectedRows === 1;
  679. }
  680. async saveCommonJson(id, field, datas) {
  681. const subProject = await this.getDataById(id);
  682. subProject.common_json = subProject.common_json ? JSON.parse(subProject.common_json) : {};
  683. const updateData = {
  684. id,
  685. };
  686. subProject.common_json[field] = datas;
  687. updateData.common_json = JSON.stringify(subProject.common_json);
  688. const result = await this.db.update(this.tableName, updateData);
  689. return result.affectedRows === 1;
  690. }
  691. async saveCommonJsons(id, field, datas) {
  692. const subProject = await this.getDataById(id);
  693. subProject.common_json = subProject.common_json ? JSON.parse(subProject.common_json) : {};
  694. const updateData = {
  695. id,
  696. };
  697. const fields = field instanceof Array ? field : [field];
  698. for (const f of fields) {
  699. if (datas[f] !== undefined) subProject.common_json[f] = datas[f];
  700. }
  701. updateData.common_json = JSON.stringify(subProject.common_json);
  702. const result = await this.db.update(this.tableName, updateData);
  703. return result.affectedRows === 1;
  704. }
  705. async updateCommonJsonDaping06(subProject, projectData) {
  706. const categoryData = await this.ctx.service.category.getAllCategory(subProject);
  707. const projCommonJson = projectData.common_json ? JSON.parse(projectData.common_json) : null;
  708. const projDaping06Set = projCommonJson && projCommonJson.daPing06_set ? projCommonJson.daPing06_set : null;
  709. if (projDaping06Set) {
  710. const subProjDaping06Set = {};
  711. const orgCategoryData = await this.ctx.service.category.getOrgAllCategory(projectData.id);
  712. const orgCb = this._.find(orgCategoryData, { id: projDaping06Set.cb }) || null;
  713. const orgSr = this._.find(orgCategoryData, { id: projDaping06Set.sr }) || null;
  714. if (orgCb) {
  715. const newCb = this._.find(categoryData, { name: orgCb.name });
  716. if (newCb) {
  717. subProjDaping06Set.cb = newCb.id;
  718. const orgCbv = this._.find(orgCb.value, { id: projDaping06Set.cb_value }) || null;
  719. if (orgCbv && orgCbv.value) {
  720. const newCbv = this._.find(newCb.value, { value: orgCbv.value });
  721. if (newCbv) {
  722. subProjDaping06Set.cb_value = newCbv.id;
  723. }
  724. }
  725. }
  726. }
  727. if (orgSr) {
  728. const newSr = this._.find(categoryData, { name: orgSr.name });
  729. if (newSr) {
  730. subProjDaping06Set.sr = newSr.id;
  731. const orgSrv = this._.find(orgSr.value, { id: projDaping06Set.sr_value }) || null;
  732. if (orgSrv && orgSrv.value) {
  733. const newSrv = this._.find(newSr.value, { value: orgSrv.value });
  734. if (newSrv) {
  735. subProjDaping06Set.sr_value = newSrv.id;
  736. }
  737. }
  738. }
  739. }
  740. const newCbShow = [];
  741. const orgGlCategory = orgCategoryData.find(item => item.name === '管理类别');
  742. for (const d of projDaping06Set.cb_show) {
  743. const org = orgGlCategory && orgGlCategory.value ? this._.find(orgGlCategory.value, { id: d }) || null : null;
  744. if (org && org.value) {
  745. const newGlCategory = categoryData.find(item => item.name === '管理类别');
  746. const newOrg = newGlCategory && newGlCategory.value ? this._.find(newGlCategory.value, { value: org.value }) : '';
  747. if (newOrg) {
  748. newCbShow.push(newOrg.id);
  749. }
  750. }
  751. }
  752. subProjDaping06Set.cb_show = newCbShow;
  753. await this.saveCommonJson(subProject.id, 'daPing06_set', subProjDaping06Set);
  754. return JSON.stringify({ daPing06_set: subProjDaping06Set });
  755. }
  756. }
  757. async refreshTpCache(spid, user_id, is_admin) {
  758. const tp_cache = {};
  759. let permission = await this.ctx.service.subProjPermission.getDataByCondition({ spid: spid, uid: user_id });
  760. if (!permission && is_admin) {
  761. await this.db.insert(this.ctx.service.subProjPermission.tableName, {
  762. id: this.uuid.v4(), spid, pid: this.ctx.session.sessionProject.id, uid: user_id
  763. });
  764. permission = await this.ctx.service.subProjPermission.getDataByCondition({ spid: spid, uid: user_id });
  765. }
  766. if (!permission) return tp_cache;
  767. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  768. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  769. ? JSON.parse(accountInfo.permission) : null;
  770. const subProject = await this.getDataById(spid);
  771. subProject.page_show = this.getPageShow(subProject.page_show);
  772. const tenders = await this.ctx.service.tender.getList('', userPermission, this.ctx.session.sessionUser.is_admin, '', subProject);
  773. for (const t of tenders) {
  774. await this.ctx.service.tenderCache.loadTenderCache(t, this.ctx.session.sessionUser.accountId);
  775. tp_cache.contract_price = this.ctx.helper.add(tp_cache.contract_price, t.contract_price);
  776. if (t.ledger_tp) tp_cache.ledger_tp = this.ctx.helper.add(tp_cache.ledger_tp, t.ledger_tp.total_price);
  777. tp_cache.advance_tp = this.ctx.helper.add(tp_cache.advance_tp, t.advance_tp);
  778. tp_cache.change_tp = this.ctx.helper.add(tp_cache.change_tp, t.change_tp);
  779. if (!t.stage_tp) continue;
  780. tp_cache.contract_tp = this.ctx.helper.add(tp_cache.contract_tp, t.stage_tp.contract_tp);
  781. tp_cache.qc_tp = this.ctx.helper.add(tp_cache.qc_tp, t.stage_tp.qc_tp);
  782. tp_cache.positive_qc_tp = this.ctx.helper.add(tp_cache.positive_qc_tp, t.stage_tp.positive_qc_tp);
  783. tp_cache.negative_qc_tp = this.ctx.helper.add(tp_cache.negative_qc_tp, t.stage_tp.negative_qc_tp);
  784. tp_cache.yf_tp = this.ctx.helper.add(tp_cache.yf_tp, t.stage_tp.yf_tp);
  785. tp_cache.sf_tp = this.ctx.helper.add(tp_cache.sf_tp, t.stage_tp.sf_tp);
  786. tp_cache.pre_contract_tp = this.ctx.helper.add(tp_cache.pre_contract_tp, t.stage_tp.pre_contract_tp);
  787. tp_cache.pre_qc_tp = this.ctx.helper.add(tp_cache.pre_qc_tp, t.stage_tp.pre_qc_tp);
  788. tp_cache.pre_positive_qc_tp = this.ctx.helper.add(tp_cache.pre_positive_qc_tp, t.stage_tp.pre_positive_qc_tp);
  789. tp_cache.pre_positive_qc_tp = this.ctx.helper.add(tp_cache.pre_positive_qc_tp, t.stage_tp.pre_positive_qc_tp);
  790. tp_cache.pre_yf_tp = this.ctx.helper.add(tp_cache.pre_yf_tp, t.stage_tp.pre_yf_tp);
  791. tp_cache.pre_sf_tp = this.ctx.helper.add(tp_cache.pre_sf_tp, t.stage_tp.pre_sf_tp);
  792. tp_cache.contract_pc_tp = this.ctx.helper.add(tp_cache.contract_pc_tp, t.stage_tp.contract_pc_tp);
  793. tp_cache.qc_pc_tp = this.ctx.helper.add(tp_cache.qc_pc_tp, t.stage_tp.qc_pc_tp);
  794. tp_cache.pc_tp = this.ctx.helper.add(tp_cache.pc_tp, t.stage_tp.pc_tp);
  795. }
  796. await this.db.update(this.ctx.service.subProjPermission.tableName, { id: permission.id, tp_cache: JSON.stringify(tp_cache)});
  797. return tp_cache;
  798. }
  799. /**
  800. * 保存标段相关信息
  801. *
  802. * @param data
  803. * @return {Promise<void>}
  804. */
  805. async saveInfo(spid, data) {
  806. for (const di in data) {
  807. if (arrayInfo.indexOf(di) >= 0) {
  808. data[di] = JSON.stringify(data[di]);
  809. }
  810. }
  811. await this.db.update(this.tableName, data, { where: { id: spid } });
  812. }
  813. }
  814. return SubProject;
  815. };