material_audit.js 49 KB

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