stage_audit.js 114 KB

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