sub_project.js 42 KB

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