material_audit.js 49 KB

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