stage_audit.js 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2019/2/27
  7. * @version
  8. */
  9. const auditConst = require('../const/audit').stage;
  10. const auditType = require('../const/audit').auditType;
  11. const smsTypeConst = require('../const/sms_type');
  12. const SMS = require('../lib/sms');
  13. const SmsAliConst = require('../const/sms_alitemplate');
  14. const wxConst = require('../const/wechat_template');
  15. const shenpiConst = require('../const/shenpi');
  16. const payConst = require('../const/deal_pay');
  17. const pushType = require('../const/audit').pushType;
  18. const syncApiConst = require('../const/sync_api');
  19. const measureType = require('../const/tender').measureType;
  20. const RevisePrice = require('../lib/revise_price');
  21. const pushOperate = require('../const/spec_3f').pushOperate;
  22. module.exports = app => {
  23. class StageAudit extends app.BaseService {
  24. /**
  25. * 构造函数
  26. *
  27. * @param {Object} ctx - egg全局变量
  28. * @return {void}
  29. */
  30. constructor(ctx) {
  31. super(ctx);
  32. this.tableName = 'stage_audit';
  33. }
  34. /**
  35. * 获取 审核人信息
  36. *
  37. * @param {Number} stageId - 期id
  38. * @param {Number} auditorId - 审核人id
  39. * @param {Number} times - 第几次审批
  40. * @return {Promise<*>}
  41. */
  42. async getAuditor(stageId, auditorId, times = 1) {
  43. const sql =
  44. '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` ' +
  45. 'FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  46. 'WHERE la.`sid` = ? and la.`aid` = ? and la.`times` = ?';
  47. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditorId, times];
  48. return await this.db.queryOne(sql, sqlParam);
  49. }
  50. async getAuditorByOrder(stageId, order, times) {
  51. const sql =
  52. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`,' +
  53. ' la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  54. ' FROM ' + this.tableName + ' AS la' +
  55. ' Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +
  56. ' WHERE la.`sid` = ? and la.`order` = ? and la.`times` = ?' +
  57. ' ORDER BY `order` DESC';
  58. const sqlParam = [stageId, order, times ? times: 1];
  59. return await this.db.queryOne(sql, sqlParam);
  60. }
  61. async getAuditorsByOrder(stageId, order, times) {
  62. const sql =
  63. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`,' +
  64. ' la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  65. ' FROM ' + this.tableName + ' AS la' +
  66. ' Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +
  67. ' WHERE la.`sid` = ? and la.`order` = ? and la.`times` = ?' +
  68. ' ORDER BY `order` DESC';
  69. const sqlParam = [stageId, order, times ? times: 1];
  70. return await this.db.query(sql, sqlParam);
  71. }
  72. async getLastestAuditor(stageId, times, status) {
  73. const sql =
  74. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.audit_type, la.audit_order,' +
  75. ' la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  76. ' FROM ' + this.tableName + ' AS la' +
  77. ' Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +
  78. ' WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ?' +
  79. ' ORDER BY `order` DESC';
  80. const sqlParam = [stageId, status, times ? times: 1];
  81. return await this.db.queryOne(sql, sqlParam);
  82. }
  83. async getLastestAuditors(stageId, times, status) {
  84. const sql =
  85. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.audit_type, la.audit_order,' +
  86. ' la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  87. ' FROM ' + this.tableName + ' AS la' +
  88. ' Left Join ' + this.ctx.service.projectAccount.tableName + ' AS pa ON la.`aid` = pa.`id`' +
  89. ' WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ?' +
  90. ' ORDER BY `order` DESC';
  91. const sqlParam = [stageId, status, times ? times: 1];
  92. const result = await this.db.query(sql, sqlParam);
  93. if (result.length === 0) return [];
  94. return result.filter(x => { return x.order === result[0].order });
  95. }
  96. /**
  97. * 获取 审核列表信息
  98. *
  99. * @param {Number} stageId - 期id
  100. * @param {Number} times - 第几次审批
  101. * @param {Number} order_sort - 列表排序方式
  102. * @return {Promise<*>}
  103. */
  104. async getAuditors(stageId, times = 1, order_sort = 'asc') {
  105. const sql = 'SELECT la.id, la.aid, la.times, la.order, la.status, la.opinion, la.begin_time, la.end_time, la.audit_type, la.audit_order,' +
  106. ' pa.name, pa.company, pa.role, pa.mobile, pa.telephone, pa.sign_path' +
  107. ` FROM ${this.tableName} la LEFT JOIN ${this.ctx.service.projectAccount.tableName} pa ON la.aid = pa.id` +
  108. ' WHERE la.sid = ? AND la.times = ?' +
  109. ' ORDER BY la.order ' + order_sort;
  110. const sqlParam = [stageId, times];
  111. const result = await this.db.query(sql, sqlParam);
  112. const max_sort = this._.max(result.map(x => { return x.audit_order; }));
  113. for (const i in result) {
  114. result[i].max_sort = max_sort;
  115. }
  116. return result;
  117. }
  118. async getAllAuditors(tenderId) {
  119. const sql =
  120. 'SELECT sa.aid, sa.tid FROM ' + this.tableName + ' sa' +
  121. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On sa.tid = t.id' +
  122. ' WHERE t.id = ?' +
  123. ' GROUP BY sa.aid';
  124. const sqlParam = [tenderId];
  125. return this.db.query(sql, sqlParam);
  126. }
  127. /**
  128. * 获取标段审核人最后一位的名称
  129. *
  130. * @param {Number} tenderId - 标段id
  131. * @param {Number} auditorId - 审核人id
  132. * @param {Number} times - 第几次审批
  133. * @return {Promise<*>}
  134. */
  135. async getStatusName(stageId) {
  136. const sql = 'SELECT pa.`name` FROM ?? AS sa Left Join ?? AS pa On sa.`aid` = pa.`id`' +
  137. ' WHERE sa.`sid` = ? and sa.`status` != ? ORDER BY sa.`times` DESC, sa.`order` DESC';
  138. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.uncheck];
  139. return await this.db.queryOne(sql, sqlParam);
  140. }
  141. /**
  142. * 获取 当前审核人
  143. *
  144. * @param {Number} stageId - 期id
  145. * @param {Number} times - 第几次审批
  146. * @return {Promise<*>}
  147. */
  148. async getCurAuditor(stageId, times = 1) {
  149. const sql =
  150. '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 ' +
  151. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  152. ' WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ?';
  153. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.checking, times];
  154. return await this.db.queryOne(sql, sqlParam);
  155. }
  156. async getCurAuditors(stageId, times = 1) {
  157. const sql =
  158. '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 ' +
  159. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  160. ' WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ?';
  161. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.checking, times];
  162. return await this.db.query(sql, sqlParam);
  163. }
  164. /**
  165. * 获取 最新审核顺序
  166. *
  167. * @param {Number} stageId - 期id
  168. * @param {Number} times - 第几次审批
  169. * @return {Promise<number>}
  170. */
  171. async getNewOrder(stageId, times = 1) {
  172. const sql = 'SELECT Max(`order`) As max_order, Max(audit_order) As max_audit_order FROM ' + this.tableName + ' Where `sid` = ? and `times` = ?';
  173. const sqlParam = [stageId, times];
  174. const result = await this.db.queryOne(sql, sqlParam);
  175. return result && result.max_order ? [result.max_order + 1, result.max_audit_order + 1] : [1, 1];
  176. }
  177. /**
  178. * 新增审核人
  179. *
  180. * @param {Number} stageId - 期id
  181. * @param {Number} auditorId - 审核人id
  182. * @param {Number} times - 第几次审批
  183. * @return {Promise<number>}
  184. */
  185. async addAuditor(stageId, auditorId, times = 1, is_gdzs = 0) {
  186. const transaction = await this.db.beginTransaction();
  187. try {
  188. let [newOrder, newAuditOrder] = await this.getNewOrder(stageId, times);
  189. // 判断是否存在固定终审,存在则newOrder - 1并使终审order+1
  190. newOrder = is_gdzs === 1 ? newOrder - 1 : newOrder;
  191. newAuditOrder = is_gdzs === 1 ? newAuditOrder - 1 : newAuditOrder;
  192. if (is_gdzs) await this._syncOrderByDelete(transaction, stageId, newOrder, times, '+');
  193. const data = {
  194. tid: this.ctx.tender.id,
  195. sid: stageId,
  196. aid: auditorId,
  197. times,
  198. order: newOrder,
  199. status: auditConst.status.uncheck,
  200. audit_order: newAuditOrder,
  201. };
  202. const result = await transaction.insert(this.tableName, data);
  203. await transaction.commit();
  204. return result.effectRows = 1;
  205. } catch (err) {
  206. await transaction.rollback();
  207. throw err;
  208. }
  209. return false;
  210. }
  211. /**
  212. * 移除审核人时,同步其后审核人order
  213. * @param transaction - 事务
  214. * @param {Number} stageId - 标段id
  215. * @param {Number} auditorId - 审核人id
  216. * @param {Number} times - 第几次审批
  217. * @return {Promise<*>}
  218. * @private
  219. */
  220. async _syncOrderByDelete(transaction, stageId, order, times, selfOperate = '-') {
  221. this.initSqlBuilder();
  222. this.sqlBuilder.setAndWhere('sid', {
  223. value: stageId,
  224. operate: '=',
  225. });
  226. this.sqlBuilder.setAndWhere('order', {
  227. value: order,
  228. operate: '>=',
  229. });
  230. this.sqlBuilder.setAndWhere('times', {
  231. value: times,
  232. operate: '=',
  233. });
  234. this.sqlBuilder.setUpdateData('order', {
  235. value: 1,
  236. selfOperate: selfOperate,
  237. });
  238. this.sqlBuilder.setUpdateData('audit_order', {
  239. value: 1,
  240. selfOperate: selfOperate,
  241. });
  242. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  243. const data = await transaction.query(sql, sqlParam);
  244. return data;
  245. }
  246. /**
  247. * 移除审核人
  248. *
  249. * @param {Number} stageId - 期id
  250. * @param {Number} auditorId - 审核人id
  251. * @param {Number} times - 第几次审批
  252. * @return {Promise<boolean>}
  253. */
  254. async deleteAuditor(stageId, auditorId, times = 1) {
  255. const transaction = await this.db.beginTransaction();
  256. try {
  257. const condition = { sid: stageId, aid: auditorId, times };
  258. const auditor = await this.getDataByCondition(condition);
  259. if (!auditor) {
  260. throw '该审核人不存在';
  261. }
  262. // 移除整个流程的人
  263. await transaction.delete(this.tableName, { sid: stageId, order: auditor.order, times});
  264. await this._syncOrderByDelete(transaction, stageId, auditor.order, times);
  265. await transaction.commit();
  266. } catch (err) {
  267. await transaction.rollback();
  268. throw err;
  269. }
  270. return true;
  271. }
  272. async _updateTender(transaction) {
  273. if (!this.ctx.tender) return;
  274. if (this.ctx.tender.data.measure_type !== measureType.gcl.value) return;
  275. const sum = await this.ctx.service.ledger.addUp({ tender_id: this.ctx.tender.id/* , is_leaf: true*/ });
  276. await transaction.update(this.ctx.service.tender.tableName, {
  277. id: this.ctx.tender.id, total_price: sum.total_price, deal_tp: sum.deal_tp
  278. });
  279. return sum;
  280. }
  281. /**
  282. * 开始审批
  283. *
  284. * @param {Number} stageId - 期id
  285. * @param {Number} times - 第几次审批
  286. * @return {Promise<boolean>}
  287. */
  288. async start(stageId, times = 1) {
  289. const audits = await this.getAllDataByCondition({ where: { sid: stageId, times, order: 1 } });
  290. if (audits.length === 0) {
  291. if(this.ctx.tender.info.shenpi.stage === shenpiConst.sp_status.gdspl) {
  292. throw '请联系管理员添加审批人';
  293. } else {
  294. throw '请先选择审批人,再上报数据';
  295. }
  296. }
  297. const transaction = await this.db.beginTransaction();
  298. try {
  299. const ledgerTp = await this._updateTender(transaction);
  300. const begin_time = new Date();
  301. const updateData = audits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time } });
  302. await transaction.updateRows(this.tableName, updateData);
  303. // 计算原报最终数据
  304. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  305. // 复制一份下一审核人数据
  306. await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, 1, transaction);
  307. await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);
  308. await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);
  309. await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);
  310. await this.ctx.service.stageSafeProd.updateHistory(this.ctx.stage, transaction);
  311. await this.ctx.service.stageTempLand.updateHistory(this.ctx.stage, transaction);
  312. // 更新期数据
  313. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  314. const stageTp = {
  315. contract_tp: tpData.contract_tp,
  316. qc_tp: tpData.qc_tp,
  317. positive_qc_tp: tpData.positive_qc_tp,
  318. negative_qc_tp: tpData.negative_qc_tp,
  319. yf_tp: yfPay.tp,
  320. sf_tp: sfPay.tp,
  321. };
  322. this.ctx.stage.tp_history.push({ times: this.ctx.stage.curTimes, order: 0, ...stageTp });
  323. await this.ctx.service.tenderCache.updateStageCache4Start(transaction, this.ctx.stage, auditConst.status.checking, audits, ledgerTp, stageTp);
  324. await transaction.update(this.ctx.service.stage.tableName, {
  325. id: stageId,
  326. status: auditConst.status.checking,
  327. ...stageTp,
  328. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  329. cache_time_r: this.ctx.stage.cache_time_l,
  330. });
  331. // 多人协同,取消下一审批人存在的锁定
  332. await this.ctx.service.stageAuditAss.cancelLock(this.ctx.stage, audits.map(x => { return x.aid; }), transaction);
  333. // 添加短信通知-需要审批提醒功能
  334. const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  335. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/stage/' + stageInfo.order);
  336. const auditIds = this._.map(audits, 'aid');
  337. const users = this._.map(this.ctx.stage.auditAssists.filter(x => { return auditIds.indexOf(x.user_id) >= 0; }), 'ass_user_id');
  338. users.push(...auditIds);
  339. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {
  340. qi: stageInfo.order,
  341. code: shenpiUrl,
  342. });
  343. // 微信模板通知
  344. const wechatData = {
  345. wap_url: shenpiUrl,
  346. qi: stageInfo.order,
  347. status: wxConst.status.check,
  348. tips: wxConst.tips.check,
  349. code: this.ctx.session.sessionProject.code,
  350. };
  351. await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);
  352. // 重新发送配置
  353. for (const a of audits) {
  354. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.JL, {
  355. pid: this.ctx.session.sessionProject.id,
  356. tid: this.ctx.tender.id,
  357. uid: a.aid,
  358. sp_type: 'stage',
  359. sp_id: a.id,
  360. table_name: this.tableName,
  361. template: wxConst.template.stage,
  362. wx_data: wechatData,
  363. });
  364. }
  365. // 上报/审批 - 检查三方特殊推送
  366. await this.ctx.service.specMsg.addStageMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.stage, pushOperate.stage.flow);
  367. await transaction.commit();
  368. // 通知发送 - 第三方更新
  369. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  370. const base_data = {
  371. tid: this.ctx.tender.id,
  372. sid: stageId,
  373. op: 'update',
  374. };
  375. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  376. base_data.op = 'update';
  377. base_data.sid = -1;
  378. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  379. }
  380. } catch (err) {
  381. await transaction.rollback();
  382. throw err;
  383. }
  384. return true;
  385. }
  386. async _checked(pid, stageId, checkData, times) {
  387. const accountId = this.ctx.session.sessionUser.accountId;
  388. const time = new Date();
  389. // 整理当前流程审核人状态更新
  390. const audits = await this.getAllDataByCondition({ where: { sid: stageId, times, status: auditConst.status.checking } });
  391. if (audits.length === 0) throw '审核数据错误';
  392. const selfAudit = audits.find(x => { return x.aid === accountId; });
  393. if (!selfAudit) throw '当前标段您无权审批';
  394. const flowAudits = await this.getAllDataByCondition({ where: { sid: stageId, times, order: selfAudit.order } });
  395. const nextAudits = await this.getAllDataByCondition({ where: { sid: stageId, times, order: selfAudit.order + 1 } });
  396. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  397. const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  398. const transaction = await this.db.beginTransaction();
  399. try {
  400. const ledgerTp = await this._updateTender(transaction);
  401. // 添加通知
  402. const noticeContent = await this.getNoticeContent(pid, stageInfo.tid, stageId, accountId, checkData.opinion);
  403. const auditors = await this.getAuditGroupByListWithOwner(stageId, times);
  404. const defaultNoticeRecord = {
  405. pid,
  406. type: pushType.stage,
  407. status: auditConst.status.checked,
  408. content: noticeContent,
  409. };
  410. const records = [];
  411. auditors.forEach(audit => {
  412. records.push({
  413. uid: audit.aid,
  414. ...defaultNoticeRecord,
  415. });
  416. });
  417. this.ctx.stage.userAssists.forEach(u => {
  418. records.push({ uid: u.ass_user_id, ...defaultNoticeRecord});
  419. });
  420. this.ctx.stage.auditAssists.forEach(u => {
  421. records.push({ uid: u.ass_user_id, ...defaultNoticeRecord});
  422. });
  423. await transaction.insert('zh_notice', records);
  424. // 更新本人审批状态
  425. await transaction.update(this.tableName, {
  426. id: selfAudit.id,
  427. status: checkData.checkType,
  428. opinion: checkData.opinion,
  429. end_time: time,
  430. });
  431. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, selfAudit.id);
  432. // 计算并合同支付最终数据
  433. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  434. const stageTp = {
  435. contract_tp: tpData.contract_tp,
  436. qc_tp: tpData.qc_tp,
  437. positive_qc_tp: tpData.positive_qc_tp,
  438. negative_qc_tp: tpData.negative_qc_tp,
  439. yf_tp: yfPay.tp,
  440. sf_tp: sfPay.tp,
  441. };
  442. this.ctx.stage.tp_history.push({ times, order: selfAudit.order, ...stageTp });
  443. if (audits.length === 1 || selfAudit.audit_type !== auditType.key.and) {
  444. // 或签更新他人审批状态
  445. if (selfAudit.audit_type === auditType.key.or) {
  446. const updateOther = [];
  447. for (const audit of audits) {
  448. if (audit.aid === selfAudit.aid) continue;
  449. updateOther.push({
  450. id: audit.id,
  451. status: auditConst.status.checkSkip,
  452. opinion: '',
  453. end_time: time,
  454. });
  455. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, audit.id);
  456. }
  457. if (updateOther.length > 0) transaction.updateRows(this.tableName, updateOther);
  458. }
  459. // 无下一审核人表示,审核结束
  460. if (nextAudits.length > 0) {
  461. // 复制一份下一审核人数据
  462. await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, nextAudits[0].order, transaction);
  463. await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);
  464. await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);
  465. await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);
  466. await this.ctx.service.stageSafeProd.updateHistory(this.ctx.stage, transaction);
  467. await this.ctx.service.stageTempLand.updateHistory(this.ctx.stage, transaction);
  468. // 流程至下一审批人
  469. const updateData = nextAudits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time: time }; });
  470. await transaction.updateRows(this.tableName, updateData);
  471. // 同步 期信息
  472. await transaction.update(this.ctx.service.stage.tableName, {
  473. id: stageId,
  474. status: auditConst.status.checking,
  475. ...stageTp,
  476. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  477. cache_time_r: this.ctx.stage.cache_time_l,
  478. });
  479. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, this.ctx.stage, auditConst.status.checking, nextAudits, flowAudits, ledgerTp, stageTp);
  480. // 多人协同,取消下一审批人存在的锁定
  481. await this.ctx.service.stageAuditAss.cancelLock(this.ctx.stage, nextAudits.map(x => { return x.aid; }), transaction);
  482. // 添加短信通知-需要审批提醒功能
  483. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/stage/' + stageInfo.order);
  484. const nextAuditIds = this._.map(nextAudits, 'aid');
  485. const users = this._.map(this._.filter(this.ctx.auditAssists, function (x) { return nextAuditIds.indexOf(x.user_id) >= 0; }), 'ass_user_id');
  486. users.push(...nextAuditIds);
  487. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {
  488. qi: stageInfo.order,
  489. code: shenpiUrl,
  490. });
  491. // 微信模板通知
  492. const wechatData = {
  493. wap_url: shenpiUrl,
  494. qi: stageInfo.order,
  495. status: wxConst.status.check,
  496. tips: wxConst.tips.check,
  497. code: this.ctx.session.sessionProject.code,
  498. };
  499. await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);
  500. // 重新发送配置
  501. for (const a of nextAudits) {
  502. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.JL, {
  503. pid: this.ctx.session.sessionProject.id,
  504. tid: this.ctx.tender.id,
  505. uid: a.aid,
  506. sp_type: 'stage',
  507. sp_id: a.id,
  508. table_name: this.tableName,
  509. template: wxConst.template.stage,
  510. wx_data: wechatData,
  511. });
  512. }
  513. } else {
  514. await this.ctx.service.revisePrice.doPriceUsed(this.ctx.stage, transaction);
  515. await this.ctx.service.tenderTag.saveTenderTag(this.ctx.tender.id, {stage_time: new Date()}, transaction);
  516. const his_id = await this.ctx.service.ledgerHistory.checkBackupLedgerHistory(this.ctx.stage.tid, this.ctx.stage.id);
  517. // 本期结束
  518. // 生成截止本期数据 final数据
  519. await this.ctx.service.stageBillsFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  520. await this.ctx.service.stagePosFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  521. await this.ctx.service.stageChangeFinal.generateFinalData(transaction, this.ctx.tender, this.ctx.stage);
  522. // 同步 期信息
  523. await transaction.update(this.ctx.service.stage.tableName, {
  524. id: stageId,
  525. status: checkData.checkType,
  526. ...stageTp,
  527. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  528. cache_time_r: this.ctx.stage.cache_time_l,
  529. his_id,
  530. });
  531. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, this.ctx.stage, checkData.checkType, nextAudits, flowAudits, ledgerTp, stageTp);
  532. await this.ctx.service.stagePay.cacheOrder(this.ctx.stage, transaction);
  533. // 添加短信通知-审批通过提醒功能
  534. const auditList = await this.getAuditors(stageId, stageInfo.times);
  535. const users = this._.uniq(this._.concat(this._.map(auditList, 'aid'), stageInfo.user_id, this._.map(this.ctx.stage.userAssists, 'ass_user_id'), this._.map(this.ctx.stage.auditAssists, 'ass_user_id')));
  536. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), SmsAliConst.template.stage_result, {
  537. qi: stageInfo.order,
  538. status: SmsAliConst.status.success,
  539. });
  540. // 微信模板通知
  541. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/stage/' + stageInfo.order);
  542. const wechatData = {
  543. wap_url: shenpiUrl,
  544. qi: stageInfo.order,
  545. status: wxConst.status.success,
  546. tips: wxConst.tips.success,
  547. code: this.ctx.session.sessionProject.code,
  548. };
  549. await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), wxConst.template.stage, wechatData);
  550. // 期审批完成,检查角色签名数据
  551. await this.ctx.service.roleRptRel.checkSignDate(transaction, this.ctx.stage, selfAudit, time);
  552. // 审批通过 - 检查三方特殊推送
  553. await this.ctx.service.specMsg.addStageMsg(transaction, pid, this.ctx.stage, pushOperate.stage.checked);
  554. }
  555. // 上报/审批 - 检查三方特殊推送
  556. await this.ctx.service.specMsg.addStageMsg(transaction, pid, this.ctx.stage, pushOperate.stage.flow);
  557. } else {
  558. // 同步 期信息
  559. await transaction.update(this.ctx.service.stage.tableName, {
  560. id: stageId,
  561. status: auditConst.status.checking,
  562. ...stageTp,
  563. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  564. cache_time_r: this.ctx.stage.cache_time_l,
  565. });
  566. }
  567. await transaction.commit();
  568. } catch (err) {
  569. await transaction.rollback();
  570. throw err;
  571. }
  572. }
  573. async _checkNo(pid, stageId, checkData, times) {
  574. const accountId = this.ctx.session.sessionUser.accountId;
  575. const time = new Date();
  576. // 整理当前流程审核人状态更新
  577. const audits = await this.getAllDataByCondition({ where: { sid: stageId, times, status: auditConst.status.checking } });
  578. if (!audits) throw '审核数据错误';
  579. const selfAudit = audits.find(x => { return x.aid === accountId; });
  580. if (!selfAudit) throw '当前标段您无权审批';
  581. const flowAudits = await this.getAllDataByCondition({ where: { sid: stageId, times: selfAudit.times, order: selfAudit.order }});
  582. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  583. const auditors = await this.getUniqAuditor(stageId, times); // 全部参与的审批人
  584. const newAuditors = auditors.map(x => {
  585. return {
  586. aid: x.aid, tid: selfAudit.tid, sid: selfAudit.sid,
  587. times: times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  588. audit_type: x.audit_type, audit_order: x.audit_order,
  589. }
  590. });
  591. const transaction = await this.db.beginTransaction();
  592. try {
  593. const ledgerTp = await this._updateTender(transaction);
  594. // 添加推送
  595. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, stageId, selfAudit.aid, checkData.opinion);
  596. const defaultNoticeRecord = {
  597. pid,
  598. type: pushType.stage,
  599. status: auditConst.status.checkNo,
  600. content: noticeContent,
  601. };
  602. const records = [
  603. {
  604. uid: this.ctx.stage.user_id,
  605. ...defaultNoticeRecord,
  606. },
  607. ];
  608. auditors.forEach(audit => {
  609. records.push({
  610. uid: audit.aid,
  611. ...defaultNoticeRecord,
  612. });
  613. });
  614. this.ctx.stage.userAssists.forEach(u => {
  615. records.push({ uid: u.ass_user_id, ...defaultNoticeRecord});
  616. });
  617. this.ctx.stage.auditAssists.forEach(u => {
  618. records.push({ uid: u.ass_user_id, ...defaultNoticeRecord});
  619. });
  620. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  621. // 计算并合同支付最终数据
  622. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  623. const stageTp = {
  624. contract_tp: tpData.contract_tp,
  625. qc_tp: tpData.qc_tp,
  626. positive_qc_tp: tpData.positive_qc_tp,
  627. negative_qc_tp: tpData.negative_qc_tp,
  628. yf_tp: yfPay.tp,
  629. sf_tp: sfPay.tp,
  630. };
  631. const orgHisIndex = this.ctx.stage.tp_history.findIndex(x => { return x.times === times && x.order === selfAudit.order; });
  632. if (orgHisIndex) this.ctx.stage.tp_history.splice(orgHisIndex, 1);
  633. this.ctx.stage.tp_history.push({ times, order: selfAudit.order, ...stageTp });
  634. const updateData = [];
  635. audits.forEach(x => {
  636. updateData.push({
  637. id: x.id,
  638. status: x.aid === selfAudit.aid ? checkData.checkType : auditConst.status.checkSkip,
  639. opinion: x.aid === selfAudit.aid ? checkData.opinion : '',
  640. end_time: x.aid === selfAudit.aid ? time : null,
  641. });
  642. });
  643. await transaction.updateRows(this.tableName, updateData);
  644. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  645. // 同步 期信息
  646. await transaction.update(this.ctx.service.stage.tableName, {
  647. id: stageId,
  648. status: checkData.checkType,
  649. ...stageTp,
  650. times: times + 1,
  651. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  652. cache_time_r: this.ctx.stage.cache_time_l,
  653. });
  654. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, this.ctx.stage, checkData.checkType,
  655. [{ aid: this.ctx.stage.user_id, audit_order: 0, audit_type: auditType.key.common, status: auditConst.status.uncheck }], flowAudits, ledgerTp, stageTp);
  656. // 拷贝新一次审核流程列表
  657. await transaction.insert(this.tableName, newAuditors);
  658. // 计算该审批人最终数据
  659. await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  660. // 复制一份最新数据给原报
  661. await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times + 1, 0, transaction);
  662. await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);
  663. await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);
  664. await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);
  665. await this.ctx.service.stageSafeProd.updateHistory(this.ctx.stage, transaction);
  666. await this.ctx.service.stageTempLand.updateHistory(this.ctx.stage, transaction);
  667. // 锁定本人数据,保留锁定数据相关确认状态
  668. await this.ctx.service.stageAuditAss.lockConfirm4CheckNo(this.ctx.stage, audits.map(x => { return x.aid; }), auditors, transaction);
  669. // 添加短信通知-审批退回提醒功能
  670. // const mobile_array = [];
  671. const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  672. const auditList = await this.getAuditors(stageId, stageInfo.times);
  673. const users = this._.uniq(this._.concat(this._.map(auditList, 'aid'), stageInfo.user_id, this._.map(this.ctx.stage.userAssists, 'ass_user_id'), this._.map(this.ctx.stage.auditAssists, 'ass_user_id')));
  674. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), SmsAliConst.template.stage_result, {
  675. qi: stageInfo.order,
  676. status: SmsAliConst.status.back,
  677. });
  678. // 微信模板通知
  679. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/stage/' + stageInfo.order);
  680. const wechatData = {
  681. wap_url: shenpiUrl,
  682. qi: stageInfo.order,
  683. status: wxConst.status.back,
  684. tips: wxConst.tips.back,
  685. code: this.ctx.session.sessionProject.code,
  686. };
  687. await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.result.toString(), wxConst.template.stage, wechatData);
  688. // 上报/审批 - 检查三方特殊推送
  689. await this.ctx.service.specMsg.addStageMsg(transaction, pid, this.ctx.stage, pushOperate.stage.flow);
  690. await transaction.commit();
  691. } catch (err) {
  692. await transaction.rollback();
  693. throw err;
  694. }
  695. }
  696. async _checkNoPre(pid, stageId, checkData, times) {
  697. const accountId = this.ctx.session.sessionUser.accountId;
  698. const time = new Date();
  699. // 整理当前流程审核人状态更新
  700. const audits = await this.getAllDataByCondition({ where: { sid: stageId, times, status: auditConst.status.checking } });
  701. if (audits.length === 0 || audits[0].order <= 1) throw '审核数据错误';
  702. const selfAudit = audits.find(x => { return x.aid === accountId; });
  703. if (!selfAudit) throw '当前标段您无权审批';
  704. const flowAudits = await this.getAllDataByCondition({ where: { sid: stageId, times: selfAudit.times, order: selfAudit.order }});
  705. // 添加重新审批后,不能用order-1,取groupby值里的上一个才对
  706. // const preAuditor = await this.getDataByCondition({sid: stageId, times: times, order: audit.order - 1});
  707. const auditors2 = await this.getAuditGroupByList(stageId, times);
  708. const preAuditors = auditors2.filter(x => { return x.audit_order === selfAudit.audit_order - 1});
  709. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  710. const transaction = await this.db.beginTransaction();
  711. try {
  712. const ledgerTp = await this._updateTender(transaction);
  713. // 添加通知
  714. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, stageId, selfAudit.aid, checkData.opinion);
  715. const defaultNoticeRecord = {
  716. pid,
  717. type: pushType.stage,
  718. status: auditConst.status.checkNoPre,
  719. content: noticeContent,
  720. };
  721. const records = [
  722. {
  723. uid: this.ctx.stage.user_id,
  724. ...defaultNoticeRecord
  725. },
  726. ];
  727. auditors2.forEach(audit => {
  728. records.push({
  729. uid: audit.aid,
  730. ...defaultNoticeRecord
  731. });
  732. });
  733. this.ctx.stage.userAssists.forEach(u => {
  734. records.push({ uid: u.ass_user_id, ...defaultNoticeRecord});
  735. });
  736. this.ctx.stage.auditAssists.forEach(u => {
  737. records.push({ uid: u.ass_user_id, ...defaultNoticeRecord});
  738. });
  739. await transaction.insert('zh_notice', records);
  740. // 计算并合同支付最终数据
  741. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  742. const stageTp = {
  743. contract_tp: tpData.contract_tp,
  744. qc_tp: tpData.qc_tp,
  745. positive_qc_tp: tpData.positive_qc_tp,
  746. negative_qc_tp: tpData.negative_qc_tp,
  747. yf_tp: yfPay.tp,
  748. sf_tp: sfPay.tp,
  749. };
  750. this.ctx.stage.tp_history.push({ times, order: selfAudit.order, ...stageTp });
  751. // 同步 期信息
  752. await transaction.update(this.ctx.service.stage.tableName, {
  753. id: stageId,
  754. times,
  755. ...stageTp,
  756. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  757. cache_time_r: this.ctx.stage.cache_time_l,
  758. });
  759. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, this.ctx.stage, checkData.checkType, preAuditors, flowAudits, ledgerTp, stageTp);
  760. // 更新同一流程所有审批人状态
  761. const updateData = [];
  762. for (const audit of audits) {
  763. if (audit.aid === selfAudit.aid) {
  764. updateData.push({
  765. id: audit.id, status: checkData.checkType, opinion: checkData.opinion, end_time: time,
  766. });
  767. } else {
  768. updateData.push({
  769. id: audit.id, status: auditConst.status.checkSkip, opinion: '', end_time: null,
  770. });
  771. }
  772. }
  773. await transaction.updateRows(this.tableName, updateData);
  774. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  775. // 顺移其后审核人流程顺序
  776. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE sid = ? AND times = ? AND `order` > ?';
  777. await transaction.query(sql, [stageId, selfAudit.times, selfAudit.order]);
  778. // 上一审批人,当前审批人 再次添加至流程
  779. const newAuditors = [];
  780. preAuditors.forEach(x => {
  781. newAuditors.push({
  782. tid: this.ctx.stage.tid, sid: this.ctx.stage.id, aid: x.aid,
  783. times: x.times, order: selfAudit.order + 1,
  784. status: auditConst.status.checking, begin_time: time,
  785. audit_type: x.audit_type, audit_order: x.audit_order,
  786. });
  787. });
  788. // 获取ids值
  789. const newAuditors_result = await transaction.insert(this.tableName, newAuditors);
  790. // 获取刚批量添加的所有list
  791. for (let j = 0; j < preAuditors.length; j++) {
  792. newAuditors[j].id = newAuditors_result.insertId + j;
  793. }
  794. const newFlowAuditors = [];
  795. flowAudits.forEach(x => {
  796. newFlowAuditors.push({
  797. tid: this.ctx.stage.tid, sid: this.ctx.stage.id, aid: x.aid,
  798. times: x.times, order: selfAudit.order + 2,
  799. status: auditConst.status.uncheck,
  800. audit_type: x.audit_type, audit_order: x.audit_order,
  801. });
  802. });
  803. await transaction.insert(this.tableName, newFlowAuditors);
  804. // 计算该审批人最终数据
  805. await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  806. // 复制一份最新数据给下一人
  807. await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, selfAudit.order + 1, transaction);
  808. await this.ctx.service.stageJgcl.updateHistory(this.ctx.stage, transaction);
  809. await this.ctx.service.stageBonus.updateHistory(this.ctx.stage, transaction);
  810. await this.ctx.service.stageOther.updateHistory(this.ctx.stage, transaction);
  811. await this.ctx.service.stageSafeProd.updateHistory(this.ctx.stage, transaction);
  812. await this.ctx.service.stageTempLand.updateHistory(this.ctx.stage, transaction);
  813. const preAuditorIds = preAuditors.map(x => { return x.aid; });
  814. // 锁定本人数据,保留锁定数据相关确认状态
  815. await this.ctx.service.stageAuditAss.lockConfirm4CheckNoPre(this.ctx.stage, audits.map(x => { return x.aid; }), preAuditorIds, transaction);
  816. // 同步 期信息
  817. await transaction.update(this.ctx.service.stage.tableName, {
  818. id: stageId,
  819. status: checkData.checkType,
  820. cache_time_r: this.ctx.stage.cache_time_l,
  821. });
  822. const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  823. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/stage/' + stageInfo.order);
  824. const users = this._.map(this.ctx.stage.auditAssists.filter(x => {return preAuditorIds.indexOf(x.user_id) >= 0 }), 'ass_user_id');
  825. users.push(...preAuditorIds);
  826. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {
  827. qi: stageInfo.order,
  828. code: shenpiUrl,
  829. });
  830. // 微信模板通知
  831. const wechatData = {
  832. wap_url: shenpiUrl,
  833. qi: stageInfo.order,
  834. status: wxConst.status.check,
  835. tips: wxConst.tips.check,
  836. code: this.ctx.session.sessionProject.code,
  837. };
  838. await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);
  839. // 重新发送配置
  840. for (const a of newAuditors) {
  841. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.JL, {
  842. pid: this.ctx.session.sessionProject.id,
  843. tid: this.ctx.tender.id,
  844. uid: a.aid,
  845. sp_type: 'stage',
  846. sp_id: a.id,
  847. table_name: this.tableName,
  848. template: wxConst.template.stage,
  849. wx_data: wechatData,
  850. });
  851. }
  852. // 上报/审批 - 检查三方特殊推送
  853. await this.ctx.service.specMsg.addStageMsg(transaction, pid, this.ctx.stage, pushOperate.stage.flow);
  854. await transaction.commit();
  855. } catch (err) {
  856. await transaction.rollback();
  857. throw err;
  858. }
  859. }
  860. /**
  861. * 审批
  862. * @param {Number} stageId - 标段id
  863. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  864. * @param {Number} times - 第几次审批
  865. * @return {Promise<void>}
  866. */
  867. async check(stageId, checkData, times = 1) {
  868. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo && checkData.checkType !== auditConst.status.checkNoPre) {
  869. throw '提交数据错误';
  870. }
  871. // // 整理当前流程审核人状态更新
  872. // const audit = await this.getDataByCondition({sid: stageId, times: times, status: auditConst.status.checking});
  873. // if (!audit) {
  874. // throw '审核数据错误';
  875. // }
  876. // const time = new Date();
  877. const pid = this.ctx.session.sessionProject.id;
  878. switch (checkData.checkType) {
  879. case auditConst.status.checked:
  880. await this._checked(pid, stageId, checkData, times);
  881. break;
  882. case auditConst.status.checkNo:
  883. await this._checkNo(pid, stageId, checkData, times);
  884. break;
  885. case auditConst.status.checkNoPre:
  886. await this._checkNoPre(pid, stageId, checkData, times);
  887. break;
  888. default:
  889. throw '无效审批操作';
  890. }
  891. // 通知发送 - 第三方更新
  892. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  893. const base_data = {
  894. tid: this.ctx.tender.id,
  895. sid: stageId,
  896. op: 'update',
  897. };
  898. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  899. base_data.op = 'update';
  900. base_data.sid = -1;
  901. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  902. }
  903. }
  904. /**
  905. * 审批
  906. * @param {Number} stageId - 标段id
  907. * @param {Number} times - 第几次审批
  908. * @return {Promise<void>}
  909. */
  910. async checkAgain(stageId, times = 1, force) {
  911. const accountId = this.ctx.session.sessionUser.accountId;
  912. const time = new Date();
  913. // 整理当前流程审核人状态更新
  914. const auditors = await this.getAllDataByCondition({
  915. where: { sid: stageId, times },
  916. orders: [['order', 'asc']],
  917. });
  918. const maxOrder = auditors[auditors.length - 1].order;
  919. const audits = auditors.filter(x => { return x.order === maxOrder});
  920. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  921. const selfAudit = audits.find(x => { return x.aid === accountId; });
  922. if (!selfAudit && !force) throw '当前标段您无权审批';
  923. const finalAudit = selfAudit || audits[0];
  924. const stageInfo = await this.ctx.service.stage.getDataById(stageId);
  925. const transaction = await this.db.beginTransaction();
  926. try {
  927. // 当前审批人2次添加至流程中
  928. const checkAgainAuditors = [], checkingAuditors = [];
  929. audits.forEach(x => {
  930. checkAgainAuditors.push({
  931. tid: x.tid, sid: x.sid, aid: x.aid,
  932. times: x.times, order: x.order + 1,
  933. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  934. begin_time: time, end_time: time, opinion: '',
  935. audit_type: x.audit_type, audit_order: x.audit_order,
  936. });
  937. });
  938. audits.forEach(x => {
  939. checkingAuditors.push({
  940. tid: x.tid, sid: x.sid, aid: x.aid,
  941. times: x.times, order: x.order + 2,
  942. status: auditConst.status.checking,
  943. begin_time: time, end_time: time, opinion: '',
  944. audit_type: x.audit_type, audit_order: x.audit_order,
  945. });
  946. });
  947. await transaction.insert(this.tableName, checkAgainAuditors);
  948. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  949. // 获取刚批量添加的所有list
  950. for (let j = 0; j < checkingAuditors.length; j++) {
  951. checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  952. }
  953. // 复制一份最新数据给下一人
  954. await this.ctx.service.stagePay.clearCacheOrder(this.ctx.stage, transaction);
  955. await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, finalAudit.order + 1, transaction);
  956. await this.ctx.service.stagePay.copyAuditStagePays(this.ctx.stage, this.ctx.stage.times, finalAudit.order + 2, transaction);
  957. await this.ctx.service.stageJgcl.updateHistory4CheckAgain(this.ctx.stage, transaction);
  958. await this.ctx.service.stageBonus.updateHistory4CheckAgain(this.ctx.stage, transaction);
  959. await this.ctx.service.stageOther.updateHistory4CheckAgain(this.ctx.stage, transaction);
  960. await this.ctx.service.stageSafeProd.updateHistory4CheckAgain(this.ctx.stage, transaction);
  961. await this.ctx.service.stageTempLand.updateHistory4CheckAgain(this.ctx.stage, transaction);
  962. // 同步 期信息
  963. const his = this.ctx.stage.tp_history.find(x => { return x.times === times && x.order === finalAudit.order });
  964. const stageTp = {
  965. contract_tp: his.contract_tp,
  966. qc_tp: his.qc_tp,
  967. positive_qc_tp: his.positive_qc_tp,
  968. negative_qc_tp: his.negative_qc_tp,
  969. yf_tp: his.tp,
  970. sf_tp: his.tp,
  971. };
  972. this.ctx.stage.tp_history.push({ times, order: finalAudit.order + 1, ...stageTp });
  973. await transaction.update(this.ctx.service.stage.tableName, {
  974. id: stageId,
  975. status: auditConst.status.checking,
  976. cache_time_r: this.ctx.stage.cache_time_l,
  977. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  978. });
  979. // 已经引用到本期的单价变更,全部取消
  980. await this.ctx.service.revisePrice.cancelPriceUsed(this.ctx.stage, transaction);
  981. // 重算所有单价变更
  982. const priceCalc = new RevisePrice(this.ctx);
  983. const pcTp = await priceCalc.stageCheckAgainPriceChange(this.ctx.stage, finalAudit.order + 2, transaction);
  984. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, this.ctx.stage, auditConst.status.checking, checkingAuditors, checkAgainAuditors, null, stageTp, pcTp);
  985. // 添加短信通知-需要审批提醒功能
  986. const shenpiUrl = await this.ctx.helper.urlToShort(this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/measure/stage/' + stageInfo.order);
  987. const auditorIds = audits.map(x => { return x.aid; });
  988. const users = this._.map(this.ctx.stage.auditAssists.filter(x => { return auditorIds.indexOf(x.user_id) >= 0; }), 'ass_user_id');
  989. users.push(...auditorIds);
  990. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), SmsAliConst.template.stage_check, {
  991. qi: stageInfo.order,
  992. code: shenpiUrl,
  993. });
  994. // 微信模板通知
  995. const wechatData = {
  996. wap_url: shenpiUrl,
  997. qi: stageInfo.order,
  998. status: wxConst.status.check,
  999. tips: wxConst.tips.check,
  1000. code: this.ctx.session.sessionProject.code,
  1001. };
  1002. await this.ctx.helper.sendWechat(users, smsTypeConst.const.JL, smsTypeConst.judge.approval.toString(), wxConst.template.stage, wechatData);
  1003. // 重新发送配置
  1004. for (const a of checkingAuditors) {
  1005. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.JL, {
  1006. pid: this.ctx.session.sessionProject.id,
  1007. tid: this.ctx.tender.id,
  1008. uid: a.aid,
  1009. sp_type: 'stage',
  1010. sp_id: a.id,
  1011. table_name: this.tableName,
  1012. template: wxConst.template.stage,
  1013. wx_data: wechatData,
  1014. });
  1015. }
  1016. // 上报/审批 - 检查三方特殊推送
  1017. await this.ctx.service.specMsg.addStageMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.stage, pushOperate.stage.flow);
  1018. await transaction.commit();
  1019. // 通知发送 - 第三方更新
  1020. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  1021. const base_data = {
  1022. tid: this.ctx.tender.id,
  1023. sid: stageId,
  1024. op: 'update',
  1025. };
  1026. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  1027. base_data.op = 'update';
  1028. base_data.sid = -1;
  1029. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  1030. }
  1031. } catch (err) {
  1032. await transaction.rollback();
  1033. throw err;
  1034. }
  1035. }
  1036. /**
  1037. * 原报撤回,直接改动审批人状态
  1038. * 如果存在审批人数据,将其改为原报流程数据,但保留原提交人
  1039. *
  1040. * 一审 1 A checking -> A uncheck status改 pay/jl:删0(jl为增量数据,只删重复部分) 1->0 删1
  1041. * ...
  1042. *
  1043. * @param stage
  1044. * @returns {Promise<void>}
  1045. * @private
  1046. */
  1047. async _userCheckCancel(stage) {
  1048. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  1049. const transaction = await this.db.beginTransaction();
  1050. try {
  1051. const ledgerTp = await this._updateTender(transaction);
  1052. // 整理当前流程审核人状态更新
  1053. // 审批人变成待审批状态
  1054. const updateData = stage.curAuditors.map(x => {
  1055. return {
  1056. id: x.id,
  1057. status: auditConst.status.uncheck,
  1058. begin_time: null,
  1059. opinion: null,
  1060. }
  1061. });
  1062. await transaction.updateRows(this.tableName, updateData);
  1063. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  1064. // 计算并合同支付最终数据
  1065. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(stage, transaction);
  1066. const stageTp = {
  1067. contract_tp: tpData.contract_tp,
  1068. qc_tp: tpData.qc_tp,
  1069. positive_qc_tp: tpData.positive_qc_tp,
  1070. negative_qc_tp: tpData.negative_qc_tp,
  1071. yf_tp: yfPay.tp,
  1072. sf_tp: sfPay.tp,
  1073. };
  1074. await transaction.update(this.ctx.service.stage.tableName, {
  1075. id: stage.id,
  1076. times: stage.times,
  1077. ...stageTp,
  1078. tp_history: JSON.stringify(this.ctx.stage.tp_history.filter(x => { return x.times < stage.times; })),
  1079. cache_time_r: this.ctx.stage.cache_time_l,
  1080. status: stage.times === 1 ? auditConst.status.uncheck : auditConst.status.checkNo,
  1081. });
  1082. // 计量明细:重复数据删除原报,新增数据修改为原报
  1083. await this.ctx.service.stageBills.updateStageBills4CheckCancel(stage.id, stage.times, 0, stage.times, 1, transaction);
  1084. await this.ctx.service.stagePos.updateStagePos4CheckCancel(stage.id, stage.times, 0, stage.times, 1, transaction);
  1085. await this.ctx.service.stageDetail.updateStageDetail4CheckCancel(stage.id, stage.times, 0, stage.times, 1, transaction);
  1086. await this.ctx.service.stageChange.updateStageChange4CheckCancel(stage.id, stage.times, 0, stage.times, 1, transaction);
  1087. // 合同支付明细:保留审批人数据,覆盖到原报中并删除该审批人合同支付数据
  1088. await this.ctx.service.stagePay.deleteAuditStagePays(stage, stage.times, 0, transaction);
  1089. await this.ctx.service.stagePay.copyAuditStagePays(stage, stage.times, 0, transaction, this.ctx.stage.times, 1);
  1090. await this.ctx.service.stagePay.deleteAuditStagePays(stage, stage.times, 1, transaction);
  1091. // 其他台账明细:不需更新历史
  1092. // 更新标段计量数据缓存
  1093. const preFlow = stage.times > 1 ? await this.getLastestAuditors(stage.id, stage.times, auditConst.status.checkNo): null;
  1094. const curFlow = [{ aid: this.ctx.stage.user_id, audit_type: auditType.key.common, audit_order: 1, status: auditConst.status.uncheck}];
  1095. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, this.ctx.stage, stage.times === 1 ? auditConst.status.uncheck : auditConst.status.checkNo,
  1096. curFlow, preFlow, ledgerTp, stageTp);
  1097. // 上报/审批 - 检查三方特殊推送
  1098. await this.ctx.service.specMsg.addStageMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.stage, pushOperate.stage.flow);
  1099. await transaction.commit();
  1100. } catch(err) {
  1101. await transaction.rollback();
  1102. throw err;
  1103. }
  1104. }
  1105. /**
  1106. * 审批人撤回审批通过,插入两条数据
  1107. *
  1108. * 一审 1 A checked 一审 1 A checked
  1109. * 二审 2 B checked pre -> 二审 2 B checked
  1110. * 三审 3 C checking cur 二审 3 B checkCancel 增 增extra_his 增tp_his
  1111. * 四审 4 D uncheck 二审 4 B checking 增 增pay_cur
  1112. * 三审 5 C uncheck order、status改
  1113. * 四审 6 D uncheck order改
  1114. *
  1115. * @param stage
  1116. * @returns {Promise<void>}
  1117. * @private
  1118. */
  1119. async _auditCheckCancel(stage) {
  1120. if (stage.curAuditors.length === 0 || stage.curAuditors[0].order <= 1) {
  1121. throw '撤回用户数据错误';
  1122. }
  1123. const accountId = this.ctx.session.sessionUser.accountId;
  1124. const selfAuditor = this.ctx.stage.preAuditors.find(x => { return x.aid === accountId; });
  1125. if (!selfAuditor) throw '撤回用户数据错误';
  1126. const time = new Date();
  1127. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  1128. const transaction = await this.db.beginTransaction();
  1129. try {
  1130. const ledgerTp = await this._updateTender(transaction);
  1131. // 整理当前流程审核人状态更新
  1132. // 顺移其后审核人流程顺序
  1133. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE sid = ? AND times = ? AND `order` > ?';
  1134. await transaction.query(sql, [stage.id, selfAuditor.times, stage.curAuditors[0].order]);
  1135. // 当前审批人2次添加至流程中
  1136. const checkCancelAuditors = [], checkingAuditors = [];
  1137. stage.preAuditors.forEach(x => {
  1138. checkCancelAuditors.push({
  1139. tid: stage.tid, sid: stage.id, aid: x.aid,
  1140. times: x.times, order: x.order + 1,
  1141. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  1142. begin_time: time, end_time: time, opinion: '',
  1143. audit_type: x.audit_type, audit_order: x.audit_order,
  1144. });
  1145. });
  1146. stage.preAuditors.forEach(x => {
  1147. checkingAuditors.push({
  1148. tid: stage.tid, sid: stage.id, aid: x.aid,
  1149. times: x.times, order: x.order + 2,
  1150. status: auditConst.status.checking,
  1151. begin_time: time, end_time: time, opinion: '',
  1152. audit_type: x.audit_type, audit_order: x.audit_order,
  1153. });
  1154. });
  1155. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  1156. // 当前审批人变成待审批
  1157. await transaction.updateRows(this.tableName, stage.curAuditors.map(x => { return {
  1158. id: x.id, begin_time: null, status: auditConst.status.uncheck, order: x.order + 2
  1159. }}));
  1160. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(stage.curAuditors, 'id'));
  1161. // 计算并合同支付最终数据
  1162. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(this.ctx.stage, transaction);
  1163. const stageTp = {
  1164. contract_tp: tpData.contract_tp,
  1165. qc_tp: tpData.qc_tp,
  1166. positive_qc_tp: tpData.positive_qc_tp,
  1167. negative_qc_tp: tpData.negative_qc_tp,
  1168. yf_tp: yfPay.tp,
  1169. sf_tp: sfPay.tp,
  1170. };
  1171. this.ctx.stage.tp_history.push({ times: stage.times, order: selfAuditor.order + 1, ...stageTp });
  1172. // 同步 期信息
  1173. await transaction.update(this.ctx.service.stage.tableName, {
  1174. id: stage.id,
  1175. times: stage.times,
  1176. ...stageTp,
  1177. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  1178. cache_time_r: this.ctx.stage.cache_time_l,
  1179. });
  1180. // 计量明细:勿需修改任何数据
  1181. // 合同支付明细:复制一份最新数据给下一人
  1182. await this.ctx.service.stagePay.copyAuditStagePays(stage, stage.times, selfAuditor.order + 2, transaction, stage.times, selfAuditor.order + 1);
  1183. // 其他台账明细:更新两份历史数据
  1184. await this.ctx.service.stageJgcl.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1185. await this.ctx.service.stageBonus.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1186. await this.ctx.service.stageOther.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1187. await this.ctx.service.stageSafeProd.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1188. await this.ctx.service.stageTempLand.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1189. // 更新标段计量数据缓存
  1190. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, stage, stage.status, checkingAuditors, checkCancelAuditors, ledgerTp, stageTp);
  1191. // 上报/审批 - 检查三方特殊推送
  1192. await this.ctx.service.specMsg.addStageMsg(transaction, this.ctx.session.sessionProject.id, stage, pushOperate.stage.flow);
  1193. await transaction.commit();
  1194. } catch(err) {
  1195. await transaction.rollback();
  1196. throw err;
  1197. }
  1198. }
  1199. /**
  1200. * 审批人撤回审批退回上一人,插入两条数据
  1201. *
  1202. * 一审 1 A checked 一审 1 A checked
  1203. * 二审 2 B checked 二审 2 B checked
  1204. * 三审 3 C checkNoPre pre -> 三审 3 C checkNoPre
  1205. * 二审 4 B checking cur 三审 4 C checkCancel 删4B 增4C 增extra_his 增tp_his
  1206. * 三审 5 C uncheck 三审 5 C checking status改 增pay_cur
  1207. * 四审 6 D uncheck 四审 6 D uncheck
  1208. *
  1209. * @param stage
  1210. * @returns {Promise<void>}
  1211. * @private
  1212. */
  1213. async _auditCheckCancelNoPre(stage) {
  1214. if (stage.curAuditors.length === 0 || stage.curAuditors[0].order <= 1) {
  1215. throw '撤回用户数据错误';
  1216. }
  1217. const accountId = this.ctx.session.sessionUser.accountId;
  1218. const selfAuditor = this.ctx.stage.preAuditors.find(x => { return x.aid === accountId; });
  1219. if (!selfAuditor) throw '撤回用户数据错误';
  1220. const time = new Date();
  1221. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  1222. const transaction = await this.db.beginTransaction();
  1223. try {
  1224. const ledgerTp = await this._updateTender(transaction);
  1225. // 整理当前流程审核人状态更新
  1226. // 删除当前审批人
  1227. await transaction.delete(this.tableName, { id: stage.curAuditors.map(x => { return x.id; }) });
  1228. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(stage.curAuditors, 'id'));
  1229. // 添加撤回人到审批流程中
  1230. const newAuditors = [];
  1231. stage.preAuditors.forEach(x => {
  1232. newAuditors.push({
  1233. tid: stage.tid, sid: stage.id, aid: x.aid,
  1234. times: x.times, order: x.order + 1,
  1235. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  1236. begin_time: time, end_time: time, opinion: '',
  1237. audit_type: x.audit_type, audit_order: x.audit_order,
  1238. });
  1239. });
  1240. await transaction.insert(this.tableName, newAuditors);
  1241. // 更新上一个人,最新审批状态为审批中
  1242. await transaction.update(this.tableName, { begin_time: time, status: auditConst.status.checking }, {
  1243. where: { sid: stage.id, times: selfAuditor.times, order: selfAuditor.order + 2 }
  1244. });
  1245. // 计算并合同支付最终数据
  1246. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(stage, transaction);
  1247. const stageTp = {
  1248. contract_tp: tpData.contract_tp,
  1249. qc_tp: tpData.qc_tp,
  1250. positive_qc_tp: tpData.positive_qc_tp,
  1251. negative_qc_tp: tpData.negative_qc_tp,
  1252. yf_tp: yfPay.tp,
  1253. sf_tp: sfPay.tp,
  1254. };
  1255. stage.tp_history.push({ times: stage.times, order: selfAuditor.order + 1, ...stageTp });
  1256. // 同步 期信息
  1257. await transaction.update(this.ctx.service.stage.tableName, {
  1258. id: stage.id,
  1259. times: stage.times,
  1260. ...stageTp,
  1261. status: auditConst.status.checking,
  1262. tp_history: JSON.stringify(stage.tp_history),
  1263. cache_time_r: stage.cache_time_l,
  1264. });
  1265. // 计量明细:勿需修改任何数据
  1266. // 合同支付明细:复制一份最新数据给下一人
  1267. await this.ctx.service.stagePay.copyAuditStagePays(stage, stage.times, selfAuditor.order + 2, transaction, stage.times, selfAuditor.order + 1);
  1268. // 其他台账明细:更新一份历史数据
  1269. await this.ctx.service.stageJgcl.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1270. await this.ctx.service.stageBonus.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1271. await this.ctx.service.stageOther.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1272. await this.ctx.service.stageSafeProd.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1273. await this.ctx.service.stageTempLand.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1274. // 更新标段计量数据缓存
  1275. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, stage, stage.status, newAuditors, stage.preAuditors, ledgerTp, stageTp);
  1276. // 上报/审批 - 检查三方特殊推送
  1277. await this.ctx.service.specMsg.addStageMsg(transaction, this.ctx.session.sessionProject.id, stage, pushOperate.stage.flow);
  1278. await transaction.commit();
  1279. } catch(err) {
  1280. await transaction.rollback();
  1281. throw err;
  1282. }
  1283. }
  1284. /**
  1285. * 审批人撤回审批退回原报
  1286. *
  1287. * 1# 一审 1 A checked 1# 一审 1 A checked
  1288. * 二审 2 B checkNo pre -> 二审 2 B checkNo
  1289. * 三审 3 C uncheck 二审 3 B checkCancel 增 pay: 2#0 -> 1#3 jl: 2#0 -> 1#3 增tp_his 增extra_his
  1290. * 二审 4 B checking 增 pay: 2#0 -> 1#4
  1291. * 三审 5 C uncheck order改
  1292. *
  1293. * 2# 一审 1 A uncheck 2# 删 pay: 2#0删 jl: 2#0删
  1294. * 二审 2 B uncheck
  1295. * 三审 3 C uncheck
  1296. *
  1297. * @param stage
  1298. * @returns {Promise<void>}
  1299. * @private
  1300. */
  1301. async _auditCheckCancelNo(stage) {
  1302. const accountId = this.ctx.session.sessionUser.accountId;
  1303. const selfAuditor = stage.preAuditors.find(x => { return x.aid === accountId && x.status === auditConst.status.checkNo; });
  1304. if (!selfAuditor) throw '该标段由他人审批退回,您不可撤回';
  1305. const time = new Date();
  1306. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  1307. const transaction = await this.db.beginTransaction();
  1308. try {
  1309. const ledgerTp = await this._updateTender(transaction);
  1310. // 整理上一个流程审核人状态更新
  1311. // 顺移其后审核人流程顺序
  1312. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE sid = ? AND times = ? AND `order` > ?';
  1313. await transaction.query(sql, [stage.id, selfAuditor.times, selfAuditor.order]);
  1314. // 当前审批人2次添加至流程中
  1315. const checkCancelAuditors = [], checkingAuditors = [];
  1316. stage.preAuditors.forEach(x => {
  1317. checkCancelAuditors.push({
  1318. tid: stage.tid, sid: stage.id, aid: x.aid,
  1319. times: x.times, order: x.order + 1,
  1320. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  1321. begin_time: time, end_time: time, opinion: '',
  1322. audit_type: x.audit_type, audit_order: x.audit_order,
  1323. });
  1324. });
  1325. stage.preAuditors.forEach(x => {
  1326. checkingAuditors.push({
  1327. tid: stage.tid, sid: stage.id, aid: x.aid,
  1328. times: x.times, order: x.order + 2,
  1329. status: auditConst.status.checking,
  1330. begin_time: time, end_time: time, opinion: '',
  1331. audit_type: x.audit_type, audit_order: x.audit_order,
  1332. });
  1333. });
  1334. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  1335. // 删除当前次审批流
  1336. await transaction.delete(this.tableName, { sid: stage.id, times: stage.times });
  1337. // 计算并合同支付最终数据
  1338. const [yfPay, sfPay] = await this.ctx.service.stagePay.calcAllStagePays(stage, transaction);
  1339. const stageTp = {
  1340. contract_tp: tpData.contract_tp,
  1341. qc_tp: tpData.qc_tp,
  1342. positive_qc_tp: tpData.positive_qc_tp,
  1343. negative_qc_tp: tpData.negative_qc_tp,
  1344. yf_tp: yfPay.tp,
  1345. sf_tp: sfPay.tp,
  1346. };
  1347. stage.tp_history.push({ times: selfAuditor.times, order: selfAuditor.order + 1, ...stageTp });
  1348. await transaction.update(this.ctx.service.stage.tableName, {
  1349. id: stage.id,
  1350. times: stage.times - 1,
  1351. ...stageTp,
  1352. tp_history: JSON.stringify(this.ctx.stage.tp_history),
  1353. cache_time_r: stage.cache_time_l,
  1354. status: auditConst.status.checking,
  1355. });
  1356. // 计量明细:重复数据删除原报,新增数据修改为原报
  1357. await this.ctx.service.stageBills.updateStageBills4CheckCancel(stage.id, selfAuditor.times, selfAuditor.order + 1, stage.times, 0, transaction);
  1358. await this.ctx.service.stagePos.updateStagePos4CheckCancel(stage.id, selfAuditor.times, selfAuditor.order + 1, stage.times, 0, transaction);
  1359. await this.ctx.service.stageDetail.updateStageDetail4CheckCancel(stage.id, selfAuditor.times, selfAuditor.order + 1, stage.times, 0, transaction);
  1360. await this.ctx.service.stageChange.updateStageChange4CheckCancel(stage.id, selfAuditor.times, selfAuditor.order + 1, stage.times, 0, transaction);
  1361. // 合同支付明细:复制一份最新数据新增的2个审批流,删除最新一次审批数据
  1362. await this.ctx.service.stagePay.copyAuditStagePays(stage, stage.times - 1, selfAuditor.order + 1, transaction, stage.times, 0);
  1363. await this.ctx.service.stagePay.copyAuditStagePays(stage, stage.times - 1, selfAuditor.order + 2, transaction, stage.times, 0);
  1364. await this.ctx.service.stagePay.deleteAuditStagePays(stage, stage.times, 0, transaction);
  1365. // 其他台账明细:更新一份历史数据
  1366. await this.ctx.service.stageJgcl.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1367. await this.ctx.service.stageBonus.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1368. await this.ctx.service.stageOther.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1369. await this.ctx.service.stageSafeProd.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1370. await this.ctx.service.stageTempLand.updateHistory4TimesOrder(stage, stage.times, [selfAuditor.order + 1], transaction);
  1371. // 更新标段计量数据缓存
  1372. await this.ctx.service.tenderCache.updateStageCache4Flow(transaction, stage, auditConst.status.checking, checkingAuditors, checkCancelAuditors, ledgerTp, stageTp);
  1373. // 上报/审批 - 检查三方特殊推送
  1374. await this.ctx.service.specMsg.addStageMsg(transaction, this.ctx.session.sessionProject.id, stage, pushOperate.stage.flow);
  1375. await transaction.commit();
  1376. } catch(err) {
  1377. await transaction.rollback();
  1378. throw err;
  1379. }
  1380. }
  1381. /**
  1382. * 会签未全部审批通过时,撤回仅修改本人状态
  1383. *
  1384. * @param stage
  1385. * @returns {Promise<void>}
  1386. * @private
  1387. */
  1388. async _auditCheckCancelAnd(stage) {
  1389. const accountId = this.ctx.session.sessionUser.accountId;
  1390. const selfAuditor = stage.flowAuditors.find(x => { return x.aid === accountId; });
  1391. if (!selfAuditor || selfAuditor.status !== auditConst.status.checked) throw '不可撤回';
  1392. const transaction = await this.db.beginTransaction();
  1393. try {
  1394. await transaction.update(this.tableName, {
  1395. id: selfAuditor.id, status: auditConst.status.checking, opinion: '', end_time: null,
  1396. });
  1397. await transaction.commit();
  1398. } catch(err) {
  1399. await transaction.rollback();
  1400. throw err;
  1401. }
  1402. }
  1403. /**
  1404. * 审批撤回
  1405. * @param {Number} stageId - 标段id
  1406. * @param {Number} times - 第几次审批
  1407. * @return {Promise<void>}
  1408. */
  1409. async checkCancel(stage) {
  1410. // 分5种情况,根据ctx.cancancel值判断:
  1411. // 1.原报发起撤回,当前流程删除,并回到待上报
  1412. // 2.审批人撤回审批通过,增加流程,并回到它审批中
  1413. // 3.审批人撤回审批退回上一人,并删除退回人,增加流程,并回到它审批中,并更新计量期状态为审批中
  1414. // 4.审批人撤回退回原报操作,删除新增的审批流,增加流程,回滚到它审批中
  1415. // 5.会签审批人撤回审批通过(还有其他审批人未审批通过),仅修改本人流程状态
  1416. if (stage.cancancel === 5) {
  1417. await this._auditCheckCancelAnd(stage);
  1418. } else {
  1419. switch (this.ctx.stage.cancancel) {
  1420. case 1: await this._userCheckCancel(stage); break;
  1421. case 2: await this._auditCheckCancel(stage); break;
  1422. case 3: await this._auditCheckCancelNoPre(stage); break;
  1423. case 4: await this._auditCheckCancelNo(stage); break;
  1424. default: throw '不可撤回,请刷新页面重试';
  1425. }
  1426. // 通知发送 - 第三方更新
  1427. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  1428. const base_data = {
  1429. tid: stage.tid,
  1430. sid: stage.id,
  1431. op: 'update',
  1432. };
  1433. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  1434. base_data.op = 'update';
  1435. base_data.sid = -1;
  1436. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  1437. }
  1438. }
  1439. }
  1440. /**
  1441. * 获取审核人需要审核的期列表
  1442. *
  1443. * @param auditorId
  1444. * @return {Promise<*>}
  1445. */
  1446. async getAuditStage(auditorId) {
  1447. const sql =
  1448. 'SELECT sa.`aid`, sa.`times`, sa.`order`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`sid`,' +
  1449. ' s.`order` As `sorder`, s.`status` As `sstatus`,' +
  1450. ' t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +
  1451. ' FROM ?? AS sa ' +
  1452. ' Left Join ?? AS s On sa.`sid` = s.`id` ' +
  1453. ' Left Join ?? As t ON sa.`tid` = t.`id`' +
  1454. ' WHERE ((sa.`aid` = ? and sa.`status` = ?) OR (s.`user_id` = ? and sa.`status` = ? and s.`status` = ? and sa.`times` = (s.`times`-1)))' +
  1455. ' ORDER BY sa.`begin_time` DESC';
  1456. const sqlParam = [
  1457. this.tableName,
  1458. this.ctx.service.stage.tableName,
  1459. this.ctx.service.tender.tableName,
  1460. auditorId,
  1461. auditConst.status.checking,
  1462. auditorId,
  1463. auditConst.status.checkNo,
  1464. auditConst.status.checkNo,
  1465. ];
  1466. return await this.db.query(sql, sqlParam);
  1467. }
  1468. /**
  1469. * 获取审核人审核的次数
  1470. *
  1471. * @param auditorId
  1472. * @return {Promise<*>}
  1473. */
  1474. async getCountByChecked(auditorId) {
  1475. return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo, auditConst.status.checkNoPre] });
  1476. }
  1477. /**
  1478. * 获取最近一次审批结束时间
  1479. *
  1480. * @param auditorId
  1481. * @return {Promise<*>}
  1482. */
  1483. async getLastEndTimeByChecked(auditorId) {
  1484. const sql = 'SELECT `end_time` FROM ?? WHERE `aid` = ? ' +
  1485. 'AND `status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo, auditConst.status.checkNoPre]) + ') ORDER BY `end_time` DESC';
  1486. const sqlParam = [this.tableName, auditorId];
  1487. const result = await this.db.queryOne(sql, sqlParam);
  1488. return result ? result.end_time : null;
  1489. }
  1490. /**
  1491. * 获取 某时间后 审批进度 更新的期
  1492. * @param {Number} pid - 查询标段
  1493. * @param {Number} uid - 查询人
  1494. * @param {Date} time - 查询时间
  1495. * @return {Promise<*>}
  1496. */
  1497. async getNoticeStage(pid, uid, time) {
  1498. let notice = await this.db.select('zh_notice', {
  1499. where: { pid, type: pushType.stage, uid },
  1500. orders: [['create_time', 'desc']],
  1501. limit: 10,
  1502. offset: 0,
  1503. });
  1504. notice = notice.map(v => {
  1505. const extra = JSON.parse(v.content);
  1506. delete v.content;
  1507. return { ...v, ...extra };
  1508. });
  1509. return notice;
  1510. }
  1511. /**
  1512. * 用于添加推送所需的content内容
  1513. * @param {Number} pid 项目id
  1514. * @param {Number} tid 台账id
  1515. * @param {Number} sid 期id
  1516. * @param {Number} uid 审核人id
  1517. */
  1518. async getNoticeContent(pid, tid, sid, uid, opinion = '') {
  1519. const noticeSql =
  1520. 'SELECT * FROM (SELECT ' +
  1521. ' t.`id` As `tid`, t.`name`, s.`order`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1522. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1523. ' LEFT JOIN ?? As s On s.`id` = ?' +
  1524. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1525. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1526. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.stage.tableName, sid, this.ctx.service.projectAccount.tableName, uid, pid];
  1527. const content = await this.db.query(noticeSql, noticeSqlParam);
  1528. if (content.length) {
  1529. content[0].opinion = opinion;
  1530. }
  1531. return content.length ? JSON.stringify(content[0]) : '';
  1532. }
  1533. /**
  1534. * 获取审核人流程列表
  1535. *
  1536. * @param auditorId
  1537. * @return {Promise<*>}
  1538. */
  1539. async getAuditGroupByList(stageId, times, transaction = false) {
  1540. // const sql =
  1541. // 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`aid`, la.`order`, la.`status`' +
  1542. // ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1543. // ' WHERE la.`sid` = ? and la.`times` = ? and la.`is_old` = 0 GROUP BY la.`aid` ORDER BY la.`order`';
  1544. // const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, times];
  1545. const sql =
  1546. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order`, la.`status`, la.audit_type, la.audit_order' +
  1547. ' FROM (SELECT `aid`, max(`order`) `order` FROM ?? WHERE `sid` = ? and `times` = ? and `is_old` = ? GROUP BY aid) sa' +
  1548. ' LEFT JOIN ?? la ON sa.`aid` = la.`aid` AND sa.`order` = la.`order`' +
  1549. ' Left JOIN ?? AS pa On la.`aid` = pa.`id` WHERE la.`sid` = ? and la.`times` = ? and la.`is_old` = ? order BY la.`order`';
  1550. const sqlParam = [this.tableName, stageId, times, 0, this.tableName, this.ctx.service.projectAccount.tableName, stageId, times, 0];
  1551. return transaction !== false ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  1552. }
  1553. /**
  1554. * 获取审核人流程列表
  1555. *
  1556. * @param auditorId
  1557. * @return {Promise<*>}
  1558. */
  1559. async getAuditGroupByListWithOwner(stageId, times) {
  1560. const result = await this.getAuditGroupByList(stageId, times);
  1561. const sql =
  1562. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As sid, 0 As `order`' +
  1563. ' FROM ' + this.ctx.service.stage.tableName + ' As s' +
  1564. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1565. ' ON s.user_id = pa.id' +
  1566. ' WHERE s.id = ?';
  1567. const sqlParam = [times, stageId, stageId];
  1568. const user = await this.db.queryOne(sql, sqlParam);
  1569. result.unshift(user);
  1570. return result;
  1571. }
  1572. /**
  1573. * 复制上一期的审批人列表给最新一期
  1574. *
  1575. * @param transaction - 新增一期的事务
  1576. * @param {Object} preStage - 上一期
  1577. * @param {Object} newStage - 最新一期
  1578. * @return {Promise<*>}
  1579. */
  1580. async copyPreStageAuditors(transaction, preStage, newStage) {
  1581. const auditors = await this.getAuditGroupByList(preStage.id, preStage.times);
  1582. const newAuditors = [];
  1583. for (const a of auditors) {
  1584. const na = {
  1585. tid: preStage.tid,
  1586. sid: newStage.id,
  1587. aid: a.aid,
  1588. times: newStage.times,
  1589. order: a.audit_order,
  1590. status: auditConst.status.uncheck,
  1591. audit_type: a.audit_type,
  1592. audit_order: a.audit_order,
  1593. };
  1594. newAuditors.push(na);
  1595. }
  1596. const result = await transaction.insert(this.tableName, newAuditors);
  1597. return (result.effectRows = auditors.length);
  1598. }
  1599. /**
  1600. * 移除审核人
  1601. *
  1602. * @param {Number} stageId - 期id
  1603. * @param {Number} status - 期状态
  1604. * @param {Number} status - 期次数
  1605. * @return {Promise<boolean>}
  1606. */
  1607. async getAuditorByStatus(stageId, status, times = 1) {
  1608. let auditor = null;
  1609. let sql = '';
  1610. let sqlParam = '';
  1611. switch (status) {
  1612. case auditConst.status.checking:
  1613. case auditConst.status.checked:
  1614. case auditConst.status.checkNoPre:
  1615. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order` ' +
  1616. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1617. ' WHERE la.`sid` = ? and la.`status` = ? order by la.`times` desc, la.`order` desc';
  1618. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, status];
  1619. auditor = await this.db.queryOne(sql, sqlParam);
  1620. break;
  1621. case auditConst.status.checkNo:
  1622. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order` ' +
  1623. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1624. ' WHERE la.`sid` = ? and la.`status` = ? and la.`times` = ? order by la.`times` desc, la.`order` desc';
  1625. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, auditConst.status.checkNo, parseInt(times) - 1];
  1626. auditor = await this.db.queryOne(sql, sqlParam);
  1627. break;
  1628. case auditConst.status.uncheck:
  1629. default:
  1630. break;
  1631. }
  1632. return auditor;
  1633. }
  1634. async getAuditorsByStatus(stageId, status, times = 1) {
  1635. let auditor = [];
  1636. let sql = '';
  1637. let sqlParam = '';
  1638. let cur;
  1639. switch (status) {
  1640. case auditConst.status.checking:
  1641. case auditConst.status.checked:
  1642. case auditConst.status.checkNoPre:
  1643. cur = await this.db.queryOne(`SELECT * From ${this.tableName} where sid = ? AND times = ? AND status = ? ORDER By times DESC, ` + '`order` DESC', [stageId, times, status]);
  1644. if (!cur) return [];
  1645. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order`, la.audit_order, la.audit_type ' +
  1646. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1647. ' WHERE la.`sid` = ? and la.`order` = ? and times = ?';
  1648. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, cur.order, times];
  1649. auditor = await this.db.query(sql, sqlParam);
  1650. break;
  1651. case auditConst.status.checkNo:
  1652. cur = await this.db.queryOne(`SELECT * From ${this.tableName} where sid = ? AND times = ? AND status = ? ORDER By times DESC, ` + '`order` DESC', [stageId, parseInt(times) - 1, status]);
  1653. if (!cur) return [];
  1654. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`sid`, la.`order`, la.audit_order, la.audit_type ' +
  1655. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  1656. ' WHERE la.`sid` = ? and la.`order` = ? and la.`times` = ?';
  1657. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, cur.order, parseInt(times) - 1];
  1658. auditor = await this.db.query(sql, sqlParam);
  1659. break;
  1660. case auditConst.status.uncheck:
  1661. default:
  1662. break;
  1663. }
  1664. return auditor;
  1665. }
  1666. /**
  1667. * 取某一期已批准审核信息(报表用)
  1668. *
  1669. * @param {Number} stageId - 期id
  1670. * @param {Number} times - 期次数
  1671. * @return {Promise<boolean>}
  1672. */
  1673. async getStageAudit(stageId, times = 1) {
  1674. const sql = 'SELECT a1.aid, a1.begin_time, a1.end_time, a1.status, a1.opinion ' + 'FROM ?? AS a1 ' + 'WHERE a1.`sid` = ? and a1.`times` = ? ' + 'ORDER BY a1.order';
  1675. const sqlParam = [this.tableName, stageId, times];
  1676. const rst = await this.db.query(sql, sqlParam);
  1677. return rst;
  1678. }
  1679. /**
  1680. * 取待审批期列表(wap用)
  1681. *
  1682. * @param auditorId
  1683. * @return {Promise<*>}
  1684. */
  1685. async getAuditStageByWap(auditorId) {
  1686. const sql =
  1687. 'SELECT sa.`aid`, sa.`times`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`sid`,' +
  1688. // ' 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`, ' +
  1689. ' s.*,' +
  1690. ' t.`name`, t.`project_id`, t.`type`, t.`user_id`,' +
  1691. ' ti.`deal_info` ' +
  1692. ' FROM ?? AS sa' +
  1693. ' Left Join ?? AS s On sa.`sid` = s.`id`' +
  1694. ' Left Join ?? As t On sa.`tid` = t.`id`' +
  1695. ' Left Join ?? AS ti ON ti.`tid` = t.`id`' +
  1696. ' WHERE sa.`aid` = ? and sa.`status` = ?';
  1697. const sqlParam = [
  1698. this.tableName,
  1699. this.ctx.service.stage.tableName,
  1700. this.ctx.service.tender.tableName,
  1701. this.ctx.service.tenderInfo.tableName,
  1702. auditorId,
  1703. auditConst.status.checking,
  1704. ];
  1705. return await this.db.query(sql, sqlParam);
  1706. }
  1707. /**
  1708. * 删除 某期 某次 全审批流程
  1709. * 私有,不做判断,不补全最新一轮审批人数据,不计算缓存
  1710. * @param {Number} sid - 标段id
  1711. * @param {Number} times - 第几次审批
  1712. * @param transaction - 删除事务
  1713. * @return {Promise<void>}
  1714. */
  1715. async _timesDelete(sid, times, transaction) {
  1716. // 审批流程
  1717. await transaction.delete(this.tableName, { sid, times });
  1718. await transaction.delete(this.ctx.service.pos.tableName, { add_stage: sid, add_times: times });
  1719. await transaction.delete(this.ctx.service.stageBills.tableName, { sid, times });
  1720. await transaction.delete(this.ctx.service.stagePos.tableName, { sid, times });
  1721. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid, times });
  1722. await transaction.delete(this.ctx.service.stageChange.tableName, { sid, stimes: times });
  1723. await transaction.delete(this.ctx.service.stagePay.tableName, { sid, stimes: times });
  1724. await transaction.delete(this.ctx.service.pay.tableName, { csid: sid, cstimes: times });
  1725. await transaction.delete(this.ctx.service.stageAuditAss.tableName, { sid, times });
  1726. // 其他台账
  1727. await this.ctx.service.stageJgcl.deleteStageTimesData(sid, times, transaction);
  1728. await this.ctx.service.stageOther.deleteStageTimesData(sid, times, transaction);
  1729. await this.ctx.service.stageBonus.deleteStageTimesData(sid, times, transaction);
  1730. await this.ctx.service.stageSafeProd.deleteStageTimesData(sid, times, transaction);
  1731. await this.ctx.service.stageTempLand.deleteStageTimesData(sid, times, transaction);
  1732. }
  1733. /**
  1734. * 删除本次审批流程
  1735. * @param {Number} stageId - 标段id
  1736. * @param {Number} times - 第几次审批
  1737. * @return {Promise<void>}
  1738. */
  1739. async timesDelete() {
  1740. const transaction = await this.db.beginTransaction();
  1741. try {
  1742. // 删除最新一次数据
  1743. await this._timesDelete(this.ctx.stage.id, this.ctx.stage.times, transaction);
  1744. // 审批退回,未重新上报时,需删除最新两次数据
  1745. const isCheckNo = this.ctx.stage.status === auditConst.status.checkNo;
  1746. const nowTimes = isCheckNo ? this.ctx.stage.times - 1 : this.ctx.stage.times;
  1747. if (isCheckNo) {
  1748. await this._timesDelete(this.ctx.stage.id, nowTimes, transaction);
  1749. }
  1750. // 添加上一次审批人
  1751. const sql = 'SELECT `tid`, `sid`, `aid`, `order`, `audit_type`, `audit_order` FROM ?? WHERE `sid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';
  1752. const sqlParam = [this.tableName, this.ctx.stage.id, nowTimes - 1];
  1753. const auditors = await this.db.query(sql, sqlParam);
  1754. let order = 1;
  1755. for (const a of auditors) {
  1756. a.times = nowTimes;
  1757. a.order = order;
  1758. a.status = auditConst.status.uncheck;
  1759. order++;
  1760. }
  1761. const ledgerTp = await this._updateTender(transaction);
  1762. // 拷贝新一次审核流程列表
  1763. await transaction.insert(this.tableName, auditors);
  1764. // 计算缓存
  1765. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(this.ctx.stage);
  1766. // 计算并合同支付最终数据
  1767. const lastAudit = await this.getDataByCondition({
  1768. sid: this.ctx.stage.id,
  1769. times: nowTimes - 1,
  1770. status: auditConst.status.checkNo,
  1771. });
  1772. if (!lastAudit) throw '审批数据错误';
  1773. await this.ctx.service.stagePay.copyStagePays4DeleteTimes(this.ctx.stage, nowTimes, 0, lastAudit.times, lastAudit.order, transaction);
  1774. const stagePay = await this.ctx.service.stagePay.getAuditorStageData(this.ctx.stage.id, lastAudit.times, lastAudit.order);
  1775. const yfPay = stagePay.find(function(x) {
  1776. return x.ptype === payConst.payType.yf;
  1777. });
  1778. const sfPay = stagePay.find(function(x) {
  1779. return x.ptype === payConst.payType.sf;
  1780. });
  1781. // 同步 期信息
  1782. const time = new Date();
  1783. await this.ctx.service.tenderCache.updateStageCache4DelTimes(transaction, this.ctx.stage, nowTimes);
  1784. await transaction.update(this.ctx.service.stage.tableName, {
  1785. id: this.ctx.stage.id,
  1786. status: auditConst.status.checkNo,
  1787. contract_tp: tpData.contract_tp,
  1788. qc_tp: tpData.qc_tp,
  1789. positive_qc_tp: tpData.positive_qc_tp,
  1790. negative_qc_tp: tpData.negative_qc_tp,
  1791. times: nowTimes,
  1792. yf_tp: yfPay ? yfPay.tp : null,
  1793. sf_tp: sfPay ? sfPay.tp : null,
  1794. tp_history: JSON.stringify(this.ctx.stage.tp_history.filter(x => { return x.times <= nowTimes; })),
  1795. cache_time_l: time,
  1796. cache_time_r: time,
  1797. });
  1798. await transaction.commit();
  1799. // 通知发送 - 第三方更新
  1800. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  1801. const base_data = {
  1802. tid: this.ctx.tender.id,
  1803. sid: this.ctx.stage.id,
  1804. op: 'update',
  1805. };
  1806. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  1807. base_data.op = 'update';
  1808. base_data.sid = -1;
  1809. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  1810. }
  1811. } catch (err) {
  1812. await transaction.rollback();
  1813. throw err;
  1814. }
  1815. }
  1816. // 固定审批流-更新
  1817. async updateNewAuditList(stage, newList) {
  1818. const transaction = await this.db.beginTransaction();
  1819. try {
  1820. // 先删除旧的审批流,再添加新的
  1821. await transaction.delete(this.tableName, { sid: stage.id, times: stage.times });
  1822. await transaction.delete(this.ctx.service.stageAuditAss.tableName, { sid: stage.id, times: stage.times });
  1823. const newAuditors = [];
  1824. for (const auditor of newList) {
  1825. newAuditors.push({
  1826. tid: stage.tid, sid: stage.id, aid: auditor.audit_id,
  1827. times: stage.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1828. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1829. });
  1830. }
  1831. if(newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1832. await transaction.commit();
  1833. } catch (err) {
  1834. await transaction.rollback();
  1835. throw err;
  1836. }
  1837. }
  1838. // 固定终审-更新
  1839. async updateLastAudit(stage, auditList, lastId) {
  1840. const transaction = await this.db.beginTransaction();
  1841. try {
  1842. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1843. const existAudit = auditList.find(x => { return x.aid === lastId });
  1844. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order)}, 0) + 1 : 1; // 最大值 + 1
  1845. if (existAudit) {
  1846. await transaction.delete(this.tableName, { sid: stage.id, times: stage.times, aid: lastId });
  1847. const sameOrder = auditList.filter(x => { return x.order === existAudit.order });
  1848. if (sameOrder.length === 1) {
  1849. const updateData = [];
  1850. auditList.forEach(x => {
  1851. if (x.order <= existAudit.order) return;
  1852. updateData.push({id: x.id, order: x.order - 1, audit_order: x.audit_order - 1});
  1853. });
  1854. if (updateData.length > 0) {
  1855. await transaction.updateRows(updateData);
  1856. }
  1857. order = order - 1;
  1858. }
  1859. }
  1860. // 添加终审
  1861. const newAuditor = {
  1862. tid: stage.tid, sid: stage.id, aid: lastId,
  1863. times: stage.times, order, status: auditConst.status.uncheck,
  1864. audit_type: auditType.key.common, audit_order: order,
  1865. };
  1866. await transaction.insert(this.tableName, newAuditor);
  1867. await transaction.commit();
  1868. } catch (err) {
  1869. await transaction.rollback();
  1870. throw err;
  1871. }
  1872. }
  1873. async getFinalAuditGroup(stageId, times) {
  1874. const sql =
  1875. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, pa.`sign_path`, la.`times`, la.`sid`, Max(la.`order`) as max_order ' +
  1876. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  1877. ' WHERE la.`sid` = ? and la.`times` = ? GROUP BY la.`aid` ORDER BY la.`order`';
  1878. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, stageId, times];
  1879. const result = await this.db.query(sql, sqlParam);
  1880. for (const r of result) {
  1881. const auditor = await this.getDataByCondition({sid: stageId, times: r.times, order: r.max_order});
  1882. r.status = auditor.status;
  1883. r.opinion = auditor.opinion;
  1884. r.begin_time = auditor.begin_time;
  1885. r.end_time = auditor.end_time;
  1886. }
  1887. return result;
  1888. }
  1889. async getNumByMonth(tid, startMonth, endMonth) {
  1890. const sql = 'SELECT COUNT(*) as num FROM ?? WHERE id in (SELECT MAX(id) FROM ?? WHERE tid = ? GROUP BY sid) AND status = ? AND end_time between ? and ?';
  1891. const sqlParam = [this.tableName, this.tableName, tid, auditConst.status.checked, startMonth, endMonth];
  1892. const result = await this.db.queryOne(sql, sqlParam);
  1893. return result ? result.num : 0;
  1894. }
  1895. /**
  1896. * 删除本次审批流程
  1897. * @param {Number} stageId - 标段id
  1898. * @param {Number} times - 第几次审批
  1899. * @param {Object} data - 更改参数
  1900. * @return {Promise<void>}
  1901. */
  1902. async saveAudit(stageId, times, data) {
  1903. const transaction = await this.db.beginTransaction();
  1904. try {
  1905. const auditors = await this.getAuditGroupByList(stageId, times);
  1906. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1907. if (data.operate !== 'del') {
  1908. const exist = await this.getDataByCondition({ sid: stageId, times, aid: data.new_aid });
  1909. if (exist) throw '该审核人已存在,请勿重复添加';
  1910. }
  1911. if (data.operate === 'add') {
  1912. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1913. throw '当前人下无法操作新增';
  1914. }
  1915. const newAudit = {
  1916. tid: this.ctx.tender.id,
  1917. sid: stageId,
  1918. aid: data.new_aid,
  1919. order: now_audit.order + 1,
  1920. audit_order: now_audit.audit_order + 1,
  1921. audit_type: auditType.key.common,
  1922. times: times,
  1923. status: 1
  1924. };
  1925. // order+1
  1926. await this._syncOrderByDelete(transaction, stageId, now_audit.order+1, times, '+');
  1927. await transaction.insert(this.tableName, newAudit);
  1928. // 更新审批流程页数据,如果存在
  1929. } else if (data.operate === 'add-sibling') {
  1930. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1931. throw '当前人下无法操作新增';
  1932. }
  1933. const newAudit = {
  1934. tid: this.ctx.tender.id,
  1935. sid: stageId,
  1936. aid: data.new_aid,
  1937. order: now_audit.order,
  1938. audit_order: now_audit.audit_order,
  1939. audit_type: now_audit.audit_type,
  1940. times: times,
  1941. status: 1
  1942. };
  1943. await transaction.insert(this.tableName, newAudit);
  1944. } else if (data.operate === 'del') {
  1945. if (now_audit.status !== auditConst.status.uncheck) {
  1946. throw '当前人无法操作删除';
  1947. }
  1948. const flowAuditors = auditors.filter(x => { return x.order === now_audit.order; });
  1949. await transaction.delete(this.tableName, { sid: stageId, times, aid: now_audit.aid, order: now_audit.order });
  1950. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, stageId, now_audit.order, times);
  1951. // 旧的更新为is_old为1
  1952. await transaction.update(this.tableName, { is_old: 1 }, {
  1953. where: {
  1954. sid: stageId,
  1955. times,
  1956. aid: data.old_aid,
  1957. }
  1958. });
  1959. } else if (data.operate === 'change') {
  1960. const nowAudit = await this.getDataByCondition({ sid: stageId, times, aid: now_audit.aid, order: now_audit.order });
  1961. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1962. throw '当前人无法操作替换';
  1963. }
  1964. nowAudit.aid = data.new_aid;
  1965. await transaction.update(this.tableName, nowAudit);
  1966. // 旧的更新为is_old为1
  1967. await transaction.update(this.tableName, { is_old: 1 }, {
  1968. where: {
  1969. sid: stageId,
  1970. times,
  1971. aid: data.old_aid,
  1972. }
  1973. });
  1974. }
  1975. if (this.ctx.tender.info.shenpi.stage === shenpiConst.sp_status.gdspl) {
  1976. const newAuditors = await transaction.select(this.tableName, { where: { sid: stageId, times } });
  1977. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors);
  1978. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1979. await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.stage, shenpiConst.sp_type.stage, uniqNewAuditorGroup);
  1980. } else if (this.ctx.tender.info.shenpi.stage === shenpiConst.sp_status.gdzs) {
  1981. const newAuditors = await this.getAuditGroupByList(stageId, times, transaction);
  1982. await this.ctx.service.shenpiAudit.updateAuditList(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.stage, shenpiConst.sp_type.stage, this._.map(newAuditors, 'aid'));
  1983. }
  1984. // 更新到审批流程方法
  1985. await transaction.commit();
  1986. } catch (err) {
  1987. await transaction.rollback();
  1988. throw err;
  1989. }
  1990. }
  1991. async getAuditorGroup(stageId, times) {
  1992. const auditors = await this.ctx.service.stageAudit.getAuditors(stageId, times); // 全部参与的审批人
  1993. return this.ctx.helper.groupAuditors(auditors);
  1994. }
  1995. async getUserGroup(stageId, times) {
  1996. const group = await this.getAuditorGroup(stageId, times);
  1997. const sql =
  1998. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As sid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1999. ' FROM ' + this.ctx.service.stage.tableName + ' As s' +
  2000. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  2001. ' ON s.user_id = pa.id' +
  2002. ' WHERE s.id = ?';
  2003. const sqlParam = [times, stageId, stageId];
  2004. const user = await this.db.queryOne(sql, sqlParam);
  2005. group.unshift([ user ]);
  2006. return group;
  2007. }
  2008. async getUniqUserGroup(stageId, times) {
  2009. const group = await this.getAuditorGroup(stageId, times);
  2010. const sql =
  2011. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As sid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  2012. ' FROM ' + this.ctx.service.stage.tableName + ' As s' +
  2013. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  2014. ' ON s.user_id = pa.id' +
  2015. ' WHERE s.id = ?';
  2016. const sqlParam = [times, stageId, stageId];
  2017. const user = await this.db.queryOne(sql, sqlParam);
  2018. user.audit_order = 0;
  2019. group.unshift([ user ]);
  2020. return this.ctx.helper.groupAuditorsUniq(group);
  2021. }
  2022. async getAuditorHistory(stageId, times, reverse = false) {
  2023. const history = [];
  2024. if (times >= 1) {
  2025. for (let i = 1; i <= times; i++) {
  2026. const auditors = await this.ctx.service.stageAudit.getAuditors(stageId, i);
  2027. const group = this.ctx.helper.groupAuditors(auditors);
  2028. const historyGroup = [];
  2029. const max_order = group.length > 0 && group[group.length - 1].length > 0 ? group[group.length - 1][0].audit_order : -1;
  2030. for (const g of group) {
  2031. const his = {
  2032. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  2033. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  2034. auditors: g
  2035. };
  2036. if (his.audit_type === auditType.key.common) {
  2037. his.name = g[0].name;
  2038. } else {
  2039. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  2040. }
  2041. his.is_final = his.audit_order === max_order;
  2042. if (g[0].begin_time) {
  2043. his.begin_time = g[0].begin_time;
  2044. const beginTime = this.ctx.moment(g[0].begin_time);
  2045. his.beginYear = beginTime.format('YYYY');
  2046. his.beginDate = beginTime.format('MM-DD');
  2047. his.beginTime = beginTime.format('HH:mm:ss');
  2048. }
  2049. let end_time;
  2050. g.forEach(x => {
  2051. if (x.status === auditConst.status.checkSkip) return;
  2052. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  2053. if (x.end_time && (!end_time || x.end_time > end_time)) {
  2054. end_time = x.end_time;
  2055. if (his.status !== auditConst.status.checking) his.status = x.status;
  2056. }
  2057. });
  2058. if (end_time) {
  2059. his.end_time = end_time;
  2060. const endTime = this.ctx.moment(end_time);
  2061. his.endYear = endTime.format('YYYY');
  2062. his.endDate = endTime.format('MM-DD');
  2063. his.endTime = endTime.format('HH:mm:ss');
  2064. }
  2065. historyGroup.push(his);
  2066. }
  2067. if (reverse) {
  2068. history.push(historyGroup.reverse());
  2069. } else {
  2070. history.push(historyGroup);
  2071. }
  2072. }
  2073. }
  2074. return history;
  2075. }
  2076. async getUniqAuditor(stageId, times) {
  2077. const auditors = await this.ctx.service.stageAudit.getAuditors(stageId, times); // 全部参与的审批人
  2078. const result = [];
  2079. auditors.forEach(x => {
  2080. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === x.audit_order; }) < 0) {
  2081. result.push(x);
  2082. }
  2083. });
  2084. return result;
  2085. }
  2086. }
  2087. return StageAudit;
  2088. };