material_audit.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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 auditType = require('../const/audit').auditType;
  11. const pushType = require('../const/audit').pushType;
  12. const pushOperate = require('../const/spec_3f').pushOperate;
  13. const smsTypeConst = require('../const/sms_type');
  14. const wxConst = require('../const/wechat_template');
  15. const shenpiConst = require('../const/shenpi');
  16. const materialConst = require('../const/material');
  17. module.exports = app => {
  18. class MaterialAudit extends app.BaseService {
  19. /**
  20. * 构造函数
  21. *
  22. * @param {Object} ctx - egg全局变量
  23. * @return {void}
  24. */
  25. constructor(ctx) {
  26. super(ctx);
  27. this.tableName = 'material_audit';
  28. }
  29. /**
  30. * 获取 审核人信息
  31. *
  32. * @param {Number} materialId - 材料调差期id
  33. * @param {Number} auditorId - 审核人id
  34. * @param {Number} times - 第几次审批
  35. * @return {Promise<*>}
  36. */
  37. async getAuditor(materialId, auditorId, times = 1) {
  38. 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` ' +
  39. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  40. ' WHERE la.`mid` = ? and la.`aid` = ? and la.`times` = ? ORDER BY la.`order` DESC';
  41. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditorId, times];
  42. return await this.db.queryOne(sql, sqlParam);
  43. }
  44. /**
  45. * 获取 审核列表信息
  46. *
  47. * @param {Number} materialId - 材料调差期id
  48. * @param {Number} times - 第几次审批
  49. * @return {Promise<*>}
  50. */
  51. async getAuditors(materialId, times = 1, order_sort = 'asc') {
  52. const sql = 'SELECT la.id, la.aid, la.times, la.order, la.status, la.opinion, la.is_old, la.begin_time, la.end_time, la.audit_type, la.audit_order,' +
  53. ' pa.name, pa.company, pa.role, pa.mobile, pa.telephone, pa.sign_path' +
  54. ` FROM ${this.tableName} la LEFT JOIN ${this.ctx.service.projectAccount.tableName} pa ON la.aid = pa.id` +
  55. ' WHERE la.mid = ? AND la.times = ?' +
  56. ' ORDER BY la.order ' + order_sort;
  57. const sqlParam = [materialId, times];
  58. const result = await this.db.query(sql, sqlParam);
  59. const max_sort = this._.max(result.map(x => { return x.audit_order; }));
  60. for (const i in result) {
  61. result[i].max_sort = max_sort;
  62. }
  63. return result;
  64. }
  65. async getLastestAuditors(materialId, times, status) {
  66. const sql =
  67. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.audit_type, la.audit_order,' +
  68. ' la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  69. ' FROM ' + this.tableName + ' AS la' +
  70. ' Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +
  71. ' WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ?' +
  72. ' ORDER BY `order` DESC';
  73. const sqlParam = [materialId, status, times ? times: 1];
  74. const result = await this.db.query(sql, sqlParam);
  75. if (result.length === 0) return [];
  76. return result.filter(x => { return x.order === result[0].order });
  77. }
  78. async getFinalAuditGroup(materialId, times = 1) {
  79. const sql =
  80. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, pa.`sign_path`, la.`times`, la.`mid`, la.`audit_order`, la.`audit_type`, Max(la.`order`) as max_order, GROUP_CONCAT(la.tp_data) as tp_data ' +
  81. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  82. ' WHERE la.`mid` = ? and la.`times` = ? GROUP BY la.`aid` ORDER BY la.`order`';
  83. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, times];
  84. const result = await this.db.query(sql, sqlParam);
  85. for (const r of result) {
  86. const auditor = await this.getDataByCondition({mid: materialId, aid: r.aid, times: r.times, order: r.max_order});
  87. r.status = auditor.status;
  88. r.opinion = auditor.opinion;
  89. r.begin_time = auditor.begin_time;
  90. r.end_time = auditor.end_time;
  91. }
  92. return result;
  93. }
  94. /**
  95. * 获取 当前审核人
  96. *
  97. * @param {Number} materialId - 材料调差期id
  98. * @param {Number} times - 第几次审批
  99. * @return {Promise<*>}
  100. */
  101. async getCurAuditor(materialId, times = 1) {
  102. const sql = 'SELECT la.`id`, 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`, la.audit_order ' +
  103. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  104. ' WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ?';
  105. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditConst.status.checking, times];
  106. return await this.db.queryOne(sql, sqlParam);
  107. }
  108. async getCurAuditors(materialId, times = 1) {
  109. const sql =
  110. '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`, la.audit_type, la.audit_order ' +
  111. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  112. ' WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ?';
  113. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditConst.status.checking, times];
  114. return await this.db.query(sql, sqlParam);
  115. }
  116. /**
  117. * 获取 最新审核顺序
  118. *
  119. * @param {Number} materialId - 材料调差期id
  120. * @param {Number} times - 第几次审批
  121. * @return {Promise<number>}
  122. */
  123. async getNewOrder(materialId, times = 1) {
  124. const sql = 'SELECT Max(??) As max_order, Max(audit_order) As max_audit_order FROM ?? Where `mid` = ? and `times` = ?';
  125. const sqlParam = ['order', this.tableName, materialId, times];
  126. const result = await this.db.queryOne(sql, sqlParam);
  127. return result && result.max_order ? [result.max_order + 1, result.max_audit_order + 1] : [1, 1];
  128. }
  129. /**
  130. * 新增审核人
  131. *
  132. * @param {Number} materialId - 材料调差期id
  133. * @param {Number} auditorId - 审核人id
  134. * @param {Number} times - 第几次审批
  135. * @return {Promise<number>}
  136. */
  137. async addAuditor(materialId, auditorId, times = 1, is_gdzs = 0) {
  138. const transaction = await this.db.beginTransaction();
  139. try {
  140. let [newOrder, newAuditOrder] = await this.getNewOrder(materialId, times);
  141. // 判断是否存在固定终审,存在则newOrder - 1并使终审order+1
  142. newOrder = is_gdzs === 1 ? newOrder - 1 : newOrder;
  143. newAuditOrder = is_gdzs === 1 ? newAuditOrder - 1 : newAuditOrder;
  144. if (is_gdzs) await this._syncOrderByDelete(transaction, materialId, newOrder, times, '+');
  145. const data = {
  146. tid: this.ctx.tender.id,
  147. mid: materialId,
  148. aid: auditorId,
  149. times,
  150. order: newOrder,
  151. status: auditConst.status.uncheck,
  152. audit_order: newAuditOrder,
  153. };
  154. const result = await transaction.insert(this.tableName, data);
  155. await transaction.commit();
  156. return result.effectRows = 1;
  157. } catch (err) {
  158. await transaction.rollback();
  159. throw err;
  160. }
  161. return false;
  162. }
  163. /**
  164. * 移除审核人时,同步其后审核人order
  165. * @param transaction - 事务
  166. * @param {Number} materialId - 材料调差期id
  167. * @param {Number} auditorId - 审核人id
  168. * @param {Number} times - 第几次审批
  169. * @return {Promise<*>}
  170. * @private
  171. */
  172. async _syncOrderByDelete(transaction, materialId, order, times, selfOperate = '-') {
  173. this.initSqlBuilder();
  174. this.sqlBuilder.setAndWhere('mid', {
  175. value: materialId,
  176. operate: '=',
  177. });
  178. this.sqlBuilder.setAndWhere('order', {
  179. value: order,
  180. operate: '>=',
  181. });
  182. this.sqlBuilder.setAndWhere('times', {
  183. value: times,
  184. operate: '=',
  185. });
  186. this.sqlBuilder.setUpdateData('order', {
  187. value: 1,
  188. selfOperate: selfOperate,
  189. });
  190. this.sqlBuilder.setUpdateData('audit_order', {
  191. value: 1,
  192. selfOperate: selfOperate,
  193. });
  194. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  195. const data = await transaction.query(sql, sqlParam);
  196. return data;
  197. }
  198. /**
  199. * 移除审核人
  200. *
  201. * @param {Number} materialId - 材料调差期id
  202. * @param {Number} auditorId - 审核人id
  203. * @param {Number} times - 第几次审批
  204. * @return {Promise<boolean>}
  205. */
  206. async deleteAuditor(materialId, auditorId, times = 1) {
  207. const transaction = await this.db.beginTransaction();
  208. try {
  209. const condition = { mid: materialId, aid: auditorId, times };
  210. const auditor = await this.getDataByCondition(condition);
  211. if (!auditor) {
  212. throw '该审核人不存在';
  213. }
  214. await transaction.delete(this.tableName, { mid: materialId, order: auditor.order, times});
  215. await this._syncOrderByDelete(transaction, materialId, auditor.order, times);
  216. await transaction.commit();
  217. } catch (err) {
  218. await transaction.rollback();
  219. throw err;
  220. }
  221. return true;
  222. }
  223. async getTpData(transaction, materialId, decimal = (this.ctx.material.decimal ? this.ctx.material.decimal : materialConst.decimal), exponent_decimal = (this.ctx.material.exponent_decimal ? this.ctx.material.exponent_decimal : materialConst.exponent_decimal)) {
  224. const materialInfo = await transaction.get(this.ctx.service.material.tableName, { id: materialId });
  225. const tp_data = {
  226. m_tp: materialInfo.m_tp !== null ? this.ctx.helper.round(materialInfo.m_tp, decimal.tp) : null,
  227. tax_tp: materialInfo.material_tax ? (materialInfo.m_tax_tp ? materialInfo.m_tax_tp : materialInfo.m_tp) :
  228. (materialInfo.m_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), decimal.tp) : null),
  229. ex_tp: materialInfo.ex_tp !== null ? this.ctx.helper.round(materialInfo.ex_tp, exponent_decimal.tp) : null,
  230. ex_tax_tp: materialInfo.ex_tax_tp !== null ? this.ctx.helper.round(materialInfo.ex_tax_tp, exponent_decimal.tp) : null,
  231. }
  232. tp_data.total_tp = this.ctx.helper.add(tp_data.m_tp, tp_data.ex_tp);
  233. tp_data.total_tax_tp = !materialInfo.material_tax ? this.ctx.helper.add(tp_data.tax_tp, tp_data.ex_tax_tp) : tp_data.ex_tax_tp;
  234. if (materialInfo.is_stage_self) {
  235. const materialStageList = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: materialId } });
  236. const stage_tp = [];
  237. for (const ms of materialStageList) {
  238. stage_tp.push({
  239. id: ms.id,
  240. sid: ms.sid,
  241. order: ms.order,
  242. m_tp: this.ctx.helper.round(ms.m_tp, decimal.tp),
  243. m_tax_tp: this.ctx.helper.round(ms.m_tax_tp, decimal.tp),
  244. });
  245. }
  246. tp_data.stage_tp = stage_tp;
  247. }
  248. return tp_data;
  249. }
  250. /**
  251. * 开始审批
  252. * @param {Number} materialId - 材料调差期id
  253. * @param {Number} times - 第几次审批
  254. * @return {Promise<boolean>}
  255. */
  256. async start(materialId, times = 1) {
  257. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, order: 1 } });
  258. if (audits.length === 0) {
  259. if(this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdspl) {
  260. throw '请联系管理员添加审批人';
  261. } else {
  262. throw '请先选择审批人,再上报数据';
  263. }
  264. }
  265. const transaction = await this.db.beginTransaction();
  266. try {
  267. const tp_data = await this.getTpData(transaction, materialId);
  268. const begin_time = new Date();
  269. const updateData = audits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time, tp_data: JSON.stringify(tp_data) } });
  270. await transaction.updateRows(this.tableName, updateData);
  271. await transaction.update(this.ctx.service.material.tableName, {
  272. id: materialId, status: auditConst.status.checking, tp_data: JSON.stringify(tp_data),
  273. });
  274. // 本期一些必要数据(如应耗数量和上期调差金额)插入到material_bills_history表里
  275. const materialBillsData = await this.ctx.service.materialBills.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
  276. if (materialBillsData.length === 0 && this.ctx.material.ex_expr === null) {
  277. if (!this.ctx.material.exponent_node && this.ctx.material.is_stage_self === 0) {
  278. throw '请至少使用一种调差方式';
  279. } else if (this.ctx.material.exponent_node) {
  280. const nodes = await this.ctx.service.materialExponentNode.getAllDataByCondition({ where: { mid: materialId } });
  281. const ex_exprs = this._.map(nodes, 'ex_expr');
  282. // 如果都为空或者null,则抛出错误
  283. if (ex_exprs.every(expr => expr === null || expr === '')) {
  284. throw '请至少使用一种调差方式';
  285. }
  286. } else if (!this.ctx.material.exponent_node && this.ctx.material.is_stage_self === 1) {
  287. const stages = await this.ctx.service.materialStage.getAllDataByCondition({where: {mid: materialId}});
  288. const stage_exprs = this._.map(stages, 'ex_expr');
  289. // 如果都为空或者null,则抛出错误
  290. if (stage_exprs.every(expr => expr === null || expr === '')) {
  291. throw '请至少使用一种调差方式';
  292. }
  293. }
  294. }
  295. // 微信模板通知
  296. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  297. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/material/' + materialInfo.order);
  298. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  299. const users = this._.map(audits, 'aid');
  300. const wechatData = {
  301. wap_url: shenpiUrl,
  302. qi: materialInfo.order,
  303. status: wxConst.status.check,
  304. tips: wxConst.tips.check,
  305. begin_time: Date.parse(new Date()),
  306. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), materialInfo.ex_tp),
  307. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), material_decimal.tp), materialInfo.ex_tax_tp),
  308. };
  309. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  310. for (const audit of audits) {
  311. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  312. pid: this.ctx.session.sessionProject.id,
  313. tid: this.ctx.tender.id,
  314. uid: audit.aid,
  315. sp_type: 'material',
  316. sp_id: audit.id,
  317. table_name: this.tableName,
  318. template: wxConst.template.material,
  319. wx_data: wechatData,
  320. });
  321. }
  322. // todo 更新标段tender状态 ?
  323. // 检查三方特殊推送
  324. await this.ctx.service.specMsg.addMaterialMsg(transaction, this.ctx.session.sessionProject.id, materialInfo, pushOperate.material.flow);
  325. await transaction.commit();
  326. } catch (err) {
  327. await transaction.rollback();
  328. throw err;
  329. }
  330. return true;
  331. }
  332. async _checked(pid, materialId, checkData, times) {
  333. const accountId = this.ctx.session.sessionUser.accountId;
  334. const time = new Date();
  335. // 整理当前流程审核人状态更新
  336. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, status: auditConst.status.checking } });
  337. if (audits.length === 0) throw '审核数据错误';
  338. const selfAudit = audits.find(x => { return x.aid === accountId; });
  339. if (!selfAudit) throw '当前标段您无权审批';
  340. const flowAudits = await this.getAllDataByCondition({ where: { mid: materialId, times, order: selfAudit.order } });
  341. const nextAudits = await this.getAllDataByCondition({ where: { mid: materialId, times, order: selfAudit.order + 1 } });
  342. const transaction = await this.db.beginTransaction();
  343. try {
  344. // 获取当前总金额及独立单价期的金额,添加到tp_data中,报表使用
  345. const tp_data = await this.getTpData(transaction, materialId);
  346. await transaction.update(this.tableName, {
  347. id: selfAudit.id,
  348. status: checkData.checkType,
  349. opinion: checkData.opinion,
  350. end_time: time,
  351. tp_data: JSON.stringify(tp_data),
  352. });
  353. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, selfAudit.id);
  354. // 获取推送必要信息
  355. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, materialId, accountId, checkData.opinion);
  356. const auditors = await this.getAuditorsWithOwner(materialId, times);
  357. // 添加推送
  358. const records = [];
  359. // const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checked, content: noticeContent }];
  360. auditors.forEach(audit => {
  361. records.push({ pid, tid: selfAudit.tid, type: pushType.material, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });
  362. });
  363. await transaction.insert('zh_notice', records);
  364. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  365. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  366. if (audits.length === 1 || selfAudit.audit_type === auditType.key.or) {
  367. // 或签更新他人审批状态
  368. if (selfAudit.audit_type === auditType.key.or) {
  369. const updateOther = [];
  370. for (const audit of audits) {
  371. if (audit.aid === selfAudit.aid) continue;
  372. updateOther.push({
  373. id: audit.id,
  374. status: auditConst.status.checkSkip,
  375. opinion: '',
  376. end_time: time,
  377. });
  378. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, audit.id);
  379. }
  380. if (updateOther.length > 0) transaction.updateRows(this.tableName, updateOther);
  381. }
  382. // 无下一审核人表示,审核结束
  383. if (nextAudits.length > 0) {
  384. // 复制一份下一审核人数据
  385. // await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, nextAudit.order, transaction);
  386. // 流程至下一审批人
  387. const updateData = nextAudits.map(x => {
  388. return {
  389. id: x.id,
  390. status: auditConst.status.checking,
  391. begin_time: time,
  392. tp_data: JSON.stringify(tp_data)
  393. };
  394. });
  395. await transaction.updateRows(this.tableName, updateData);
  396. // 同步 期信息
  397. await transaction.update(this.ctx.service.material.tableName, {
  398. id: materialId, status: auditConst.status.checking,
  399. });
  400. const begin_audit = await this.getDataByCondition({
  401. mid: materialId,
  402. order: 1,
  403. });
  404. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/material/' + materialInfo.order);
  405. // 微信模板通知
  406. const wechatData = {
  407. wap_url: shenpiUrl,
  408. qi: materialInfo.order,
  409. status: wxConst.status.check,
  410. tips: wxConst.tips.check,
  411. begin_time: Date.parse(begin_audit.begin_time),
  412. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), materialInfo.ex_tp),
  413. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1 + materialInfo.rate / 100), material_decimal.tp), materialInfo.ex_tax_tp),
  414. };
  415. await this.ctx.helper.sendWechat(this._.map(nextAudits, 'aid'), smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  416. // 重新发送配置
  417. for (const a of nextAudits) {
  418. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  419. pid: this.ctx.session.sessionProject.id,
  420. tid: this.ctx.tender.id,
  421. uid: a.aid,
  422. sp_type: 'material',
  423. sp_id: a.id,
  424. table_name: this.tableName,
  425. template: wxConst.template.material,
  426. wx_data: wechatData,
  427. });
  428. }
  429. // 检查三方特殊推送
  430. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  431. } else {
  432. // 本期结束
  433. // 同步 期信息
  434. await transaction.update(this.ctx.service.material.tableName, {
  435. id: materialId, status: checkData.checkType,
  436. });
  437. // 处理旧数据,防止重复插入到历史表
  438. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, {
  439. tid: this.ctx.tender.id,
  440. order: this.ctx.material.order
  441. });
  442. const mbhList = [];
  443. const materialBillsData = await this.ctx.service.materialBills.getAllDataByCondition({where: {tid: this.ctx.tender.id}});
  444. for (const mb of materialBillsData) {
  445. if (mb.code === '') {
  446. throw '调差工料编号不能为空';
  447. }
  448. const newMbh = {
  449. tid: this.ctx.tender.id,
  450. mid: this.ctx.material.id,
  451. order: this.ctx.material.order,
  452. mb_id: mb.id,
  453. quantity: mb.quantity,
  454. expr: mb.expr,
  455. msg_tp: mb.msg_tp,
  456. msg_times: mb.msg_times,
  457. msg_spread: mb.msg_spread,
  458. m_up_risk: mb.m_up_risk,
  459. m_down_risk: mb.m_down_risk,
  460. m_spread: mb.m_spread,
  461. m_tp: mb.m_tp,
  462. pre_tp: mb.pre_tp,
  463. m_tax_tp: mb.m_tax_tp,
  464. tax_pre_tp: mb.tax_pre_tp,
  465. origin: mb.origin,
  466. is_summary: mb.is_summary,
  467. m_tax: mb.m_tax,
  468. };
  469. mbhList.push(newMbh);
  470. }
  471. if (mbhList.length !== 0) await transaction.insert(this.ctx.service.materialBillsHistory.tableName, mbhList);
  472. // 处理旧数据,防止重复插入到历史表
  473. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, {
  474. tid: this.ctx.tender.id,
  475. order: this.ctx.material.order
  476. });
  477. const materialExponentData = await this.ctx.service.materialExponent.getAllDataByCondition({where: {tid: this.ctx.tender.id}});
  478. const mehList = [];
  479. for (const me of materialExponentData) {
  480. const newMeh = {
  481. tid: this.ctx.tender.id,
  482. mid: this.ctx.material.id,
  483. order: this.ctx.material.order,
  484. me_id: me.id,
  485. type: me.type,
  486. weight_num: me.weight_num,
  487. basic_price: me.basic_price,
  488. basic_times: me.basic_times,
  489. m_price: me.m_price,
  490. calc_num: me.calc_num,
  491. is_summary: me.is_summary,
  492. };
  493. mehList.push(newMeh);
  494. }
  495. if (mehList.length !== 0) await transaction.insert(this.ctx.service.materialExponentHistory.tableName, mehList);
  496. // 微信模板通知
  497. const begin_audit = await this.getDataByCondition({
  498. mid: materialId,
  499. order: 1,
  500. });
  501. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), materialInfo.user_id));
  502. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/material/' + materialInfo.order);
  503. const wechatData = {
  504. wap_url: shenpiUrl,
  505. qi: materialInfo.order,
  506. status: wxConst.status.success,
  507. tips: wxConst.tips.success,
  508. begin_time: Date.parse(begin_audit.begin_time),
  509. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), materialInfo.ex_tp),
  510. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1 + materialInfo.rate / 100), material_decimal.tp), materialInfo.ex_tax_tp),
  511. };
  512. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.result.toString(), wxConst.template.material, wechatData);
  513. // 检查三方特殊推送
  514. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  515. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.checked);
  516. }
  517. } else {
  518. // 同步 期信息
  519. await transaction.update(this.ctx.service.material.tableName, {
  520. id: materialId,
  521. status: auditConst.status.checking,
  522. });
  523. }
  524. await transaction.commit();
  525. } catch (err) {
  526. await transaction.rollback();
  527. throw err;
  528. }
  529. }
  530. async _checkNo(pid, materialId, checkData, times) {
  531. const accountId = this.ctx.session.sessionUser.accountId;
  532. const time = new Date();
  533. // 整理当前流程审核人状态更新
  534. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, status: auditConst.status.checking } });
  535. if (!audits) throw '审核数据错误';
  536. const selfAudit = audits.find(x => { return x.aid === accountId; });
  537. if (!selfAudit) throw '当前标段您无权审批';
  538. const flowAudits = await this.getAllDataByCondition({ where: { mid: materialId, times: selfAudit.times, order: selfAudit.order }});
  539. const auditors = await this.getUniqAuditor(materialId, times); // 全部参与的审批人
  540. const newAuditors = auditors.map(x => {
  541. return {
  542. aid: x.aid, tid: selfAudit.tid, mid: selfAudit.mid,
  543. times: times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  544. audit_type: x.audit_type, audit_order: x.audit_order,
  545. }
  546. });
  547. const transaction = await this.db.beginTransaction();
  548. try {
  549. const tp_data = await this.getTpData(transaction, materialId);
  550. const updateData = [];
  551. audits.forEach(x => {
  552. updateData.push({
  553. id: x.id,
  554. status: x.aid === selfAudit.aid ? checkData.checkType : auditConst.status.checkSkip,
  555. opinion: x.aid === selfAudit.aid ? checkData.opinion : '',
  556. end_time: x.aid === selfAudit.aid ? time : null,
  557. tp_data: JSON.stringify(tp_data),
  558. });
  559. });
  560. await transaction.updateRows(this.tableName, updateData);
  561. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  562. // 添加到消息推送表
  563. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, materialId, selfAudit.aid, checkData.opinion);
  564. const records = [{ pid, tid: selfAudit.tid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checkNo, content: noticeContent }];
  565. auditors.forEach(audit => {
  566. records.push({ pid, tid: selfAudit.tid, type: pushType.material, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });
  567. });
  568. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  569. // 同步期信息
  570. await transaction.update(this.ctx.service.material.tableName, {
  571. id: materialId, status: checkData.checkType,
  572. times: times + 1,
  573. tp_data: JSON.stringify(tp_data),
  574. });
  575. // 拷贝新一次审核流程列表
  576. await transaction.insert(this.tableName, newAuditors);
  577. // 微信模板通知
  578. const begin_audit = await this.getDataByCondition({
  579. mid: materialId,
  580. order: 1,
  581. });
  582. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  583. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  584. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), materialInfo.user_id));
  585. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/material/' + materialInfo.order);
  586. const wechatData = {
  587. wap_url: shenpiUrl,
  588. qi: materialInfo.order,
  589. status: wxConst.status.back,
  590. tips: wxConst.tips.back,
  591. begin_time: Date.parse(begin_audit.begin_time),
  592. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), materialInfo.ex_tp),
  593. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), material_decimal.tp), materialInfo.ex_tax_tp),
  594. };
  595. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.result.toString(), wxConst.template.material, wechatData);
  596. // 检查三方特殊推送
  597. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  598. await transaction.commit();
  599. } catch (err) {
  600. await transaction.rollback();
  601. throw err;
  602. }
  603. }
  604. async _checkNoPre(pid, materialId, checkData, times) {
  605. const accountId = this.ctx.session.sessionUser.accountId;
  606. const time = new Date();
  607. // 整理当前流程审核人状态更新
  608. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, status: auditConst.status.checking } });
  609. if (audits.length === 0 || audits[0].order <= 1) throw '审核数据错误';
  610. const selfAudit = audits.find(x => { return x.aid === accountId; });
  611. if (!selfAudit) throw '当前标段您无权审批';
  612. const flowAudits = await this.getAllDataByCondition({ where: { mid: materialId, times: selfAudit.times, order: selfAudit.order }});
  613. // 添加重新审批后,不能用order-1,取groupby值里的上一个才对
  614. const auditors2 = await this.getAuditGroupByList(materialId, times);
  615. const preAuditors = auditors2.filter(x => { return x.audit_order === selfAudit.audit_order - 1});
  616. const transaction = await this.db.beginTransaction();
  617. try {
  618. const tp_data = await this.getTpData(transaction, materialId);
  619. // 添加到消息推送表
  620. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, materialId, selfAudit.aid, checkData.opinion);
  621. const records = [{ pid, tid: selfAudit.tid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checkNoPre, content: noticeContent }];
  622. auditors2.forEach(audit => {
  623. records.push({ pid, tid: selfAudit.tid, type: pushType.material, uid: audit.aid, status: auditConst.status.checkNoPre, content: noticeContent });
  624. });
  625. await transaction.insert('zh_notice', records);
  626. const updateData = [];
  627. for (const audit of audits) {
  628. if (audit.aid === selfAudit.aid) {
  629. updateData.push({
  630. id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time, tp_data: JSON.stringify(tp_data)
  631. });
  632. } else {
  633. updateData.push({
  634. id: audit.id, status: auditConst.status.checkSkip, opinion: '', end_time: null, tp_data: JSON.stringify(tp_data)
  635. });
  636. }
  637. }
  638. await transaction.updateRows(this.tableName, updateData);
  639. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  640. // 顺移其后审核人流程顺序
  641. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE mid = ? AND times = ? AND `order` > ?';
  642. await transaction.query(sql, [materialId, selfAudit.times, selfAudit.order]);
  643. const newAuditors = [];
  644. preAuditors.forEach(x => {
  645. newAuditors.push({
  646. tid: selfAudit.tid, mid: materialId, aid: x.aid,
  647. times: x.times, order: selfAudit.order + 1,
  648. status: auditConst.status.checking, begin_time: time,
  649. audit_type: x.audit_type, audit_order: x.audit_order,
  650. tp_data: JSON.stringify(tp_data),
  651. });
  652. });
  653. const newAuditors_result = await transaction.insert(this.tableName, newAuditors);
  654. // 获取刚批量添加的所有list
  655. for (let j = 0; j < preAuditors.length; j++) {
  656. newAuditors[j].id = newAuditors_result.insertId + j;
  657. }
  658. const newFlowAuditors = [];
  659. flowAudits.forEach(x => {
  660. newFlowAuditors.push({
  661. tid: selfAudit.tid, mid: materialId, aid: x.aid,
  662. times: x.times, order: selfAudit.order + 2,
  663. status: auditConst.status.uncheck,
  664. audit_type: x.audit_type, audit_order: x.audit_order,
  665. });
  666. });
  667. await transaction.insert(this.tableName, newFlowAuditors);
  668. // 微信模板通知
  669. const begin_audit = await this.getDataByCondition({
  670. mid: materialId,
  671. order: 1,
  672. });
  673. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  674. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  675. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/material/' + materialInfo.order);
  676. const wechatData = {
  677. wap_url: shenpiUrl,
  678. qi: materialInfo.order,
  679. status: wxConst.status.check,
  680. tips: wxConst.tips.check,
  681. begin_time: Date.parse(begin_audit.begin_time),
  682. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), materialInfo.ex_tp),
  683. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), material_decimal.tp), materialInfo.ex_tax_tp),
  684. };
  685. await this.ctx.helper.sendWechat(this._.map(preAuditors, 'aid'), smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  686. for (const a of newAuditors) {
  687. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  688. pid: this.ctx.session.sessionProject.id,
  689. tid: this.ctx.tender.id,
  690. uid: a.aid,
  691. sp_type: 'material',
  692. sp_id: a.id,
  693. table_name: this.tableName,
  694. template: wxConst.template.material,
  695. wx_data: wechatData,
  696. });
  697. }
  698. // 检查三方特殊推送
  699. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  700. await transaction.commit();
  701. } catch (error) {
  702. await transaction.rollback();
  703. throw error;
  704. }
  705. }
  706. /**
  707. * 审批
  708. * @param {Number} materialId - 材料调差期id
  709. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  710. * @param {Number} times - 第几次审批
  711. * @return {Promise<void>}
  712. */
  713. async check(materialId, checkData, times = 1) {
  714. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo && checkData.checkType !== auditConst.status.checkNoPre) {
  715. throw '提交数据错误';
  716. }
  717. const pid = this.ctx.session.sessionProject.id;
  718. switch (checkData.checkType) {
  719. case auditConst.status.checked:
  720. await this._checked(pid, materialId, checkData, times);
  721. break;
  722. case auditConst.status.checkNo:
  723. await this._checkNo(pid, materialId, checkData, times);
  724. break;
  725. case auditConst.status.checkNoPre:
  726. await this._checkNoPre(pid, materialId, checkData, times);
  727. break;
  728. default:
  729. throw '无效审批操作';
  730. }
  731. }
  732. /**
  733. * 用于添加推送所需的content内容
  734. * @param {Number} pid 项目id
  735. * @param {Number} tid 台账id
  736. * @param {Number} mid 期id
  737. * @param {Number} uid 审批人id
  738. */
  739. async getNoticeContent(pid, tid, mid, uid, opinion = '') {
  740. const noticeSql = 'SELECT * FROM (SELECT ' +
  741. ' t.`id` As `tid`, ma.`mid`, t.`name`, m.`order`, pa.`name` As `su_name`, pa.role As `su_role`' +
  742. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  743. ' LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +
  744. ' LEFT JOIN ?? As ma ON m.`id` = ma.`mid`' +
  745. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  746. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  747. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.material.tableName, mid, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];
  748. const content = await this.db.query(noticeSql, noticeSqlParam);
  749. if (content.length) {
  750. content[0].opinion = opinion;
  751. }
  752. return content.length ? JSON.stringify(content[0]) : '';
  753. }
  754. /**
  755. * 审批
  756. * @param {Number} materialId - 材料调差期id
  757. * @param {Number} times - 第几次审批
  758. * @return {Promise<void>}
  759. */
  760. async checkAgain(materialId, times = 1) {
  761. const accountId = this.ctx.session.sessionUser.accountId;
  762. const time = new Date();
  763. // 整理当前流程审核人状态更新
  764. const auditors = await this.getAllDataByCondition({
  765. where: { mid: materialId, times },
  766. orders: [['order', 'asc']],
  767. });
  768. const maxOrder = auditors[auditors.length - 1].order;
  769. const audits = auditors.filter(x => { return x.order === maxOrder});
  770. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  771. const selfAudit = audits.find(x => { return x.aid === accountId; });
  772. if (!selfAudit) throw '当前标段您无权审批';
  773. const finalAudit = selfAudit || audits[0];
  774. const transaction = await this.db.beginTransaction();
  775. try {
  776. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  777. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  778. const material_exponent_decimal = materialInfo && materialInfo.exponent_decimal ? JSON.parse(materialInfo.exponent_decimal) : materialConst.exponent_decimal;
  779. const tp_data = await this.getTpData(transaction, materialId, material_decimal, material_exponent_decimal);
  780. const checkAgainAuditors = [], checkingAuditors = [];
  781. audits.forEach(x => {
  782. checkAgainAuditors.push({
  783. tid: x.tid, mid: x.mid, aid: x.aid,
  784. times: x.times, order: x.order + 1,
  785. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  786. begin_time: time, end_time: time, opinion: '',
  787. audit_type: x.audit_type, audit_order: x.audit_order,
  788. });
  789. });
  790. audits.forEach(x => {
  791. checkingAuditors.push({
  792. tid: x.tid, mid: x.mid, aid: x.aid,
  793. times: x.times, order: x.order + 2,
  794. status: auditConst.status.checking,
  795. begin_time: time, end_time: time, opinion: '',
  796. audit_type: x.audit_type, audit_order: x.audit_order,
  797. tp_data: JSON.stringify(tp_data),
  798. });
  799. });
  800. await transaction.insert(this.tableName, checkAgainAuditors);
  801. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  802. // 获取刚批量添加的所有list
  803. for (let j = 0; j < checkingAuditors.length; j++) {
  804. checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  805. }
  806. // 本期结束
  807. // 同步 期信息
  808. await transaction.update(this.ctx.service.material.tableName, {
  809. id: materialId, status: auditConst.status.checking,
  810. final_auditor_str: '',
  811. });
  812. // 微信模板通知
  813. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/material/' + materialInfo.order);
  814. const wechatData = {
  815. wap_url: shenpiUrl,
  816. qi: materialInfo.order,
  817. status: wxConst.status.check,
  818. tips: wxConst.tips.check,
  819. begin_time: Date.parse(new Date()),
  820. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), materialInfo.ex_tp),
  821. hs_m_tp: this.ctx.helper.add(this.ctx.helper.round(this.ctx.helper.mul(materialInfo.m_tp, 1+materialInfo.rate/100), material_decimal.tp), materialInfo.ex_tax_tp),
  822. };
  823. await this.ctx.helper.sendWechat(this._.map(checkingAuditors, 'aid'), smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  824. for (const a of checkingAuditors) {
  825. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  826. pid: this.ctx.session.sessionProject.id,
  827. tid: this.ctx.tender.id,
  828. uid: a.aid,
  829. sp_type: 'material',
  830. sp_id: a.id,
  831. table_name: this.tableName,
  832. template: wxConst.template.material,
  833. wx_data: wechatData,
  834. });
  835. }
  836. // 检查三方特殊推送
  837. await this.ctx.service.specMsg.addMaterialMsg(transaction, this.ctx.session.sessionProject.id, materialInfo, pushOperate.material.flow);
  838. await transaction.commit();
  839. } catch (err) {
  840. await transaction.rollback();
  841. throw err;
  842. }
  843. }
  844. /**
  845. * 获取审核人需要审核的期列表
  846. *
  847. * @param auditorId
  848. * @return {Promise<*>}
  849. */
  850. async getAuditMaterial(auditorId, spid = '') {
  851. const spSql = spid ? ' and t.`spid` = "' + spid + '"' : '';
  852. const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`mid`,' +
  853. ' m.`order` As `morder`, m.`status` As `mstatus`,' +
  854. ' t.`name`, t.`project_id`, t.`type`, t.`user_id`, t.`spid` ' +
  855. ' FROM ?? AS ma' +
  856. ' LEFT JOIN ?? AS m On ma.mid = m.id' +
  857. ' LEFT JOIN ?? As t On m.tid = t.id' +
  858. ' WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`user_id` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' + spSql +
  859. ' ORDER BY ma.`begin_time` DESC';
  860. 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];
  861. const result = await this.db.query(sql, sqlParam);
  862. // 过滤result中存在重复sid的值, 保留最新的一条
  863. const filterResult = [];
  864. const midArr = [];
  865. for (const r of result) {
  866. if (midArr.indexOf(r.mid) === -1) {
  867. filterResult.push(r);
  868. midArr.push(r.mid);
  869. }
  870. }
  871. return filterResult;
  872. }
  873. /**
  874. * 获取审核人审核的次数
  875. *
  876. * @param auditorId
  877. * @return {Promise<*>}
  878. */
  879. async getCountByChecked(auditorId, spid = '') {
  880. if (spid) {
  881. const sql = 'SELECT count(*) AS count FROM ?? AS a LEFT JOIN ?? AS t ON a.tid = t.id WHERE a.`aid` = ? AND a.`status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo, auditConst.status.checkNoPre]) + ') AND t.`spid` = ?';
  882. const sqlParam = [this.tableName, this.ctx.service.tender.tableName, auditorId, spid];
  883. const result = await this.db.queryOne(sql, sqlParam);
  884. return result.count ? result.count : 0;
  885. }
  886. return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo, auditConst.status.checkNoPre] });
  887. }
  888. /**
  889. * 获取最近一次审批结束时间
  890. *
  891. * @param auditorId
  892. * @return {Promise<*>}
  893. */
  894. async getLastEndTimeByChecked(auditorId, spid = '') {
  895. const sqSql = spid ? ' AND t.`spid` = "' + spid + '"' : '';
  896. const sql = 'SELECT a.`end_time` FROM ?? AS a LEFT JOIN ?? AS t ON a.`tid` = t.`id` WHERE a.`aid` = ? ' +
  897. 'AND a.`status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo]) + ')' + sqSql +
  898. ' ORDER BY a.`end_time` DESC';
  899. const sqlParam = [this.tableName, this.ctx.service.tender.tableName, auditorId];
  900. const result = await this.db.queryOne(sql, sqlParam);
  901. return result ? result.end_time : null;
  902. }
  903. /**
  904. * 获取 某时间后 审批进度 更新的期
  905. * @param {Number} pid - 查询标段
  906. * @param {Number} uid - 查询人
  907. * @param {Date} time - 查询时间
  908. * @return {Promise<*>}
  909. */
  910. async getNoticeMaterial(pid, uid, time) {
  911. // const sql = 'SELECT * FROM (SELECT t.`name`, t.`project_id`, t.`type`, t.`user_id`, ' +
  912. // ' m.`order` As `m_order`, m.`status` As `m_status`, ' +
  913. // ' ma.`aid`, ma.`times`, ma.`order`, ma.`end_time`, ma.`tid`, ma.`mid`, ma.`status`, ' +
  914. // ' pa.`name` As `su_name`, pa.role As `su_role`, pa.company As `su_company`' +
  915. // ' FROM (SELECT * FROM ?? WHERE `user_id` = ? OR `id` in (SELECT `tid` FROM ?? WHERE `aid` = ? GROUP BY `tid`)) As t' +
  916. // ' LEFT JOIN ?? As m On t.`id` = m.`tid`' +
  917. // ' LEFT JOIN ?? As ma ON m.`id` = ma.`mid`' +
  918. // ' LEFT JOIN ?? As pa ON ma.`aid` = pa.`id`' +
  919. // ' WHERE ma.`end_time` > ? and t.`project_id` = ?' +
  920. // ' ORDER By ma.`end_time` DESC LIMIT 1000) as new_t GROUP BY new_t.`tid`' +
  921. // ' ORDER BY new_t.`end_time`';
  922. // const sqlParam = [this.ctx.service.tender.tableName, uid, this.tableName, uid, this.ctx.service.material.tableName, this.tableName,
  923. // this.ctx.service.projectAccount.tableName, time, pid];
  924. // return await this.db.query(sql, sqlParam);
  925. let notice = await this.db.select('zh_notice', {
  926. where: { pid, type: pushType.material, uid },
  927. orders: [['create_time', 'desc']],
  928. limit: 10, offset: 0,
  929. });
  930. notice = notice.map(v => {
  931. const extra = JSON.parse(v.content);
  932. delete v.content;
  933. return { ...v, ...extra };
  934. });
  935. return notice;
  936. }
  937. /**
  938. * 获取审核人流程列表
  939. *
  940. * @param auditorId
  941. * @return {Promise<*>}
  942. */
  943. async getAuditGroupByList(materialId, times) {
  944. // const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`tid`, la.`mid`, la.`aid`, la.`order`, la.`status`, la.audit_type, la.audit_order ' +
  945. // ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  946. // ' WHERE la.`mid` = ? and la.`times` = ? GROUP BY la.`aid` ORDER BY la.`order`';
  947. // const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, times];
  948. const sql =
  949. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`order`, la.`status`, la.audit_type, la.audit_order ' +
  950. ' FROM (SELECT `aid`, max(`order`) `order` FROM ?? WHERE `mid` = ? and `times` = ? and `is_old` = ? GROUP BY aid) sa' +
  951. ' LEFT JOIN ?? la ON sa.`aid` = la.`aid` AND sa.`order` = la.`order`' +
  952. ' Left JOIN ?? AS pa On la.`aid` = pa.`id` WHERE la.`mid` = ? and la.`times` = ? and la.`is_old` = ? order BY la.`order`';
  953. const sqlParam = [this.tableName, materialId, times, 0, this.tableName, this.ctx.service.projectAccount.tableName, materialId, times, 0];
  954. return await this.db.query(sql, sqlParam);
  955. }
  956. /**
  957. * 获取审核人流程列表(包括原报)
  958. * @param {Number} materialId 调差id
  959. * @param {Number} times 审核次数
  960. * @return {Promise<Array>} 查询结果集(包括原报)
  961. */
  962. async getAuditorsWithOwner(materialId, times = 1) {
  963. const result = await this.getAuditGroupByList(materialId, times);
  964. const sql =
  965. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As mid, 0 As `order`' +
  966. ' FROM ' +
  967. this.ctx.service.material.tableName +
  968. ' As s' +
  969. ' LEFT JOIN ' +
  970. this.ctx.service.projectAccount.tableName +
  971. ' As pa' +
  972. ' ON s.user_id = pa.id' +
  973. ' WHERE s.id = ?';
  974. const sqlParam = [times, materialId, materialId];
  975. const user = await this.db.queryOne(sql, sqlParam);
  976. result.unshift(user);
  977. return result;
  978. }
  979. /**
  980. * 获取tender下所有的审核列表(报表用)
  981. * @param {Number} tenderId
  982. */
  983. async getAuditorsByTender(tenderId) {
  984. const sql = 'SELECT la.`tid`, la.`mid`, la.`aid`, la.`order`, la.`times`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`' +
  985. ' FROM ?? AS la ' +
  986. ' WHERE la.`tid` = ?';
  987. const sqlParam = [this.tableName, tenderId];
  988. return await this.db.query(sql, sqlParam);
  989. }
  990. /**
  991. * 复制上一期的审批人列表给最新一期
  992. *
  993. * @param transaction - 新增一期的事务
  994. * @param {Object} preMaterial - 上一期
  995. * @param {Object} newaMaterial - 最新一期
  996. * @return {Promise<*>}
  997. */
  998. async copyPreMaterialAuditors(transaction, preMaterial, newMaterial) {
  999. const auditors = await this.getAuditGroupByList(preMaterial.id, preMaterial.times);
  1000. const newAuditors = [];
  1001. for (const a of auditors) {
  1002. const na = {
  1003. tid: preMaterial.tid,
  1004. mid: newMaterial.id,
  1005. aid: a.aid,
  1006. times: newMaterial.times,
  1007. order: a.audit_order,
  1008. status: auditConst.status.uncheck,
  1009. audit_type: a.audit_type,
  1010. audit_order: a.audit_order,
  1011. };
  1012. newAuditors.push(na);
  1013. }
  1014. if (newAuditors.length > 0) {
  1015. const result = await transaction.insert(this.tableName, newAuditors);
  1016. return (result.effectRows = auditors.length);
  1017. } else {
  1018. return true;
  1019. }
  1020. }
  1021. /**
  1022. * 移除审核人
  1023. *
  1024. * @param {Number} materialId - 材料调差期id
  1025. * @param {Number} status - 期状态
  1026. * @param {Number} status - 期次数
  1027. * @return {Promise<boolean>}
  1028. */
  1029. async getAuditorByStatus(materialId, status, times = 1) {
  1030. let auditor = null;
  1031. let sql = '';
  1032. let sqlParam = '';
  1033. switch (status) {
  1034. case auditConst.status.checking :
  1035. case auditConst.status.checked :
  1036. case auditConst.status.checkNoPre :
  1037. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  1038. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1039. ' WHERE la.`mid` = ? and la.`status` = ? ' +
  1040. ' ORDER BY la.`times` desc, la.`order` desc';
  1041. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, status];
  1042. auditor = await this.db.queryOne(sql, sqlParam);
  1043. break;
  1044. case auditConst.status.checkNo :
  1045. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  1046. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  1047. ' WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ?' +
  1048. ' ORDER BY la.`times` desc, la.`order` desc';
  1049. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditConst.status.checkNo, parseInt(times) - 1];
  1050. auditor = await this.db.queryOne(sql, sqlParam);
  1051. break;
  1052. case auditConst.status.uncheck :
  1053. default:break;
  1054. }
  1055. return auditor;
  1056. }
  1057. async getAuditorsByStatus(materialId, status, times = 1) {
  1058. let auditor = [];
  1059. let sql = '';
  1060. let sqlParam = '';
  1061. let cur;
  1062. switch (status) {
  1063. case auditConst.status.checking:
  1064. case auditConst.status.checked:
  1065. case auditConst.status.checkNoPre:
  1066. cur = await this.db.queryOne(`SELECT * From ${this.tableName} where mid = ? AND times = ? AND status = ? ORDER By times DESC, ` + '`order` DESC', [materialId, times, status]);
  1067. if (!cur) return [];
  1068. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`order`, la.`status`, la.audit_order, la.audit_type ' +
  1069. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1070. ' WHERE la.`mid` = ? and la.`order` = ? and times = ?';
  1071. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, cur.order, times];
  1072. auditor = await this.db.query(sql, sqlParam);
  1073. break;
  1074. case auditConst.status.checkNo:
  1075. cur = await this.db.queryOne(`SELECT * From ${this.tableName} where mid = ? AND times = ? AND status = ? ORDER By times DESC, ` + '`order` DESC', [materialId, parseInt(times) - 1, status]);
  1076. if (!cur) return [];
  1077. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`order`, la.`status`, la.audit_order, la.audit_type ' +
  1078. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1079. ' WHERE la.`mid` = ? and la.`order` = ? and la.`times` = ?';
  1080. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, cur.order, parseInt(times) - 1];
  1081. auditor = await this.db.query(sql, sqlParam);
  1082. break;
  1083. case auditConst.status.uncheck:
  1084. default:
  1085. break;
  1086. }
  1087. return auditor;
  1088. }
  1089. async getAllAuditors(tenderId) {
  1090. const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +
  1091. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +
  1092. ' WHERE t.id = ?' +
  1093. ' GROUP BY ma.aid';
  1094. const sqlParam = [tenderId];
  1095. return this.db.query(sql, sqlParam);
  1096. }
  1097. /**
  1098. * 取待审批期列表(wap用)
  1099. *
  1100. * @param auditorId
  1101. * @return {Promise<*>}
  1102. */
  1103. async getAuditMaterialByWap(auditorId) {
  1104. const sql =
  1105. 'SELECT sa.`aid`, sa.`times`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`mid`,' +
  1106. // ' s.`order` As `sorder`, s.`status` As `sstatus`, s.`s_time`, s.`contract_tp`, s.`qc_tp`, s.`pre_contract_tp`, s.`pre_qc_tp`, s.`yf_tp`, s.`pre_yf_tp`, ' +
  1107. ' s.*,' +
  1108. ' t.`name`, t.`project_id`, t.`type`, t.`user_id`, t.`spid`,' +
  1109. ' ti.`deal_info` ' +
  1110. ' FROM ?? AS sa' +
  1111. ' Left Join ?? AS s On sa.`mid` = s.`id`' +
  1112. ' Left Join ?? As t On sa.`tid` = t.`id`' +
  1113. ' Left Join ?? AS ti ON ti.`tid` = t.`id`' +
  1114. ' WHERE sa.`aid` = ? and sa.`status` = ?';
  1115. const sqlParam = [
  1116. this.tableName,
  1117. this.ctx.service.material.tableName,
  1118. this.ctx.service.tender.tableName,
  1119. this.ctx.service.tenderInfo.tableName,
  1120. auditorId,
  1121. auditConst.status.checking,
  1122. ];
  1123. return await this.db.query(sql, sqlParam);
  1124. }
  1125. async updateNewAuditList(material, newList) {
  1126. const transaction = await this.db.beginTransaction();
  1127. try {
  1128. // 先删除旧的审批流,再添加新的
  1129. await transaction.delete(this.tableName, { mid: material.id, times: material.times });
  1130. const newAuditors = [];
  1131. for (const auditor of newList) {
  1132. newAuditors.push({
  1133. tid: material.tid, mid: material.id, aid: auditor.audit_id,
  1134. times: material.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1135. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1136. });
  1137. }
  1138. if(newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1139. await transaction.commit();
  1140. } catch (err) {
  1141. await transaction.rollback();
  1142. throw err;
  1143. }
  1144. }
  1145. async updateLastAudit(material, auditList, lastId) {
  1146. const transaction = await this.db.beginTransaction();
  1147. try {
  1148. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1149. const existAudit = auditList.find(x => { return x.aid === lastId });
  1150. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order)}, 0) + 1 : 1; // 最大值 + 1
  1151. // const idList = this._.map(auditList, 'aid');
  1152. // let order = idList.length + 1;
  1153. if (existAudit) {
  1154. await transaction.delete(this.tableName, {mid: material.id, times: material.times, aid: lastId});
  1155. const sameOrder = auditList.filter(x => { return x.order === existAudit.order });
  1156. if (sameOrder.length === 1) {
  1157. const updateData = [];
  1158. auditList.forEach(x => {
  1159. if (x.order <= existAudit.order) return;
  1160. updateData.push({id: x.id, order: x.order - 1, audit_order: x.audit_order - 1});
  1161. });
  1162. if (updateData.length > 0) {
  1163. await transaction.updateRows(this.tableName, updateData);
  1164. }
  1165. order = order - 1;
  1166. }
  1167. }
  1168. // 添加终审
  1169. const newAuditor = {
  1170. tid: material.tid, mid: material.id, aid: lastId,
  1171. times: material.times, order, status: auditConst.status.uncheck,
  1172. audit_type: auditType.key.common, audit_order: order,
  1173. };
  1174. await transaction.insert(this.tableName, newAuditor);
  1175. await transaction.commit();
  1176. } catch (err) {
  1177. await transaction.rollback();
  1178. throw err;
  1179. }
  1180. }
  1181. async getNumByMonth(tid, startMonth, endMonth) {
  1182. const sql = 'SELECT COUNT(*) as num FROM ?? t1 JOIN (SELECT MAX(id) as max_id FROM ?? WHERE tid = ? GROUP BY mid) t2 ON t1.id = t2.max_id WHERE t1.status = ? AND t1.end_time between ? and ?';
  1183. // const sql = 'SELECT COUNT(*) as num FROM ?? WHERE id in (SELECT MAX(id) FROM ?? WHERE tid = ? GROUP BY mid) AND status = ? AND end_time between ? and ?';
  1184. const sqlParam = [this.tableName, this.tableName, tid, auditConst.status.checked, startMonth, endMonth];
  1185. const result = await this.db.queryOne(sql, sqlParam);
  1186. return result ? result.num : 0;
  1187. }
  1188. /**
  1189. * 删除本次审批流程
  1190. * @param {Number} materialId - 调差id
  1191. * @param {Number} times - 第几次审批
  1192. * @param {Object} data - 更改参数
  1193. * @return {Promise<void>}
  1194. */
  1195. async saveAudit(materialId, times, sp_group, data) {
  1196. const transaction = await this.db.beginTransaction();
  1197. try {
  1198. const auditors = await this.getAuditGroupByList(materialId, times);
  1199. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1200. if (data.operate !== 'del') {
  1201. const exist = await this.getDataByCondition({ mid: materialId, times, aid: data.new_aid, is_old: 0 });
  1202. if (exist) throw '该审核人已存在,请勿重复添加';
  1203. }
  1204. if (data.operate === 'add') {
  1205. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1206. throw '当前人下无法操作新增';
  1207. }
  1208. const newAudit = {
  1209. tid: this.ctx.tender.id,
  1210. mid: materialId,
  1211. aid: data.new_aid,
  1212. order: now_audit.order + 1,
  1213. audit_order: now_audit.audit_order + 1,
  1214. audit_type: auditType.key.common,
  1215. times: times,
  1216. status: 1
  1217. };
  1218. // order+1
  1219. await this._syncOrderByDelete(transaction, materialId, now_audit.order+1, times, '+');
  1220. await transaction.insert(this.tableName, newAudit);
  1221. // 更新审批流程页数据,如果存在
  1222. } else if (data.operate === 'add-sibling') {
  1223. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1224. throw '当前人下无法操作新增';
  1225. }
  1226. const newAudit = {
  1227. tid: this.ctx.tender.id,
  1228. mid: materialId,
  1229. aid: data.new_aid,
  1230. order: now_audit.order,
  1231. audit_order: now_audit.audit_order,
  1232. audit_type: now_audit.audit_type,
  1233. times: times,
  1234. status: 1
  1235. };
  1236. await transaction.insert(this.tableName, newAudit);
  1237. } else if (data.operate === 'del') {
  1238. if (now_audit.status !== auditConst.status.uncheck) {
  1239. throw '当前人无法操作删除';
  1240. }
  1241. const flowAuditors = auditors.filter(x => { return x.order === now_audit.order; });
  1242. await transaction.delete(this.tableName, { mid: materialId, times, aid: now_audit.aid, order: now_audit.order });
  1243. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, materialId, now_audit.order, times);
  1244. // 旧的更新为is_old为1
  1245. await transaction.update(this.tableName, { is_old: 1 }, {
  1246. where: {
  1247. mid: materialId,
  1248. times,
  1249. aid: data.old_aid,
  1250. }
  1251. });
  1252. } else if (data.operate === 'change') {
  1253. const nowAudit = await this.getDataByCondition({ mid: materialId, times, aid: now_audit.aid, order: now_audit.order });
  1254. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1255. throw '当前人无法操作替换';
  1256. }
  1257. nowAudit.aid = data.new_aid;
  1258. await transaction.update(this.tableName, nowAudit);
  1259. // 旧的更新为is_old为1
  1260. await transaction.update(this.tableName, { is_old: 1 }, {
  1261. where: {
  1262. mid: materialId,
  1263. times,
  1264. aid: data.old_aid,
  1265. }
  1266. });
  1267. }
  1268. if (this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdspl) {
  1269. const newAuditors = await transaction.select(this.tableName, { where: { mid: materialId, times } });
  1270. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors.filter(x => { return x.is_old === 0; }));
  1271. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1272. await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.material, shenpiConst.sp_type.material, uniqNewAuditorGroup, sp_group);
  1273. } else if (this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs) {
  1274. const newAuditors = await this.getAuditGroupByList(materialId, times, transaction);
  1275. await this.ctx.service.shenpiAudit.updateAuditList(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.material, shenpiConst.sp_type.material, this._.map(newAuditors, 'aid'));
  1276. }
  1277. // 更新到审批流程方法
  1278. await transaction.commit();
  1279. } catch (err) {
  1280. await transaction.rollback();
  1281. throw err;
  1282. }
  1283. }
  1284. async getAuditorGroup(materialId, times) {
  1285. const auditors = await this.getAuditors(materialId, times); // 全部参与的审批人
  1286. const newAuditors = auditors.filter(x => { return x.is_old === 0; });
  1287. return this.ctx.helper.groupAuditors(newAuditors);
  1288. }
  1289. async getUserGroup(materialId, times) {
  1290. const group = await this.getAuditorGroup(materialId, times);
  1291. const sql =
  1292. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As mid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1293. ' FROM ' + this.ctx.service.material.tableName + ' As m' +
  1294. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1295. ' ON m.user_id = pa.id' +
  1296. ' WHERE m.id = ?';
  1297. const sqlParam = [times, materialId, materialId];
  1298. const user = await this.db.queryOne(sql, sqlParam);
  1299. group.unshift([ user ]);
  1300. return group;
  1301. }
  1302. async getUniqUserGroup(materialId, times) {
  1303. const group = await this.getAuditorGroup(materialId, times);
  1304. const sql =
  1305. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As mid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1306. ' FROM ' + this.ctx.service.material.tableName + ' As m' +
  1307. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1308. ' ON m.user_id = pa.id' +
  1309. ' WHERE m.id = ?';
  1310. const sqlParam = [times, materialId, materialId];
  1311. const user = await this.db.queryOne(sql, sqlParam);
  1312. user.audit_order = 0;
  1313. group.unshift([ user ]);
  1314. return this.ctx.helper.groupAuditorsUniq(group);
  1315. }
  1316. async getAuditorHistory(materialId, times, reverse = false) {
  1317. const history = [];
  1318. if (times >= 1) {
  1319. for (let i = 1; i <= times; i++) {
  1320. const auditors = await this.getAuditors(materialId, i);
  1321. const group = this.ctx.helper.groupAuditors(auditors);
  1322. const historyGroup = [];
  1323. const max_order = group.length > 0 && group[group.length - 1].length > 0 ? group[group.length - 1][0].audit_order : -1;
  1324. for (const g of group) {
  1325. const his = {
  1326. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  1327. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  1328. auditors: g
  1329. };
  1330. if (his.audit_type === auditType.key.common) {
  1331. his.name = g[0].name;
  1332. } else {
  1333. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  1334. }
  1335. his.is_final = his.audit_order === max_order;
  1336. if (g[0].begin_time) {
  1337. his.begin_time = g[0].begin_time;
  1338. const beginTime = this.ctx.moment(g[0].begin_time);
  1339. his.beginYear = beginTime.format('YYYY');
  1340. his.beginDate = beginTime.format('MM-DD');
  1341. his.beginTime = beginTime.format('HH:mm:ss');
  1342. }
  1343. let end_time;
  1344. g.forEach(x => {
  1345. if (x.status === auditConst.status.checkSkip) return;
  1346. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  1347. if (x.end_time && (!end_time || x.end_time > end_time)) {
  1348. end_time = x.end_time;
  1349. if (his.status !== auditConst.status.checking) his.status = x.status;
  1350. }
  1351. });
  1352. if (end_time) {
  1353. his.end_time = end_time;
  1354. const endTime = this.ctx.moment(end_time);
  1355. his.endYear = endTime.format('YYYY');
  1356. his.endDate = endTime.format('MM-DD');
  1357. his.endTime = endTime.format('HH:mm:ss');
  1358. }
  1359. historyGroup.push(his);
  1360. }
  1361. if (reverse) {
  1362. history.push(historyGroup.reverse());
  1363. } else {
  1364. history.push(historyGroup);
  1365. }
  1366. }
  1367. }
  1368. return history;
  1369. }
  1370. async getUniqAuditor(materialId, times) {
  1371. const auditors = await this.getAuditors(materialId, times); // 全部参与的审批人
  1372. const result = [];
  1373. auditors.forEach(x => {
  1374. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === r.audit_order; }) < 0) {
  1375. result.push(x);
  1376. }
  1377. });
  1378. return result;
  1379. }
  1380. /**
  1381. * 获取审核人已经审核过的审批信息(包括退回,通过,重新审批等)
  1382. *
  1383. * @param auditorId
  1384. * @return {Promise<*>}
  1385. */
  1386. async getDonesByAudit(auditorId, spid = '') {
  1387. const spSql = spid ? ' and t.`spid` = "' + spid + '"' : '';
  1388. const status = [auditConst.status.checked, auditConst.status.checkNo, auditConst.status.checkNoPre, auditConst.status.checkAgain];
  1389. const sql =
  1390. 'SELECT la.`status`, la.`end_time` as `shenpi_time`, la.`mid`, t.`id`, m.`order` As `morder`, t.`name`, t.`spid` ' +
  1391. ' FROM ?? AS la Left Join ?? AS t ON la.`tid` = t.`id` LEFT JOIN ?? AS m ON la.`mid` = m.`id`' +
  1392. ' WHERE la.`aid` = ? AND la.`status` in (' + this.ctx.helper.getInArrStrSqlFilter(status) +')' + spSql +
  1393. ' ORDER BY la.`end_time` DESC';
  1394. const sqlParam = [
  1395. this.tableName,
  1396. this.ctx.service.tender.tableName,
  1397. this.ctx.service.material.tableName,
  1398. auditorId,
  1399. ];
  1400. return await this.db.query(sql, sqlParam);
  1401. }
  1402. }
  1403. return MaterialAudit;
  1404. };