stage_audit.js 133 KB

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