stage.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. 'use strict';
  2. /**
  3. * 期计量 数据模型
  4. *
  5. * @author Mai
  6. * @date 2018/8/13
  7. * @version
  8. */
  9. const auditConst = require('../const/audit');
  10. const payConst = require('../const/deal_pay.js');
  11. const roleRelSvr = require('./role_rpt_rel');
  12. const fs = require('fs');
  13. const path = require('path');
  14. const _ = require('lodash');
  15. const projectLogConst = require('../const/project_log');
  16. const syncApiConst = require('../const/sync_api');
  17. const RevisePrice = require('../lib/revise_price');
  18. module.exports = app => {
  19. class Stage extends app.BaseService {
  20. /**
  21. * 构造函数
  22. *
  23. * @param {Object} ctx - egg全局变量
  24. * @return {void}
  25. */
  26. constructor(ctx) {
  27. super(ctx);
  28. this.tableName = 'stage';
  29. }
  30. /**
  31. * 根据id查找数据
  32. *
  33. * @param {Number} id - 数据库中的id
  34. * @return {Object} - 返回单条数据
  35. */
  36. async getDataById(id) {
  37. const result = await this.db.get(this.tableName, { id });
  38. if (result) { result.tp_history = result.tp_history ? JSON.parse(result.tp_history) : []; }
  39. return result;
  40. }
  41. /**
  42. * 根据条件查找单条数据
  43. *
  44. * @param {Object} condition - 筛选条件
  45. * @return {Object} - 返回单条数据
  46. */
  47. async getDataByCondition(condition) {
  48. const result = await this.db.get(this.tableName, condition);
  49. if (result) { result.tp_history = result.tp_history ? JSON.parse(result.tp_history) : []; }
  50. return result;
  51. }
  52. /**
  53. * 根据条件查找列表数据
  54. *
  55. * @param {Object} condition - 筛选条件
  56. * @return {Array} - 返回数据
  57. */
  58. async getAllDataByCondition(condition) {
  59. const result = await this.db.select(this.tableName, condition);
  60. for (const r of result) {
  61. r.tp_history = r.tp_history ? JSON.parse(r.tp_history) : [];
  62. }
  63. return result;
  64. }
  65. async loadStageUser(stage) {
  66. const status = auditConst.stage.status;
  67. const accountId = this.ctx.session.sessionUser.accountId;
  68. stage.user = await this.ctx.service.projectAccount.getAccountInfoById(stage.user_id);
  69. stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times); // 全部参与的审批人
  70. stage.auditorIds = this._.map(stage.auditors, 'aid');
  71. stage.curAuditors = stage.auditors.filter(x => { return x.status === status.checking; }); // 当前流程中审批中的审批人
  72. // 分组审批时,根据受限筛选当前审批人
  73. if (stage.curAuditors.length > 0 && stage.curAuditors[0].audit_type === auditConst.auditType.key.multi) {
  74. stage.curAuditors.sort((a, b) => { return a.audit_group_order - b.audit_group_order; });
  75. const filter = [];
  76. stage.curAuditors.forEach(x => {
  77. if (!x.audit_group_limit) {
  78. filter.push(x);
  79. } else {
  80. const exist = filter.find(f => { return f.audit_group === x.audit_group && f.audit_group_order < x.audit_group_order; });
  81. if (!exist) filter.push(x);
  82. }
  83. });
  84. stage.curAuditors = filter;
  85. }
  86. stage.curAuditorIds = this._.map(stage.curAuditors, 'aid');
  87. stage.flowAuditors = stage.curAuditors.length > 0 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order; }) : []; // 当前流程中参与的审批人(包含会签时,审批通过的人)
  88. stage.flowAuditorIds = this._.map(stage.flowAuditors, 'aid');
  89. stage.nextAuditors = stage.curAuditors.length > 0 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order + 1; }) : [];
  90. stage.nextAuditorIds = this._.map(stage.nextAuditors, 'aid');
  91. stage.auditorGroups = this.ctx.helper.groupAuditors(stage.auditors);
  92. stage.userGroups = this.ctx.helper.groupAuditorsUniq(stage.auditorGroups);
  93. stage.userGroups.unshift([{
  94. aid: stage.user.id, order: 0, times: stage.times, audit_order: 0, audit_type: auditConst.auditType.key.common,
  95. name: stage.user.name, role: stage.user.role, company: stage.user.company
  96. }]);
  97. stage.finalAuditorIds = stage.userGroups[stage.userGroups.length - 1].map(x => { return x.aid; });
  98. stage.relaAuditor = this._.findLast(stage.auditors, x => { return x.aid === accountId });
  99. stage.assists = await this.service.stageAuditAss.getData(stage); // 全部协同人
  100. stage.assists = stage.assists.filter(x => {
  101. return x.user_id === stage.user_id || stage.auditorIds.indexOf(x.user_id) >= 0;
  102. }); // 过滤无效协同人
  103. stage.userAssists = stage.assists.filter(x => { return x.user_id === stage.user_id; }); // 原报协同人
  104. stage.userAssistIds = this._.map(stage.userAssists, 'ass_user_id');
  105. stage.auditAssists = stage.assists.filter(x => { return x.user_id !== stage.user_id; }); // 审批协同人
  106. stage.auditAssistIds = this._.map(stage.auditAssists, 'ass_user_id');
  107. stage.relaAssists = stage.assists.filter(x => { return x.user_id === accountId }); // 登录人的协同人
  108. stage.userIds = stage.status === status.uncheck // 当前流程下全部参与人id
  109. ? [stage.user_id, ...stage.userAssistIds]
  110. : [stage.user_id, ...stage.userAssistIds, ...stage.auditorIds, ...stage.auditAssistIds];
  111. }
  112. async loadStageAuditViewData(stage) {
  113. const times = stage.status === auditConst.stage.status.checkNo ? stage.times - 1 : stage.times;
  114. if (!stage.user) stage.user = await this.ctx.service.projectAccount.getAccountInfoById(stage.user_id);
  115. stage.auditHistory = await this.ctx.service.stageAudit.getAuditorHistory(stage.id, times);
  116. // 获取审批流程中左边列表
  117. if (stage.status === auditConst.stage.status.checkNo && stage.user_id !== this.ctx.session.sessionUser.accountId) {
  118. const auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, times); // 全部参与的审批人
  119. const auditorGroups = this.ctx.helper.groupAuditors(auditors);
  120. stage.auditors2 = this.ctx.helper.groupAuditorsUniq(auditorGroups);
  121. stage.auditors2.unshift([{
  122. aid: stage.user.id, order: 0, times: stage.times - 1, audit_order: 0, audit_type: auditConst.auditType.key.common,
  123. name: stage.user.name, role: stage.user.role, company: stage.user.company
  124. }]);
  125. } else {
  126. stage.auditors2 = stage.userGroups;
  127. }
  128. if (stage.status === auditConst.stage.status.uncheck || stage.status === auditConst.stage.status.checkNo) {
  129. stage.auditorList = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times);
  130. }
  131. }
  132. async loadPreCheckedStage(stage) {
  133. if (stage.order > 1) {
  134. if (stage.status === auditConst.stage.status.checked) {
  135. stage.preCheckedStage = await this.getDataByCondition({ tid: stage.tid, order: stage.order - 1 });
  136. } else {
  137. const preCheckedStages = await this.getAllDataByCondition({
  138. where: { tid: stage.tid, status: auditConst.stage.status.checked },
  139. orders: [['order', 'desc']],
  140. });
  141. stage.preCheckedStage = preCheckedStages[0];
  142. }
  143. stage.isCheckFirst = stage.order > 1 ? (stage.preCheckedStage ? stage.preCheckedStage.order === stage.order - 1 : false) : true;
  144. } else {
  145. stage.preCheckedStage = undefined;
  146. stage.isCheckFirst = true;
  147. }
  148. }
  149. async doCheckStage(stage, force = false) {
  150. const status = auditConst.stage.status;
  151. await this.loadStageUser(stage);
  152. await this.loadPreCheckedStage(stage);
  153. const accountId = this.ctx.session.sessionUser.accountId, shareIds = [];
  154. const isTenderTourist = await this.service.tenderTourist.getDataByCondition({ tid: stage.tid, user_id: accountId });
  155. const permission = this.ctx.session.sessionUser.permission;
  156. if (stage.status === status.uncheck) {
  157. stage.readOnly = accountId !== stage.user_id && stage.userAssistIds.indexOf(accountId) < 0;
  158. if (!stage.readOnly) {
  159. stage.assist = stage.userAssists.find(x => { return x.ass_user_id === accountId; });
  160. }
  161. stage.curTimes = stage.times;
  162. stage.curOrder = 0;
  163. } else if (stage.status === status.checkNo) {
  164. stage.readOnly = accountId !== stage.user_id && stage.userAssistIds.indexOf(accountId) < 0;
  165. const checkNoAudit = await this.service.stageAudit.getDataByCondition({
  166. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  167. });
  168. if (!stage.readOnly) {
  169. stage.assist = stage.userAssists.find(x => { return x.ass_user_id === accountId; });
  170. stage.curTimes = stage.times;
  171. stage.curOrder = 0;
  172. } else {
  173. stage.curTimes = stage.times - 1;
  174. stage.curOrder = checkNoAudit.order;
  175. }
  176. } else if (stage.status === status.checked) {
  177. stage.readOnly = true;
  178. stage.curTimes = stage.times;
  179. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  180. } else if (stage.curAuditors.length > 0) {
  181. stage.curTimes = stage.times;
  182. const ass = stage.auditAssists.find(x => { return stage.flowAuditorIds.indexOf(x.user_id) >= 0 && x.ass_user_id === accountId; });
  183. const inCurFlow = stage.flowAuditorIds.indexOf(accountId) >= 0 || ass;
  184. if (inCurFlow) {
  185. stage.assist = ass;
  186. stage.curOrder = stage.curAuditors[0].order;
  187. // 会签,会签人审批通过时,只读,但是curOrder需按原来的取值
  188. if (stage.curAuditors[0].audit_type === auditConst.auditType.key.and) {
  189. stage.readOnly = !_.isEqual(stage.flowAuditorIds, stage.curAuditorIds);
  190. stage.canCheck = true;
  191. } else if (stage.curAuditors[0].audit_type === auditConst.auditType.key.union) {
  192. stage.readOnly = stage.relaAuditor.status !== status.checking;
  193. stage.canCheck = !stage.readOnly;
  194. }
  195. } else {
  196. stage.curOrder = stage.curAuditors[0].order - 1;
  197. stage.readOnly = true;
  198. }
  199. }
  200. if (stage.readOnly) {
  201. stage.assist = accountId === stage.user_id || stage.auditorIds.indexOf(accountId) >= 0
  202. ? null
  203. : stage.assists.find(x => { return x.ass_user_id === accountId});
  204. }
  205. if (stage.userIds.indexOf(accountId) >= 0) {
  206. stage.filePermission = true;
  207. } else if (!!isTenderTourist || force) {
  208. stage.filePermission = this.tender && this.tender.touristPermission ? this.tender.touristPermission.file : false;
  209. } else {
  210. stage.filePermission = false;
  211. }
  212. let time = stage.readOnly ? stage.cache_time_r : stage.cache_time_l;
  213. if (!time) time = stage.in_time ? stage.in_time : new Date();
  214. stage.cacheTime = time.getTime();
  215. // 历史台账
  216. if (stage.status === status.checked) {
  217. stage.ledgerHis = await this.service.ledgerHistory.getDataById(stage.his_id);
  218. }
  219. // 是否台账修订中
  220. const lastRevise = await this.service.ledgerRevise.getLastestRevise(stage.tid);
  221. stage.revising = (lastRevise && lastRevise.status !== auditConst.revise.status.checked) || false;
  222. return stage;
  223. }
  224. async doCheckStageCanCancel(stage) {
  225. // 获取当前审批人的上一个审批人,判断是否是当前登录人,并赋予撤回功能,(当审批人存在有审批过时,上一人不允许再撤回)
  226. const status = auditConst.stage.status;
  227. const accountId = this.ctx.session.sessionUser.accountId;
  228. stage.cancancel = 0;
  229. if (stage.status !== status.checked && stage.status !== status.uncheck) {
  230. if (stage.status !== status.checkNo) {
  231. // 找出当前操作人上一个审批人,包括审批完成的和退回上一个审批人的,同时当前操作人为第一人时,就是则为原报
  232. // 当前流程存在审批人 主动进行任何审批操作时,不可撤回
  233. if (stage.flowAuditors.find(x => { return x.status !== auditConst.stage.status.checking && x.status !== auditConst.stage.status.checkSkip; })
  234. && stage.flowAuditorIds.indexOf(accountId) < 0) return;
  235. const flowAssists = stage.auditAssists.filter(x => { return stage.flowAuditorIds.indexOf(x.user_id) >= 0; });
  236. if (flowAssists.find(x => { return x.confirm; })) return; //当前流程存在协审人确认时,不可撤回
  237. if (stage.curAuditorIds.indexOf(accountId) < 0 && stage.flowAuditorIds.indexOf(accountId) >= 0) {
  238. if (stage.curAuditors[0].audit_type === auditConst.auditType.key.multi) return; // 当前审批流程为分组审批时,不允许撤回
  239. const selfAudit = stage.flowAuditors.find(x => { return x.aid === accountId; });
  240. if (!selfAudit || selfAudit.status !== status.checked) return;
  241. if (selfAudit.audit_group_order) {
  242. const nextChecked = stage.flowAuditors.find(x => { return x.audit_group_order > selfAudit.audit_group_order && x.status === status.checked; });
  243. if (!nextChecked) stage.cancancel = 5;
  244. } else {
  245. stage.cancancel = 5; // 会签/协同 未全部审批通过时,审批人撤回审批通过(或签需要多人审批通过是亦然)
  246. }
  247. return;
  248. }
  249. const preAuditors = stage.curAuditors[0].order !== 1 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order - 1; }) : [];
  250. const preAuditorCheckAgain = preAuditors.find(pa => { return pa.status === status.checkAgain; });
  251. const preAuditorCheckCancel = preAuditors.find(pa => { return pa.status === status.checkCancel; });
  252. const preAuditorHasOld = preAuditors.find(pa => { return pa.is_old === 1; });
  253. const preAuditorIds = (preAuditorCheckAgain ? [] : preAuditors.map(x => { return x.aid })); // 重审不可撤回
  254. if ((this._.isEqual(stage.flowAuditorIds, preAuditorIds) && preAuditorCheckCancel) || preAuditorHasOld) {
  255. return; // 不可以多次撤回
  256. }
  257. const preAuditHasCheckNoPre = preAuditors.find(pa => { return pa.status === status.checkNoPre; });
  258. const preAuditChecked = preAuditors.find(pa => { return pa.status === status.checked && pa.aid === accountId; });
  259. const preAuditCheckNoPre = preAuditors.find(pa => { return pa.status === status.checkNoPre && pa.aid === accountId; });
  260. if (preAuditorIds.indexOf(accountId) >= 0) {
  261. if (preAuditHasCheckNoPre) {
  262. if (preAuditCheckNoPre) {
  263. stage.cancancel = 3;// 审批人撤回审批退回上一人
  264. }
  265. } else if (preAuditChecked) {
  266. stage.cancancel = 2;// 审批人撤回审批通过
  267. }
  268. stage.preAuditors = preAuditors;
  269. } else if (preAuditors.length === 0 && accountId === stage.user_id) {
  270. stage.cancancel = 1;// 原报撤回
  271. }
  272. } else {
  273. const lastAuditors = await this.service.stageAudit.getAuditors(stage.id, stage.times - 1);
  274. const onAuditor = _.findLast(lastAuditors, { status: status.checkNo });
  275. if (onAuditor.aid === accountId) {
  276. stage.cancancel = 4;// 审批人撤回退回原报
  277. stage.preAuditors = lastAuditors.filter(x => { return x.order === onAuditor.order });
  278. }
  279. }
  280. }
  281. }
  282. async checkStage(sid) {
  283. if (!this.ctx.stage) {
  284. const stage = await this.ctx.service.stage.getDataById(sid);
  285. if (!stage) throw '校验的期数据不存在';
  286. await this.doCheckStage(stage);
  287. this.ctx.stage = stage;
  288. }
  289. }
  290. /**
  291. * 获取 最新一期 期计量
  292. * @param tenderId
  293. * @param includeUnCheck
  294. * @return {Promise<*>}
  295. */
  296. async getLastestStage(tenderId, includeUnCheck = false) {
  297. this.initSqlBuilder();
  298. this.sqlBuilder.setAndWhere('tid', {
  299. value: tenderId,
  300. operate: '=',
  301. });
  302. if (!includeUnCheck) {
  303. this.sqlBuilder.setAndWhere('status', {
  304. value: auditConst.stage.status.uncheck,
  305. operate: '!=',
  306. });
  307. }
  308. this.sqlBuilder.orderBy = [['order', 'desc']];
  309. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  310. const stage = await this.db.queryOne(sql, sqlParam);
  311. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  312. return stage;
  313. }
  314. /**
  315. * 获取 最新一期 期计量
  316. * @param tenderId
  317. * @param includeUnCheck
  318. * @return {Promise<*>}
  319. */
  320. async getFlowLatestStage(tenderId, includeUnCheck = false) {
  321. const stages = await this.getAllDataByCondition({ where: {tid: tenderId}, orders: [['order', 'desc']] });
  322. const flowStages = [];
  323. for (const s of stages) {
  324. if (s.status !== auditConst.stage.status.checked) flowStages.push(s);
  325. }
  326. let stage;
  327. if (flowStages.length === 0) {
  328. stage = stages[0];
  329. } else {
  330. const firstFlowStage = flowStages[flowStages.length - 1];
  331. if (includeUnCheck) {
  332. stage = firstFlowStage;
  333. } else {
  334. stage = firstFlowStage.status === auditConst.stage.status.uncheck ? stages[flowStages.length] : firstFlowStage;
  335. }
  336. }
  337. return stage;
  338. }
  339. async getUnCompleteStages(tenderId) {
  340. return this.db.query(`SELECT * From ${this.tableName} WHERE tid = ? and status <> ?`, [tenderId, auditConst.stage.status.checked]);
  341. }
  342. async getNumByChecked(tenderId) {
  343. const num = await this.db.queryOne(`SELECT COUNT(*) as num From ${this.tableName} WHERE tid = ? and status = ?`, [tenderId, auditConst.stage.status.checked]);
  344. return num ? num.num : 0;
  345. }
  346. /**
  347. * 获取 最新一期 审批完成的 期计量
  348. * @param tenderId
  349. * @return {Promise<*>}
  350. */
  351. async getLastestCompleteStage(tenderId) {
  352. this.initSqlBuilder();
  353. this.sqlBuilder.setAndWhere('tid', {
  354. value: tenderId,
  355. operate: '=',
  356. });
  357. this.sqlBuilder.setAndWhere('status', {
  358. value: auditConst.stage.status.checked,
  359. operate: '=',
  360. });
  361. this.sqlBuilder.orderBy = [['order', 'desc']];
  362. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  363. const stage = await this.db.queryOne(sql, sqlParam);
  364. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  365. return stage;
  366. }
  367. /**
  368. * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理)
  369. * @param tenderId
  370. * @return {Promise<void>}
  371. */
  372. async getValidStagesShort(tenderId) {
  373. const sql = 'select * from zh_stage where tid = ? order by zh_stage.order';
  374. const sqlParam = [tenderId];
  375. return await this.db.query(sql, sqlParam);
  376. }
  377. async getListByArchives(tid, ids) {
  378. if (ids.length === 0) return [];
  379. const sql = 'SELECT c.* FROM ?? as c LEFT JOIN (SELECT sid, MAX(end_time) as end_time FROM ?? WHERE ' +
  380. 'tid = ? AND sid in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') GROUP BY sid) as ca ON c.id = ca.sid WHERE' +
  381. ' c.tid = ? AND c.id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') AND c.status = ? ORDER BY c.order ASC';
  382. const params = [this.tableName, this.ctx.service.stageAudit.tableName, tid, tid, auditConst.stage.status.checked];
  383. const list = await this.db.query(sql, params);
  384. return list;
  385. }
  386. /**
  387. * 获取某一期信息(报表用)
  388. * @param stageId
  389. * @return {Promise<void>}
  390. */
  391. async getStageById(stageId) {
  392. const sql = 'select * from zh_stage where id = ? order by zh_stage.order';
  393. const sqlParam = [stageId];
  394. return await this.db.query(sql, sqlParam);
  395. }
  396. async checkStageGatherData(stage, force = false) {
  397. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  398. if (stage.status !== auditConst.stage.status.checked) {
  399. await this.doCheckStage(stage, force);
  400. if (!stage.readOnly && stage.check_calc) {
  401. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  402. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  403. stage.contract_tp = tpData.contract_tp;
  404. stage.qc_tp = tpData.qc_tp;
  405. stage.positive_qc_tp = tpData.positive_qc_tp;
  406. stage.negative_qc_tp = tpData.negative_qc_tp;
  407. stage.contract_pc_tp = pcSum.contract_pc_tp;
  408. stage.qc_pc_tp = pcSum.qc_pc_tp;
  409. stage.pc_tp = pcSum.pc_tp;
  410. stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;
  411. stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;
  412. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  413. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  414. stage.yf_tp = tp.yf;
  415. stage.sf_tp = tp.sf;
  416. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  417. await this.update({
  418. check_calc: false,
  419. contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,
  420. positive_qc_tp: stage.positive_qc_tp, negative_qc_tp: stage.negative_qc_tp,
  421. contract_pc_tp: stage.contract_pc_tp || 0, qc_pc_tp: stage.qc_pc_tp || 0, pc_tp: stage.pc_tp || 0,
  422. positive_qc_pc_tp: stage.positive_qc_pc_tp || 0, negative_qc_pc_tp: stage.negative_qc_pc_tp || 0,
  423. yf_tp: stage.yf_tp, sf_tp: stage.sf_tp,
  424. }, { id: stage.id });
  425. } else if (stage.tp_history) {
  426. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  427. if (his) {
  428. stage.contract_tp = his.contract_tp;
  429. stage.qc_tp = his.qc_tp;
  430. stage.positive_qc_tp = his.positive_qc_tp;
  431. stage.negative_qc_tp = his.negative_qc_tp;
  432. stage.yf_tp = his.yf_tp;
  433. stage.sf_tp = his.sf_tp;
  434. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  435. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  436. }
  437. }
  438. }
  439. }
  440. async _checkStageValid(stage) {
  441. if (stage.status === auditConst.stage.status.uncheck && !this.ctx.tender.isTourist) {
  442. const assist = await this.ctx.service.auditAss.getAllDataByCondition({ where: { tid: stage.tid, user_id: stage.user_id } });
  443. const assistId = assist.map(x => { return x.ass_user_id });
  444. return stage.user_id === this.ctx.session.sessionUser.accountId || assistId.indexOf(this.ctx.session.sessionUser.accountId) >= 0;
  445. } else {
  446. return true;
  447. }
  448. }
  449. /**
  450. * 获取标段下的全部计量期,按倒序
  451. * @param tenderId
  452. * @return {Promise<void>}
  453. */
  454. async getValidStages(tenderId, force = false) {
  455. let stages = await this.db.select(this.tableName, {
  456. where: { tid: tenderId },
  457. orders: [['order', 'desc']],
  458. });
  459. for (const s of stages) {
  460. s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : [];
  461. s.valid = await this._checkStageValid(s);
  462. }
  463. if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) {
  464. stages = stages.filter(x => { return x.valid; });
  465. }
  466. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  467. if (stages.length === 0) return stages;
  468. for (const s of stages) {
  469. if (s.status !== auditConst.stage.status.checked) await this.checkStageGatherData(s, force);
  470. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  471. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  472. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  473. if (s.yf_tp && s.sf_tp === 0) {
  474. const sf = await this.ctx.service.stagePay.getHistorySf(s);
  475. if (sf && s.readOnly) {
  476. await this.ctx.service.stage.update({ sf_tp: sf.tp, pre_sf_tp: sf.pre_tp }, { id: s.id });
  477. }
  478. s.sf_tp = sf ? sf.tp : 0;
  479. }
  480. }
  481. return stages;
  482. }
  483. async getNextStages(tenderId, order) {
  484. const sql = 'SELECT * FROM ?? WHERE tid = ? AND `order` > ?';
  485. return await this.db.query(sql, [this.tableName, tenderId, order]);
  486. }
  487. async _getSumTp(condition, ...field) {
  488. const fieldSql = [];
  489. for (const f of field) {
  490. fieldSql.push('SUM(`' + f + '`) as ' + '`' + f + '`');
  491. }
  492. const sql = 'SELECT ' + fieldSql.join(', ') + ' FROM ' + this.tableName + ' ' + this.ctx.helper.whereSql(condition);
  493. return await this.db.queryOne(sql);
  494. }
  495. /**
  496. *
  497. * @param tenderId - 标段id
  498. * @param date - 计量年月
  499. * @param period - 开始-截止日期
  500. * @return {Promise<void>}
  501. */
  502. async addStage(tender, date, period) {
  503. const stages = await this.getAllDataByCondition({
  504. where: { tid: tender.id },
  505. orders: [['order', 'DESC']],
  506. });
  507. const preStage = stages[0];
  508. const preCheckedStage = stages.find(x => { return x.status === auditConst.stage.status.checked; });
  509. const order = stages.length + 1;
  510. const newStage = {
  511. sid: this.uuid.v4(),
  512. tid: tender.id,
  513. order,
  514. in_time: new Date(),
  515. s_time: date,
  516. period,
  517. times: 1,
  518. status: auditConst.stage.status.uncheck,
  519. user_id: tender.user_id, // this.ctx.session.sessionUser.accountId,
  520. check_calc: false,
  521. };
  522. newStage.cache_time_l = newStage.in_time;
  523. newStage.cache_time_r = newStage.in_time;
  524. if (preStage) {
  525. newStage.im_type = preStage.im_type;
  526. newStage.im_pre = preStage.im_pre;
  527. newStage.im_gather = preStage.im_gather;
  528. newStage.im_gather_node = preStage.im_gather_node;
  529. if (preCheckedStage) {
  530. newStage.pre_contract_tp = this.ctx.helper.sum([preCheckedStage.pre_contract_tp, preCheckedStage.contract_tp, preCheckedStage.contract_pc_tp]);
  531. newStage.pre_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_qc_tp, preCheckedStage.qc_tp, preCheckedStage.qc_pc_tp]);
  532. newStage.pre_positive_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_positive_qc_tp, preCheckedStage.positive_qc_tp, preCheckedStage.positive_qc_pc_tp]);
  533. newStage.pre_negative_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_negative_qc_tp, preCheckedStage.negative_qc_tp, preCheckedStage.negative_qc_pc_tp]);
  534. newStage.pre_yf_tp = this.ctx.helper.add(preCheckedStage.pre_yf_tp, preCheckedStage.yf_tp);
  535. if (preCheckedStage.order === 1 || preCheckedStage.pre_sf_tp) {
  536. newStage.pre_sf_tp = this.ctx.helper.add(preCheckedStage.pre_sf_tp, preCheckedStage.sf_tp);
  537. } else {
  538. const sumTp = await this._getSumTp({tid: preCheckedStage.tid}, 'sf_tp');
  539. newStage.pre_sf_tp = sumTp.sf_tp || 0;
  540. }
  541. }
  542. } else {
  543. const projFunRela = this.ctx.subProject.fun_rela;
  544. newStage.im_type = projFunRela.imType;
  545. }
  546. const transaction = await this.db.beginTransaction();
  547. try {
  548. // 新增期记录
  549. const result = await transaction.insert(this.tableName, newStage);
  550. if (result.affectedRows === 1) {
  551. newStage.id = result.insertId;
  552. newStage.preCheckedStage = preCheckedStage;
  553. } else {
  554. throw '新增期数据失败';
  555. }
  556. // 存在上一期时,复制上一期审批流程
  557. if (preStage) {
  558. const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);
  559. if (!auditResult) {
  560. throw '复制上一期审批流程失败';
  561. }
  562. }
  563. // 新增期合同支付数据
  564. const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);
  565. if (!dealResult) {
  566. throw '新增期合同支付数据失败';
  567. }
  568. // 新增期其他台账数据
  569. let pcTp = { contract_pc_tp: 0, qc_pc_tp: 0, pc_tp: 0, positive_qc_pc_tp: 0, negative_qc_pc_tp: 0 };
  570. if (preCheckedStage) {
  571. const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preCheckedStage, transaction);
  572. if (!jgclResult) throw '初始化甲供材料数据失败';
  573. const yjclResult = await this.ctx.service.stageYjcl.addInitialStageData(newStage, preCheckedStage, transaction);
  574. if (!yjclResult) throw '初始化甲供材料数据失败';
  575. const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preCheckedStage, transaction);
  576. if (!otherResult) throw '初始化其他台账数据失败';
  577. const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preCheckedStage, transaction);
  578. if (!safeResult) throw '初始化其他台账数据失败';
  579. const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preCheckedStage, transaction);
  580. if (!tempResult) throw '初始化其他台账数据失败';
  581. }
  582. if (preStage && preCheckedStage && preStage.order === preCheckedStage.order) {
  583. const priceCalc = new RevisePrice(this.ctx);
  584. pcTp = await priceCalc.newStagePriceChange(newStage, preStage, transaction);
  585. }
  586. if (order === 1 || (preStage && preCheckedStage && preStage.order === preCheckedStage.order)) {
  587. await this.ctx.service.tenderCache.updateStageCache4Add(transaction, newStage, pcTp);
  588. }
  589. // 新增期拷贝报表相关配置/签名角色 等
  590. if (preStage) {
  591. const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction);
  592. await this.ctx.service.roleRptRel.addInitialStageData(tender.id, newStage, preStage);
  593. }
  594. await transaction.commit();
  595. // 通知发送 - 第三方更新
  596. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  597. const base_data = {
  598. tid: tender.id,
  599. sid: result.insertId,
  600. op: 'insert',
  601. };
  602. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  603. // 存在上一期时
  604. base_data.op = preStage ? 'update' : 'insert';
  605. base_data.sid = -1;
  606. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  607. }
  608. return newStage;
  609. } catch (err) {
  610. await transaction.rollback();
  611. throw err;
  612. }
  613. }
  614. /**
  615. * 编辑计量期
  616. *
  617. * @param {Number} tenderId - 标段Id
  618. * @param {Number} order - 第N期
  619. * @param {String} date - 计量年月
  620. * @param {String} period - 开始-截止时间
  621. * @return {Promise<void>}
  622. */
  623. async saveStage(tenderId, order, date, period) {
  624. await this.db.update(this.tableName, {
  625. s_time: date,
  626. period,
  627. }, { where: { tid: tenderId, order } });
  628. }
  629. /**
  630. * 设置 中间计量 生成规则,并生成数据
  631. * @param {Number} tenderId - 标段id
  632. * @param {Number} order - 期序号
  633. * @param {Number} data - 中间计量生成规则
  634. * @return {Promise<void>}
  635. */
  636. async buildDetailData(tenderId, order, data) {
  637. const conn = await this.db.beginTransaction();
  638. try {
  639. await conn.update(this.tableName, { im_type: data.im_type, im_pre: data.im_pre , im_start_num: data.im_start_num }, { where: { tid: tenderId, order } });
  640. // to do 生成中间计量数据
  641. await conn.commit();
  642. } catch (err) {
  643. await conn.rollback();
  644. throw err;
  645. }
  646. }
  647. async getChangeSubtotal(stage) {
  648. const result = {};
  649. const bg = await this.ctx.service.stageChange.getSubtotal(stage);
  650. const importBg = await this.ctx.service.stageImportChange.getSubtotal(stage);
  651. result.common = this.ctx.helper.add(bg.common, importBg.common);
  652. result.great = this.ctx.helper.add(bg.great, importBg.great);
  653. result.more = this.ctx.helper.add(bg.more, importBg.more);
  654. return result;
  655. }
  656. /**
  657. * 获取 当期的 计算基数
  658. * @return {Promise<any>}
  659. */
  660. async getStagePayCalcBase(stage, tenderInfo) {
  661. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  662. const param = tenderInfo.deal_param;
  663. const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  664. const qdSum = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage);
  665. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  666. const bg = await this.getChangeSubtotal(stage);
  667. for (const cb of calcBase) {
  668. switch (cb.code) {
  669. case 'htj':
  670. cb.value = param.contractPrice;
  671. break;
  672. case 'zlje':
  673. cb.value = param.zanLiePrice;
  674. break;
  675. case 'htjszl':
  676. cb.value = this.ctx.helper.sub(this.ctx.helper.sub(param.contractPrice, param.zanLiePrice), param.jrgPrice);
  677. break;
  678. case 'kgyfk':
  679. cb.value = param.startAdvance;
  680. break;
  681. case 'clyfk':
  682. cb.value = param.materialAdvance;
  683. break;
  684. case 'bqwc':
  685. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  686. break;
  687. case 'bqht':
  688. cb.value = sum.contract_tp; //this.ctx.helper.add(sum.contract_tp, pcSum.contract_pc_tp);
  689. break;
  690. case 'bqbg':
  691. cb.value = sum.qc_tp; //this.ctx.helper.add(sum.qc_tp, pcSum.qc_pc_tp);
  692. break;
  693. case 'bqqdwc':
  694. cb.value = this.ctx.helper.sum([qdSum.contract_tp, qdSum.qc_tp, pcSum.pc_tp]);
  695. break;
  696. case 'bqqdht':
  697. cb.value = qdSum.contract_tp;
  698. break;
  699. case 'bqqdbg':
  700. cb.value = qdSum.qc_tp;
  701. break;
  702. case 'ybbqwc':
  703. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*([0-9]{0,2}-)?1[0-9]{2}(-|$)');
  704. const sumPc = await this.ctx.service.stageBillsPc.getSumTotalPriceGcl(stage, '^[^0-9]*([0-9]{0,2}-)?1[0-9]{2}(-|$)');
  705. cb.value = this.ctx.helper.sum([sumGcl.contract_tp, sumGcl.qc_tp, sumPc.pc_tp]);
  706. break;
  707. case 'ybbqbg':
  708. cb.value = bg.common;
  709. break;
  710. case 'jdbqbg':
  711. cb.value = bg.more;
  712. break;
  713. case 'zdbqbg':
  714. cb.value = bg.great;
  715. break;
  716. default:
  717. cb.value = 0;
  718. }
  719. }
  720. return calcBase;
  721. }
  722. async updateCheckCalcFlag(stage, check) {
  723. const result = await this.db.update(this.tableName, { id: stage.id, check_calc: check, update_calc_time: new Date() });
  724. return result.affectedRows === 1;
  725. }
  726. async updateExprCalcTime(stage) {
  727. const result = await this.db.update(this.tableName, { id: stage.id, update_expr_calc_time: new Date() });
  728. return result.affectedRows === 1;
  729. }
  730. async updateCacheTime(sid) {
  731. const result = await this.db.update(this.tableName, { id: sid, cache_time_l: new Date() });
  732. return result.affectedRows === 1;
  733. }
  734. /**
  735. * 删除计量期
  736. *
  737. * @param {Number} id - 期Id
  738. * @return {Promise<void>}
  739. */
  740. async deleteStage(id) {
  741. const stageInfo = await this.getDataById(id);
  742. await this.loadPreCheckedStage(stageInfo);
  743. const transaction = await this.db.beginTransaction();
  744. try {
  745. // 通知发送 - 第三方更新
  746. // if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  747. // const base_data = {
  748. // tid: this.ctx.tender.id,
  749. // sid: id,
  750. // op: 'delete',
  751. // };
  752. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  753. // // 是否还存在其他期
  754. // base_data.op = stageInfo.order === 1 ? 'delete' : 'update';
  755. // base_data.sid = -1;
  756. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  757. // }
  758. await transaction.delete(this.tableName, { id });
  759. if (stageInfo.isCheckFirst) await this.ctx.service.tenderCache.updateStageCache4Del(transaction, stageInfo);
  760. await transaction.delete(this.ctx.service.pos.tableName, { add_stage: id });
  761. await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });
  762. await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });
  763. await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });
  764. await transaction.delete(this.ctx.service.stageChangeFinal.tableName, { sid: id });
  765. await transaction.delete(this.ctx.service.stageImportChange.tableName, { sid: id });
  766. await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });
  767. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });
  768. await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });
  769. await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });
  770. await transaction.delete(this.ctx.service.stageRela.tableName, { sid: id });
  771. await transaction.delete(this.ctx.service.stageRelaBills.tableName, { sid: id });
  772. await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { sid: id });
  773. await transaction.delete(this.ctx.service.stageRelaIm.tableName, { sid: id });
  774. await transaction.delete(this.ctx.service.stageRelaImBills.tableName, { sid: id });
  775. await transaction.delete(this.ctx.service.stageAuditAss.tableName, { sid: id });
  776. // 删除计量合同支付附件
  777. const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });
  778. if (payList) {
  779. for (const pt of payList) {
  780. if (pt.attachment !== null && pt.attachment !== '') {
  781. const payAttList = JSON.parse(pt.attachment);
  782. for (const pat of payAttList) {
  783. if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {
  784. await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));
  785. }
  786. }
  787. }
  788. }
  789. }
  790. await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });
  791. await this.ctx.service.pay.doDeleteStage(stageInfo, transaction);
  792. // 删除计量附件文件
  793. const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: stageInfo.tid, sid: stageInfo.order } });
  794. if (attList.length !== 0) {
  795. for (const att of attList) {
  796. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  797. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  798. }
  799. }
  800. }
  801. await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: stageInfo.tid, sid: stageInfo.order });
  802. // 其他台账
  803. await transaction.delete(this.ctx.service.stageJgcl.tableName, { sid: id });
  804. const bonus = await this.ctx.service.stageBonus.getStageData(stageInfo);
  805. if (bonus && bonus.length > 0) {
  806. for (const b of bonus) {
  807. for (const f of b.proof_file) {
  808. if (fs.existsSync(path.join(this.app.baseDir, f.filepath))) {
  809. await fs.unlinkSync(path.join(this.app.baseDir, f.filepath));
  810. }
  811. }
  812. }
  813. }
  814. await transaction.delete(this.ctx.service.stageYjcl.tableName, {sid: id});
  815. await transaction.delete(this.ctx.service.stageBonus.tableName, { sid: id });
  816. await transaction.delete(this.ctx.service.stageOther.tableName, { sid: id });
  817. // 同步删除进度里所选的期
  818. await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: stageInfo.tid, order: stageInfo.order });
  819. const detailAtt = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: id } });
  820. if (detailAtt && detailAtt.length > 0) {
  821. for (const da of detailAtt) {
  822. da.attachment = da.attachment ? JSON.parse(da.attachment) : [];
  823. for (const daa of da.attachment) {
  824. if (fs.existsSync(path.join(this.app.baseDir, daa.filepath))) {
  825. await fs.unlinkSync(path.join(this.app.baseDir, daa.filepath));
  826. }
  827. }
  828. }
  829. }
  830. await transaction.delete(this.ctx.service.stageDetailAtt.tableName, { sid: id });
  831. // 重算进度计量总金额
  832. await this.ctx.service.scheduleStage.calcStageSjTp(transaction, stageInfo.tid);
  833. // 删除收方单及附件
  834. const shoufangAttList = await this.ctx.service.stageShoufangAtt.getAllDataByCondition({ where: { sid: id } });
  835. if (shoufangAttList.length !== 0) {
  836. for (const att of shoufangAttList) {
  837. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  838. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  839. }
  840. }
  841. }
  842. await transaction.delete(this.ctx.service.stageShoufangAtt.tableName, { sid: id });
  843. const shoufangList = await this.ctx.service.stageShoufang.getAllDataByCondition({ where: { sid: id } });
  844. if (shoufangList.length !== 0) {
  845. for (const att of shoufangList) {
  846. if (fs.existsSync(path.join(this.app.baseDir, 'app/' + att.qrcode))) {
  847. await fs.unlinkSync(path.join(this.app.baseDir, 'app/' + att.qrcode));
  848. }
  849. }
  850. }
  851. await transaction.delete(this.ctx.service.stageShoufang.tableName, { sid: id });
  852. await transaction.delete(this.ctx.service.cooperationConfirm.tableName, { sid: id });
  853. // 记录删除日志
  854. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.stage, projectLogConst.status.delete, '第' + stageInfo.order + '期');
  855. await transaction.commit();
  856. return true;
  857. } catch (err) {
  858. await transaction.rollback();
  859. throw err;
  860. }
  861. }
  862. /**
  863. * 获取 多期的 计算基数 -(材料调差调用)
  864. * @return {Promise<any>}
  865. */
  866. async getMaterialCalcBase(stage_list, tenderInfo) {
  867. const calcBase = JSON.parse(JSON.stringify(payConst.materialCalcBase));
  868. const param = tenderInfo.deal_param;
  869. const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);
  870. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPriceByMaterial(stage_list);
  871. for (const cb of calcBase) {
  872. switch (cb.code) {
  873. case 'htj':
  874. cb.value = param.contractPrice;
  875. break;
  876. case 'zlje':
  877. cb.value = param.zanLiePrice;
  878. break;
  879. case 'htjszl':
  880. cb.value = this.ctx.helper.sub(this.ctx.helper.sub(param.contractPrice, param.zanLiePrice), param.jrgPrice);
  881. break;
  882. case 'kgyfk':
  883. cb.value = param.startAdvance;
  884. break;
  885. case 'clyfk':
  886. cb.value = param.materialAdvance;
  887. break;
  888. case 'bqwc':
  889. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  890. break;
  891. case 'bqht':
  892. cb.value = sum.contract_tp;
  893. break;
  894. case 'bqbg':
  895. cb.value = sum.qc_tp;
  896. break;
  897. case 'yib':
  898. case 'erb':
  899. case 'sanb':
  900. case 'sib':
  901. case 'wub':
  902. case 'liub':
  903. case 'qib':
  904. case 'bab':
  905. case 'jiub':
  906. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, cb.filter);
  907. const sumPc = await this.ctx.service.stageBillsPc.getSumTotalPriceGclByMaterial(stage_list, cb.filter);
  908. cb.value = this.ctx.helper.sum([sumGcl.contract_tp, sumGcl.qc_tp, sumPc.pc_tp]);
  909. break;
  910. case 'bqyf':
  911. cb.value = this.ctx.helper.roundNum(this._.sumBy(stage_list, 'yf_tp'), 2);
  912. break;
  913. default:
  914. cb.value = 0;
  915. }
  916. }
  917. return calcBase;
  918. }
  919. /**
  920. * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)
  921. * @param stage_id_list
  922. * @return {Promise<void>}
  923. */
  924. async getStageMsgByStageId(stage_id_list) {
  925. const list = [];
  926. stage_id_list = stage_id_list.toString().split(',');
  927. for (const sid of stage_id_list) {
  928. const stage = await this.getDataById(sid);
  929. stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);
  930. // todo 不确定是否使用,暂时注释,待测试验证
  931. // stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);
  932. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  933. stage.curTimes = stage.times;
  934. list.push(stage);
  935. }
  936. return list;
  937. }
  938. async getStageByDataCollect(tenderId, stage_tp) {
  939. const allStages = await this.db.select(this.tableName, {
  940. columns: ['id', 'user_id', 'times', 'status', 's_time', 'contract_tp', 'qc_tp', 'pc_tp', 'pre_contract_tp', 'pre_qc_tp', 'pre_yf_tp', 'yf_tp', 'pre_sf_tp', 'sf_tp', 'tp_history'],
  941. where: { tid: tenderId },
  942. orders: [['order', 'desc']],
  943. });
  944. const stages = this._.filter(allStages, function(s) {
  945. return s.status !== auditConst.stage.status.uncheck;
  946. });
  947. // if (stages.length > 0 && stages[0].status === auditConst.stage.status.uncheck) {
  948. // stages.splice(0, 1);
  949. // }
  950. // 最新一期计量(未审批完成),取上一个人的期详细数据,应实时计算
  951. const stage = stages[0];
  952. if (stages.length === 0) return stages;
  953. // await this.checkStageGatherDataByDataCollect(stage);
  954. if (stage.status !== auditConst.stage.status.checked) {
  955. // 批量把stage_tp的值赋值给stage
  956. _.forEach(stage_tp, function(value, key) {
  957. stage[key] = stage_tp[key] ? stage_tp[key] : null;
  958. });
  959. }
  960. for (const s of stages) {
  961. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  962. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  963. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  964. // s.yf_tp = this.ctx.helper.add(s.pre_yf_tp, s.yf_tp);
  965. // s.sf_tp = this.ctx.helper.add(s.pre_sf_tp, s.sf_tp);
  966. }
  967. return stages;
  968. }
  969. async doCheckStageByDataCollect(stage) {
  970. const status = auditConst.stage.status;
  971. await this.loadStageUser(stage);
  972. if (stage.status === status.checkNo) {
  973. stage.readOnly = false;
  974. const checkNoAudit = await this.service.stageAudit.getDataByCondition({
  975. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  976. });
  977. stage.curTimes = stage.times - 1;
  978. stage.curOrder = checkNoAudit.order;
  979. } else if (stage.status === status.checked) {
  980. stage.readOnly = true;
  981. stage.curTimes = stage.times;
  982. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  983. } else {
  984. stage.readOnly = false;
  985. stage.curTimes = stage.times;
  986. stage.curOrder = stage.curAuditors[0].order - 1;
  987. }
  988. return stage;
  989. }
  990. async checkStageGatherDataByDataCollect(stage) {
  991. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  992. if (stage.status !== auditConst.stage.status.checked) {
  993. await this.doCheckStageByDataCollect(stage);
  994. if (!stage.readOnly && stage.check_calc) {
  995. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  996. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  997. stage.contract_tp = tpData.contract_tp;
  998. stage.qc_tp = tpData.qc_tp;
  999. stage.positive_qc_tp = tpData.positive_qc_tp;
  1000. stage.negative_qc_tp = tpData.negative_qc_tp;
  1001. stage.contract_pc_tp = pcSum.contract_pc_tp;
  1002. stage.qc_pc_tp = pcSum.qc_pc_tp;
  1003. stage.pc_tp = pcSum.pc_tp;
  1004. stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;
  1005. stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;
  1006. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  1007. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  1008. stage.yf_tp = tp.yf;
  1009. stage.sf_tp = tp.sf;
  1010. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  1011. } else if (stage.tp_history) {
  1012. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  1013. if (his) {
  1014. stage.contract_tp = his.contract_tp;
  1015. stage.qc_tp = his.qc_tp;
  1016. stage.positive_qc_tp = his.positive_qc_tp;
  1017. stage.negative_qc_tp = his.negative_qc_tp;
  1018. stage.yf_tp = his.yf_tp;
  1019. stage.sf_tp = his.sf_tp;
  1020. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  1021. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  1022. }
  1023. }
  1024. }
  1025. }
  1026. async isLastStage(tid, sid) {
  1027. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1028. return lastStage ? lastStage.id === sid : false;
  1029. }
  1030. }
  1031. return Stage;
  1032. };