sub_project.js 41 KB

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