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