material_audit.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2019/2/27
  7. * @version
  8. */
  9. const auditConst = require('../const/audit').material;
  10. const pushType = require('../const/audit').pushType;
  11. const smsTypeConst = require('../const/sms_type');
  12. const wxConst = require('../const/wechat_template');
  13. const shenpiConst = require('../const/shenpi');
  14. module.exports = app => {
  15. class MaterialAudit extends app.BaseService {
  16. /**
  17. * 构造函数
  18. *
  19. * @param {Object} ctx - egg全局变量
  20. * @return {void}
  21. */
  22. constructor(ctx) {
  23. super(ctx);
  24. this.tableName = 'material_audit';
  25. }
  26. /**
  27. * 获取 审核人信息
  28. *
  29. * @param {Number} materialId - 材料调差期id
  30. * @param {Number} auditorId - 审核人id
  31. * @param {Number} times - 第几次审批
  32. * @return {Promise<*>}
  33. */
  34. async getAuditor(materialId, auditorId, times = 1) {
  35. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  36. 'FROM ?? AS la, ?? AS pa ' +
  37. 'WHERE la.`mid` = ? and la.`aid` = ? and la.`times` = ?' +
  38. ' and la.`aid` = pa.`id`';
  39. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditorId, times];
  40. return await this.db.queryOne(sql, sqlParam);
  41. }
  42. /**
  43. * 获取 审核列表信息
  44. *
  45. * @param {Number} materialId - 材料调差期id
  46. * @param {Number} times - 第几次审批
  47. * @return {Promise<*>}
  48. */
  49. async getAuditors(materialId, times = 1) {
  50. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`, g.`sort` ' +
  51. 'FROM ?? AS la, ?? AS pa, (SELECT `aid`,(@i:=@i+1) as `sort` FROM ??, (select @i:=0) as it WHERE `mid` = ? AND `times` = ? GROUP BY `aid`) as g ' +
  52. 'WHERE la.`mid` = ? and la.`times` = ? and la.`aid` = pa.`id` and g.`aid` = la.`aid` order by la.`order`';
  53. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.tableName, materialId, times, materialId, times];
  54. const result = await this.db.query(sql, sqlParam);
  55. const sql2 = 'SELECT COUNT(a.`aid`) as num FROM (SELECT `aid` FROM ?? WHERE `mid` = ? AND `times` = ? GROUP BY `aid`) as a';
  56. const sqlParam2 = [this.tableName, materialId, times];
  57. const count = await this.db.queryOne(sql2, sqlParam2);
  58. for (const i in result) {
  59. result[i].max_sort = count.num;
  60. }
  61. return result;
  62. }
  63. /**
  64. * 获取 当前审核人
  65. *
  66. * @param {Number} materialId - 材料调差期id
  67. * @param {Number} times - 第几次审批
  68. * @return {Promise<*>}
  69. */
  70. async getCurAuditor(materialId, times = 1) {
  71. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  72. 'FROM ?? AS la, ?? AS pa ' +
  73. 'WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ?' +
  74. ' and la.`aid` = pa.`id`';
  75. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditConst.status.checking, times];
  76. return await this.db.queryOne(sql, sqlParam);
  77. }
  78. /**
  79. * 获取 最新审核顺序
  80. *
  81. * @param {Number} materialId - 材料调差期id
  82. * @param {Number} times - 第几次审批
  83. * @return {Promise<number>}
  84. */
  85. async getNewOrder(materialId, times = 1) {
  86. const sql = 'SELECT Max(??) As max_order FROM ?? Where `mid` = ? and `times` = ?';
  87. const sqlParam = ['order', this.tableName, materialId, times];
  88. const result = await this.db.queryOne(sql, sqlParam);
  89. return result && result.max_order ? result.max_order + 1 : 1;
  90. }
  91. /**
  92. * 新增审核人
  93. *
  94. * @param {Number} materialId - 材料调差期id
  95. * @param {Number} auditorId - 审核人id
  96. * @param {Number} times - 第几次审批
  97. * @return {Promise<number>}
  98. */
  99. async addAuditor(materialId, auditorId, times = 1, is_gdzs = 0) {
  100. const transaction = await this.db.beginTransaction();
  101. try {
  102. let newOrder = await this.getNewOrder(materialId, times);
  103. // 判断是否存在固定终审,存在则newOrder - 1并使终审order+1
  104. newOrder = is_gdzs === 1 ? newOrder - 1 : newOrder;
  105. if (is_gdzs) await this._syncOrderByDelete(transaction, materialId, newOrder, times, '+');
  106. const data = {
  107. tid: this.ctx.tender.id,
  108. mid: materialId,
  109. aid: auditorId,
  110. times,
  111. order: newOrder,
  112. status: auditConst.status.uncheck,
  113. };
  114. const result = await transaction.insert(this.tableName, data);
  115. await transaction.commit();
  116. return result.effectRows = 1;
  117. } catch (err) {
  118. await transaction.rollback();
  119. throw err;
  120. }
  121. return false;
  122. }
  123. /**
  124. * 移除审核人时,同步其后审核人order
  125. * @param transaction - 事务
  126. * @param {Number} materialId - 材料调差期id
  127. * @param {Number} auditorId - 审核人id
  128. * @param {Number} times - 第几次审批
  129. * @return {Promise<*>}
  130. * @private
  131. */
  132. async _syncOrderByDelete(transaction, materialId, order, times, selfOperate = '-') {
  133. this.initSqlBuilder();
  134. this.sqlBuilder.setAndWhere('mid', {
  135. value: materialId,
  136. operate: '=',
  137. });
  138. this.sqlBuilder.setAndWhere('order', {
  139. value: order,
  140. operate: '>=',
  141. });
  142. this.sqlBuilder.setAndWhere('times', {
  143. value: times,
  144. operate: '=',
  145. });
  146. this.sqlBuilder.setUpdateData('order', {
  147. value: 1,
  148. selfOperate: selfOperate,
  149. });
  150. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  151. const data = await transaction.query(sql, sqlParam);
  152. return data;
  153. }
  154. /**
  155. * 移除审核人
  156. *
  157. * @param {Number} materialId - 材料调差期id
  158. * @param {Number} auditorId - 审核人id
  159. * @param {Number} times - 第几次审批
  160. * @return {Promise<boolean>}
  161. */
  162. async deleteAuditor(materialId, auditorId, times = 1) {
  163. const transaction = await this.db.beginTransaction();
  164. try {
  165. const condition = { mid: materialId, aid: auditorId, times };
  166. const auditor = await this.getDataByCondition(condition);
  167. if (!auditor) {
  168. throw '该审核人不存在';
  169. }
  170. await this._syncOrderByDelete(transaction, materialId, auditor.order, times);
  171. await transaction.delete(this.tableName, condition);
  172. await transaction.commit();
  173. } catch (err) {
  174. await transaction.rollback();
  175. throw err;
  176. }
  177. return true;
  178. }
  179. /**
  180. * 开始审批
  181. * @param {Number} materialId - 材料调差期id
  182. * @param {Number} times - 第几次审批
  183. * @return {Promise<boolean>}
  184. */
  185. async start(materialId, times = 1) {
  186. const audit = await this.getDataByCondition({ mid: materialId, times, order: 1 });
  187. if (!audit) {
  188. if(this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdspl) {
  189. throw '请联系管理员添加审批人';
  190. } else {
  191. throw '请先选择审批人,再上报数据';
  192. }
  193. }
  194. const transaction = await this.db.beginTransaction();
  195. try {
  196. await transaction.update(this.tableName, { id: audit.id, status: auditConst.status.checking, begin_time: new Date() });
  197. await transaction.update(this.ctx.service.material.tableName, {
  198. id: materialId, status: auditConst.status.checking,
  199. });
  200. // 本期一些必要数据(如应耗数量和上期调差金额)插入到material_bills_history表里
  201. const materialBillsData = await this.ctx.service.materialBills.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
  202. if (materialBillsData.length === 0 && this.ctx.material.ex_expr === null) {
  203. throw '请至少使用一种调差方式';
  204. }
  205. const mbhList = [];
  206. for (const mb of materialBillsData) {
  207. if (mb.code === '') {
  208. throw '调差工料编号不能为空';
  209. }
  210. const newMbh = {
  211. tid: this.ctx.tender.id,
  212. mid: this.ctx.material.id,
  213. order: this.ctx.material.order,
  214. mb_id: mb.id,
  215. quantity: mb.quantity,
  216. expr: mb.expr,
  217. msg_tp: mb.msg_tp,
  218. msg_times: mb.msg_times,
  219. msg_spread: mb.msg_spread,
  220. m_up_risk: mb.m_up_risk,
  221. m_down_risk: mb.m_down_risk,
  222. m_spread: mb.m_spread,
  223. m_tp: mb.m_tp,
  224. pre_tp: mb.pre_tp,
  225. is_summary: mb.is_summary,
  226. };
  227. mbhList.push(newMbh);
  228. }
  229. if(mbhList.length !== 0) await transaction.insert(this.ctx.service.materialBillsHistory.tableName, mbhList);
  230. const materialExponentData = await this.ctx.service.materialExponent.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
  231. const mehList = [];
  232. for (const me of materialExponentData) {
  233. const newMeh = {
  234. tid: this.ctx.tender.id,
  235. mid: this.ctx.material.id,
  236. order: this.ctx.material.order,
  237. me_id: me.id,
  238. type: me.type,
  239. weight_num: me.weight_num,
  240. basic_price: me.basic_price,
  241. basic_times: me.basic_times,
  242. m_price: me.m_price,
  243. calc_num: me.calc_num,
  244. is_summary: me.is_summary,
  245. };
  246. mehList.push(newMeh);
  247. }
  248. if(mehList.length !== 0) await transaction.insert(this.ctx.service.materialExponentHistory.tableName, mehList);
  249. // 微信模板通知
  250. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  251. const wechatData = {
  252. qi: materialInfo.order,
  253. status: wxConst.status.check,
  254. tips: wxConst.tips.check,
  255. begin_time: Date.parse(new Date()),
  256. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, 2), this.ctx.helper.round(materialInfo.ex_tp, 2)),
  257. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), 2), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.rate/100), 2)),
  258. };
  259. await this.ctx.helper.sendWechat(audit.aid, smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  260. // 添加短信通知-需要审批提醒功能
  261. // const smsUser = await this.ctx.service.projectAccount.getDataById(audit.aid);
  262. // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '') {
  263. // const smsType = JSON.parse(smsUser.sms_type);
  264. // if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {
  265. // const tenderInfo = await this.ctx.service.tender.getDataById(audit.tid);
  266. // const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);
  267. // const sms = new SMS(this.ctx);
  268. // const tenderName = await sms.contentChange(tenderInfo.name);
  269. // const content = '【纵横计量支付】' + tenderName + '第' + stageInfo.order + '期,需要您审批。';
  270. // sms.send(smsUser.auth_mobile, content);
  271. // }
  272. // }
  273. // todo 更新标段tender状态 ?
  274. await transaction.commit();
  275. } catch (err) {
  276. await transaction.rollback();
  277. throw err;
  278. }
  279. return true;
  280. }
  281. async _checked(pid, materialId, checkData, times) {
  282. const time = new Date();
  283. // 整理当前流程审核人状态更新
  284. const audit = await this.getDataByCondition({ mid: materialId, times, status: auditConst.status.checking });
  285. if (!audit) {
  286. throw '审核数据错误';
  287. }
  288. // 获取审核人列表
  289. const sql = 'SELECT `tid`, `mid`, `aid`, `order` FROM ?? WHERE `mid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';
  290. const sqlParam = [this.tableName, materialId, times];
  291. const auditors = await this.db.query(sql, sqlParam);
  292. const nextAudit = await this.getDataByCondition({ mid: materialId, times, order: audit.order + 1 });
  293. const transaction = await this.db.beginTransaction();
  294. try {
  295. await transaction.update(this.tableName, { id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time });
  296. // 获取推送必要信息
  297. const noticeContent = await this.getNoticeContent(pid, audit.tid, materialId, audit.aid);
  298. // 添加推送
  299. const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checked, content: noticeContent }];
  300. auditors.forEach(audit => {
  301. records.push({ pid, type: pushType.material, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });
  302. });
  303. await transaction.insert('zh_notice', records);
  304. const begin_audit = await this.getDataByCondition({
  305. mid: materialId,
  306. order: 1,
  307. });
  308. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  309. // 无下一审核人表示,审核结束
  310. if (nextAudit) {
  311. // 复制一份下一审核人数据
  312. // await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, nextAudit.order, transaction);
  313. // 流程至下一审批人
  314. await transaction.update(this.tableName, { id: nextAudit.id, status: auditConst.status.checking, begin_time: time });
  315. // 同步 期信息
  316. await transaction.update(this.ctx.service.material.tableName, {
  317. id: materialId, status: auditConst.status.checking,
  318. });
  319. // 微信模板通知
  320. const wechatData = {
  321. qi: materialInfo.order,
  322. status: wxConst.status.check,
  323. tips: wxConst.tips.check,
  324. begin_time: Date.parse(begin_audit.begin_time),
  325. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, 2), this.ctx.helper.round(materialInfo.ex_tp, 2)),
  326. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), 2), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.rate/100), 2)),
  327. };
  328. await this.ctx.helper.sendWechat(nextAudit.aid, smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  329. // 添加短信通知-需要审批提醒功能
  330. // const smsUser = await this.ctx.service.projectAccount.getDataById(nextAudit.aid);
  331. // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '') {
  332. // const smsType = JSON.parse(smsUser.sms_type);
  333. // if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {
  334. // const tenderInfo = await this.ctx.service.tender.getDataById(nextAudit.tid);
  335. // const stageInfo = await this.ctx.service.stage.getDataById(nextAudit.sid);
  336. // const sms = new SMS(this.ctx);
  337. // const tenderName = await sms.contentChange(tenderInfo.name);
  338. // const content = '【纵横计量支付】' + tenderName + '第' + stageInfo.order + '期,需要您审批。';
  339. // sms.send(smsUser.auth_mobile, content);
  340. // }
  341. // }
  342. } else {
  343. // 本期结束
  344. // 生成截止本期数据 final数据
  345. // console.time('generatePre');
  346. // await this.ctx.service.stageBillsFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  347. // await this.ctx.service.stagePosFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  348. // console.timeEnd('generatePre');
  349. // 同步 期信息
  350. await transaction.update(this.ctx.service.material.tableName, {
  351. id: materialId, status: checkData.checkType,
  352. });
  353. // 微信模板通知
  354. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), materialInfo.user_id));
  355. const wechatData = {
  356. qi: materialInfo.order,
  357. status: wxConst.status.success,
  358. tips: wxConst.tips.success,
  359. begin_time: Date.parse(begin_audit.begin_time),
  360. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, 2), this.ctx.helper.round(materialInfo.ex_tp, 2)),
  361. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), 2), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.rate/100), 2)),
  362. };
  363. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.result.toString(), wxConst.template.material, wechatData);
  364. // 添加短信通知-审批通过提醒功能
  365. // const mobile_array = [];
  366. // const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  367. // const auditList = await this.getAuditors(stageId, stageInfo.times);
  368. // const smsUser1 = await this.ctx.service.projectAccount.getDataById(stageInfo.user_id);
  369. // if (smsUser1.auth_mobile !== undefined && smsUser1.sms_type !== '') {
  370. // const smsType = JSON.parse(smsUser1.sms_type);
  371. // if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {
  372. // mobile_array.push(smsUser1.auth_mobile);
  373. // }
  374. // }
  375. // for (const user of auditList) {
  376. // const smsUser = await this.ctx.service.projectAccount.getDataById(user.aid);
  377. // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '') {
  378. // const smsType = JSON.parse(smsUser.sms_type);
  379. // if (mobile_array.indexOf(smsUser.auth_mobile) === -1 && smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {
  380. // mobile_array.push(smsUser.auth_mobile);
  381. // }
  382. // }
  383. // }
  384. // if (mobile_array.length > 0) {
  385. // const tenderInfo = await this.ctx.service.tender.getDataById(stageInfo.tid);
  386. // const sms = new SMS(this.ctx);
  387. // const tenderName = await sms.contentChange(tenderInfo.name);
  388. // const content = '【纵横计量支付】' + tenderName + '第' + stageInfo.order + '期,审批通过。';
  389. // sms.send(mobile_array, content);
  390. // }
  391. }
  392. await transaction.commit();
  393. } catch (err) {
  394. await transaction.rollback();
  395. throw err;
  396. }
  397. }
  398. async _checkNo(pid, materialId, checkData, times) {
  399. const time = new Date();
  400. // 整理当前流程审核人状态更新
  401. const audit = await this.getDataByCondition({ mid: materialId, times, status: auditConst.status.checking });
  402. if (!audit) {
  403. throw '审核数据错误';
  404. }
  405. const sql = 'SELECT `tid`, `mid`, `aid`, `order` FROM ?? WHERE `mid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';
  406. const sqlParam = [this.tableName, materialId, times];
  407. const auditors = await this.db.query(sql, sqlParam);
  408. let order = 1;
  409. for (const a of auditors) {
  410. a.times = times + 1;
  411. a.order = order;
  412. a.status = auditConst.status.uncheck;
  413. order++;
  414. }
  415. const transaction = await this.db.beginTransaction();
  416. try {
  417. await transaction.update(this.tableName, { id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time });
  418. // 添加到消息推送表
  419. const noticeContent = await this.getNoticeContent(pid, audit.tid, materialId, audit.aid);
  420. const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checkNo, content: noticeContent }];
  421. auditors.forEach(audit => {
  422. records.push({ pid, type: pushType.material, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });
  423. });
  424. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  425. // 同步期信息
  426. await transaction.update(this.ctx.service.material.tableName, {
  427. id: materialId, status: checkData.checkType,
  428. times: times + 1,
  429. });
  430. // 拷贝新一次审核流程列表
  431. await transaction.insert(this.tableName, auditors);
  432. // 删除material_bills_history信息
  433. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, {
  434. tid: this.ctx.tender.id,
  435. order: this.ctx.material.order,
  436. });
  437. // 删除material_exponent_history信息
  438. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, {
  439. tid: this.ctx.tender.id,
  440. order: this.ctx.material.order,
  441. });
  442. // 微信模板通知
  443. const begin_audit = await this.getDataByCondition({
  444. mid: materialId,
  445. order: 1,
  446. });
  447. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  448. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), materialInfo.user_id));
  449. const wechatData = {
  450. qi: materialInfo.order,
  451. status: wxConst.status.back,
  452. tips: wxConst.tips.back,
  453. begin_time: Date.parse(begin_audit.begin_time),
  454. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, 2), this.ctx.helper.round(materialInfo.ex_tp, 2)),
  455. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), 2), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.rate/100), 2)),
  456. };
  457. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.result.toString(), wxConst.template.material, wechatData);
  458. // 计算该审批人最终数据
  459. // await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  460. // 复制一份最新数据给原报
  461. // await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times + 1, 0, transaction);
  462. // 添加短信通知-审批退回提醒功能
  463. // const mobile_array = [];
  464. // const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  465. // const auditList = await this.getAuditors(stageId, stageInfo.times);
  466. // const smsUser1 = await this.ctx.service.projectAccount.getDataById(stageInfo.user_id);
  467. // if (smsUser1.auth_mobile !== '' && smsUser1.auth_mobile !== undefined && smsUser1.sms_type !== '') {
  468. // const smsType = JSON.parse(smsUser1.sms_type);
  469. // if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {
  470. // mobile_array.push(smsUser1.auth_mobile);
  471. // }
  472. // }
  473. // for (const user of auditList) {
  474. // const smsUser = await this.ctx.service.projectAccount.getDataById(user.aid);
  475. // if (smsUser.auth_mobile !== '' && smsUser.auth_mobile !== undefined && smsUser.sms_type !== '') {
  476. // const smsType = JSON.parse(smsUser.sms_type);
  477. // if (mobile_array.indexOf(smsUser.auth_mobile) === -1 && smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.result.toString()) !== -1) {
  478. // mobile_array.push(smsUser.auth_mobile);
  479. // }
  480. // }
  481. // }
  482. // if (mobile_array.length > 0) {
  483. // const tenderInfo = await this.ctx.service.tender.getDataById(stageInfo.tid);
  484. // const sms = new SMS(this.ctx);
  485. // const tenderName = await sms.contentChange(tenderInfo.name);
  486. // const content = '【纵横计量支付】' + tenderName + '第' + stageInfo.order + '期,审批退回。';
  487. // sms.send(mobile_array, content);
  488. // }
  489. await transaction.commit();
  490. } catch (err) {
  491. await transaction.rollback();
  492. throw err;
  493. }
  494. }
  495. async _checkNoPre(pid, materialId, checkData, times) {
  496. const time = new Date();
  497. // 整理当前流程审核人状态更新
  498. const audit = await this.getDataByCondition({ mid: materialId, times, status: auditConst.status.checking });
  499. if (!audit || audit.order <= 1) {
  500. throw '审核数据错误';
  501. }
  502. // 添加重新审批后,不能用order-1,取groupby值里的上一个才对
  503. const auditors2 = await this.getAuditGroupByList(materialId, times);
  504. const auditorIndex = await auditors2.findIndex(function(item) {
  505. return item.aid === audit.aid;
  506. });
  507. const preAuditor = auditors2[auditorIndex - 1];
  508. const noticeContent = await this.getNoticeContent(pid, audit.tid, materialId, audit.aid);
  509. const transaction = await this.db.beginTransaction();
  510. try {
  511. // 添加到消息推送表
  512. const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checkNoPre, content: noticeContent }];
  513. auditors2.forEach(audit => {
  514. records.push({ pid, type: pushType.material, uid: audit.aid, status: auditConst.status.checkNoPre, content: noticeContent });
  515. });
  516. await transaction.insert('zh_notice', records);
  517. await transaction.update(this.tableName, { id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time });
  518. // 顺移气候审核人流程顺序
  519. this.initSqlBuilder();
  520. this.sqlBuilder.setAndWhere('mid', { value: materialId, operate: '=' });
  521. this.sqlBuilder.setAndWhere('order', { value: audit.order, operate: '>' });
  522. this.sqlBuilder.setUpdateData('order', { value: 2, selfOperate: '+' });
  523. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  524. const data = await transaction.query(sql, sqlParam);
  525. const newAuditors = [];
  526. newAuditors.push({
  527. tid: audit.tid, mid: audit.mid, aid: preAuditor.aid,
  528. times: audit.times, order: audit.order + 1, status: auditConst.status.checking,
  529. begin_time: time,
  530. });
  531. newAuditors.push({
  532. tid: audit.tid, mid: audit.mid, aid: audit.aid,
  533. times: audit.times, order: audit.order + 2, status: auditConst.status.uncheck,
  534. });
  535. // 微信模板通知
  536. const begin_audit = await this.getDataByCondition({
  537. mid: materialId,
  538. order: 1,
  539. });
  540. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  541. const wechatData = {
  542. qi: materialInfo.order,
  543. status: wxConst.status.check,
  544. tips: wxConst.tips.check,
  545. begin_time: Date.parse(begin_audit.begin_time),
  546. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, 2), this.ctx.helper.round(materialInfo.ex_tp, 2)),
  547. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), 2), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.rate/100), 2)),
  548. };
  549. await this.ctx.helper.sendWechat(preAuditor.aid, smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  550. await transaction.insert(this.tableName, newAuditors);
  551. await transaction.commit();
  552. } catch (error) {
  553. await transaction.rollback();
  554. throw error;
  555. }
  556. }
  557. /**
  558. * 审批
  559. * @param {Number} materialId - 材料调差期id
  560. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  561. * @param {Number} times - 第几次审批
  562. * @return {Promise<void>}
  563. */
  564. async check(materialId, checkData, times = 1) {
  565. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo && checkData.checkType !== auditConst.status.checkNoPre) {
  566. throw '提交数据错误';
  567. }
  568. const pid = this.ctx.session.sessionProject.id;
  569. switch (checkData.checkType) {
  570. case auditConst.status.checked:
  571. await this._checked(pid, materialId, checkData, times);
  572. break;
  573. case auditConst.status.checkNo:
  574. await this._checkNo(pid, materialId, checkData, times);
  575. break;
  576. case auditConst.status.checkNoPre:
  577. await this._checkNoPre(pid, materialId, checkData, times);
  578. break;
  579. default:
  580. throw '无效审批操作';
  581. }
  582. }
  583. /**
  584. * 用于添加推送所需的content内容
  585. * @param {Number} pid 项目id
  586. * @param {Number} tid 台账id
  587. * @param {Number} mid 期id
  588. * @param {Number} uid 审批人id
  589. */
  590. async getNoticeContent(pid, tid, mid, uid) {
  591. const noticeSql = 'SELECT * FROM (SELECT ' +
  592. ' t.`id` As `tid`, ma.`mid`, t.`name`, m.`order`, pa.`name` As `su_name`, pa.role As `su_role`' +
  593. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  594. ' LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +
  595. ' LEFT JOIN ?? As ma ON m.`id` = ma.`mid`' +
  596. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  597. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  598. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.material.tableName, mid, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];
  599. const content = await this.db.query(noticeSql, noticeSqlParam);
  600. return content.length ? JSON.stringify(content[0]) : '';
  601. }
  602. /**
  603. * 审批
  604. * @param {Number} materialId - 材料调差期id
  605. * @param {Number} times - 第几次审批
  606. * @return {Promise<void>}
  607. */
  608. async checkAgain(materialId, times = 1) {
  609. const time = new Date();
  610. // 整理当前流程审核人状态更新
  611. const audit = (await this.getAllDataByCondition({ where: { mid: materialId, times }, orders: [['order', 'desc']], limit: 1, offset: 0 }))[0];
  612. if (!audit || audit.order <= 1) {
  613. throw '审核数据错误';
  614. }
  615. const transaction = await this.db.beginTransaction();
  616. try {
  617. // 当前审批人2次添加至流程中
  618. const newAuditors = [];
  619. newAuditors.push({
  620. tid: audit.tid, mid: audit.mid, aid: audit.aid,
  621. times: audit.times, order: audit.order + 1, status: auditConst.status.checkAgain,
  622. begin_time: time, end_time: time, opinion: '',
  623. });
  624. newAuditors.push({
  625. tid: audit.tid, mid: audit.mid, aid: audit.aid,
  626. times: audit.times, order: audit.order + 2, status: auditConst.status.checking,
  627. begin_time: time,
  628. });
  629. await transaction.insert(this.tableName, newAuditors);
  630. // 复制一份最新数据给下一人
  631. // await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, audit.order + 2, transaction);
  632. // 本期结束
  633. // 生成截止本期数据 final数据
  634. // await this.ctx.service.stageBillsFinal.delGenerateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  635. // await this.ctx.service.stagePosFinal.delGenerateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  636. // 同步 期信息
  637. await transaction.update(this.ctx.service.material.tableName, {
  638. id: materialId, status: auditConst.status.checking,
  639. });
  640. // // 添加短信通知-需要审批提醒功能
  641. // const smsUser = await this.ctx.service.projectAccount.getDataById(audit.aid);
  642. // if (smsUser.auth_mobile !== undefined && smsUser.sms_type !== '') {
  643. // const smsType = JSON.parse(smsUser.sms_type);
  644. // if (smsType[smsTypeConst.const.JL] !== undefined && smsType[smsTypeConst.const.JL].indexOf(smsTypeConst.judge.approval.toString()) !== -1) {
  645. // const tenderInfo = await this.ctx.service.tender.getDataById(audit.tid);
  646. // const stageInfo = await this.ctx.service.stage.getDataById(audit.sid);
  647. // const sms = new SMS(this.ctx);
  648. // const tenderName = await sms.contentChange(tenderInfo.name);
  649. // const content = '【纵横计量支付】' + tenderName + '第' + stageInfo.order + '期,需要您审批。';
  650. // sms.send(smsUser.auth_mobile, content);
  651. // }
  652. // }
  653. await transaction.commit();
  654. } catch (err) {
  655. await transaction.rollback();
  656. throw err;
  657. }
  658. }
  659. /**
  660. * 获取审核人需要审核的期列表
  661. *
  662. * @param auditorId
  663. * @return {Promise<*>}
  664. */
  665. async getAuditMaterial(auditorId) {
  666. const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`mid`,' +
  667. ' m.`order` As `morder`, m.`status` As `mstatus`,' +
  668. ' t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +
  669. ' FROM ?? AS ma, ?? AS m, ?? As t ' +
  670. ' WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`user_id` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' +
  671. ' and ma.`mid` = m.`id` and ma.`tid` = t.`id` ORDER BY ma.`begin_time` DESC';
  672. const sqlParam = [this.tableName, this.ctx.service.material.tableName, this.ctx.service.tender.tableName, auditorId, auditConst.status.checking, auditorId, auditConst.status.checkNo, auditConst.status.checkNo];
  673. return await this.db.query(sql, sqlParam);
  674. }
  675. /**
  676. * 获取 某时间后 审批进度 更新的期
  677. * @param {Number} pid - 查询标段
  678. * @param {Number} uid - 查询人
  679. * @param {Date} time - 查询时间
  680. * @return {Promise<*>}
  681. */
  682. async getNoticeMaterial(pid, uid, time) {
  683. // const sql = 'SELECT * FROM (SELECT t.`name`, t.`project_id`, t.`type`, t.`user_id`, ' +
  684. // ' m.`order` As `m_order`, m.`status` As `m_status`, ' +
  685. // ' ma.`aid`, ma.`times`, ma.`order`, ma.`end_time`, ma.`tid`, ma.`mid`, ma.`status`, ' +
  686. // ' pa.`name` As `su_name`, pa.role As `su_role`, pa.company As `su_company`' +
  687. // ' FROM (SELECT * FROM ?? WHERE `user_id` = ? OR `id` in (SELECT `tid` FROM ?? WHERE `aid` = ? GROUP BY `tid`)) As t' +
  688. // ' LEFT JOIN ?? As m On t.`id` = m.`tid`' +
  689. // ' LEFT JOIN ?? As ma ON m.`id` = ma.`mid`' +
  690. // ' LEFT JOIN ?? As pa ON ma.`aid` = pa.`id`' +
  691. // ' WHERE ma.`end_time` > ? and t.`project_id` = ?' +
  692. // ' ORDER By ma.`end_time` DESC LIMIT 1000) as new_t GROUP BY new_t.`tid`' +
  693. // ' ORDER BY new_t.`end_time`';
  694. // const sqlParam = [this.ctx.service.tender.tableName, uid, this.tableName, uid, this.ctx.service.material.tableName, this.tableName,
  695. // this.ctx.service.projectAccount.tableName, time, pid];
  696. // return await this.db.query(sql, sqlParam);
  697. let notice = await this.db.select('zh_notice', {
  698. where: { pid, type: pushType.material, uid },
  699. orders: [['create_time', 'desc']],
  700. limit: 10, offset: 0,
  701. });
  702. notice = notice.map(v => {
  703. const extra = JSON.parse(v.content);
  704. delete v.content;
  705. return { ...v, ...extra };
  706. });
  707. return notice;
  708. }
  709. /**
  710. * 获取审核人流程列表
  711. *
  712. * @param auditorId
  713. * @return {Promise<*>}
  714. */
  715. async getAuditGroupByList(materialId, times) {
  716. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  717. 'FROM ?? AS la, ?? AS pa ' +
  718. 'WHERE la.`mid` = ? and la.`times` = ? and la.`aid` = pa.`id` GROUP BY la.`aid` ORDER BY la.`order`';
  719. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, times];
  720. return await this.db.query(sql, sqlParam);
  721. }
  722. /**
  723. * 获取审核人流程列表(包括原报)
  724. * @param {Number} materialId 调差id
  725. * @param {Number} times 审核次数
  726. * @return {Promise<Array>} 查询结果集(包括原报)
  727. */
  728. async getAuditorsWithOwner(materialId, times = 1) {
  729. const result = await this.getAuditGroupByList(materialId, times);
  730. const sql =
  731. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As mid, 0 As `order`' +
  732. ' FROM ' +
  733. this.ctx.service.material.tableName +
  734. ' As s' +
  735. ' LEFT JOIN ' +
  736. this.ctx.service.projectAccount.tableName +
  737. ' As pa' +
  738. ' ON s.user_id = pa.id' +
  739. ' WHERE s.id = ?';
  740. const sqlParam = [times, materialId, materialId];
  741. const user = await this.db.queryOne(sql, sqlParam);
  742. result.unshift(user);
  743. return result;
  744. }
  745. /**
  746. * 复制上一期的审批人列表给最新一期
  747. *
  748. * @param transaction - 新增一期的事务
  749. * @param {Object} preMaterial - 上一期
  750. * @param {Object} newaMaterial - 最新一期
  751. * @return {Promise<*>}
  752. */
  753. async copyPreMaterialAuditors(transaction, preMaterial, newMaterial) {
  754. const auditors = await this.getAuditGroupByList(preMaterial.id, preMaterial.times);
  755. const newAuditors = [];
  756. for (const a of auditors) {
  757. const na = {
  758. tid: preMaterial.tid,
  759. mid: newMaterial.id,
  760. aid: a.aid,
  761. times: newMaterial.times,
  762. order: newAuditors.length + 1,
  763. status: auditConst.status.uncheck,
  764. };
  765. newAuditors.push(na);
  766. }
  767. const result = await transaction.insert(this.tableName, newAuditors);
  768. return result.affectedRows === auditors.length;
  769. }
  770. /**
  771. * 移除审核人
  772. *
  773. * @param {Number} materialId - 材料调差期id
  774. * @param {Number} status - 期状态
  775. * @param {Number} status - 期次数
  776. * @return {Promise<boolean>}
  777. */
  778. async getAuditorByStatus(materialId, status, times = 1) {
  779. let auditor = null;
  780. let sql = '';
  781. let sqlParam = '';
  782. switch (status) {
  783. case auditConst.status.checking :
  784. case auditConst.status.checked :
  785. case auditConst.status.checkNoPre :
  786. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  787. 'FROM ?? AS la, ?? AS pa ' +
  788. 'WHERE la.`mid` = ? and la.`status` = ? and la.`aid` = pa.`id` order by la.`times` desc, la.`order` desc';
  789. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, status];
  790. auditor = await this.db.queryOne(sql, sqlParam);
  791. break;
  792. case auditConst.status.checkNo :
  793. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  794. 'FROM ?? AS la, ?? AS pa ' +
  795. 'WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ? and la.`aid` = pa.`id` order by la.`times` desc, la.`order` desc';
  796. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditConst.status.checkNo, parseInt(times) - 1];
  797. auditor = await this.db.queryOne(sql, sqlParam);
  798. break;
  799. case auditConst.status.uncheck :
  800. default:break;
  801. }
  802. return auditor;
  803. }
  804. async getAllAuditors(tenderId) {
  805. const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +
  806. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +
  807. ' WHERE t.id = ?' +
  808. ' GROUP BY ma.aid';
  809. const sqlParam = [tenderId];
  810. return this.db.query(sql, sqlParam);
  811. }
  812. async updateNewAuditList(material, newIdList) {
  813. const transaction = await this.db.beginTransaction();
  814. try {
  815. // 先删除旧的审批流,再添加新的
  816. await transaction.delete(this.tableName, { mid: material.id, times: material.times });
  817. const newAuditors = [];
  818. let order = 1;
  819. for (const aid of newIdList) {
  820. newAuditors.push({
  821. tid: material.tid, mid: material.id, aid,
  822. times: material.times, order, status: auditConst.status.uncheck,
  823. });
  824. order++;
  825. }
  826. if(newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  827. await transaction.commit();
  828. } catch (err) {
  829. await transaction.rollback();
  830. throw err;
  831. }
  832. }
  833. async updateLastAudit(material, auditList, lastId) {
  834. const transaction = await this.db.beginTransaction();
  835. try {
  836. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  837. const idList = this._.map(auditList, 'aid');
  838. let order = idList.length + 1;
  839. if (idList.indexOf(lastId) !== -1) {
  840. await transaction.delete(this.tableName, { mid: material.id, times: material.times, aid: lastId });
  841. const audit = this._.find(auditList, { 'aid': lastId });
  842. // 顺移之后审核人流程顺序
  843. await this._syncOrderByDelete(transaction, material.id, audit.order, material.times);
  844. order = order - 1;
  845. }
  846. // 添加终审
  847. const newAuditor = {
  848. tid: material.tid, mid: material.id, aid: lastId,
  849. times: material.times, order, status: auditConst.status.uncheck,
  850. };
  851. await transaction.insert(this.tableName, newAuditor);
  852. await transaction.commit();
  853. } catch (err) {
  854. await transaction.rollback();
  855. throw err;
  856. }
  857. }
  858. }
  859. return MaterialAudit;
  860. };