material_audit.js 49 KB

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