tender.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. 'use strict';
  2. /**
  3. * 标段数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/11/30
  7. * @version
  8. */
  9. const tenderConst = require('../const/tender');
  10. const auditConst = require('../const/audit');
  11. const projectLogConst = require('../const/project_log');
  12. const fs = require('fs');
  13. const path = require('path');
  14. const commonQueryColumns = [
  15. 'id', 'project_id', 'name', 'status', 'category', 'ledger_times', 'ledger_status', 'measure_type', 'user_id', 'valuation', 'create_time',
  16. 'total_price', 'deal_tp', 'copy_id', 's2b_gxby_check', 's2b_gxby_limit', 's2b_dagl_check', 's2b_dagl_limit', 'has_rela', 'his_id', 'rpt_show_level',
  17. 'build_status', 'settle_order', 'spid',
  18. ];
  19. module.exports = app => {
  20. class Tender extends app.BaseService {
  21. /**
  22. * 构造函数
  23. *
  24. * @param {Object} ctx - egg全局变量
  25. * @return {void}
  26. */
  27. constructor(ctx) {
  28. super(ctx);
  29. this.tableName = 'tender';
  30. // 状态相关
  31. this.status = {
  32. TRY: 1,
  33. NORMAL: 2,
  34. DISABLE: 3,
  35. };
  36. this.displayStatus = [];
  37. this.displayStatus[this.status.TRY] = '试用';
  38. this.displayStatus[this.status.NORMAL] = '正常';
  39. this.displayStatus[this.status.DISABLE] = '禁用';
  40. this.statusClass = [];
  41. this.statusClass[this.status.TRY] = 'warning';
  42. this.statusClass[this.status.NORMAL] = 'success';
  43. this.statusClass[this.status.DISABLE] = 'danger';
  44. }
  45. /**
  46. * 数据规则
  47. *
  48. * @param {String} scene - 场景
  49. * @return {Object} - 返回数据规则
  50. */
  51. rule(scene) {
  52. let rule = {};
  53. switch (scene) {
  54. case 'add':
  55. rule = {
  56. name: { type: 'string', required: true, min: 2 },
  57. type: { type: 'string', required: true, min: 1 },
  58. };
  59. break;
  60. case 'save':
  61. rule = {
  62. name: { type: 'string', required: true, min: 2 },
  63. type: { type: 'string', required: true, min: 1 },
  64. };
  65. default:
  66. break;
  67. }
  68. return rule;
  69. }
  70. /**
  71. * 获取你所参与的标段的列表
  72. *
  73. * @param {String} listStatus - 取列表状态,如果是管理页要传
  74. * @param {String} permission - 根据权限取值
  75. * @param {Number} getAll - 是否取所有标段
  76. * @return {Array} - 返回标段数据
  77. */
  78. async getList(listStatus = '', permission = null, getAll = 0, buildStatusFilter = '') {
  79. if (!this.ctx.subProject) return [];
  80. // 获取当前项目信息
  81. const session = this.ctx.session;
  82. let sql = '';
  83. let sqlParam = [];
  84. if (listStatus === 'manage') {
  85. const userFilter = getAll ? '' : this.db.format(' And t.user_id = ? ', [session.sessionUser.accountId]);
  86. // 管理页面只取属于自己创建的标段
  87. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`ledger_times`, t.`ledger_status`, t.`measure_type`, t.`user_id`, t.`create_time`, t.`total_price`, t.`deal_tp`, t.`spid`,' +
  88. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company` ' +
  89. ' FROM ?? As t ' +
  90. ' Left Join ?? As pa ' +
  91. ' ON t.`user_id` = pa.`id` ' +
  92. ' WHERE t.`spid` = ? ' + buildStatusFilter + userFilter + ' ORDER BY CONVERT(t.`name` USING GBK) ASC';
  93. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.ctx.subProject.id];
  94. } else if (getAll === 1 || (permission !== null && permission.tender !== undefined && permission.tender.indexOf('2') !== -1)) {
  95. // 具有查看所有标段权限的用户查阅标段
  96. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`ledger_times`, t.`ledger_status`, t.`measure_type`, t.`user_id`, t.`create_time`, t.`total_price`, t.`deal_tp`, t.`spid`,' +
  97. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company` ' +
  98. ' FROM ?? As t ' +
  99. ' Left Join ?? As pa ' +
  100. ' ON t.`user_id` = pa.`id` ' +
  101. ' WHERE t.`spid` = ?' + buildStatusFilter + ' ORDER BY CONVERT(t.`name` USING GBK) ASC';
  102. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.ctx.subProject.id];
  103. } else {
  104. // 根据用户权限查阅标段
  105. // tender 163条数据,project_account 68条数据测试
  106. // 查询两张表耗时0.003s,查询tender左连接project_account耗时0.002s
  107. const changeProjectSql = this.ctx.subProject.page_show.openChangeProject ? ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  108. ' t.id IN ( SELECT cpa.`tid` FROM ' + this.ctx.service.changeProjectAudit.tableName + ' AS cpa WHERE cpa.`aid` = ' + session.sessionUser.accountId + ' GROUP BY cpa.`tid`))' : '';
  109. const changeApplySql = this.ctx.subProject.page_show.openChangeApply ? ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  110. ' t.id IN ( SELECT caa.`tid` FROM ' + this.ctx.service.changeApplyAudit.tableName + ' AS caa WHERE caa.`aid` = ' + session.sessionUser.accountId + ' GROUP BY caa.`tid`))' : '';
  111. const changePlanSql = this.ctx.subProject.page_show.openChangePlan ? ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  112. ' t.id IN ( SELECT cpla.`tid` FROM ' + this.ctx.service.changePlanAudit.tableName + ' AS cpla WHERE cpla.`aid` = ' + session.sessionUser.accountId + ' GROUP BY cpla.`tid`))' : '';
  113. const changeProjectXsSql = this.ctx.subProject.page_show.openChangeProject ? ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  114. ' t.id IN ( SELECT cpxa.`tid` FROM ' + this.ctx.service.changeProjectXsAudit.tableName + ' AS cpxa WHERE cpxa.`aid` = ' + session.sessionUser.accountId + ' GROUP BY cpxa.`tid`))' : '';
  115. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`ledger_times`, t.`ledger_status`, t.`measure_type`, t.`user_id`, t.`create_time`, t.`total_price`, t.`deal_tp`,' +
  116. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company` ' +
  117. // ' FROM ?? As t, ?? As pa ' +
  118. // ' WHERE t.`project_id` = ? AND t.`user_id` = pa.`id` AND (' +
  119. ' FROM ?? As t ' +
  120. ' Left Join ?? As pa ' +
  121. ' ON t.`user_id` = pa.`id` ' +
  122. ' WHERE t.`spid` = ? ' + buildStatusFilter + ' AND (' +
  123. // 创建的标段
  124. ' t.`user_id` = ?' +
  125. // 参与审批 台账 的标段
  126. ' OR (t.`ledger_status` != ' + auditConst.ledger.status.uncheck + ' AND ' +
  127. ' t.id IN ( SELECT la.`tender_id` FROM ?? As la WHERE la.`audit_id` = ? GROUP BY la.`tender_id`))' +
  128. // 参与审批 计量期 的标段
  129. ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  130. ' t.id IN ( SELECT sa.`tid` FROM ?? As sa WHERE sa.`aid` = ? GROUP BY sa.`tid`))' +
  131. // 参与协审
  132. ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  133. ' t.id IN ( SELECT sa.`tid` FROM ?? As sa WHERE sa.`ass_user_id` = ? GROUP BY sa.`tid`))' +
  134. // 参与审批 结算期 的标段
  135. ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  136. ' t.id IN ( SELECT sa.`tid` FROM ?? As sa WHERE sa.`audit_id` = ? GROUP BY sa.`tid`))' +
  137. // 参与审批 变更令 的标段
  138. ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  139. ' t.id IN ( SELECT ca.`tid` FROM ?? AS ca WHERE ca.`uid` = ? GROUP BY ca.`tid`))' +
  140. // 参与审批 台账修订 的标段
  141. ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  142. ' t.id IN ( SELECT ra.`tender_id` FROM ?? AS ra WHERE ra.`audit_id` = ? GROUP BY ra.`tender_id`))' +
  143. // 参与审批 材料调差 的标段
  144. ' OR (t.`ledger_status` = ' + auditConst.ledger.status.checked + ' AND ' +
  145. ' t.id IN ( SELECT ma.`tid` FROM ?? AS ma WHERE ma.`aid` = ? GROUP BY ma.`tid`))' +
  146. // 参与审批 预付款 的标段
  147. ' OR (t.id IN ( SELECT ad.`tid` FROM ?? AS ad WHERE ad.`audit_id` = ? GROUP BY ad.`tid`))' +
  148. // 参与审批 变更立项书及变更申请 的标段
  149. changeProjectSql + changeApplySql + changePlanSql + changeProjectXsSql +
  150. // 游客权限的标段
  151. ' OR (t.id IN ( SELECT tt.`tid` FROM ?? AS tt WHERE tt.`user_id` = ?))' +
  152. // 未参与,但可见的标段
  153. ') ORDER BY CONVERT(t.`name` USING GBK) ASC';
  154. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.ctx.subProject.id, session.sessionUser.accountId,
  155. this.ctx.service.ledgerAudit.tableName, session.sessionUser.accountId,
  156. this.ctx.service.stageAudit.tableName, session.sessionUser.accountId,
  157. this.ctx.service.auditAss.tableName, session.sessionUser.accountId,
  158. this.ctx.service.settleAudit.tableName, session.sessionUser.accountId,
  159. this.ctx.service.changeAudit.tableName, session.sessionUser.accountId,
  160. this.ctx.service.reviseAudit.tableName, session.sessionUser.accountId,
  161. this.ctx.service.materialAudit.tableName, session.sessionUser.accountId,
  162. this.ctx.service.advanceAudit.tableName, session.sessionUser.accountId,
  163. this.ctx.service.tenderTourist.tableName, session.sessionUser.accountId,
  164. ];
  165. }
  166. const list = await this.db.query(sql, sqlParam);
  167. for (const l of list) {
  168. l.category = l.category && l.category !== '' ? JSON.parse(l.category) : null;
  169. }
  170. return list;
  171. }
  172. /**
  173. * 获取你所参与的标段的列表 - 完工
  174. *
  175. * @param {String} listStatus - 取列表状态,如果是管理页要传
  176. * @param {String} permission - 根据权限取值
  177. * @param {Number} getAll - 是否取所有标段
  178. * @return {Array} - 返回标段数据
  179. */
  180. async getFinishList(listStatus = '', permission = null, getAll = 0) {
  181. const buildStatusFilter = this.db.format(' AND build_status = ?', [tenderConst.buildStatus.status.finish]);
  182. return await this.getList(listStatus, permission, getAll, buildStatusFilter);
  183. }
  184. /**
  185. * 获取你所参与的标段的列表 - 在建
  186. *
  187. * @param {String} listStatus - 取列表状态,如果是管理页要传
  188. * @param {String} permission - 根据权限取值
  189. * @param {Number} getAll - 是否取所有标段
  190. * @return {Array} - 返回标段数据
  191. */
  192. async getBuildList(listStatus = '', permission = null, getAll = 0) {
  193. const buildStatusFilter = this.db.format(' AND build_status = ?', [tenderConst.buildStatus.status.build]);
  194. return await this.getList(listStatus, permission, getAll, buildStatusFilter);
  195. }
  196. async getList4Select(selectType) {
  197. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  198. const userPermission = accountInfo !== undefined && accountInfo.permission !== '' ? JSON.parse(accountInfo.permission) : null;
  199. const tenderList = await this.ctx.service.tender.getList('', userPermission, this.ctx.session.sessionUser.is_admin);
  200. for (const t of tenderList) {
  201. if (t.ledger_status === auditConst.ledger.status.checked) {
  202. t.lastStage = await this.ctx.service.stage.getLastestStage(t.id, false);
  203. t.completeStage = await this.ctx.service.stage.getLastestCompleteStage(t.id);
  204. }
  205. }
  206. switch (selectType) {
  207. case 'ledger': return tenderList.filter(x => {
  208. return x.ledger_status === auditConst.ledger.status.checked;
  209. });
  210. case 'revise': tenderList.filter(x => {
  211. return x.ledger_status === auditConst.ledger.status.checked;
  212. });
  213. case 'stage': return tenderList.filter(x => {
  214. return x.ledger_status === auditConst.ledger.status.checked && !!x.lastStage;
  215. });
  216. case 'stage-checked': return tenderList.filter(x => {
  217. return !!x.completeStage;
  218. });
  219. default: return tenderList;
  220. }
  221. }
  222. async getTender(id, columns = commonQueryColumns) {
  223. this.initSqlBuilder();
  224. this.sqlBuilder.setAndWhere('id', {
  225. value: id,
  226. operate: '=',
  227. });
  228. this.sqlBuilder.columns = columns;
  229. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  230. const tender = await this.db.queryOne(sql, sqlParam);
  231. if (tender && this._.includes(columns, 'category')) {
  232. tender.category = tender.category && tender.category !== '' ? JSON.parse(tender.category) : null;
  233. }
  234. return tender;
  235. }
  236. async getManageTenderList(projectId) {
  237. return await this.ctx.service.tender.getAllDataByCondition({ where: { project_id: projectId }});
  238. }
  239. /**
  240. * 新增标段
  241. *
  242. * @param {Object} data - 提交的数据
  243. * @return {Boolean} - 返回新增结果
  244. */
  245. async add(data) {
  246. let result = false;
  247. this.transaction = await this.db.beginTransaction();
  248. try {
  249. // 获取当前用户信息
  250. const sessionUser = this.ctx.session.sessionUser;
  251. // 获取当前项目信息
  252. const sessionProject = this.ctx.session.sessionProject;
  253. const insertData = {
  254. name: data.name,
  255. status: tenderConst.status.APPROVAL,
  256. project_id: sessionProject.id,
  257. user_id: sessionUser.accountId,
  258. create_time: new Date(),
  259. category: JSON.stringify(data.category),
  260. valuation: data.valuation,
  261. spid: data.spid,
  262. };
  263. const operate = await this.transaction.insert(this.tableName, insertData);
  264. result = operate.insertId > 0;
  265. if (!result) {
  266. throw '新增标段数据失败';
  267. }
  268. await this.ctx.service.tenderCache.insertTenderCache(this.transaction, operate.insertId, sessionUser.accountId);
  269. if (data.spid) await this.ctx.service.subProject.addRelaTender(this.transaction, data.spid, operate.insertId);
  270. // 获取合同支付模板 并添加到标段
  271. result = await this.ctx.service.pay.addDefaultPayData(operate.insertId, this.transaction);
  272. if (!result) {
  273. throw '新增合同支付数据失败';
  274. }
  275. await this.ctx.service.tenderTag.addTenderTag(operate.insertId, sessionProject.id, this.transaction);
  276. await this.transaction.commit();
  277. const sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`ledger_times`, t.`ledger_status`, t.`measure_type`, t.`user_id`, t.`create_time`, t.`total_price`, t.`deal_tp`, t.`spid`,' +
  278. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company` ' +
  279. ' FROM ?? As t ' +
  280. ' Left Join ?? As pa ' +
  281. ' ON t.`user_id` = pa.`id` ' +
  282. ' WHERE t.`id` = ?';
  283. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, operate.insertId];
  284. const tender = await this.db.queryOne(sql, sqlParam);
  285. if (tender) {
  286. tender.category = tender.category && tender.category !== '' ? JSON.parse(tender.category) : null;
  287. }
  288. // 是否加入到决策大屏中
  289. if (sessionProject.page_show.addDataCollect === 0) {
  290. await this.ctx.service.datacollectTender.add(sessionProject.id, operate.insertId);
  291. }
  292. return tender;
  293. } catch (error) {
  294. await this.transaction.rollback();
  295. throw error;
  296. }
  297. }
  298. /**
  299. * 保存标段
  300. *
  301. * @param {Object} postData - 表单post过来的数据
  302. * @param {Number} id - 用于判断修改还是新增的id
  303. * @return {Boolean} - 返回执行结果
  304. */
  305. async save(postData, id = 0) {
  306. id = parseInt(id);
  307. const tender = await this.getDataById(id);
  308. const rowData = {
  309. id,
  310. name: postData.name,
  311. type: postData.type,
  312. category: JSON.stringify(postData.category),
  313. };
  314. const conn = await this.db.beginTransaction();
  315. try {
  316. if (tender.spid !== postData.spid) {
  317. if (postData.spid) await this.ctx.service.subProject.addRelaTender(conn, postData.spid, id);
  318. if (tender.spid) await this.ctx.service.subProject.removeRelaTender(conn, tender.spid, id);
  319. const subProject = await this.ctx.service.subProject.getDataById(postData.spid);
  320. await this._addSubProjPermission(conn, subProject, [id]);
  321. }
  322. rowData.spid = postData.spid || '';
  323. const result = await conn.update(this.tableName, rowData);
  324. await conn.commit();
  325. return result.affectedRows > 0;
  326. } catch(err) {
  327. await conn.rollback();
  328. throw err;
  329. }
  330. }
  331. /**
  332. * 假删除
  333. *
  334. * @param {Number} id - 删除的id
  335. * @return {Boolean} - 删除结果
  336. */
  337. async deleteTenderById(id) {
  338. const updateData = {
  339. status: this.status.DISABLE,
  340. id,
  341. };
  342. const result = await this.db.update(this.tableName, updateData);
  343. return result.affectedRows > 0;
  344. }
  345. /**
  346. * 真删除
  347. * @param {Number} id - 删除的标段id
  348. * @return {Promise<boolean>} - 结果
  349. */
  350. async deleteTenderNoBackup(id) {
  351. const transaction = await this.db.beginTransaction();
  352. try {
  353. const tenderMsg = await this.getDataById(id);
  354. // 先删除附件文件
  355. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { tid: id } });
  356. const newAttList = await this.ctx.service.materialFile.getAllMaterialFiles(id);
  357. const changeProjectAttList = await this.ctx.service.changeProjectAtt.getAllDataByCondition({ where: { tid: id } });
  358. const changeApplyAttList = await this.ctx.service.changeApplyAtt.getAllDataByCondition({ where: { tid: id } });
  359. const changePlanAttList = await this.ctx.service.changePlanAtt.getAllDataByCondition({ where: { tid: id } });
  360. const advanceAttList = await this.ctx.service.advanceFile.getAllDataByCondition({ where: { tid: id } });
  361. attList.concat(newAttList, changeProjectAttList, changeApplyAttList, changePlanAttList, advanceAttList);
  362. await this.ctx.helper.delFiles(attList);
  363. await transaction.delete(this.tableName, { id });
  364. await transaction.delete(this.ctx.service.tenderInfo.tableName, { tid: id });
  365. await transaction.delete(this.ctx.service.tenderCache.tableName, { id });
  366. await transaction.delete(this.ctx.service.tenderTourist.tableName, { tid: id });
  367. await transaction.delete(this.ctx.service.tenderMap.tableName, { tid: id });
  368. await transaction.delete(this.ctx.service.tenderTag.tableName, { tid: id });
  369. await transaction.delete(this.ctx.service.ledger.departTableName(id), { tender_id: id });
  370. await transaction.delete(this.ctx.service.ledgerAudit.tableName, { tender_id: id });
  371. await transaction.delete(this.ctx.service.pos.departTableName(id), { tid: id });
  372. await transaction.delete(this.ctx.service.pay.tableName, { tid: id });
  373. await transaction.delete(this.ctx.service.stage.tableName, { tid: id });
  374. await transaction.delete(this.ctx.service.stageAudit.tableName, { tid: id });
  375. await transaction.delete(this.ctx.service.stageBills.departTableName(id), { tid: id });
  376. await transaction.delete(this.ctx.service.stagePos.departTableName(id), { tid: id });
  377. await transaction.delete(this.ctx.service.stageBillsDgn.tableName, { tid: id });
  378. await transaction.delete(this.ctx.service.stageBillsFinal.departTableName(id), { tid: id });
  379. await transaction.delete(this.ctx.service.stagePosFinal.departTableName(id), { tid: id });
  380. await transaction.delete(this.ctx.service.stageDetail.tableName, { tid: id });
  381. await transaction.delete(this.ctx.service.stagePay.tableName, { tid: id });
  382. await transaction.delete(this.ctx.service.stageChange.tableName, { tid: id });
  383. await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: id });
  384. await transaction.delete(this.ctx.service.stageJgcl.tableName, { tid: id });
  385. await transaction.delete(this.ctx.service.stageBonus.tableName, { tid: id });
  386. await transaction.delete(this.ctx.service.stageOther.tableName, { tid: id });
  387. await transaction.delete(this.ctx.service.stageRela.tableName, { tid: id });
  388. await transaction.delete(this.ctx.service.stageRelaBills.tableName, { tid: id });
  389. await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { tid: id });
  390. await transaction.delete(this.ctx.service.change.tableName, { tid: id });
  391. await transaction.delete(this.ctx.service.changeAudit.tableName, { tid: id });
  392. await transaction.delete(this.ctx.service.changeAuditList.tableName, { tid: id });
  393. await transaction.delete(this.ctx.service.changeCompany.tableName, { tid: id });
  394. await transaction.delete(this.ctx.service.changeLedger.tableName, { tender_id: id });
  395. await transaction.delete(this.ctx.service.changePos.tableName, { tid: id });
  396. await transaction.delete(this.ctx.service.changeReviseLog.tableName, { tid: id });
  397. await transaction.delete(this.ctx.service.changeProject.tableName, { tid: id });
  398. await transaction.delete(this.ctx.service.changeProjectAudit.tableName, { tid: id });
  399. await transaction.delete(this.ctx.service.changeProjectXsAudit.tableName, { tid: id });
  400. await transaction.delete(this.ctx.service.changeProjectAtt.tableName, { tid: id });
  401. await transaction.delete(this.ctx.service.changeApply.tableName, { tid: id });
  402. await transaction.delete(this.ctx.service.changeApplyAudit.tableName, { tid: id });
  403. await transaction.delete(this.ctx.service.changeApplyList.tableName, { tid: id });
  404. await transaction.delete(this.ctx.service.changeApplyAtt.tableName, { tid: id });
  405. await transaction.delete(this.ctx.service.changePlan.tableName, { tid: id });
  406. await transaction.delete(this.ctx.service.changePlanAudit.tableName, { tid: id });
  407. await transaction.delete(this.ctx.service.changePlanList.tableName, { tid: id });
  408. await transaction.delete(this.ctx.service.changePlanAtt.tableName, { tid: id });
  409. await transaction.delete(this.ctx.service.ledgerRevise.tableName, { tid: id });
  410. await transaction.delete(this.ctx.service.reviseAudit.tableName, { tender_id: id });
  411. await transaction.delete(this.ctx.service.reviseBills.departTableName(id), { tender_id: id });
  412. await transaction.delete(this.ctx.service.revisePos.departTableName(id), { tid: id });
  413. await transaction.delete(this.ctx.service.material.tableName, { tid: id });
  414. await transaction.delete(this.ctx.service.materialAudit.tableName, { tid: id });
  415. await transaction.delete(this.ctx.service.materialBills.tableName, { tid: id });
  416. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { tid: id });
  417. await transaction.delete(this.ctx.service.materialList.tableName, { tid: id });
  418. await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { tid: id });
  419. await transaction.delete(this.ctx.service.materialExponent.tableName, { tid: id });
  420. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, { tid: id });
  421. await transaction.delete(this.ctx.service.materialListGcl.tableName, { tid: id });
  422. await transaction.delete(this.ctx.service.materialListSelf.tableName, { tid: id });
  423. await transaction.delete(this.ctx.service.materialChecklist.tableName, { tid: id });
  424. await transaction.delete(this.ctx.service.materialFile.tableName, { tid: id });
  425. await transaction.delete(this.ctx.service.signatureUsed.tableName, { tender_id: id });
  426. await transaction.delete(this.ctx.service.signatureRole.tableName, { tender_id: id });
  427. await transaction.delete(this.ctx.service.changeAtt.tableName, { tid: id });
  428. // await transaction.delete(this.ctx.service.materialFile.tableName, { tid: id });
  429. await transaction.delete(this.ctx.service.advanceFile.tableName, { tid: id });
  430. await transaction.delete(this.ctx.service.datacollectTender.tableName, { pid: this.ctx.session.sessionProject.id, tid: id });
  431. await transaction.delete(this.ctx.service.schedule.tableName, { tid: id });
  432. await transaction.delete(this.ctx.service.scheduleAudit.tableName, { tid: id });
  433. await transaction.delete(this.ctx.service.scheduleLedger.tableName, { tid: id });
  434. await transaction.delete(this.ctx.service.scheduleLedgerHistory.tableName, { tid: id });
  435. await transaction.delete(this.ctx.service.scheduleLedgerMonth.tableName, { tid: id });
  436. await transaction.delete(this.ctx.service.scheduleMonth.tableName, { tid: id });
  437. await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: id });
  438. await transaction.delete(this.ctx.service.shenpiAudit.tableName, { tid: id });
  439. // 记录删除日志
  440. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.tender, projectLogConst.status.delete, tenderMsg.name, id);
  441. await transaction.commit();
  442. return true;
  443. } catch (err) {
  444. this.ctx.helper.log(err);
  445. await transaction.rollback();
  446. return false;
  447. }
  448. }
  449. async getCheckTender(tid) {
  450. const tender = await this.ctx.service.tender.getTender(tid);
  451. if (tender.measure_type) tender.info = await this.ctx.service.tenderInfo.getTenderInfo(tid);
  452. return tender;
  453. }
  454. async checkTender(tid) {
  455. if (this.ctx.tender) return;
  456. this.ctx.tender = await this.getCheckTender(tid);
  457. }
  458. async setTenderType(tender, type) {
  459. const templateId = await this.ctx.service.valuation.getValuationTemplate(tender.valuation, type);
  460. if (templateId === -1) throw '该模式下,台账模板不存在';
  461. // 获取标段项目节点模板
  462. const tenderNodeTemplateData = await this.ctx.service.tenderNodeTemplate.getData(templateId);
  463. const conn = await this.db.beginTransaction();
  464. try {
  465. await conn.update(this.tableName, { id: tender.id, measure_type: type });
  466. // 复制模板数据到标段数据表
  467. const result = await this.ctx.service.ledger.innerAdd(tenderNodeTemplateData, tender.id, conn);
  468. if (!result) {
  469. throw '初始化台账失败';
  470. }
  471. await conn.commit();
  472. } catch (err) {
  473. await conn.rollback();
  474. throw err;
  475. }
  476. }
  477. async checkTenderCanFinish(tender) {
  478. // 检查台账、台账修订、预付款、计量期、材差期、变更令状态
  479. if (tender.ledger_status !== auditConst.ledger.status.checked) return false;
  480. const lastRevise = await this.ctx.service.ledgerRevise.getLastestRevise(tender.id, true);
  481. if (lastRevise && lastRevise.status !== auditConst.revise.status.checked) return false;
  482. const advanceOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.advance.tableName} WHERE tid = ${tender.id} AND status <> ${auditConst.advance.status.checked}`);
  483. if (advanceOn) return false;
  484. const stageOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.stage.tableName} WHERE tid = ${tender.id} AND status <> ${auditConst.stage.status.checked}`);
  485. if (stageOn) return false;
  486. const materialOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.material.tableName} WHERE tid = ${tender.id} AND status <> ${auditConst.material.status.checked}`);
  487. if (materialOn) return false;
  488. const changeOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.change.tableName} WHERE tid = ${tender.id} AND valid = 1 AND status <> ${auditConst.flow.status.checked}`);
  489. if (changeOn) return false;
  490. const changeApplyOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.changeApply.tableName} WHERE tid = ${tender.id} AND status <> ${auditConst.changeApply.status.checked}`);
  491. if (changeApplyOn) return false;
  492. const changeProjectOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.changeProject.tableName} WHERE tid = ${tender.id} AND status <> ${auditConst.changeProject.status.checked}`);
  493. if (changeProjectOn) return false;
  494. const changePlanOn = await this.db.queryOne(`SELECT * FROM ${this.ctx.service.changePlan.tableName} WHERE tid = ${tender.id} AND status <> ${auditConst.changePlan.status.checked}`);
  495. if (changePlanOn) return false;
  496. return true;
  497. }
  498. async saveBuildStatus(tender, status) {
  499. const str = tenderConst.buildStatus.statusStr[status];
  500. if (!str) throw '参数错误';
  501. if (status === tenderConst.buildStatus.status.finish) {
  502. const check = await this.checkTenderCanFinish(tender);
  503. if (!check) throw '存在未审批完成的流程,请审批完成后再修改状态';
  504. }
  505. await this.defaultUpdate({ id: tender.id, build_status: status });
  506. }
  507. async saveApiRela(tid, updateData) {
  508. await this.db.update(this.tableName, updateData, {where: { id: tid } });
  509. }
  510. async saveTenderData(tid, updateData) {
  511. return await this.db.update(this.tableName, updateData, { where: { id: tid } });
  512. }
  513. /**
  514. * 获取你所参与的施工标段的列表
  515. *
  516. * @param {String} listStatus - 取列表状态,如果是管理页要传
  517. * @param {String} permission - 根据权限取值
  518. * @param {Number} getAll - 是否取所有标段
  519. * @return {Array} - 返回标段数据
  520. */
  521. async getConstructionList(listStatus = '', permission = null, getAll = 0) {
  522. // 获取当前项目信息
  523. const session = this.ctx.session;
  524. let sql = '';
  525. let sqlParam = [];
  526. if (getAll === 1 || (permission !== null && permission.construction !== undefined && permission.construction.indexOf('1') !== -1)) {
  527. // 具有查看所有标段权限的用户查阅标段
  528. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`user_id`, t.`create_time`,' +
  529. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company` ' +
  530. ' FROM ?? As t ' +
  531. ' Left Join ?? As pa ' +
  532. ' ON t.`user_id` = pa.`id` ' +
  533. ' WHERE t.`project_id` = ? AND t.`spid` = ? ORDER BY CONVERT(t.`name` USING GBK) ASC';
  534. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, session.sessionProject.id, this.ctx.subProject.id];
  535. } else {
  536. // 根据用户权限查阅标段
  537. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`user_id`, t.`create_time`,' +
  538. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company` ' +
  539. // ' FROM ?? As t, ?? As pa ' +
  540. // ' WHERE t.`project_id` = ? AND t.`user_id` = pa.`id` AND (' +
  541. ' FROM ?? As t ' +
  542. ' Left Join ?? As pa ' +
  543. ' ON t.`user_id` = pa.`id` ' +
  544. ' WHERE t.`project_id` = ? AND t.`spid` = ? AND ' +
  545. // 参与施工 的标段
  546. ' t.id IN ( SELECT ca.`tid` FROM ?? As ca WHERE ca.`uid` = ?)' +
  547. ' ORDER BY CONVERT(t.`name` USING GBK) ASC';
  548. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, session.sessionProject.id, this.ctx.subProject.id,
  549. this.ctx.service.constructionAudit.tableName, session.sessionUser.accountId,
  550. ];
  551. }
  552. const list = await this.db.query(sql, sqlParam);
  553. for (const l of list) {
  554. l.category = l.category && l.category !== '' ? JSON.parse(l.category) : null;
  555. }
  556. return list;
  557. }
  558. /**
  559. * 获取你所参与的合同标段的列表
  560. *
  561. * @param {String} listStatus - 取列表状态,如果是管理页要传
  562. * @param {String} permission - 根据权限取值
  563. * @param {Number} getAll - 是否取所有标段
  564. * @return {Array} - 返回标段数据
  565. */
  566. async getContractList(listStatus = '', permission = null, getAll = 0) {
  567. // 获取当前项目信息
  568. const session = this.ctx.session;
  569. let sql = '';
  570. let sqlParam = [];
  571. if (getAll === 1) {
  572. // 具有查看所有标段权限的用户查阅标段
  573. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`user_id`, t.`create_time`,' +
  574. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company`, t.`spid` ' +
  575. ' FROM ?? As t ' +
  576. ' Left Join ?? As pa ' +
  577. ' ON t.`user_id` = pa.`id` ' +
  578. ' WHERE t.`project_id` = ? AND t.`spid` = ? ORDER BY CONVERT(t.`name` USING GBK) ASC';
  579. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, session.sessionProject.id, this.ctx.subProject.id];
  580. } else {
  581. // 根据用户权限查阅标段
  582. sql = 'SELECT t.`id`, t.`project_id`, t.`name`, t.`status`, t.`category`, t.`user_id`, t.`create_time`,' +
  583. ' pa.`name` As `user_name`, pa.`role` As `user_role`, pa.`company` As `user_company`, t.`spid` ' +
  584. // ' FROM ?? As t, ?? As pa ' +
  585. // ' WHERE t.`project_id` = ? AND t.`user_id` = pa.`id` AND (' +
  586. ' FROM ?? As t ' +
  587. ' Left Join ?? As pa ' +
  588. ' ON t.`user_id` = pa.`id` ' +
  589. ' WHERE t.`project_id` = ? AND ' +
  590. // 参与施工 的标段
  591. ' t.id IN ( SELECT ca.`tid` FROM ?? As ca WHERE ca.`uid` = ?)' +
  592. ' AND t.`spid` = ? ORDER BY CONVERT(t.`name` USING GBK) ASC';
  593. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, session.sessionProject.id,
  594. this.ctx.service.contractAudit.tableName, session.sessionUser.accountId, this.ctx.subProject.id,
  595. ];
  596. }
  597. const list = await this.db.query(sql, sqlParam);
  598. for (const l of list) {
  599. l.category = l.category && l.category !== '' ? JSON.parse(l.category) : null;
  600. }
  601. return list;
  602. }
  603. async bindSp(pid, spid, tids) {
  604. const subProject = await this.ctx.service.subProject.getDataById(spid);
  605. const orgRelaTenderId = subProject.rela_tender !== '' ? subProject.rela_tender.split(',') : [];
  606. orgRelaTenderId.push(...tids);
  607. // 更新category
  608. const orgCategoryData = await this.ctx.service.category.getOrgAllCategory(pid);
  609. const newCategoryData = await this.ctx.service.category.getAllCategory(subProject);
  610. const updateTenders = [];
  611. for (const tid of tids) {
  612. const tender = await this.getDataById(tid);
  613. const oneUpdate = {
  614. id: tid,
  615. spid,
  616. };
  617. if (tender.category) {
  618. const newCategory = [];
  619. const orgCategory = JSON.parse(tender.category);
  620. for (const c of orgCategory) {
  621. const orgC = orgCategoryData.find(item => item.id === c.cid);
  622. if (orgC) {
  623. const newC = newCategoryData.find(item => item.name === orgC.name);
  624. if (newC) {
  625. const orgV = orgC.value.find(item => item.id === c.value);
  626. if (orgV) {
  627. const newV = newC.value.find(item => item.value === orgV.value);
  628. if (newV) {
  629. newCategory.push({
  630. cid: newC.id,
  631. value: newV.id,
  632. });
  633. }
  634. }
  635. }
  636. }
  637. }
  638. if (newCategory.length > 0) {
  639. oneUpdate.category = JSON.stringify(newCategory);
  640. }
  641. }
  642. updateTenders.push(oneUpdate);
  643. }
  644. const conn = await this.db.beginTransaction();
  645. try {
  646. await conn.updateRows(this.tableName, updateTenders);
  647. await conn.update(this.ctx.service.subProject.tableName, { id: subProject.id, rela_tender: this._.uniq(orgRelaTenderId).join(',') });
  648. await conn.update(this.ctx.service.budget.tableName, { id: subProject.budget_id, rela_tender: this._.uniq(orgRelaTenderId).join(',') });
  649. await this._addSubProjPermission(conn, subProject, tids);
  650. await conn.commit();
  651. return true;
  652. } catch (error) {
  653. await conn.rollback();
  654. throw error;
  655. }
  656. // return await this.ctx.subProject.setRelaTender({ id: spid, rela_tender: newTids });
  657. }
  658. async _addSubProjPermission(conn, subProject, tids) {
  659. // 需要把所有审批人也迁移至项目下
  660. const subProjPermissionAudits = await this.ctx.service.subProjPermission.getAllDataByCondition({ where: { spid: subProject.id } });
  661. const hadUids = this._.map(subProjPermissionAudits, 'uid');
  662. const newUids = this._.cloneDeep(hadUids) || [];
  663. const stageAuditsSql = `SELECT aid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND aid NOT IN (${newUids.join(',')})` : ''} GROUP BY aid`;
  664. const stageAuditParams = [this.ctx.service.stageAudit.tableName];
  665. const stageResult = await conn.query(stageAuditsSql, stageAuditParams);
  666. newUids.push(...this._.map(stageResult, 'aid'));
  667. const ledgerAuditsSql = `SELECT audit_id FROM ?? WHERE tender_id in (${tids.join(',')}) ${newUids.length > 0 ? ` AND audit_id NOT IN (${newUids.join(',')})` : ''} GROUP BY audit_id`;
  668. const ledgerAuditParams = [this.ctx.service.ledgerAudit.tableName];
  669. const ledgerResult = await conn.query(ledgerAuditsSql, ledgerAuditParams);
  670. newUids.push(...this._.map(ledgerResult, 'audit_id'));
  671. const auditAssAuditsSql = `SELECT ass_user_id FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND ass_user_id NOT IN (${newUids.join(',')})` : ''} GROUP BY ass_user_id`;
  672. const auditAssAuditParams = [this.ctx.service.auditAss.tableName];
  673. const auditAssResult = await conn.query(auditAssAuditsSql, auditAssAuditParams);
  674. newUids.push(...this._.map(auditAssResult, 'ass_user_id'));
  675. const settleAuditsSql = `SELECT audit_id FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND audit_id NOT IN (${newUids.join(',')})` : ''} GROUP BY audit_id`;
  676. const settleAuditParams = [this.ctx.service.settleAudit.tableName];
  677. const settleResult = await conn.query(settleAuditsSql, settleAuditParams);
  678. newUids.push(...this._.map(settleResult, 'audit_id'));
  679. const changeAuditsSql = `SELECT uid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND uid NOT IN (${newUids.join(',')})` : ''} GROUP BY uid`;
  680. const changeAuditParams = [this.ctx.service.changeAudit.tableName];
  681. const changeResult = await conn.query(changeAuditsSql, changeAuditParams);
  682. newUids.push(...this._.map(changeResult, 'uid'));
  683. const changeApplyAuditsSql = `SELECT aid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND aid NOT IN (${newUids.join(',')})` : ''} GROUP BY aid`;
  684. const changeApplyAuditParams = [this.ctx.service.changeApplyAudit.tableName];
  685. const changeApplyResult = await conn.query(changeApplyAuditsSql, changeApplyAuditParams);
  686. newUids.push(...this._.map(changeApplyResult, 'aid'));
  687. const changeProjectAuditsSql = `SELECT aid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND aid NOT IN (${newUids.join(',')})` : ''} GROUP BY aid`;
  688. const changeProjectAuditParams = [this.ctx.service.changeProjectAudit.tableName];
  689. const changeProjectResult = await conn.query(changeProjectAuditsSql, changeProjectAuditParams);
  690. newUids.push(...this._.map(changeProjectResult, 'aid'));
  691. const changeProjectXsAuditsSql = `SELECT aid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND aid NOT IN (${newUids.join(',')})` : ''} GROUP BY aid`;
  692. const changeProjectXsAuditParams = [this.ctx.service.changeProjectXsAudit.tableName];
  693. const changeProjectXsResult = await conn.query(changeProjectXsAuditsSql, changeProjectXsAuditParams);
  694. newUids.push(...this._.map(changeProjectXsResult, 'aid'));
  695. const changePlanAuditsSql = `SELECT aid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND aid NOT IN (${newUids.join(',')})` : ''} GROUP BY aid`;
  696. const changePlanAuditParams = [this.ctx.service.changePlanAudit.tableName];
  697. const changePlanResult = await conn.query(changePlanAuditsSql, changePlanAuditParams);
  698. newUids.push(...this._.map(changePlanResult, 'aid'));
  699. const reviseAuditsSql = `SELECT audit_id FROM ?? WHERE tender_id in (${tids.join(',')}) ${newUids.length > 0 ? ` AND audit_id NOT IN (${newUids.join(',')})` : ''} GROUP BY audit_id`;
  700. const reviseAuditParams = [this.ctx.service.reviseAudit.tableName];
  701. const reviseResult = await conn.query(reviseAuditsSql, reviseAuditParams);
  702. newUids.push(...this._.map(reviseResult, 'audit_id'));
  703. const materialAuditsSql = `SELECT aid FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND aid NOT IN (${newUids.join(',')})` : ''} GROUP BY aid`;
  704. const materialAuditParams = [this.ctx.service.materialAudit.tableName];
  705. const materialResult = await conn.query(materialAuditsSql, materialAuditParams);
  706. newUids.push(...this._.map(materialResult, 'aid'));
  707. const advanceAuditsSql = `SELECT audit_id FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND audit_id NOT IN (${newUids.join(',')})` : ''} GROUP BY audit_id`;
  708. const advanceAuditParams = [this.ctx.service.advanceAudit.tableName];
  709. const advanceResult = await conn.query(advanceAuditsSql, advanceAuditParams);
  710. newUids.push(...this._.map(advanceResult, 'audit_id'));
  711. const tenderTouristSql = `SELECT user_id FROM ?? WHERE tid in (${tids.join(',')}) ${newUids.length > 0 ? ` AND user_id NOT IN (${newUids.join(',')})` : ''} GROUP BY user_id`;
  712. const tenderTouristParams = [this.ctx.service.tenderTourist.tableName];
  713. const tenderTouristResult = await conn.query(tenderTouristSql, tenderTouristParams);
  714. newUids.push(...this._.map(tenderTouristResult, 'user_id'));
  715. const diffUids = this._.difference(newUids, hadUids);
  716. if (diffUids.length > 0) {
  717. const insertData = diffUids.map(x => {
  718. return { id: this.uuid.v4(), spid: subProject.id, pid: subProject.project_id, uid: x };
  719. });
  720. await conn.insert(this.ctx.service.subProjPermission.tableName, insertData);
  721. }
  722. }
  723. async getNoSpTenders(pid) {
  724. const list = await this.getAllDataByCondition({ where: { project_id: pid, spid: '' }, orders: [['create_time', 'desc']] });
  725. const accountList = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { project_id: pid } });
  726. for (const l of list) {
  727. const user = accountList.find(item => item.id === l.user_id);
  728. l.user_name = user ? user.name : '';
  729. }
  730. return list;
  731. }
  732. }
  733. return Tender;
  734. };