stage_audit.js 139 KB

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