material_audit.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  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, 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)) {
  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, decimal.tp) : null,
  230. ex_tax_tp: materialInfo.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.exponent_rate/100), 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. throw '请至少使用一种调差方式';
  278. }
  279. // 微信模板通知
  280. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  281. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  282. const users = this._.map(audits, 'aid');
  283. const wechatData = {
  284. qi: materialInfo.order,
  285. status: wxConst.status.check,
  286. tips: wxConst.tips.check,
  287. begin_time: Date.parse(new Date()),
  288. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), this.ctx.helper.round(materialInfo.ex_tp, material_decimal.tp)),
  289. 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), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.exponent_rate/100), material_decimal.tp)),
  290. };
  291. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  292. for (const audit of audits) {
  293. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  294. pid: this.ctx.session.sessionProject.id,
  295. tid: this.ctx.tender.id,
  296. uid: audit.aid,
  297. sp_type: 'material',
  298. sp_id: audit.id,
  299. table_name: this.tableName,
  300. template: wxConst.template.material,
  301. wx_data: wechatData,
  302. });
  303. }
  304. // todo 更新标段tender状态 ?
  305. // 检查三方特殊推送
  306. await this.ctx.service.specMsg.addMaterialMsg(transaction, this.ctx.session.sessionProject.id, materialInfo, pushOperate.material.flow);
  307. await transaction.commit();
  308. } catch (err) {
  309. await transaction.rollback();
  310. throw err;
  311. }
  312. return true;
  313. }
  314. async _checked(pid, materialId, checkData, times) {
  315. const accountId = this.ctx.session.sessionUser.accountId;
  316. const time = new Date();
  317. // 整理当前流程审核人状态更新
  318. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, status: auditConst.status.checking } });
  319. if (audits.length === 0) throw '审核数据错误';
  320. const selfAudit = audits.find(x => { return x.aid === accountId; });
  321. if (!selfAudit) throw '当前标段您无权审批';
  322. const flowAudits = await this.getAllDataByCondition({ where: { mid: materialId, times, order: selfAudit.order } });
  323. const nextAudits = await this.getAllDataByCondition({ where: { mid: materialId, times, order: selfAudit.order + 1 } });
  324. const transaction = await this.db.beginTransaction();
  325. try {
  326. // 获取当前总金额及独立单价期的金额,添加到tp_data中,报表使用
  327. const tp_data = await this.getTpData(transaction, materialId);
  328. await transaction.update(this.tableName, {
  329. id: selfAudit.id,
  330. status: checkData.checkType,
  331. opinion: checkData.opinion,
  332. end_time: time,
  333. tp_data: JSON.stringify(tp_data),
  334. });
  335. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, selfAudit.id);
  336. // 获取推送必要信息
  337. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, materialId, accountId, checkData.opinion);
  338. const auditors = await this.getAuditorsWithOwner(materialId, times);
  339. // 添加推送
  340. const records = [];
  341. // const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checked, content: noticeContent }];
  342. auditors.forEach(audit => {
  343. records.push({ pid, type: pushType.material, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });
  344. });
  345. await transaction.insert('zh_notice', records);
  346. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  347. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  348. if (audits.length === 1 || selfAudit.audit_type === auditType.key.or) {
  349. // 或签更新他人审批状态
  350. if (selfAudit.audit_type === auditType.key.or) {
  351. const updateOther = [];
  352. for (const audit of audits) {
  353. if (audit.aid === selfAudit.aid) continue;
  354. updateOther.push({
  355. id: audit.id,
  356. status: auditConst.status.checkSkip,
  357. opinion: '',
  358. end_time: time,
  359. });
  360. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, audit.id);
  361. }
  362. if (updateOther.length > 0) transaction.updateRows(this.tableName, updateOther);
  363. }
  364. // 无下一审核人表示,审核结束
  365. if (nextAudits.length > 0) {
  366. // 复制一份下一审核人数据
  367. // await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, nextAudit.order, transaction);
  368. // 流程至下一审批人
  369. const updateData = nextAudits.map(x => {
  370. return {
  371. id: x.id,
  372. status: auditConst.status.checking,
  373. begin_time: time,
  374. tp_data: JSON.stringify(tp_data)
  375. };
  376. });
  377. await transaction.updateRows(this.tableName, updateData);
  378. // 同步 期信息
  379. await transaction.update(this.ctx.service.material.tableName, {
  380. id: materialId, status: auditConst.status.checking,
  381. });
  382. const begin_audit = await this.getDataByCondition({
  383. mid: materialId,
  384. order: 1,
  385. });
  386. // 微信模板通知
  387. const wechatData = {
  388. qi: materialInfo.order,
  389. status: wxConst.status.check,
  390. tips: wxConst.tips.check,
  391. begin_time: Date.parse(begin_audit.begin_time),
  392. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), this.ctx.helper.round(materialInfo.ex_tp, material_decimal.tp)),
  393. 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), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1 + materialInfo.exponent_rate / 100), material_decimal.tp)),
  394. };
  395. await this.ctx.helper.sendWechat(this._.map(nextAudits, 'aid'), smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  396. // 重新发送配置
  397. for (const a of nextAudits) {
  398. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  399. pid: this.ctx.session.sessionProject.id,
  400. tid: this.ctx.tender.id,
  401. uid: a.aid,
  402. sp_type: 'material',
  403. sp_id: a.id,
  404. table_name: this.tableName,
  405. template: wxConst.template.material,
  406. wx_data: wechatData,
  407. });
  408. }
  409. // 检查三方特殊推送
  410. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  411. } else {
  412. // 本期结束
  413. // 同步 期信息
  414. await transaction.update(this.ctx.service.material.tableName, {
  415. id: materialId, status: checkData.checkType,
  416. });
  417. // 处理旧数据,防止重复插入到历史表
  418. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, {
  419. tid: this.ctx.tender.id,
  420. order: this.ctx.material.order
  421. });
  422. const mbhList = [];
  423. const materialBillsData = await this.ctx.service.materialBills.getAllDataByCondition({where: {tid: this.ctx.tender.id}});
  424. for (const mb of materialBillsData) {
  425. if (mb.code === '') {
  426. throw '调差工料编号不能为空';
  427. }
  428. const newMbh = {
  429. tid: this.ctx.tender.id,
  430. mid: this.ctx.material.id,
  431. order: this.ctx.material.order,
  432. mb_id: mb.id,
  433. quantity: mb.quantity,
  434. expr: mb.expr,
  435. msg_tp: mb.msg_tp,
  436. msg_times: mb.msg_times,
  437. msg_spread: mb.msg_spread,
  438. m_up_risk: mb.m_up_risk,
  439. m_down_risk: mb.m_down_risk,
  440. m_spread: mb.m_spread,
  441. m_tp: mb.m_tp,
  442. pre_tp: mb.pre_tp,
  443. m_tax_tp: mb.m_tax_tp,
  444. tax_pre_tp: mb.tax_pre_tp,
  445. origin: mb.origin,
  446. is_summary: mb.is_summary,
  447. m_tax: mb.m_tax,
  448. };
  449. mbhList.push(newMbh);
  450. }
  451. if (mbhList.length !== 0) await transaction.insert(this.ctx.service.materialBillsHistory.tableName, mbhList);
  452. // 处理旧数据,防止重复插入到历史表
  453. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, {
  454. tid: this.ctx.tender.id,
  455. order: this.ctx.material.order
  456. });
  457. const materialExponentData = await this.ctx.service.materialExponent.getAllDataByCondition({where: {tid: this.ctx.tender.id}});
  458. const mehList = [];
  459. for (const me of materialExponentData) {
  460. const newMeh = {
  461. tid: this.ctx.tender.id,
  462. mid: this.ctx.material.id,
  463. order: this.ctx.material.order,
  464. me_id: me.id,
  465. type: me.type,
  466. weight_num: me.weight_num,
  467. basic_price: me.basic_price,
  468. basic_times: me.basic_times,
  469. m_price: me.m_price,
  470. calc_num: me.calc_num,
  471. is_summary: me.is_summary,
  472. };
  473. mehList.push(newMeh);
  474. }
  475. if (mehList.length !== 0) await transaction.insert(this.ctx.service.materialExponentHistory.tableName, mehList);
  476. // 微信模板通知
  477. const begin_audit = await this.getDataByCondition({
  478. mid: materialId,
  479. order: 1,
  480. });
  481. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), materialInfo.user_id));
  482. const wechatData = {
  483. qi: materialInfo.order,
  484. status: wxConst.status.success,
  485. tips: wxConst.tips.success,
  486. begin_time: Date.parse(begin_audit.begin_time),
  487. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), this.ctx.helper.round(materialInfo.ex_tp, material_decimal.tp)),
  488. 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), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1 + materialInfo.exponent_rate / 100), material_decimal.tp)),
  489. };
  490. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.result.toString(), wxConst.template.material, wechatData);
  491. // 检查三方特殊推送
  492. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  493. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.checked);
  494. }
  495. } else {
  496. // 同步 期信息
  497. await transaction.update(this.ctx.service.material.tableName, {
  498. id: materialId,
  499. status: auditConst.status.checking,
  500. });
  501. }
  502. await transaction.commit();
  503. } catch (err) {
  504. await transaction.rollback();
  505. throw err;
  506. }
  507. }
  508. async _checkNo(pid, materialId, checkData, times) {
  509. const accountId = this.ctx.session.sessionUser.accountId;
  510. const time = new Date();
  511. // 整理当前流程审核人状态更新
  512. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, status: auditConst.status.checking } });
  513. if (!audits) throw '审核数据错误';
  514. const selfAudit = audits.find(x => { return x.aid === accountId; });
  515. if (!selfAudit) throw '当前标段您无权审批';
  516. const flowAudits = await this.getAllDataByCondition({ where: { mid: materialId, times: selfAudit.times, order: selfAudit.order }});
  517. const auditors = await this.getUniqAuditor(materialId, times); // 全部参与的审批人
  518. const newAuditors = auditors.map(x => {
  519. return {
  520. aid: x.aid, tid: selfAudit.tid, mid: selfAudit.mid,
  521. times: times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  522. audit_type: x.audit_type, audit_order: x.audit_order,
  523. }
  524. });
  525. const transaction = await this.db.beginTransaction();
  526. try {
  527. const tp_data = await this.getTpData(transaction, materialId);
  528. const updateData = [];
  529. audits.forEach(x => {
  530. updateData.push({
  531. id: x.id,
  532. status: x.aid === selfAudit.aid ? checkData.checkType : auditConst.status.checkSkip,
  533. opinion: x.aid === selfAudit.aid ? checkData.opinion : '',
  534. end_time: x.aid === selfAudit.aid ? time : null,
  535. tp_data: JSON.stringify(tp_data),
  536. });
  537. });
  538. await transaction.updateRows(this.tableName, updateData);
  539. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  540. // 添加到消息推送表
  541. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, materialId, selfAudit.aid, checkData.opinion);
  542. const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checkNo, content: noticeContent }];
  543. auditors.forEach(audit => {
  544. records.push({ pid, type: pushType.material, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });
  545. });
  546. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  547. // 同步期信息
  548. await transaction.update(this.ctx.service.material.tableName, {
  549. id: materialId, status: checkData.checkType,
  550. times: times + 1,
  551. tp_data: JSON.stringify(tp_data),
  552. });
  553. // 拷贝新一次审核流程列表
  554. await transaction.insert(this.tableName, newAuditors);
  555. // 微信模板通知
  556. const begin_audit = await this.getDataByCondition({
  557. mid: materialId,
  558. order: 1,
  559. });
  560. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  561. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  562. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), materialInfo.user_id));
  563. const wechatData = {
  564. qi: materialInfo.order,
  565. status: wxConst.status.back,
  566. tips: wxConst.tips.back,
  567. begin_time: Date.parse(begin_audit.begin_time),
  568. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), this.ctx.helper.round(materialInfo.ex_tp, material_decimal.tp)),
  569. 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), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.exponent_rate/100), material_decimal.tp)),
  570. };
  571. await this.ctx.helper.sendWechat(users, smsTypeConst.const.TC, smsTypeConst.judge.result.toString(), wxConst.template.material, wechatData);
  572. // 检查三方特殊推送
  573. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  574. await transaction.commit();
  575. } catch (err) {
  576. await transaction.rollback();
  577. throw err;
  578. }
  579. }
  580. async _checkNoPre(pid, materialId, checkData, times) {
  581. const accountId = this.ctx.session.sessionUser.accountId;
  582. const time = new Date();
  583. // 整理当前流程审核人状态更新
  584. const audits = await this.getAllDataByCondition({ where: { mid: materialId, times, status: auditConst.status.checking } });
  585. if (audits.length === 0 || audits[0].order <= 1) throw '审核数据错误';
  586. const selfAudit = audits.find(x => { return x.aid === accountId; });
  587. if (!selfAudit) throw '当前标段您无权审批';
  588. const flowAudits = await this.getAllDataByCondition({ where: { mid: materialId, times: selfAudit.times, order: selfAudit.order }});
  589. // 添加重新审批后,不能用order-1,取groupby值里的上一个才对
  590. const auditors2 = await this.getAuditGroupByList(materialId, times);
  591. const preAuditors = auditors2.filter(x => { return x.audit_order === selfAudit.audit_order - 1});
  592. const transaction = await this.db.beginTransaction();
  593. try {
  594. const tp_data = await this.getTpData(transaction, materialId);
  595. // 添加到消息推送表
  596. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, materialId, selfAudit.aid, checkData.opinion);
  597. const records = [{ pid, type: pushType.material, uid: this.ctx.material.user_id, status: auditConst.status.checkNoPre, content: noticeContent }];
  598. auditors2.forEach(audit => {
  599. records.push({ pid, type: pushType.material, uid: audit.aid, status: auditConst.status.checkNoPre, content: noticeContent });
  600. });
  601. await transaction.insert('zh_notice', records);
  602. const updateData = [];
  603. for (const audit of audits) {
  604. if (audit.aid === selfAudit.aid) {
  605. updateData.push({
  606. id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time, tp_data: JSON.stringify(tp_data)
  607. });
  608. } else {
  609. updateData.push({
  610. id: audit.id, status: auditConst.status.checkSkip, opinion: '', end_time: null, tp_data: JSON.stringify(tp_data)
  611. });
  612. }
  613. }
  614. await transaction.updateRows(this.tableName, updateData);
  615. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  616. // 顺移其后审核人流程顺序
  617. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE mid = ? AND times = ? AND `order` > ?';
  618. await transaction.query(sql, [materialId, selfAudit.times, selfAudit.order]);
  619. const newAuditors = [];
  620. preAuditors.forEach(x => {
  621. newAuditors.push({
  622. tid: selfAudit.tid, mid: materialId, aid: x.aid,
  623. times: x.times, order: selfAudit.order + 1,
  624. status: auditConst.status.checking, begin_time: time,
  625. audit_type: x.audit_type, audit_order: x.audit_order,
  626. tp_data: JSON.stringify(tp_data),
  627. });
  628. });
  629. const newAuditors_result = await transaction.insert(this.tableName, newAuditors);
  630. // 获取刚批量添加的所有list
  631. for (let j = 0; j < preAuditors.length; j++) {
  632. newAuditors[j].id = newAuditors_result.insertId + j;
  633. }
  634. const newFlowAuditors = [];
  635. flowAudits.forEach(x => {
  636. newFlowAuditors.push({
  637. tid: selfAudit.tid, mid: materialId, aid: x.aid,
  638. times: x.times, order: selfAudit.order + 2,
  639. status: auditConst.status.uncheck,
  640. audit_type: x.audit_type, audit_order: x.audit_order,
  641. });
  642. });
  643. await transaction.insert(this.tableName, newFlowAuditors);
  644. // 微信模板通知
  645. const begin_audit = await this.getDataByCondition({
  646. mid: materialId,
  647. order: 1,
  648. });
  649. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  650. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  651. const wechatData = {
  652. qi: materialInfo.order,
  653. status: wxConst.status.check,
  654. tips: wxConst.tips.check,
  655. begin_time: Date.parse(begin_audit.begin_time),
  656. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), this.ctx.helper.round(materialInfo.ex_tp, material_decimal.tp)),
  657. 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), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.exponent_rate/100), material_decimal.tp)),
  658. };
  659. await this.ctx.helper.sendWechat(this._.map(preAuditors, 'aid'), smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  660. for (const a of newAuditors) {
  661. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  662. pid: this.ctx.session.sessionProject.id,
  663. tid: this.ctx.tender.id,
  664. uid: a.aid,
  665. sp_type: 'material',
  666. sp_id: a.id,
  667. table_name: this.tableName,
  668. template: wxConst.template.material,
  669. wx_data: wechatData,
  670. });
  671. }
  672. // 检查三方特殊推送
  673. await this.ctx.service.specMsg.addMaterialMsg(transaction, pid, materialInfo, pushOperate.material.flow);
  674. await transaction.commit();
  675. } catch (error) {
  676. await transaction.rollback();
  677. throw error;
  678. }
  679. }
  680. /**
  681. * 审批
  682. * @param {Number} materialId - 材料调差期id
  683. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  684. * @param {Number} times - 第几次审批
  685. * @return {Promise<void>}
  686. */
  687. async check(materialId, checkData, times = 1) {
  688. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo && checkData.checkType !== auditConst.status.checkNoPre) {
  689. throw '提交数据错误';
  690. }
  691. const pid = this.ctx.session.sessionProject.id;
  692. switch (checkData.checkType) {
  693. case auditConst.status.checked:
  694. await this._checked(pid, materialId, checkData, times);
  695. break;
  696. case auditConst.status.checkNo:
  697. await this._checkNo(pid, materialId, checkData, times);
  698. break;
  699. case auditConst.status.checkNoPre:
  700. await this._checkNoPre(pid, materialId, checkData, times);
  701. break;
  702. default:
  703. throw '无效审批操作';
  704. }
  705. }
  706. /**
  707. * 用于添加推送所需的content内容
  708. * @param {Number} pid 项目id
  709. * @param {Number} tid 台账id
  710. * @param {Number} mid 期id
  711. * @param {Number} uid 审批人id
  712. */
  713. async getNoticeContent(pid, tid, mid, uid, opinion = '') {
  714. const noticeSql = 'SELECT * FROM (SELECT ' +
  715. ' t.`id` As `tid`, ma.`mid`, t.`name`, m.`order`, pa.`name` As `su_name`, pa.role As `su_role`' +
  716. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  717. ' LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +
  718. ' LEFT JOIN ?? As ma ON m.`id` = ma.`mid`' +
  719. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  720. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  721. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.material.tableName, mid, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];
  722. const content = await this.db.query(noticeSql, noticeSqlParam);
  723. if (content.length) {
  724. content[0].opinion = opinion;
  725. }
  726. return content.length ? JSON.stringify(content[0]) : '';
  727. }
  728. /**
  729. * 审批
  730. * @param {Number} materialId - 材料调差期id
  731. * @param {Number} times - 第几次审批
  732. * @return {Promise<void>}
  733. */
  734. async checkAgain(materialId, times = 1) {
  735. const accountId = this.ctx.session.sessionUser.accountId;
  736. const time = new Date();
  737. // 整理当前流程审核人状态更新
  738. const auditors = await this.getAllDataByCondition({
  739. where: { mid: materialId, times },
  740. orders: [['order', 'asc']],
  741. });
  742. const maxOrder = auditors[auditors.length - 1].order;
  743. const audits = auditors.filter(x => { return x.order === maxOrder});
  744. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  745. const selfAudit = audits.find(x => { return x.aid === accountId; });
  746. if (!selfAudit) throw '当前标段您无权审批';
  747. const finalAudit = selfAudit || audits[0];
  748. const transaction = await this.db.beginTransaction();
  749. try {
  750. const materialInfo = await this.ctx.service.material.getDataById(materialId);
  751. const material_decimal = materialInfo && materialInfo.decimal ? JSON.parse(materialInfo.decimal) : materialConst.decimal;
  752. const tp_data = await this.getTpData(transaction, materialId, material_decimal);
  753. const checkAgainAuditors = [], checkingAuditors = [];
  754. audits.forEach(x => {
  755. checkAgainAuditors.push({
  756. tid: x.tid, mid: x.mid, aid: x.aid,
  757. times: x.times, order: x.order + 1,
  758. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  759. begin_time: time, end_time: time, opinion: '',
  760. audit_type: x.audit_type, audit_order: x.audit_order,
  761. });
  762. });
  763. audits.forEach(x => {
  764. checkingAuditors.push({
  765. tid: x.tid, mid: x.mid, aid: x.aid,
  766. times: x.times, order: x.order + 2,
  767. status: auditConst.status.checking,
  768. begin_time: time, end_time: time, opinion: '',
  769. audit_type: x.audit_type, audit_order: x.audit_order,
  770. tp_data: JSON.stringify(tp_data),
  771. });
  772. });
  773. await transaction.insert(this.tableName, checkAgainAuditors);
  774. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  775. // 获取刚批量添加的所有list
  776. for (let j = 0; j < checkingAuditors.length; j++) {
  777. checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  778. }
  779. // 本期结束
  780. // 同步 期信息
  781. await transaction.update(this.ctx.service.material.tableName, {
  782. id: materialId, status: auditConst.status.checking,
  783. final_auditor_str: '',
  784. });
  785. // 微信模板通知
  786. const wechatData = {
  787. qi: materialInfo.order,
  788. status: wxConst.status.check,
  789. tips: wxConst.tips.check,
  790. begin_time: Date.parse(new Date()),
  791. m_tp: this.ctx.helper.add(this.ctx.helper.round(materialInfo.m_tp, material_decimal.tp), this.ctx.helper.round(materialInfo.ex_tp, material_decimal.tp)),
  792. 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), this.ctx.helper.round(this.ctx.helper.mul(materialInfo.ex_tp, 1+materialInfo.exponent_rate/100), material_decimal.tp)),
  793. };
  794. await this.ctx.helper.sendWechat(this._.map(checkingAuditors, 'aid'), smsTypeConst.const.TC, smsTypeConst.judge.approval.toString(), wxConst.template.material, wechatData);
  795. for (const a of checkingAuditors) {
  796. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.TC, {
  797. pid: this.ctx.session.sessionProject.id,
  798. tid: this.ctx.tender.id,
  799. uid: a.aid,
  800. sp_type: 'material',
  801. sp_id: a.id,
  802. table_name: this.tableName,
  803. template: wxConst.template.material,
  804. wx_data: wechatData,
  805. });
  806. }
  807. // 检查三方特殊推送
  808. await this.ctx.service.specMsg.addMaterialMsg(transaction, this.ctx.session.sessionProject.id, materialInfo, pushOperate.material.flow);
  809. await transaction.commit();
  810. } catch (err) {
  811. await transaction.rollback();
  812. throw err;
  813. }
  814. }
  815. /**
  816. * 获取审核人需要审核的期列表
  817. *
  818. * @param auditorId
  819. * @return {Promise<*>}
  820. */
  821. async getAuditMaterial(auditorId) {
  822. const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`mid`,' +
  823. ' m.`order` As `morder`, m.`status` As `mstatus`,' +
  824. ' t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +
  825. ' FROM ?? AS ma, ?? AS m, ?? As t ' +
  826. ' WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`user_id` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' +
  827. ' and ma.`mid` = m.`id` and ma.`tid` = t.`id` ORDER BY ma.`begin_time` DESC';
  828. 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];
  829. const result = await this.db.query(sql, sqlParam);
  830. // 过滤result中存在重复sid的值, 保留最新的一条
  831. const filterResult = [];
  832. const midArr = [];
  833. for (const r of result) {
  834. if (midArr.indexOf(r.mid) === -1) {
  835. filterResult.push(r);
  836. midArr.push(r.mid);
  837. }
  838. }
  839. return filterResult;
  840. }
  841. /**
  842. * 获取审核人审核的次数
  843. *
  844. * @param auditorId
  845. * @return {Promise<*>}
  846. */
  847. async getCountByChecked(auditorId) {
  848. return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo, auditConst.status.checkNoPre] });
  849. }
  850. /**
  851. * 获取最近一次审批结束时间
  852. *
  853. * @param auditorId
  854. * @return {Promise<*>}
  855. */
  856. async getLastEndTimeByChecked(auditorId) {
  857. const sql = 'SELECT `end_time` FROM ?? WHERE `aid` = ? ' +
  858. 'AND `status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo]) + ') ORDER BY `end_time` DESC';
  859. const sqlParam = [this.tableName, auditorId];
  860. const result = await this.db.queryOne(sql, sqlParam);
  861. return result ? result.end_time : null;
  862. }
  863. /**
  864. * 获取 某时间后 审批进度 更新的期
  865. * @param {Number} pid - 查询标段
  866. * @param {Number} uid - 查询人
  867. * @param {Date} time - 查询时间
  868. * @return {Promise<*>}
  869. */
  870. async getNoticeMaterial(pid, uid, time) {
  871. // const sql = 'SELECT * FROM (SELECT t.`name`, t.`project_id`, t.`type`, t.`user_id`, ' +
  872. // ' m.`order` As `m_order`, m.`status` As `m_status`, ' +
  873. // ' ma.`aid`, ma.`times`, ma.`order`, ma.`end_time`, ma.`tid`, ma.`mid`, ma.`status`, ' +
  874. // ' pa.`name` As `su_name`, pa.role As `su_role`, pa.company As `su_company`' +
  875. // ' FROM (SELECT * FROM ?? WHERE `user_id` = ? OR `id` in (SELECT `tid` FROM ?? WHERE `aid` = ? GROUP BY `tid`)) As t' +
  876. // ' LEFT JOIN ?? As m On t.`id` = m.`tid`' +
  877. // ' LEFT JOIN ?? As ma ON m.`id` = ma.`mid`' +
  878. // ' LEFT JOIN ?? As pa ON ma.`aid` = pa.`id`' +
  879. // ' WHERE ma.`end_time` > ? and t.`project_id` = ?' +
  880. // ' ORDER By ma.`end_time` DESC LIMIT 1000) as new_t GROUP BY new_t.`tid`' +
  881. // ' ORDER BY new_t.`end_time`';
  882. // const sqlParam = [this.ctx.service.tender.tableName, uid, this.tableName, uid, this.ctx.service.material.tableName, this.tableName,
  883. // this.ctx.service.projectAccount.tableName, time, pid];
  884. // return await this.db.query(sql, sqlParam);
  885. let notice = await this.db.select('zh_notice', {
  886. where: { pid, type: pushType.material, uid },
  887. orders: [['create_time', 'desc']],
  888. limit: 10, offset: 0,
  889. });
  890. notice = notice.map(v => {
  891. const extra = JSON.parse(v.content);
  892. delete v.content;
  893. return { ...v, ...extra };
  894. });
  895. return notice;
  896. }
  897. /**
  898. * 获取审核人流程列表
  899. *
  900. * @param auditorId
  901. * @return {Promise<*>}
  902. */
  903. async getAuditGroupByList(materialId, times) {
  904. // 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 ' +
  905. // ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  906. // ' WHERE la.`mid` = ? and la.`times` = ? GROUP BY la.`aid` ORDER BY la.`order`';
  907. // const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, times];
  908. const sql =
  909. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`order`, la.`status`, la.audit_type, la.audit_order ' +
  910. ' FROM (SELECT `aid`, max(`order`) `order` FROM ?? WHERE `mid` = ? and `times` = ? and `is_old` = ? GROUP BY aid) sa' +
  911. ' LEFT JOIN ?? la ON sa.`aid` = la.`aid` AND sa.`order` = la.`order`' +
  912. ' Left JOIN ?? AS pa On la.`aid` = pa.`id` WHERE la.`mid` = ? and la.`times` = ? and la.`is_old` = ? order BY la.`order`';
  913. const sqlParam = [this.tableName, materialId, times, 0, this.tableName, this.ctx.service.projectAccount.tableName, materialId, times, 0];
  914. return await this.db.query(sql, sqlParam);
  915. }
  916. /**
  917. * 获取审核人流程列表(包括原报)
  918. * @param {Number} materialId 调差id
  919. * @param {Number} times 审核次数
  920. * @return {Promise<Array>} 查询结果集(包括原报)
  921. */
  922. async getAuditorsWithOwner(materialId, times = 1) {
  923. const result = await this.getAuditGroupByList(materialId, times);
  924. const sql =
  925. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As mid, 0 As `order`' +
  926. ' FROM ' +
  927. this.ctx.service.material.tableName +
  928. ' As s' +
  929. ' LEFT JOIN ' +
  930. this.ctx.service.projectAccount.tableName +
  931. ' As pa' +
  932. ' ON s.user_id = pa.id' +
  933. ' WHERE s.id = ?';
  934. const sqlParam = [times, materialId, materialId];
  935. const user = await this.db.queryOne(sql, sqlParam);
  936. result.unshift(user);
  937. return result;
  938. }
  939. /**
  940. * 获取tender下所有的审核列表(报表用)
  941. * @param {Number} tenderId
  942. */
  943. async getAuditorsByTender(tenderId) {
  944. const sql = 'SELECT la.`tid`, la.`mid`, la.`aid`, la.`order`, la.`times`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`' +
  945. ' FROM ?? AS la ' +
  946. ' WHERE la.`tid` = ?';
  947. const sqlParam = [this.tableName, tenderId];
  948. return await this.db.query(sql, sqlParam);
  949. }
  950. /**
  951. * 复制上一期的审批人列表给最新一期
  952. *
  953. * @param transaction - 新增一期的事务
  954. * @param {Object} preMaterial - 上一期
  955. * @param {Object} newaMaterial - 最新一期
  956. * @return {Promise<*>}
  957. */
  958. async copyPreMaterialAuditors(transaction, preMaterial, newMaterial) {
  959. const auditors = await this.getAuditGroupByList(preMaterial.id, preMaterial.times);
  960. const newAuditors = [];
  961. for (const a of auditors) {
  962. const na = {
  963. tid: preMaterial.tid,
  964. mid: newMaterial.id,
  965. aid: a.aid,
  966. times: newMaterial.times,
  967. order: a.audit_order,
  968. status: auditConst.status.uncheck,
  969. audit_type: a.audit_type,
  970. audit_order: a.audit_order,
  971. };
  972. newAuditors.push(na);
  973. }
  974. if (newAuditors.length > 0) {
  975. const result = await transaction.insert(this.tableName, newAuditors);
  976. return (result.effectRows = auditors.length);
  977. } else {
  978. return true;
  979. }
  980. }
  981. /**
  982. * 移除审核人
  983. *
  984. * @param {Number} materialId - 材料调差期id
  985. * @param {Number} status - 期状态
  986. * @param {Number} status - 期次数
  987. * @return {Promise<boolean>}
  988. */
  989. async getAuditorByStatus(materialId, status, times = 1) {
  990. let auditor = null;
  991. let sql = '';
  992. let sqlParam = '';
  993. switch (status) {
  994. case auditConst.status.checking :
  995. case auditConst.status.checked :
  996. case auditConst.status.checkNoPre :
  997. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  998. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  999. ' WHERE la.`mid` = ? and la.`status` = ? ' +
  1000. ' ORDER BY la.`times` desc, la.`order` desc';
  1001. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, status];
  1002. auditor = await this.db.queryOne(sql, sqlParam);
  1003. break;
  1004. case auditConst.status.checkNo :
  1005. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`aid`, la.`order` ' +
  1006. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  1007. ' WHERE la.`mid` = ? and la.`status` = ? and la.`times` = ?' +
  1008. ' ORDER BY la.`times` desc, la.`order` desc';
  1009. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, auditConst.status.checkNo, parseInt(times) - 1];
  1010. auditor = await this.db.queryOne(sql, sqlParam);
  1011. break;
  1012. case auditConst.status.uncheck :
  1013. default:break;
  1014. }
  1015. return auditor;
  1016. }
  1017. async getAuditorsByStatus(materialId, status, times = 1) {
  1018. let auditor = [];
  1019. let sql = '';
  1020. let sqlParam = '';
  1021. let cur;
  1022. switch (status) {
  1023. case auditConst.status.checking:
  1024. case auditConst.status.checked:
  1025. case auditConst.status.checkNoPre:
  1026. cur = await this.db.queryOne(`SELECT * From ${this.tableName} where mid = ? AND times = ? AND status = ? ORDER By times DESC, ` + '`order` DESC', [materialId, times, status]);
  1027. if (!cur) return [];
  1028. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`order`, la.`status`, la.audit_order, la.audit_type ' +
  1029. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1030. ' WHERE la.`mid` = ? and la.`order` = ? and times = ?';
  1031. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, cur.order, times];
  1032. auditor = await this.db.query(sql, sqlParam);
  1033. break;
  1034. case auditConst.status.checkNo:
  1035. 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]);
  1036. if (!cur) return [];
  1037. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`mid`, la.`order`, la.`status`, la.audit_order, la.audit_type ' +
  1038. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1039. ' WHERE la.`mid` = ? and la.`order` = ? and la.`times` = ?';
  1040. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, materialId, cur.order, parseInt(times) - 1];
  1041. auditor = await this.db.query(sql, sqlParam);
  1042. break;
  1043. case auditConst.status.uncheck:
  1044. default:
  1045. break;
  1046. }
  1047. return auditor;
  1048. }
  1049. async getAllAuditors(tenderId) {
  1050. const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +
  1051. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +
  1052. ' WHERE t.id = ?' +
  1053. ' GROUP BY ma.aid';
  1054. const sqlParam = [tenderId];
  1055. return this.db.query(sql, sqlParam);
  1056. }
  1057. async updateNewAuditList(material, newList) {
  1058. const transaction = await this.db.beginTransaction();
  1059. try {
  1060. // 先删除旧的审批流,再添加新的
  1061. await transaction.delete(this.tableName, { mid: material.id, times: material.times });
  1062. const newAuditors = [];
  1063. for (const auditor of newList) {
  1064. newAuditors.push({
  1065. tid: material.tid, mid: material.id, aid: auditor.audit_id,
  1066. times: material.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1067. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1068. });
  1069. }
  1070. if(newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1071. await transaction.commit();
  1072. } catch (err) {
  1073. await transaction.rollback();
  1074. throw err;
  1075. }
  1076. }
  1077. async updateLastAudit(material, auditList, lastId) {
  1078. const transaction = await this.db.beginTransaction();
  1079. try {
  1080. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1081. const existAudit = auditList.find(x => { return x.aid === lastId });
  1082. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order)}, 0) + 1 : 1; // 最大值 + 1
  1083. // const idList = this._.map(auditList, 'aid');
  1084. // let order = idList.length + 1;
  1085. if (existAudit) {
  1086. await transaction.delete(this.tableName, {mid: material.id, times: material.times, aid: lastId});
  1087. const sameOrder = auditList.filter(x => { return x.order === existAudit.order });
  1088. if (sameOrder.length === 1) {
  1089. const updateData = [];
  1090. auditList.forEach(x => {
  1091. if (x.order <= existAudit.order) return;
  1092. updateData.push({id: x.id, order: x.order - 1, audit_order: x.audit_order - 1});
  1093. });
  1094. if (updateData.length > 0) {
  1095. await transaction.updateRows(updateData);
  1096. }
  1097. order = order - 1;
  1098. }
  1099. }
  1100. // 添加终审
  1101. const newAuditor = {
  1102. tid: material.tid, mid: material.id, aid: lastId,
  1103. times: material.times, order, status: auditConst.status.uncheck,
  1104. audit_type: auditType.key.common, audit_order: order,
  1105. };
  1106. await transaction.insert(this.tableName, newAuditor);
  1107. await transaction.commit();
  1108. } catch (err) {
  1109. await transaction.rollback();
  1110. throw err;
  1111. }
  1112. }
  1113. async getNumByMonth(tid, startMonth, endMonth) {
  1114. 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 ?';
  1115. // 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 ?';
  1116. const sqlParam = [this.tableName, this.tableName, tid, auditConst.status.checked, startMonth, endMonth];
  1117. const result = await this.db.queryOne(sql, sqlParam);
  1118. return result ? result.num : 0;
  1119. }
  1120. /**
  1121. * 删除本次审批流程
  1122. * @param {Number} materialId - 调差id
  1123. * @param {Number} times - 第几次审批
  1124. * @param {Object} data - 更改参数
  1125. * @return {Promise<void>}
  1126. */
  1127. async saveAudit(materialId, times, sp_group, data) {
  1128. const transaction = await this.db.beginTransaction();
  1129. try {
  1130. const auditors = await this.getAuditGroupByList(materialId, times);
  1131. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1132. if (data.operate !== 'del') {
  1133. const exist = await this.getDataByCondition({ mid: materialId, times, aid: data.new_aid, is_old: 0 });
  1134. if (exist) throw '该审核人已存在,请勿重复添加';
  1135. }
  1136. if (data.operate === 'add') {
  1137. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1138. throw '当前人下无法操作新增';
  1139. }
  1140. const newAudit = {
  1141. tid: this.ctx.tender.id,
  1142. mid: materialId,
  1143. aid: data.new_aid,
  1144. order: now_audit.order + 1,
  1145. audit_order: now_audit.audit_order + 1,
  1146. audit_type: auditType.key.common,
  1147. times: times,
  1148. status: 1
  1149. };
  1150. // order+1
  1151. await this._syncOrderByDelete(transaction, materialId, now_audit.order+1, times, '+');
  1152. await transaction.insert(this.tableName, newAudit);
  1153. // 更新审批流程页数据,如果存在
  1154. } else if (data.operate === 'add-sibling') {
  1155. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1156. throw '当前人下无法操作新增';
  1157. }
  1158. const newAudit = {
  1159. tid: this.ctx.tender.id,
  1160. mid: materialId,
  1161. aid: data.new_aid,
  1162. order: now_audit.order,
  1163. audit_order: now_audit.audit_order,
  1164. audit_type: now_audit.audit_type,
  1165. times: times,
  1166. status: 1
  1167. };
  1168. await transaction.insert(this.tableName, newAudit);
  1169. } else if (data.operate === 'del') {
  1170. if (now_audit.status !== auditConst.status.uncheck) {
  1171. throw '当前人无法操作删除';
  1172. }
  1173. const flowAuditors = auditors.filter(x => { return x.order === now_audit.order; });
  1174. await transaction.delete(this.tableName, { mid: materialId, times, aid: now_audit.aid, order: now_audit.order });
  1175. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, materialId, now_audit.order, times);
  1176. // 旧的更新为is_old为1
  1177. await transaction.update(this.tableName, { is_old: 1 }, {
  1178. where: {
  1179. mid: materialId,
  1180. times,
  1181. aid: data.old_aid,
  1182. }
  1183. });
  1184. } else if (data.operate === 'change') {
  1185. const nowAudit = await this.getDataByCondition({ mid: materialId, times, aid: now_audit.aid, order: now_audit.order });
  1186. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1187. throw '当前人无法操作替换';
  1188. }
  1189. nowAudit.aid = data.new_aid;
  1190. await transaction.update(this.tableName, nowAudit);
  1191. // 旧的更新为is_old为1
  1192. await transaction.update(this.tableName, { is_old: 1 }, {
  1193. where: {
  1194. mid: materialId,
  1195. times,
  1196. aid: data.old_aid,
  1197. }
  1198. });
  1199. }
  1200. if (this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdspl) {
  1201. const newAuditors = await transaction.select(this.tableName, { where: { mid: materialId, times } });
  1202. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors.filter(x => { return x.is_old === 0; }));
  1203. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1204. await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.material, shenpiConst.sp_type.material, uniqNewAuditorGroup, sp_group);
  1205. } else if (this.ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs) {
  1206. const newAuditors = await this.getAuditGroupByList(materialId, times, transaction);
  1207. 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'));
  1208. }
  1209. // 更新到审批流程方法
  1210. await transaction.commit();
  1211. } catch (err) {
  1212. await transaction.rollback();
  1213. throw err;
  1214. }
  1215. }
  1216. async getAuditorGroup(materialId, times) {
  1217. const auditors = await this.getAuditors(materialId, times); // 全部参与的审批人
  1218. const newAuditors = auditors.filter(x => { return x.is_old === 0; });
  1219. return this.ctx.helper.groupAuditors(newAuditors);
  1220. }
  1221. async getUserGroup(materialId, times) {
  1222. const group = await this.getAuditorGroup(materialId, times);
  1223. const sql =
  1224. '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' +
  1225. ' FROM ' + this.ctx.service.material.tableName + ' As m' +
  1226. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1227. ' ON m.user_id = pa.id' +
  1228. ' WHERE m.id = ?';
  1229. const sqlParam = [times, materialId, materialId];
  1230. const user = await this.db.queryOne(sql, sqlParam);
  1231. group.unshift([ user ]);
  1232. return group;
  1233. }
  1234. async getUniqUserGroup(materialId, times) {
  1235. const group = await this.getAuditorGroup(materialId, times);
  1236. const sql =
  1237. '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' +
  1238. ' FROM ' + this.ctx.service.material.tableName + ' As m' +
  1239. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1240. ' ON m.user_id = pa.id' +
  1241. ' WHERE m.id = ?';
  1242. const sqlParam = [times, materialId, materialId];
  1243. const user = await this.db.queryOne(sql, sqlParam);
  1244. user.audit_order = 0;
  1245. group.unshift([ user ]);
  1246. return this.ctx.helper.groupAuditorsUniq(group);
  1247. }
  1248. async getAuditorHistory(materialId, times, reverse = false) {
  1249. const history = [];
  1250. if (times >= 1) {
  1251. for (let i = 1; i <= times; i++) {
  1252. const auditors = await this.getAuditors(materialId, i);
  1253. const group = this.ctx.helper.groupAuditors(auditors);
  1254. const historyGroup = [];
  1255. const max_order = group.length > 0 && group[group.length - 1].length > 0 ? group[group.length - 1][0].audit_order : -1;
  1256. for (const g of group) {
  1257. const his = {
  1258. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  1259. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  1260. auditors: g
  1261. };
  1262. if (his.audit_type === auditType.key.common) {
  1263. his.name = g[0].name;
  1264. } else {
  1265. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  1266. }
  1267. his.is_final = his.audit_order === max_order;
  1268. if (g[0].begin_time) {
  1269. his.begin_time = g[0].begin_time;
  1270. const beginTime = this.ctx.moment(g[0].begin_time);
  1271. his.beginYear = beginTime.format('YYYY');
  1272. his.beginDate = beginTime.format('MM-DD');
  1273. his.beginTime = beginTime.format('HH:mm:ss');
  1274. }
  1275. let end_time;
  1276. g.forEach(x => {
  1277. if (x.status === auditConst.status.checkSkip) return;
  1278. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  1279. if (x.end_time && (!end_time || x.end_time > end_time)) {
  1280. end_time = x.end_time;
  1281. if (his.status !== auditConst.status.checking) his.status = x.status;
  1282. }
  1283. });
  1284. if (end_time) {
  1285. his.end_time = end_time;
  1286. const endTime = this.ctx.moment(end_time);
  1287. his.endYear = endTime.format('YYYY');
  1288. his.endDate = endTime.format('MM-DD');
  1289. his.endTime = endTime.format('HH:mm:ss');
  1290. }
  1291. historyGroup.push(his);
  1292. }
  1293. if (reverse) {
  1294. history.push(historyGroup.reverse());
  1295. } else {
  1296. history.push(historyGroup);
  1297. }
  1298. }
  1299. }
  1300. return history;
  1301. }
  1302. async getUniqAuditor(materialId, times) {
  1303. const auditors = await this.getAuditors(materialId, times); // 全部参与的审批人
  1304. const result = [];
  1305. auditors.forEach(x => {
  1306. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === r.audit_order; }) < 0) {
  1307. result.push(x);
  1308. }
  1309. });
  1310. return result;
  1311. }
  1312. }
  1313. return MaterialAudit;
  1314. };