change.js 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const audit = require('../const/audit');
  10. const fs = require('fs');
  11. const path = require('path');
  12. const changeConst = require('../const/change');
  13. const smsTypeConst = require('../const/sms_type');
  14. const SMS = require('../lib/sms');
  15. const SmsAliConst = require('../const/sms_alitemplate');
  16. const wxConst = require('../const/wechat_template');
  17. const pushType = require('../const/audit').pushType;
  18. const projectLogConst = require('../const/project_log');
  19. const pushOperate = require('../const/spec_3f').pushOperate;
  20. module.exports = app => {
  21. class Change extends app.BaseService {
  22. /**
  23. * 构造函数
  24. *
  25. * @param {Object} ctx - egg全局变量
  26. * @return {void}
  27. */
  28. constructor(ctx) {
  29. super(ctx);
  30. this.tableName = 'change';
  31. }
  32. /**
  33. * 查找数据
  34. *
  35. * @param {Object} data - 筛选表单中的get数据
  36. * @return {void}
  37. */
  38. searchFilter(data) {
  39. this.initSqlBuilder();
  40. // this.sqlBuilder.columns = ['id', 'username', 'real_name', 'create_time', 'last_login', 'login_ip',
  41. // 'group_id', 'token', 'can_login'];
  42. data.type = parseInt(data.status);
  43. if (data.keyword !== undefined) {
  44. switch (data.type) {
  45. // 用户名
  46. case 1:
  47. this.sqlBuilder.setAndWhere('username', {
  48. value: this.db.escape(data.keyword + '%'),
  49. operate: 'like',
  50. });
  51. break;
  52. // 姓名
  53. case 2:
  54. this.sqlBuilder.setAndWhere('real_name', {
  55. value: this.db.escape(data.keyword + '%'),
  56. operate: 'like',
  57. });
  58. break;
  59. // 联系电话
  60. case 3:
  61. this.sqlBuilder.setAndWhere('telephone', {
  62. value: this.db.escape(data.keyword + '%'),
  63. operate: 'like',
  64. });
  65. break;
  66. default:
  67. break;
  68. }
  69. }
  70. // 办事处筛选
  71. if (data.office !== undefined && data.office !== '') {
  72. this.sqlBuilder.setAndWhere('office', {
  73. value: this.db.escape(data.office),
  74. operate: '=',
  75. });
  76. }
  77. }
  78. async add(tenderId, userId, code, plan_code, name, delimit = 100) {
  79. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE `tid` = ? AND ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?))';
  80. const sqlParam = [this.tableName, tenderId, code, audit.flow.status.checked, code, audit.flow.status.checked];
  81. const codeCount = await this.db.queryOne(sql, sqlParam);
  82. const count = codeCount.count;
  83. if (count > 0) {
  84. throw '变更令号重复';
  85. }
  86. // 初始化事务
  87. this.transaction = await this.db.beginTransaction();
  88. let result = false;
  89. try {
  90. const cid = this.uuid.v4();
  91. const change = {
  92. cid,
  93. tid: tenderId,
  94. uid: userId,
  95. status: audit.flow.status.uncheck,
  96. times: 1,
  97. valid: true,
  98. in_time: new Date(),
  99. code,
  100. name,
  101. plan_code,
  102. state: 3,
  103. delimit,
  104. // tp_decimal: this.ctx.tender.info.decimal.tp,
  105. // up_decimal: this.ctx.tender.info.decimal.up,
  106. };
  107. if (plan_code) {
  108. const planInfo = await this.ctx.service.changePlan.getDataByCondition({ tid: tenderId, code: plan_code });
  109. if (planInfo) {
  110. change.org_name = planInfo.org_name;
  111. change.peg = planInfo.peg;
  112. change.org_code = planInfo.new_code;
  113. change.new_code = planInfo.c_new_code;
  114. change.new_name = planInfo.design_name;
  115. // 工程变更类别读取
  116. const projectData = await this.ctx.service.project.getDataById(this.ctx.session.sessionProject.id);
  117. const fun_set = await this.ctx.service.project.getFunSet(projectData.fun_set);
  118. const classInfo = this._.find(fun_set.change_class, function(item) {
  119. return item.name === planInfo.class || (item.checked && item.new_name === planInfo.class);
  120. });
  121. change.class = classInfo ? classInfo.value : this._.find(fun_set.change_class, { checked: true }).value;
  122. const qualityIndex = planInfo.quality && this._.indexOf(changeConst.qualityName, planInfo.quality) !== -1 ? this._.indexOf(changeConst.qualityName, planInfo.quality) : 0;
  123. change.quality = qualityIndex ? qualityIndex : changeConst.quality.common.value;
  124. let content = planInfo.reason ? planInfo.reason.replace(/[\r\n]/g, '\r\n') : '';
  125. content = content + (planInfo.content ? (planInfo.reason ? '\r\n' : '') + planInfo.content.replace(/[\r\n]/g, '\r\n') : '');
  126. change.content = content ? content : null;
  127. change.expr = planInfo.expr;
  128. }
  129. }
  130. const operate = await this.transaction.insert(this.tableName, change);
  131. if (operate.affectedRows <= 0) {
  132. throw '新建变更令数据失败';
  133. }
  134. // 把提交人信息添加到zh_change_audit
  135. const userInfo = await this.ctx.service.projectAccount.getDataById(userId);
  136. const changeaudit = [
  137. {
  138. tid: tenderId,
  139. cid,
  140. uid: userId,
  141. name: userInfo.name,
  142. jobs: userInfo.role,
  143. company: userInfo.company,
  144. times: 1,
  145. usite: 0,
  146. usort: 0,
  147. status: 2,
  148. },
  149. ];
  150. // 并把之前存在的变更令审批人添加到zh_change_audit
  151. // 先找出标段最近存在的变更令审批人的变更令info
  152. const changeInfo = await this.ctx.service.change.getHaveAuditLastInfo(tenderId);
  153. if (changeInfo) {
  154. // 再获取非原报审批人
  155. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  156. let sort = 1;
  157. for (const audit of auditList) {
  158. if (audit.usite !== 0) {
  159. const oneaudit = {
  160. tid: tenderId,
  161. cid,
  162. uid: audit.uid,
  163. name: audit.name,
  164. jobs: audit.jobs,
  165. company: audit.company,
  166. times: 1,
  167. usite: audit.usite,
  168. usort: sort++,
  169. status: 1,
  170. };
  171. changeaudit.push(oneaudit);
  172. }
  173. }
  174. }
  175. await this.transaction.insert(this.ctx.service.changeAudit.tableName, changeaudit);
  176. result = change;
  177. this.transaction.commit();
  178. } catch (error) {
  179. console.log(error);
  180. // 回滚
  181. await this.transaction.rollback();
  182. }
  183. return result;
  184. }
  185. async getHaveAuditLastInfo(tenderId) {
  186. const sql = 'SELECT a.* FROM ?? as a LEFT JOIN ?? as b ON a.`cid` = b.`cid` WHERE a.`tid` = ? AND b.`usite` > 0 ORDER BY a.`in_time` DESC';
  187. const sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId];
  188. return await this.db.queryOne(sql, sqlParam);
  189. }
  190. async pendingDatas(tenderId, userId) {
  191. return await this.getAllDataByCondition({
  192. tid: tenderId,
  193. uid: userId,
  194. status: audit.flow.status.checking,
  195. });
  196. }
  197. async uncheckDatas(tenderId, userId) {
  198. return await this.getAllDataByCondition({
  199. tid: tenderId,
  200. uid: userId,
  201. status: audit.flow.status.uncheck,
  202. });
  203. }
  204. async checkingDatas(tenderId, userId) {
  205. return await this.getAllDataByCondition({
  206. tid: tenderId,
  207. uid: userId,
  208. status: audit.flow.status.checking,
  209. });
  210. }
  211. async checkedDatas(tenderId, userId) {
  212. return await this.getAllDataByCondition({
  213. tid: tenderId,
  214. uid: userId,
  215. status: audit.flow.status.checked,
  216. });
  217. }
  218. async checkNoDatas(tenderId, userId) {
  219. return await this.getAllDataByCondition({
  220. tid: tenderId,
  221. uid: userId,
  222. status: audit.flow.status.checkNo,
  223. });
  224. }
  225. async checkNoCount(tenderId, userId) {
  226. return await this.count({
  227. tid: tenderId,
  228. uid: userId,
  229. status: audit.flow.status.checkNo,
  230. });
  231. }
  232. /**
  233. * 获取变更令列表
  234. * @param {int} tenderId - 标段id
  235. * @param {int} status - 状态
  236. * @param {int} hadlimit - 分页
  237. * @return {object} list - 列表
  238. */
  239. async getListByStatus(tenderId, status = 0, hadlimit = 1, sortBy = '', orderBy = '', state = 0) {
  240. let sql = '';
  241. let sqlParam = '';
  242. const stateSql = state ? ' AND a.state = ' + state : '';
  243. if (this.ctx.tender.isTourist && status === 0) {
  244. sql = 'SELECT a.* FROM ?? As a WHERE a.tid = ?' + stateSql;
  245. sqlParam = [this.tableName, tenderId];
  246. } else {
  247. switch (status) {
  248. case 0: // 包含你的所有变更令
  249. sql =
  250. 'SELECT a.* FROM ?? AS a WHERE a.tid = ? AND' +
  251. ' (a.uid = ? OR (a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))' +
  252. ' OR (a.status = ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times - 1 = b.times GROUP BY b.cid))' +
  253. ' OR a.status = ?)' + stateSql;
  254. sqlParam = [
  255. this.tableName,
  256. tenderId,
  257. this.ctx.session.sessionUser.accountId,
  258. audit.flow.status.uncheck,
  259. this.ctx.service.changeAudit.tableName,
  260. this.ctx.session.sessionUser.accountId,
  261. audit.flow.status.back,
  262. this.ctx.service.changeAudit.tableName,
  263. this.ctx.session.sessionUser.accountId,
  264. audit.flow.status.checked,
  265. ];
  266. break;
  267. case 1: // 待处理(你的)
  268. sql = 'SELECT a.* FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?)' + stateSql;
  269. sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  270. break;
  271. case 5: // 待上报(所有的)PS:取未上报,退回,修订的变更令
  272. sql =
  273. 'SELECT a.* FROM ?? AS a WHERE' +
  274. ' ((a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))' +
  275. ' OR (a.status = ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times - 1 = b.times GROUP BY b.cid)))' +
  276. // 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? GROUP BY b.cid)' +
  277. ' AND (a.status = ? OR a.status = ? OR a.status = ?) AND a.tid = ?' + stateSql;
  278. sqlParam = [
  279. this.tableName,
  280. audit.flow.status.uncheck,
  281. this.ctx.service.changeAudit.tableName,
  282. this.ctx.session.sessionUser.accountId,
  283. audit.flow.status.back,
  284. this.ctx.service.changeAudit.tableName,
  285. this.ctx.session.sessionUser.accountId,
  286. audit.flow.status.uncheck,
  287. audit.flow.status.back,
  288. audit.flow.status.revise,
  289. tenderId,
  290. ];
  291. break;
  292. case 2: // 进行中(所有的)
  293. case 4: // 终止(所有的)
  294. sql =
  295. 'SELECT a.* FROM ?? AS a WHERE ' +
  296. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) AND ' +
  297. 'a.status = ? AND a.tid = ?' + stateSql;
  298. sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  299. break;
  300. case 3: // 已完成(所有的)
  301. sql = 'SELECT a.* FROM ?? AS a WHERE a.status = ? AND a.tid = ?' + stateSql;
  302. sqlParam = [this.tableName, status, tenderId];
  303. break;
  304. default:
  305. break;
  306. }
  307. }
  308. if (sortBy && orderBy) {
  309. if (sortBy === 'code') {
  310. sql += ' ORDER BY CHAR_LENGTH(a.code) ' + orderBy + ',convert(a.code using gbk) ' + orderBy;
  311. } else {
  312. sql += ' ORDER BY a.in_time ' + orderBy;
  313. }
  314. } else {
  315. sql += ' ORDER BY a.in_time DESC';
  316. }
  317. if (hadlimit) {
  318. const limit = this.ctx.pageSize ? this.ctx.pageSize : this.app.config.pageSize;
  319. const offset = limit * (this.ctx.page - 1);
  320. const limitString = offset >= 0 ? offset + ',' + limit : limit;
  321. sql += ' LIMIT ' + limitString;
  322. }
  323. const list = await this.db.query(sql, sqlParam);
  324. return list;
  325. }
  326. /**
  327. * 获取变更令个数
  328. * @param {int} tenderId - 标段id
  329. * @param {int} status - 状态
  330. * @return {void}
  331. */
  332. async getCountByStatus(tenderId, status, state = 0) {
  333. const stateSql = state ? ' AND a.state = ' + state : '';
  334. if (this.ctx.tender.isTourist && status === 0) {
  335. const sql5 = 'SELECT count(*) AS count FROM ?? AS a WHERE a.tid = ?' + stateSql + ' ORDER BY a.in_time DESC';
  336. const sqlParam5 = [this.tableName, tenderId];
  337. const result5 = await this.db.query(sql5, sqlParam5);
  338. return result5[0].count;
  339. }
  340. switch (status) {
  341. case 0: // 包含你的所有变更令
  342. const sql =
  343. 'SELECT count(*) AS count FROM ?? AS a WHERE a.tid = ? AND ' +
  344. '(a.uid = ? OR (a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))' +
  345. ' OR (a.status = ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times - 1 = b.times GROUP BY b.cid))' +
  346. ' OR a.status = ? )' + stateSql;
  347. const sqlParam = [
  348. this.tableName,
  349. tenderId,
  350. this.ctx.session.sessionUser.accountId,
  351. audit.flow.status.uncheck,
  352. this.ctx.service.changeAudit.tableName,
  353. this.ctx.session.sessionUser.accountId,
  354. audit.flow.status.back,
  355. this.ctx.service.changeAudit.tableName,
  356. this.ctx.session.sessionUser.accountId,
  357. audit.flow.status.checked,
  358. ];
  359. const result = await this.db.query(sql, sqlParam);
  360. return result[0].count;
  361. case 1: // 待处理(你的)
  362. // return await this.ctx.service.changeAudit.count({
  363. // tid: tenderId,
  364. // uid: this.ctx.session.sessionUser.accountId,
  365. // status: 2,
  366. // });
  367. const sql6 = 'SELECT count(*) AS count FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?)' + stateSql;
  368. const sqlParam6 = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  369. const result6 = await this.db.query(sql6, sqlParam6);
  370. return result6[0].count;
  371. case 5: // 待上报(所有的)PS:取未上报,退回,修订的变更令
  372. const sql2 =
  373. 'SELECT count(*) AS count FROM ?? AS a WHERE' +
  374. ' ((a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))' +
  375. ' OR (a.status = ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times - 1 = b.times GROUP BY b.cid)))' +
  376. // 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) ' +
  377. ' AND (a.status = ? OR a.status = ? OR a.status = ?) AND a.tid = ?' + stateSql;
  378. const sqlParam2 = [
  379. this.tableName,
  380. audit.flow.status.uncheck,
  381. this.ctx.service.changeAudit.tableName,
  382. this.ctx.session.sessionUser.accountId,
  383. audit.flow.status.back,
  384. this.ctx.service.changeAudit.tableName,
  385. this.ctx.session.sessionUser.accountId,
  386. audit.flow.status.uncheck,
  387. audit.flow.status.back,
  388. audit.flow.status.revise,
  389. tenderId,
  390. ];
  391. const result2 = await this.db.query(sql2, sqlParam2);
  392. return result2[0].count;
  393. case 2: // 进行中(所有的)
  394. case 4: // 终止(所有的)
  395. const sql3 =
  396. 'SELECT count(*) AS count FROM ?? AS a WHERE ' +
  397. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) AND a.status = ? AND a.tid = ?' + stateSql;
  398. const sqlParam3 = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  399. const result3 = await this.db.query(sql3, sqlParam3);
  400. return result3[0].count;
  401. case 3: // 已完成(所有的)
  402. const sql4 = 'SELECT count(*) AS count FROM ?? AS a WHERE a.status = ? AND a.tid = ?' + stateSql;
  403. const sqlParam4 = [this.tableName, status, tenderId];
  404. const result4 = await this.db.query(sql4, sqlParam4);
  405. return result4[0].count;
  406. default:
  407. break;
  408. }
  409. }
  410. async getTp(tenderId, status) {
  411. if (this.ctx.tender.isTourist && status === 0) {
  412. const sql5 = 'SELECT SUM(cast (total_price as decimal(18,6))) AS total_price FROM ?? WHERE tid = ?';
  413. const sqlParam5 = [this.tableName, tenderId];
  414. const result5 = await this.db.query(sql5, sqlParam5);
  415. return result5[0].total_price ? result5[0].total_price : 0;
  416. }
  417. switch (status) {
  418. case 0: // 包含你的所有变更令
  419. const sql =
  420. 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? AS a WHERE a.tid = ? AND ' +
  421. '(a.uid = ? OR (a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))' +
  422. ' OR (a.status = ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times - 1 = b.times GROUP BY b.cid))' +
  423. ' OR a.status = ? )';
  424. const sqlParam = [
  425. this.tableName,
  426. tenderId,
  427. this.ctx.session.sessionUser.accountId,
  428. audit.flow.status.uncheck,
  429. this.ctx.service.changeAudit.tableName,
  430. this.ctx.session.sessionUser.accountId,
  431. audit.flow.status.back,
  432. this.ctx.service.changeAudit.tableName,
  433. this.ctx.session.sessionUser.accountId,
  434. audit.flow.status.checked,
  435. ];
  436. const result = await this.db.query(sql, sqlParam);
  437. return result[0].total_price ? result[0].total_price : 0;
  438. case 1: // 待处理(你的)
  439. const sql6 = 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?)';
  440. const sqlParam6 = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  441. const result6 = await this.db.query(sql6, sqlParam6);
  442. return result6[0].total_price ? result6[0].total_price : 0;
  443. case 5: // 待上报(所有的)PS:取未上报,退回,修订的变更令
  444. const sql2 =
  445. 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? AS a WHERE' +
  446. ' ((a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))' +
  447. ' OR (a.status = ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times - 1 = b.times GROUP BY b.cid)))' +
  448. // 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) ' +
  449. ' AND (a.status = ? OR a.status = ? OR a.status = ?) AND a.tid = ?';
  450. const sqlParam2 = [
  451. this.tableName,
  452. audit.flow.status.uncheck,
  453. this.ctx.service.changeAudit.tableName,
  454. this.ctx.session.sessionUser.accountId,
  455. audit.flow.status.back,
  456. this.ctx.service.changeAudit.tableName,
  457. this.ctx.session.sessionUser.accountId,
  458. audit.flow.status.uncheck,
  459. audit.flow.status.back,
  460. audit.flow.status.revise,
  461. tenderId,
  462. ];
  463. const result2 = await this.db.query(sql2, sqlParam2);
  464. return result2[0].total_price ? result2[0].total_price : 0;
  465. case 2: // 进行中(所有的)
  466. case 4: // 终止(所有的)
  467. const sql3 =
  468. 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? AS a WHERE ' +
  469. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) AND a.status = ? AND a.tid = ?';
  470. const sqlParam3 = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  471. const result3 = await this.db.query(sql3, sqlParam3);
  472. return result3[0].total_price ? result3[0].total_price : 0;
  473. case 3: // 已完成(所有的)
  474. const sql4 = 'SELECT SUM(cast (total_price as decimal(18,6))) AS total_price FROM ?? WHERE status = ? AND tid = ?';
  475. const sqlParam4 = [this.tableName, status, tenderId];
  476. const result4 = await this.db.query(sql4, sqlParam4);
  477. return result4[0].total_price ? result4[0].total_price : 0;
  478. default:
  479. break;
  480. }
  481. }
  482. /**
  483. * 获取变更令个数
  484. * @param {int} tenderId - 标段id
  485. * @param {int} quality - 变更性质
  486. * @return {void}
  487. */
  488. async getCountByQuality(tenderId, quality) {
  489. return await this.db.count(this.tableName, { tid: tenderId, quality });
  490. }
  491. /**
  492. * 获取变更令个数
  493. * @param {int} tenderId - 标段id
  494. * @param {int} status - 状态
  495. * @return {void}
  496. */
  497. async getCountByStatus2(tenderId, status) {
  498. if (status === audit.filter.status.uncheck) {
  499. const sql =
  500. 'SELECT count(*) AS count FROM ?? WHERE ' +
  501. 'tid = ? AND (status = ? OR status = ? OR status = ?)';
  502. const sqlParam = [
  503. this.tableName,
  504. tenderId,
  505. audit.flow.status.uncheck,
  506. audit.flow.status.back,
  507. audit.flow.status.revise,
  508. ];
  509. const result = await this.db.queryOne(sql, sqlParam);
  510. return result ? result.count : 0;
  511. }
  512. return await this.db.count(this.tableName, { tid: tenderId, status });
  513. }
  514. /**
  515. * 获取已批复变更令的总金额
  516. * @param {int} tenderId - 标段id
  517. * @param {int} quality - 变更性质
  518. * @return {void}
  519. */
  520. async getChangeTp(tenderId) {
  521. const sql = 'SELECT SUM(`total_price`) AS tp, SUM(`positive_tp`) AS p_tp, SUM(`negative_tp`) AS n_tp FROM ?? WHERE tid = ? AND status = ?';
  522. const sqlParam = [this.tableName, tenderId, audit.flow.status.checked];
  523. const result = await this.db.queryOne(sql, sqlParam);
  524. return result ? [result.tp, result.p_tp, result.n_tp] : [0, 0, 0];
  525. }
  526. /**
  527. * 上报或重新上报或保存修改功能
  528. * @param {int} postData - 表单提交的数据
  529. * @param {int} tenderId - 标段id
  530. * @return {void}
  531. */
  532. async save(postData, tenderId) {
  533. // 初始化事务
  534. this.transaction = await this.db.beginTransaction();
  535. let result = false;
  536. try {
  537. // 变更令信息
  538. const changeInfo = await this.getDataByCondition({ cid: postData.cid });
  539. // 该变更令原报人信息
  540. const lastUser = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 0);
  541. // 先删除本次原有的变更审批人和清单
  542. await this.ctx.service.changeAudit.deleteAuditData(this.transaction, changeInfo.cid, changeInfo.times);
  543. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid: changeInfo.cid });
  544. let change_status = false;
  545. // 获取变更令提交状态
  546. if (postData.changestatus !== undefined && parseInt(postData.changestatus) === 1) {
  547. change_status = true;
  548. // 更新原报人审批状态
  549. await this.transaction.update(this.ctx.service.changeAudit.tableName, {
  550. id: lastUser.id,
  551. status: audit.flow.auditStatus.checked,
  552. sin_time: new Date(),
  553. });
  554. }
  555. // 再插入postData里的变更审批人和清单
  556. if (postData.changeaudit !== undefined && postData.changeaudit !== '') {
  557. const changeAudit = postData.changeaudit.split(',');
  558. const insertCA = [];
  559. let uSite = 1;
  560. let uSort = parseInt(lastUser.usort) + 1;
  561. for (const [index, ca] of changeAudit.entries()) {
  562. const auditInfo = ca.split('/%/');
  563. const uStatus = change_status && index === 0 ? audit.flow.auditStatus.checking : audit.flow.auditStatus.uncheck;
  564. const sin_time = change_status && index === 0 ? new Date() : null;
  565. const caArray = {
  566. tid: tenderId,
  567. cid: changeInfo.cid,
  568. uid: auditInfo[0],
  569. name: auditInfo[1],
  570. jobs: auditInfo[2],
  571. company: auditInfo[3],
  572. times: changeInfo.times,
  573. usite: uSite,
  574. usort: uSort,
  575. status: uStatus,
  576. sin_time,
  577. };
  578. uSite++;
  579. uSort++;
  580. insertCA.push(caArray);
  581. // 添加短信通知-需要审批提醒功能
  582. if (change_status && index === 0) {
  583. const sms = new SMS(this.ctx);
  584. const code = await sms.contentChange(changeInfo.code);
  585. const shenpiUrl = await this.ctx.helper.urlToShort(
  586. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  587. );
  588. await this.ctx.helper.sendAliSms(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  589. biangeng: code,
  590. code: shenpiUrl,
  591. });
  592. // 微信模板通知
  593. const wechatData = {
  594. wap_url: shenpiUrl,
  595. status: wxConst.status.check,
  596. tips: wxConst.tips.check,
  597. code: this.ctx.session.sessionProject.code,
  598. c_name: changeInfo.name,
  599. };
  600. await this.ctx.helper.sendWechat(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  601. }
  602. }
  603. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insertCA);
  604. }
  605. let changeList = [];
  606. if (postData.changelist !== undefined && postData.changelist !== '') {
  607. changeList = postData.changelist.split('^_^');
  608. }
  609. let changeWhiteList = [];
  610. if (postData.changewhitelist !== undefined && postData.changewhitelist !== '') {
  611. changeWhiteList = postData.changewhitelist.split('^_^');
  612. }
  613. changeList.push.apply(changeList, changeWhiteList);
  614. const insertCL = [];
  615. let total_price = 0;
  616. if (changeList.length > 0) {
  617. for (const cl of changeList) {
  618. const clInfo = cl.split('*;*');
  619. const clArray = {
  620. tid: tenderId,
  621. cid: changeInfo.cid,
  622. lid: clInfo[8],
  623. code: clInfo[0],
  624. name: clInfo[1],
  625. bwmx: clInfo[2],
  626. unit: clInfo[3],
  627. unit_price: clInfo[4],
  628. oamount: clInfo[5],
  629. camount: clInfo[6],
  630. samount: '',
  631. detail: clInfo[7],
  632. spamount: clInfo[6],
  633. xmj_code: clInfo[9] !== '' ? clInfo[9] : null,
  634. xmj_jldy: clInfo[10] !== '' ? clInfo[10] : null,
  635. gcl_id: clInfo[11] !== '' ? clInfo[11] : '',
  636. };
  637. if (clInfo[4] === '') {
  638. delete clArray.unit_price;
  639. }
  640. insertCL.push(clArray);
  641. total_price = this.ctx.helper.accAdd(total_price, this.ctx.helper.mul(clArray.unit_price, clArray.spamount, this.ctx.tender.info.decimal.tp));
  642. }
  643. await this.transaction.insert(this.ctx.service.changeAuditList.tableName, insertCL);
  644. }
  645. // 修改变更令基本数据
  646. const cArray = {
  647. code: postData.code,
  648. name: postData.name,
  649. peg: postData.peg,
  650. org_name: postData.org_name,
  651. org_code: postData.org_code,
  652. new_name: postData.new_name,
  653. new_code: postData.new_code,
  654. content: postData.content,
  655. basis: postData.basis,
  656. expr: postData.expr,
  657. memo: postData.memo,
  658. type: postData.type.join(','),
  659. class: postData.class,
  660. quality: postData.quality,
  661. company: postData.company,
  662. charge: postData.charge,
  663. w_code: postData.w_code,
  664. total_price,
  665. // tp_decimal: this.ctx.tender.info.decimal.tp,
  666. };
  667. const options = {
  668. where: {
  669. cid: changeInfo.cid,
  670. },
  671. };
  672. if (change_status) {
  673. cArray.tp_decimal = this.ctx.tender.info.decimal.tp;
  674. cArray.up_decimal = this.ctx.tender.info.decimal.up;
  675. cArray.status = audit.flow.status.checking;
  676. cArray.cin_time = Date.parse(new Date()) / 1000;
  677. }
  678. await this.transaction.update(this.tableName, cArray, options);
  679. await this.transaction.commit();
  680. result = true;
  681. } catch (error) {
  682. await this.transaction.rollback();
  683. result = false;
  684. }
  685. return result;
  686. }
  687. /**
  688. * 保存变更信息
  689. * @param {int} postData - 表单提交的数据
  690. * @param {int} tenderId - 标段id
  691. * @return {void}
  692. */
  693. async saveInfo(postData, delimit = 100) {
  694. // 初始化事务
  695. const transaction = await this.db.beginTransaction();
  696. let result = false;
  697. try {
  698. result = {};
  699. const options = {
  700. where: {
  701. cid: this.ctx.change.cid,
  702. },
  703. };
  704. if (postData.state && parseInt(postData.state) !== this.ctx.change.state) {
  705. // 变更清单需要同步设置计量上限值
  706. // 判断是否存在已调用清单,并判断新上限值是否比它小,更新计量上限值
  707. const changeList = await this.ctx.service.changeAuditList.getList(this.ctx.change.cid);
  708. // 获取是否已存在调用变更令
  709. let changeUsedData = await this.ctx.service.stageChange.getFinalUsedData(this.ctx.tender.id, this.ctx.change.cid);
  710. changeUsedData = this._.orderBy(this._.filter(changeUsedData, function(item) {
  711. return item.qty !== null;
  712. }), ['sorder'], ['desc']);
  713. const useChangeUsedData = [];
  714. if (changeUsedData.length > 0) { // 防止未创建期时调用
  715. for (const cu of changeUsedData) {
  716. const index = this._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  717. if (index !== -1) {
  718. useChangeUsedData[index].qty = this.ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  719. } else {
  720. useChangeUsedData.push(cu);
  721. }
  722. }
  723. }
  724. const updateList = [];
  725. for (const cl of changeList) {
  726. const one = {
  727. id: cl.id,
  728. };
  729. if (useChangeUsedData.length > 0 && this._.findIndex(useChangeUsedData, { cbid: cl.id }) !== -1) {
  730. // 获取比例值
  731. const uc = this._.find(useChangeUsedData, { cbid: cl.id });
  732. const minLimit = Math.ceil(this.ctx.helper.div(uc.qty, cl.camount) * 100);
  733. if (minLimit < delimit) {
  734. one.delimit = delimit;
  735. cl.delimit = delimit;
  736. }
  737. } else if (cl.delimit !== delimit) {
  738. one.delimit = delimit;
  739. cl.delimit = delimit;
  740. }
  741. if (!this._.isEqual(one, { id: cl.id })) updateList.push(one);
  742. }
  743. if (updateList.length > 0) await transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateList);
  744. result.changeList = changeList;
  745. result.deLimit = delimit;
  746. if (this.ctx.change.delimit !== delimit) postData.delimit = delimit;
  747. }
  748. await transaction.update(this.tableName, postData, options);
  749. await transaction.commit();
  750. result.msg = '保存成功';
  751. } catch (error) {
  752. await transaction.rollback();
  753. result = false;
  754. }
  755. return result;
  756. }
  757. /**
  758. * 保存变更信息
  759. * @param {int} order_by - 表单提交的数据
  760. * @return {void}
  761. */
  762. async saveOrderBy(order_by, newLedgerList = []) {
  763. const transaction = await this.db.beginTransaction();
  764. let result = [];
  765. try {
  766. const postData = { order_by };
  767. let changeList = await this.ctx.service.changeAuditList.getList(this.ctx.change.cid);
  768. if (order_by) {
  769. let i = 1;
  770. const updateArray = [];
  771. for (const cl of changeList) {
  772. updateArray.push({
  773. id: cl.id,
  774. order: i,
  775. });
  776. cl.order = i;
  777. i++;
  778. }
  779. if (updateArray.length > 0) await transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateArray);
  780. } else {
  781. await this.ctx.service.changeAuditList.saveLedgerListDatas(newLedgerList, null, order_by);
  782. changeList = await this.ctx.service.changeAuditList.getList(this.ctx.change.cid, order_by);
  783. }
  784. const options = {
  785. where: {
  786. cid: this.ctx.change.cid,
  787. },
  788. };
  789. await transaction.update(this.tableName, postData, options);
  790. await transaction.commit();
  791. result = { changeList,
  792. usedList: await this.ctx.service.stageChange.getFinalUsedData(this.ctx.tender.id, this.ctx.change.cid) };
  793. } catch (error) {
  794. await transaction.rollback();
  795. result = false;
  796. }
  797. return result;
  798. }
  799. /**
  800. * 审批通过
  801. * @param {Number} pid 项目id
  802. * @param {int} postData - 表单提交的数据
  803. * @param {int} changeData - 变更令的数据
  804. * @return {void}
  805. */
  806. async approvalSuccess(pid, postData, changeData) {
  807. // 初始化事务
  808. this.transaction = await this.db.beginTransaction();
  809. let result = false;
  810. try {
  811. // 获取所有审核人列表
  812. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  813. // console.log('auditors', auditors);
  814. // console.log('postData', postData);
  815. // 添加到消息推送表
  816. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  817. const records = [];
  818. auditors.forEach(auditor => {
  819. records.push({
  820. pid,
  821. type: pushType.change,
  822. uid: auditor.uid,
  823. status: audit.flow.status.checked,
  824. content: noticeContent,
  825. });
  826. });
  827. await this.transaction.insert('zh_notice', records);
  828. // 判断是否终审方法需要更改了,因为存在修改审批流程的操作,会使判断是否终审有问题
  829. const curAudit = await this.ctx.service.changeAudit.getCurAuditor(changeData.cid, changeData.times);
  830. const nextAudit = await this.ctx.service.changeAudit.getDataByCondition({ cid: changeData.cid, times: changeData.times, usort: curAudit.usort + 1, status: audit.flow.auditStatus.uncheck });
  831. // 设置审批人通过
  832. const audit_update = {
  833. id: curAudit.id,
  834. sdesc: postData.sdesc,
  835. status: audit.flow.auditStatus.checked,
  836. sin_time: new Date(),
  837. };
  838. const change_update = {
  839. w_code: postData.w_code,
  840. status: audit.flow.status.checking,
  841. cin_time: Date.parse(new Date()) / 1000,
  842. };
  843. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  844. await this.ctx.service.noticeAgain.stopNoticeAgain(this.transaction, this.ctx.service.changeAudit.tableName, curAudit.id);
  845. // 清单数据更新
  846. const bills_list = postData.bills_list.split(',');
  847. let total_price = 0;
  848. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  849. for (const bl of bills_list) {
  850. const listInfo = bl.split('_');
  851. const lid = listInfo[0];
  852. const amount = listInfo[1] !== 'null' && listInfo[1] !== '' ? listInfo[1] : null;
  853. const changeListInfo = await this.ctx.service.changeAuditList.getDataById(lid);
  854. if (changeListInfo !== undefined) {
  855. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(changeListInfo.unit_price, amount, tp_decimal));
  856. const audit_amount = changeListInfo.audit_amount !== null && changeListInfo.audit_amount !== '' ? changeListInfo.audit_amount.split(',') : [];
  857. audit_amount.push(amount);
  858. const list_update = {
  859. id: lid,
  860. audit_amount: audit_amount.join(','),
  861. spamount: amount !== null ? parseFloat(amount) : null,
  862. };
  863. if (postData.audit_next_id === undefined) {
  864. list_update.samount = amount !== null ? amount : '';
  865. list_update.checked_amount = amount !== null ? parseFloat(amount) : 0;
  866. list_update.checked_price = amount !== null ? this.ctx.helper.mul(changeListInfo.unit_price, list_update.checked_amount, tp_decimal) : 0;
  867. }
  868. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  869. }
  870. }
  871. if (!nextAudit) {
  872. // 变更令审批完成
  873. change_update.status = audit.flow.status.checked;
  874. change_update.p_code = postData.p_code;
  875. change_update.sin_time = Date.parse(new Date()) / 1000;
  876. change_update.is_revise = 0;
  877. await this.ctx.service.tenderTag.saveTenderTag(changeData.tid, { bgl_time: new Date() }, this.transaction);
  878. await this.ctx.service.changeAuditList.updateToLedger(this.transaction, changeData.tid, changeData.cid);
  879. // 审批通过 - 检查三方特殊推送
  880. await this.ctx.service.specMsg.addChangeMsg(this.transaction, this.ctx.session.sessionProject.id, changeData, pushOperate.change.checked);
  881. // 添加短信通知-审批通过提醒功能
  882. // const mobile_array = [];
  883. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  884. const users = this._.map(auditList, 'uid');
  885. const sms = new SMS(this.ctx);
  886. const code = await sms.contentChange(changeData.code);
  887. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  888. biangeng: code,
  889. status: SmsAliConst.status.success,
  890. });
  891. // 微信模板通知
  892. const shenpiUrl = await this.ctx.helper.urlToShort(
  893. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  894. );
  895. const wechatData = {
  896. wap_url: shenpiUrl,
  897. status: wxConst.status.success,
  898. tips: wxConst.tips.success,
  899. code: this.ctx.session.sessionProject.code,
  900. c_name: changeData.name,
  901. };
  902. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  903. } else {
  904. // 设置下一个审批人为审批状态
  905. const nextAudit_update = {
  906. id: nextAudit.id,
  907. status: audit.flow.auditStatus.checking,
  908. sin_time: new Date(),
  909. };
  910. await this.transaction.update(this.ctx.service.changeAudit.tableName, nextAudit_update);
  911. // 添加短信通知-需要审批提醒功能
  912. const sms = new SMS(this.ctx);
  913. const code = await sms.contentChange(changeData.code);
  914. const shenpiUrl = await this.ctx.helper.urlToShort(
  915. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  916. );
  917. await this.ctx.helper.sendAliSms(nextAudit.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  918. biangeng: code,
  919. code: shenpiUrl,
  920. });
  921. // 微信模板通知
  922. const wechatData = {
  923. wap_url: shenpiUrl,
  924. status: wxConst.status.check,
  925. tips: wxConst.tips.check,
  926. code: this.ctx.session.sessionProject.code,
  927. c_name: changeData.name,
  928. };
  929. await this.ctx.helper.sendWechat(nextAudit.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  930. // 重新发送配置
  931. await this.ctx.service.noticeAgain.addNoticeAgain(this.transaction, smsTypeConst.const.BG, {
  932. pid: this.ctx.session.sessionProject.id,
  933. tid: changeData.tid,
  934. uid: nextAudit.uid,
  935. sp_type: 'change',
  936. sp_id: nextAudit.id,
  937. table_name: this.ctx.service.changeAudit.tableName,
  938. template: wxConst.template.change,
  939. wx_data: wechatData,
  940. });
  941. }
  942. change_update.total_price = total_price;
  943. const options = {
  944. where: {
  945. cid: postData.change_id,
  946. },
  947. };
  948. await this.transaction.update(this.tableName, change_update, options);
  949. await this.transaction.commit();
  950. result = true;
  951. } catch (error) {
  952. console.log(error);
  953. await this.transaction.rollback();
  954. result = false;
  955. }
  956. return result;
  957. }
  958. /**
  959. * 审批终止
  960. * @param {int} postData - 表单提交的数据
  961. * @return {void}
  962. */
  963. async approvalStop(postData) {
  964. // 初始化事务
  965. this.transaction = await this.db.beginTransaction();
  966. let result = false;
  967. try {
  968. // 设置审批人终止
  969. const audit_update = {
  970. id: postData.audit_id,
  971. sdesc: postData.sdesc,
  972. status: 4,
  973. sin_time: new Date(),
  974. };
  975. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  976. await this.ctx.service.noticeAgain.stopNoticeAgain(this.transaction, this.ctx.service.changeAudit.tableName, postData.audit_id);
  977. // 设置变更令终止
  978. const change_update = {
  979. w_code: postData.w_code,
  980. status: 4,
  981. cin_time: Date.parse(new Date()) / 1000,
  982. };
  983. const options = {
  984. where: {
  985. cid: postData.change_id,
  986. },
  987. };
  988. await this.transaction.update(this.tableName, change_update, options);
  989. await this.transaction.commit();
  990. result = true;
  991. } catch (error) {
  992. await this.transaction.rollback();
  993. result = false;
  994. }
  995. return result;
  996. }
  997. /**
  998. * 审批退回到原报人
  999. * @param {Number} pid 项目id
  1000. * @param {int} postData - 表单提交的数据
  1001. * @param {int} changeData - 变更令的数据
  1002. * @return {void}
  1003. */
  1004. async approvalBack(pid, postData, changeData) {
  1005. // 初始化事务
  1006. this.transaction = await this.db.beginTransaction();
  1007. let result = false;
  1008. try {
  1009. // 获取所有审核人列表
  1010. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1011. // 添加到消息推送表
  1012. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  1013. const records = [];
  1014. auditors.forEach(auditor => {
  1015. records.push({
  1016. pid,
  1017. type: pushType.change,
  1018. uid: auditor.uid,
  1019. status: audit.flow.status.backnew,
  1020. content: noticeContent,
  1021. });
  1022. });
  1023. await this.transaction.insert('zh_notice', records);
  1024. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  1025. // 设置审批人退回
  1026. const audit_update = {
  1027. id: postData.audit_id,
  1028. sdesc: postData.sdesc,
  1029. status: audit.flow.auditStatus.back,
  1030. sin_time: new Date(),
  1031. };
  1032. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1033. await this.ctx.service.noticeAgain.stopNoticeAgain(this.transaction, this.ctx.service.changeAudit.tableName, postData.audit_id);
  1034. // 新增新一次的审批人列表
  1035. // 获取当前次数审批人列表
  1036. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  1037. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 1, 0);
  1038. let usort = lastauditInfo.usort + 1;
  1039. const newTimes = changeInfo.times + 1;
  1040. const insert_audit_array = [];
  1041. for (const al of auditList) {
  1042. const insert_audit = {
  1043. tid: al.tid,
  1044. cid: al.cid,
  1045. uid: al.uid,
  1046. name: al.name,
  1047. jobs: al.jobs,
  1048. company: al.company,
  1049. times: newTimes,
  1050. usite: al.usite,
  1051. usort,
  1052. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  1053. };
  1054. insert_audit_array.push(insert_audit);
  1055. usort++;
  1056. }
  1057. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1058. // 变更金额也退回
  1059. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1060. where: { cid: changeInfo.cid },
  1061. });
  1062. // 生成内容保存表至zh_change_history中,用于撤回
  1063. await this.ctx.service.changeHistory.saveHistory(this.transaction, changeData, changeList);
  1064. let total_price = 0;
  1065. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1066. for (const cl of changeList) {
  1067. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1068. }
  1069. // 设置变更令退回
  1070. const change_update = {
  1071. w_code: postData.w_code,
  1072. status: audit.flow.status.back,
  1073. times: newTimes,
  1074. cin_time: Date.parse(new Date()) / 1000,
  1075. total_price,
  1076. tp_decimal: null,
  1077. up_decimal: null,
  1078. };
  1079. const options = {
  1080. where: {
  1081. cid: postData.change_id,
  1082. },
  1083. };
  1084. await this.transaction.update(this.tableName, change_update, options);
  1085. await this.transaction.commit();
  1086. result = true;
  1087. const users = this._.map(insert_audit_array, 'uid');
  1088. const sms = new SMS(this.ctx);
  1089. const code = await sms.contentChange(changeData.code);
  1090. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  1091. biangeng: code,
  1092. status: SmsAliConst.status.back,
  1093. });
  1094. // 微信模板通知
  1095. const shenpiUrl = await this.ctx.helper.urlToShort(
  1096. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  1097. );
  1098. const wechatData = {
  1099. wap_url: shenpiUrl,
  1100. status: wxConst.status.back,
  1101. tips: wxConst.tips.back,
  1102. code: this.ctx.session.sessionProject.code,
  1103. c_name: changeInfo.name,
  1104. };
  1105. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  1106. } catch (error) {
  1107. await this.transaction.rollback();
  1108. result = false;
  1109. }
  1110. return result;
  1111. }
  1112. /**
  1113. * 审批退回到上一个审批人
  1114. * @param {Number} pid 项目id
  1115. * @param {int} postData - 表单提交的数据
  1116. * @param {int} changeData - 变更令的数据
  1117. * @return {void}
  1118. */
  1119. async approvalBackNew(pid, postData, changeData) {
  1120. // 初始化事务
  1121. this.transaction = await this.db.beginTransaction();
  1122. let result = false;
  1123. try {
  1124. // 获取所有审核人列表
  1125. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1126. // 添加到消息推送表
  1127. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  1128. const records = [];
  1129. auditors.forEach(auditor => {
  1130. records.push({
  1131. pid,
  1132. type: pushType.change,
  1133. uid: auditor.uid,
  1134. status: audit.flow.status.back,
  1135. content: noticeContent,
  1136. });
  1137. });
  1138. await this.transaction.insert('zh_notice', records);
  1139. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  1140. // 设置审批人退回
  1141. const audit_update = {
  1142. id: postData.audit_id,
  1143. sdesc: postData.sdesc,
  1144. status: audit.flow.auditStatus.backnew,
  1145. sin_time: new Date(),
  1146. };
  1147. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1148. await this.ctx.service.noticeAgain.stopNoticeAgain(this.transaction, this.ctx.service.changeAudit.tableName, postData.audit_id);
  1149. // 获取当前审批人信息
  1150. const auditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_id);
  1151. // 获取当前次数审批人列表
  1152. const auditList = await this.ctx.service.changeAudit.getNextAuditList(changeInfo.cid, auditInfo.usort);
  1153. let usort = auditInfo.usort + 1;
  1154. // 获取上一个审批人信息
  1155. const lastauditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_last_id);
  1156. // 新增2个审批人到审批列表中
  1157. const insert_audit1 = {
  1158. tid: lastauditInfo.tid,
  1159. cid: lastauditInfo.cid,
  1160. uid: lastauditInfo.uid,
  1161. name: lastauditInfo.name,
  1162. jobs: lastauditInfo.jobs,
  1163. company: lastauditInfo.company,
  1164. times: lastauditInfo.times,
  1165. usite: lastauditInfo.usite,
  1166. usort,
  1167. status: audit.flow.auditStatus.checking,
  1168. sin_time: new Date(),
  1169. };
  1170. const result_audit = await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1171. usort++;
  1172. // 新增2个审批人到审批列表中
  1173. const insert_audit2 = {
  1174. tid: auditInfo.tid,
  1175. cid: auditInfo.cid,
  1176. uid: auditInfo.uid,
  1177. name: auditInfo.name,
  1178. jobs: auditInfo.jobs,
  1179. company: auditInfo.company,
  1180. times: auditInfo.times,
  1181. usite: auditInfo.usite,
  1182. usort,
  1183. status: audit.flow.auditStatus.uncheck,
  1184. };
  1185. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1186. // 把接下未审批的审批人排序都加2
  1187. for (const al of auditList) {
  1188. const audit_update = {
  1189. id: al.id,
  1190. usort: al.usort + 2,
  1191. };
  1192. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1193. }
  1194. // 审批列表数据也要回退
  1195. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1196. where: { cid: changeInfo.cid },
  1197. });
  1198. let total_price = 0;
  1199. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1200. for (const cl of changeList) {
  1201. const audit_amount = cl.audit_amount.split(',');
  1202. const last_amount = audit_amount[audit_amount.length - 1] ? audit_amount[audit_amount.length - 1] : 0;
  1203. audit_amount.splice(-1, 1);
  1204. const list_update = {
  1205. id: cl.id,
  1206. audit_amount: audit_amount.join(','),
  1207. spamount: parseFloat(last_amount),
  1208. };
  1209. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1210. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1211. }
  1212. // 设置变更令退回
  1213. const change_update = {
  1214. w_code: postData.w_code,
  1215. status: audit.flow.status.backnew,
  1216. cin_time: Date.parse(new Date()) / 1000,
  1217. total_price,
  1218. };
  1219. const options = {
  1220. where: {
  1221. cid: postData.change_id,
  1222. },
  1223. };
  1224. await this.transaction.update(this.tableName, change_update, options);
  1225. await this.transaction.commit();
  1226. result = true;
  1227. const sms = new SMS(this.ctx);
  1228. const code = await sms.contentChange(changeData.code);
  1229. const shenpiUrl = await this.ctx.helper.urlToShort(
  1230. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  1231. );
  1232. await this.ctx.helper.sendAliSms(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1233. biangeng: code,
  1234. code: shenpiUrl,
  1235. });
  1236. // 微信模板通知
  1237. const wechatData = {
  1238. wap_url: shenpiUrl,
  1239. status: wxConst.status.check,
  1240. tips: wxConst.tips.check,
  1241. code: this.ctx.session.sessionProject.code,
  1242. c_name: changeInfo.name,
  1243. };
  1244. await this.ctx.helper.sendWechat(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1245. // 重新发送配置
  1246. await this.ctx.service.noticeAgain.addNoticeAgain(this.transaction, smsTypeConst.const.BG, {
  1247. pid: this.ctx.session.sessionProject.id,
  1248. tid: this.ctx.change.tid,
  1249. uid: lastauditInfo.uid,
  1250. sp_type: 'change',
  1251. sp_id: result_audit.insertId,
  1252. table_name: this.ctx.service.changeAudit.tableName,
  1253. template: wxConst.template.change,
  1254. wx_data: wechatData,
  1255. });
  1256. } catch (error) {
  1257. console.log(error);
  1258. await this.transaction.rollback();
  1259. result = false;
  1260. }
  1261. return result;
  1262. }
  1263. /**
  1264. * 查询可用的变更令
  1265. * @param bills - 查询的清单
  1266. * @param pos - 查询的部位
  1267. * @return {Promise<*>} - 可用的变更令列表
  1268. */
  1269. async getValidChanges(tender, stage, data, noValue) {
  1270. const bills = data.bills, pos = data.pos;
  1271. const self = this;
  1272. const getFilterPart = function(field, value) {
  1273. return value
  1274. ? field + ' = ' + self.db.escape(value)
  1275. : self.db.format("(?? = null or ?? = '')", [field, field]);
  1276. };
  1277. let filter = getFilterPart('cb.code', bills.b_code) +
  1278. ' And ' + getFilterPart('cb.name', bills.name) +
  1279. ' And ' + getFilterPart('cb.unit', bills.unit) +
  1280. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price);
  1281. // if (data.pos) filter = filter + ' And ' + getFilterPart('cb.bwmx', pos.name);
  1282. const sql =
  1283. 'SELECT c.cid, c.code, c.name, c.w_code, c.p_code, c.peg, c.org_name, c.org_code, c.new_name, c.new_code,' +
  1284. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge,' +
  1285. ' cb.id As cbid, cb.code As b_code, cb.name As b_name, cb.unit As b_unit, cb.samount As b_amount, cb.detail As b_detail, cb.bwmx As b_bwmx, cb.gcl_id, cb.is_valuation, cb.delimit,' +
  1286. ' scb.used_amount' +
  1287. ' FROM ' + this.tableName + ' As c ' +
  1288. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  1289. ' Left Join (' +
  1290. ' SELECT SUM(qty) As used_amount, cbid' +
  1291. ' FROM ' + this.ctx.service.stageChangeFinal.tableName +
  1292. ' WHERE tid = ? and sorder < ?' +
  1293. ' GROUP BY cbid' +
  1294. ' ) As scb ON cb.id = scb.cbid' +
  1295. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  1296. ' ORDER BY c.in_time';
  1297. const sqlParam = [tender.id, stage.order, tender.id, audit.flow.status.checked];
  1298. let changes = await this.db.query(sql, sqlParam);
  1299. if (noValue) {
  1300. if (data.noValue) {
  1301. changes = changes.filter(c => {
  1302. return !c.is_valuation;
  1303. });
  1304. } else {
  1305. changes = changes.filter(c => {
  1306. return c.is_valuation;
  1307. });
  1308. }
  1309. }
  1310. for (const c of changes) {
  1311. let sSql = 'SELECT * FROM ' + this.ctx.service.stageChange.tableName + ' WHERE sid = ? and cbid = ?';
  1312. const sSqlParam = [stage.id, c.cbid];
  1313. if (stage.readOnly) {
  1314. sSql = sSql + ' and (stimes < ? or (stimes = ? and sorder <= ?))';
  1315. sSqlParam.push(stage.curTimes, stage.curTimes, stage.curOrder);
  1316. }
  1317. const stageUsedData = await this.db.query(sSql, sSqlParam);
  1318. const filter = this.ctx.helper.filterLastestData(stageUsedData, ['pid', 'lid', 'no_value'], 'stimes', 'sorder');
  1319. c.stage_used_amount = this.ctx.helper.sum(filter.map(x => { return x.qty }));
  1320. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1321. ' FROM ?? As ca ' +
  1322. ' Left Join ?? As pa ' +
  1323. ' On ca.uid = pa.id ' +
  1324. ' Where ca.cid = ?';
  1325. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1326. c.attachments = await this.db.query(aSql, aSqlParam);
  1327. }
  1328. return changes;
  1329. }
  1330. /**
  1331. * 查询变更令 + 变更令执行
  1332. * @param tid
  1333. * @return {Promise<void>}
  1334. */
  1335. async getChangeAndUsedInfo(tid) {
  1336. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1337. let filter;
  1338. if (lastStage.id === this.ctx.stage.id) {
  1339. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1340. lastStage.order,
  1341. lastStage.order,
  1342. this.ctx.stage.curTimes,
  1343. this.ctx.stage.curTimes,
  1344. this.ctx.stage.curOrder,
  1345. ]);
  1346. } else {
  1347. if (lastStage.status === audit.stage.status.uncheck) {
  1348. filter = ' And s.order < ' + lastStage.order;
  1349. } else if (lastStage.status === audit.stage.status.checked) {
  1350. filter = '';
  1351. } else if (lastStage.status === audit.stage.status.checkNo) {
  1352. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And sChange.`stimes` <= ?))', [lastStage.order, lastStage.order, lastStage.times]);
  1353. } else {
  1354. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(lastStage.id, lastStage.times);
  1355. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1356. lastStage.order,
  1357. lastStage.order,
  1358. lastStage.times,
  1359. lastStage.times,
  1360. curAuditor.order - 1,
  1361. ]);
  1362. }
  1363. }
  1364. const sql =
  1365. 'SELECT C.*, Sum(U.utp) As used_tp, TRUNCATE(Sum(U.utp) / C.total_price * 100 + 0.005, 2) As used_pt' +
  1366. ' FROM ' + this.tableName + ' As C' +
  1367. ' LEFT JOIN (SELECT sc.tid, sc.cid, sc.cbid, IF(SUM(sc.qty) > 0, TRUNCATE(SUM(sc.qty) * cb.unit_price + ?, ?), TRUNCATE(SUM(sc.qty) * cb.unit_price - ?, ?)) As utp,' +
  1368. ' IF(SUM(sc.qty) > 0, TRUNCATE(SUM(sc.qty) * cb.unit_price + ?, ?), 0, ?)) As utp_po, IF(SUM(sc.qty) > 0, 0, TRUNCATE(SUM(sc.qty) * cb.unit_price - ?, ?)) As utp_ne' +
  1369. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1370. ' INNER JOIN (' +
  1371. ' SELECT MAX(`stimes`) As `stimes`, MAX(`sorder`) As `sorder`, `lid`, `pid`, `cbid`, sChange.`sid` ' +
  1372. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sChange ' +
  1373. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' As s' +
  1374. ' ON sChange.sid = s.id' +
  1375. ' WHERE sChange.tid = ?' + filter +
  1376. ' GROUP By `lid`, `pid`, `cbid`, `sid`' +
  1377. ' ) As m' +
  1378. ' ON sc.stimes = m.stimes And sc.sorder = m.sorder And sc.`cbid` = m.`cbid` AND sc.`sid` = m.`sid` And sc.`lid` = m.`lid` And sc.`pid` = m.`pid`' +
  1379. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName +
  1380. ' As cb ON sc.cbid = cb.id' +
  1381. ' GROUP By sc.`cbid`' +
  1382. ' ) As U ON C.cid = U.cid' +
  1383. ' WHERE C.tid = ? And C.status = ? And C.valid' +
  1384. ' GROUP By C.cid' +
  1385. ' ORDER By in_time';
  1386. // 舍入步长
  1387. const step = parseFloat('0.' + '0000000'.substr(0, this.ctx.tender.info.decimal.tp) + '5');
  1388. const sqlParam = [step, this.ctx.tender.info.decimal.tp, step, this.ctx.tender.info.decimal.tp, tid, tid, audit.flow.status.checked];
  1389. const data = await this.db.query(sql, sqlParam);
  1390. return data;
  1391. }
  1392. /**
  1393. * 查询可用的变更令
  1394. * @param { string } cid - 查询的清单
  1395. * @return {Promise<*>} - 可用的变更令列表
  1396. */
  1397. async delete(cid) {
  1398. // 初始化事务
  1399. this.transaction = await this.db.beginTransaction();
  1400. let result = false;
  1401. try {
  1402. const changeInfo = await this.getDataByCondition({ cid });
  1403. // 先删除清单,审批人列表
  1404. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid });
  1405. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid });
  1406. // 再删除附件和附件文件ni zuo
  1407. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid } });
  1408. await this.ctx.helper.delFiles(attList);
  1409. await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1410. await this.transaction.delete(this.ctx.service.changeHistory.tableName, { cid });
  1411. // if (attList.length !== 0) {
  1412. // for (const att of attList) {
  1413. // await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1414. // }
  1415. // await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1416. // }
  1417. // 最后删除变更令
  1418. await this.transaction.delete(this.tableName, { cid });
  1419. // 记录删除日志
  1420. await this.ctx.service.projectLog.addProjectLog(this.transaction, projectLogConst.type.change, projectLogConst.status.delete, changeInfo.code);
  1421. await this.transaction.commit();
  1422. result = true;
  1423. } catch (e) {
  1424. await this.transaction.rollback();
  1425. result = false;
  1426. }
  1427. return result;
  1428. }
  1429. /**
  1430. * 重新审批变更令
  1431. * @param { string } cid - 查询的清单
  1432. * @return {Promise<*>} - 可用的变更令列表
  1433. */
  1434. async checkRevise(cid) {
  1435. // 初始化事务
  1436. this.transaction = await this.db.beginTransaction();
  1437. let result = false;
  1438. try {
  1439. const changeData = await this.getDataByCondition({ cid });
  1440. const pid = this.ctx.session.sessionProject.id;
  1441. // 获取所有审核人列表
  1442. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1443. // 添加到消息推送表
  1444. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, '发起重新审批');
  1445. const records = [];
  1446. auditors.forEach(auditor => {
  1447. records.push({
  1448. pid,
  1449. type: pushType.change,
  1450. uid: auditor.uid,
  1451. status: audit.flow.status.revise,
  1452. content: noticeContent,
  1453. });
  1454. });
  1455. await this.transaction.insert('zh_notice', records);
  1456. // 获取当前次数审批人列表
  1457. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  1458. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeData.cid, changeData.times, 1, 0);
  1459. let usort = lastauditInfo.usort + 1;
  1460. const newTimes = changeData.times + 1;
  1461. const insert_audit_array = [];
  1462. // 新增一个发起修订状态到审批流程中
  1463. const revise_audit = {
  1464. tid: auditList[0].tid,
  1465. cid: auditList[0].cid,
  1466. uid: auditList[0].uid,
  1467. name: auditList[0].name,
  1468. jobs: auditList[0].jobs,
  1469. company: auditList[0].company,
  1470. times: changeData.times,
  1471. usite: 0,
  1472. usort,
  1473. status: audit.flow.auditStatus.revise,
  1474. sin_time: new Date(),
  1475. };
  1476. insert_audit_array.push(revise_audit);
  1477. usort++;
  1478. // 新增新一次的审批人列表
  1479. for (const al of auditList) {
  1480. const insert_audit = {
  1481. tid: al.tid,
  1482. cid: al.cid,
  1483. uid: al.uid,
  1484. name: al.name,
  1485. jobs: al.jobs,
  1486. company: al.company,
  1487. times: newTimes,
  1488. usite: al.usite,
  1489. usort,
  1490. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  1491. };
  1492. insert_audit_array.push(insert_audit);
  1493. usort++;
  1494. }
  1495. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1496. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1497. where: { cid: changeData.cid },
  1498. });
  1499. // 生成内容保存表至zh_change_history中,用于撤销修订回退
  1500. await this.ctx.service.changeHistory.saveHistory(this.transaction, changeData, changeList);
  1501. // 申请变更金额更新为上一次审批审批变更后数量,清空audit_amount值
  1502. const updateTpList = [];
  1503. const readySettle = await this.ctx.service.settle.getReadySettle(changeData.tid);
  1504. const settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1505. const settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1506. const insertSettleList = [];
  1507. for (const cl of changeList) {
  1508. let settleInfo = null;
  1509. if (cl.gcl_id) {
  1510. settleInfo = cl.mx_id ? this._.find(settlePos, { lid: cl.gcl_id, pid: cl.mx_id }) : this._.find(settleBills, { lid: cl.gcl_id });
  1511. if (settleInfo) {
  1512. insertSettleList.push({
  1513. tid: changeData.tid,
  1514. cid: changeData.cid,
  1515. gcl_id: cl.gcl_id,
  1516. mx_id: cl.mx_id,
  1517. amount: cl.checked_amount,
  1518. });
  1519. }
  1520. }
  1521. updateTpList.push({ id: cl.id, camount: cl.spamount, audit_amount: null, samount: settleInfo ? cl.spamount : '' });
  1522. }
  1523. if (updateTpList.length > 0) {
  1524. await this.transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateTpList);
  1525. }
  1526. // let total_price = 0;
  1527. // const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1528. // for (const cl of changeList) {
  1529. // total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1530. // }
  1531. // 设置变更令修订状态
  1532. const change_update = {
  1533. w_code: changeData.w_code,
  1534. status: audit.flow.status.revise,
  1535. times: newTimes,
  1536. cin_time: Date.parse(new Date()) / 1000,
  1537. // total_price,
  1538. tp_decimal: null,
  1539. up_decimal: null,
  1540. is_revise: 1,
  1541. };
  1542. const options = {
  1543. where: {
  1544. cid: changeData.cid,
  1545. },
  1546. };
  1547. await this.transaction.update(this.tableName, change_update, options);
  1548. // 添加已结算清单到change_settle_list表中,防止删除
  1549. await this.transaction.delete(this.ctx.service.changeSettleList.tableName, { cid });
  1550. if (insertSettleList.length > 0) await this.transaction.insert(this.ctx.service.changeSettleList.tableName, insertSettleList);
  1551. await this.transaction.commit();
  1552. result = true;
  1553. } catch (error) {
  1554. await this.transaction.rollback();
  1555. result = false;
  1556. }
  1557. return result;
  1558. }
  1559. /**
  1560. * 撤销修订变更令
  1561. * @param { string } cid - 查询的清单
  1562. * @return {Promise<*>} - 可用的变更令列表
  1563. */
  1564. async cancelRevise(cid, times) {
  1565. // 初始化事务
  1566. this.transaction = await this.db.beginTransaction();
  1567. let result = false;
  1568. try {
  1569. const changeData = await this.getDataByCondition({ cid });
  1570. const pid = this.ctx.session.sessionProject.id;
  1571. // 获取所有审核人列表
  1572. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1573. // 添加到消息推送表
  1574. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, '撤销重新审批');
  1575. const records = [];
  1576. auditors.forEach(auditor => {
  1577. records.push({
  1578. pid,
  1579. type: pushType.change,
  1580. uid: auditor.uid,
  1581. status: audit.flow.status.checked,
  1582. content: noticeContent,
  1583. });
  1584. });
  1585. await this.transaction.insert('zh_notice', records);
  1586. await this.ctx.service.changeHistory.returnHistory(this.transaction, cid);
  1587. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid, times });
  1588. await this.transaction.delete(this.ctx.service.changeHistory.tableName, { cid });
  1589. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(cid, times - 1, 1, 0);
  1590. // 新增一个撤销修订状态到审批流程中
  1591. const revise_audit = {
  1592. tid: lastauditInfo.tid,
  1593. cid,
  1594. uid: this.ctx.session.sessionUser.accountId,
  1595. name: lastauditInfo.name,
  1596. jobs: lastauditInfo.jobs,
  1597. company: lastauditInfo.company,
  1598. times: times - 1,
  1599. usite: 0,
  1600. usort: lastauditInfo.usort + 1,
  1601. status: audit.flow.auditStatus.cancelRevise,
  1602. sin_time: new Date(),
  1603. };
  1604. await this.transaction.insert(this.ctx.service.changeAudit.tableName, revise_audit);
  1605. await this.transaction.commit();
  1606. result = true;
  1607. } catch (error) {
  1608. console.log(error);
  1609. await this.transaction.rollback();
  1610. result = false;
  1611. }
  1612. return result;
  1613. }
  1614. /**
  1615. * 重新审批变更令
  1616. * @param { string } cid - 查询的清单
  1617. * @return {Promise<*>} - 可用的变更令列表
  1618. */
  1619. async checkAgain(cid) {
  1620. // 初始化事务
  1621. const time = new Date();
  1622. this.transaction = await this.db.beginTransaction();
  1623. let result = false;
  1624. try {
  1625. const changeInfo = await this.getDataByCondition({ cid });
  1626. // 获取终审
  1627. const zsAudit = await this.ctx.service.changeAudit.getAuditorByStatus(cid, changeInfo.times, audit.flow.auditStatus.checked);
  1628. const lastAudit = (
  1629. await this.ctx.service.changeAudit.getAllDataByCondition({
  1630. where: { cid },
  1631. orders: [['usort', 'desc']],
  1632. limit: 1,
  1633. offset: 0,
  1634. })
  1635. )[0];
  1636. let usort = lastAudit.usort + 1;
  1637. const insert_audit_array = [];
  1638. // 新增2个审批状态到审批列表中
  1639. insert_audit_array.push({
  1640. tid: changeInfo.tid,
  1641. cid: changeInfo.cid,
  1642. uid: zsAudit.uid,
  1643. name: zsAudit.name,
  1644. jobs: zsAudit.jobs,
  1645. company: zsAudit.company,
  1646. times: zsAudit.times,
  1647. usite: zsAudit.usite,
  1648. usort,
  1649. sin_time: time,
  1650. status: audit.flow.auditStatus.checkAgain,
  1651. sdesc: '',
  1652. });
  1653. usort++;
  1654. // 新增2个审批人到审批列表中
  1655. insert_audit_array.push({
  1656. tid: changeInfo.tid,
  1657. cid: changeInfo.cid,
  1658. uid: zsAudit.uid,
  1659. name: zsAudit.name,
  1660. jobs: zsAudit.jobs,
  1661. company: zsAudit.company,
  1662. times: zsAudit.times,
  1663. usite: zsAudit.usite,
  1664. usort,
  1665. status: audit.flow.auditStatus.checking,
  1666. sin_time: time,
  1667. });
  1668. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1669. // 审批列表数据也要回退
  1670. let total_price = 0;
  1671. const tp_decimal = changeInfo.tp_decimal ? changeInfo.tp_decimal : this.ctx.tender.info.decimal.tp;
  1672. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1673. where: { cid: changeInfo.cid },
  1674. });
  1675. const updateChangeList = [];
  1676. const readySettle = await this.ctx.service.settle.getReadySettle(changeInfo.tid);
  1677. const settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1678. const settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1679. const insertSettleList = [];
  1680. for (const cl of changeList) {
  1681. if (cl.gcl_id) {
  1682. const settleInfo = cl.mx_id ? this._.find(settlePos, { lid: cl.gcl_id, pid: cl.mx_id }) : this._.find(settleBills, { lid: cl.gcl_id });
  1683. if (settleInfo) {
  1684. insertSettleList.push({
  1685. tid: changeInfo.tid,
  1686. cid: changeInfo.cid,
  1687. gcl_id: cl.gcl_id,
  1688. mx_id: cl.mx_id,
  1689. amount: cl.checked_amount,
  1690. });
  1691. }
  1692. }
  1693. const audit_amount = cl.audit_amount.split(',');
  1694. const last_amount = audit_amount[audit_amount.length - 1] ? audit_amount[audit_amount.length - 1] : 0;
  1695. audit_amount.splice(-1, 1);
  1696. const list_update = {
  1697. id: cl.id,
  1698. audit_amount: audit_amount.join(','),
  1699. samount: '',
  1700. spamount: parseFloat(last_amount),
  1701. };
  1702. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1703. updateChangeList.push(list_update);
  1704. }
  1705. if (updateChangeList.length > 0) await this.transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateChangeList);
  1706. // 设置变更令审批中
  1707. const change_update = {
  1708. p_code: null,
  1709. status: audit.flow.status.checking,
  1710. cin_time: Date.parse(time) / 1000,
  1711. sin_time: null,
  1712. total_price,
  1713. };
  1714. const options = {
  1715. where: {
  1716. cid: changeInfo.cid,
  1717. },
  1718. };
  1719. await this.transaction.update(this.tableName, change_update, options);
  1720. // 添加已结算清单到change_settle_list表中,防止删除
  1721. await this.transaction.delete(this.ctx.service.changeSettleList.tableName, { cid });
  1722. if (insertSettleList.length > 0) await this.transaction.insert(this.ctx.service.changeSettleList.tableName, insertSettleList);
  1723. await this.transaction.commit();
  1724. result = true;
  1725. // const sms = new SMS(this.ctx);
  1726. // const code = await sms.contentChange(changeInfo.code);
  1727. // const shenpiUrl = await this.ctx.helper.urlToShort(
  1728. // this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  1729. // );
  1730. // await this.ctx.helper.sendAliSms(zsAudit.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1731. // biangeng: code,
  1732. // code: shenpiUrl,
  1733. // });
  1734. //
  1735. // // 微信模板通知
  1736. // const wechatData = {
  1737. // wap_url: shenpiUrl,
  1738. // status: wxConst.status.check,
  1739. // tips: wxConst.tips.check,
  1740. // code: this.ctx.session.sessionProject.code,
  1741. // c_name: changeInfo.name,
  1742. // };
  1743. // await this.ctx.helper.sendWechat(zsAudit.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1744. } catch (error) {
  1745. console.log(error);
  1746. await this.transaction.rollback();
  1747. result = false;
  1748. }
  1749. return result;
  1750. }
  1751. /**
  1752. * 判断是否有重名的变更令
  1753. * @param cid
  1754. * @param code
  1755. * @param tid
  1756. * @return {Promise<void>}
  1757. */
  1758. async isRepeat(cid, code, tid) {
  1759. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?)) AND `cid` != ? AND `tid` = ?';
  1760. const sqlParam = [this.tableName, code, audit.flow.status.checked, code, audit.flow.status.checked, cid, tid];
  1761. const result = await this.db.queryOne(sql, sqlParam);
  1762. return result.count !== 0;
  1763. }
  1764. async getAllCheckedChanges(tid) {
  1765. return await this.getAllDataByCondition({
  1766. where: { tid, status: audit.flow.status.checked },
  1767. orders: [['in_time', 'desc']],
  1768. });
  1769. }
  1770. /**
  1771. * 用于添加推送所需的content内容
  1772. * @param {Number} pid 项目id
  1773. * @param {Number} tid 台账id
  1774. * @param {Number} cid 变更id
  1775. * @param {Number} uid 审核人id
  1776. */
  1777. async getNoticeContent(pid, tid, cid, uid, opinion = '') {
  1778. const noticeSql =
  1779. 'SELECT * FROM (SELECT ' +
  1780. ' t.`id` As `tid`, t.`name`, c.`cid`, c.`code` As `c_code`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1781. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1782. ' LEFT JOIN ?? As c ON c.`cid` = ?' +
  1783. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1784. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1785. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.change.tableName, cid, this.ctx.service.projectAccount.tableName, uid, pid];
  1786. const content = await this.db.query(noticeSql, noticeSqlParam);
  1787. if (content.length) {
  1788. content[0].opinion = opinion;
  1789. }
  1790. return content.length ? JSON.stringify(content[0]) : '';
  1791. }
  1792. /**
  1793. * 获取当前标段其他变更令
  1794. * @param {Number} tid - 标段id
  1795. * @param {Number} cid - 当前变更令
  1796. */
  1797. async getOthersChange(tid, cid) {
  1798. const sql = 'SELECT * FROM ?? WHERE tid = ? AND cid != ? ORDER By `in_time` desc ';
  1799. const sqlParam = [this.tableName, tid, cid];
  1800. const data = await this.db.query(sql, sqlParam);
  1801. const changeClassObj = {};
  1802. for (const c in changeConst.class) {
  1803. if (changeConst.class.hasOwnProperty(c)) {
  1804. const item = changeConst.class[c];
  1805. changeClassObj[item.value] = item.name;
  1806. }
  1807. }
  1808. for (let i = 0; i < data.length; i++) {
  1809. data[i].class = changeClassObj[data[i].class];
  1810. }
  1811. return data;
  1812. }
  1813. /**
  1814. * 拷贝变更令至当前变更令
  1815. * @param {String} cid - 当前变更令
  1816. * @param {String} copy_cid - 要拷贝的变更令
  1817. */
  1818. async handleCopyChange(cid, copy_cid) {
  1819. // const change = await this.getDataByCondition({ cid });
  1820. const copyChange = await this.getDataByCondition({ cid: copy_cid });
  1821. return await this.update({ peg: copyChange.peg, org_name: copyChange.org_name, org_code: copyChange.org_code, new_name: copyChange.new_name, content: copyChange.content, basis: copyChange.basis, expr: copyChange.expr, memo: copyChange.memo, type: copyChange.type,
  1822. class: copyChange.class, quality: copyChange.quality, company: copyChange.company, charge: copyChange.charge, new_code: copyChange.new_code }, {
  1823. cid,
  1824. });
  1825. }
  1826. async updateDecimalAndTp() {
  1827. // 判断是否可修改
  1828. // 判断t_type是否为费用
  1829. const transaction = await this.db.beginTransaction();
  1830. try {
  1831. await this.ctx.service.changeAuditList.calcCamountSum(transaction, true);
  1832. await transaction.commit();
  1833. return true;
  1834. } catch (err) {
  1835. await transaction.rollback();
  1836. throw err;
  1837. }
  1838. }
  1839. async updateChangeSelect(data) {
  1840. const conn = await this.db.beginTransaction();
  1841. try {
  1842. for (const d of data) {
  1843. await conn.update(this.tableName, { selected: d.selected }, { where: { cid: d.cid } });
  1844. }
  1845. await conn.commit();
  1846. } catch (err) {
  1847. await conn.rollback();
  1848. throw err;
  1849. }
  1850. }
  1851. async getAllChangeHasMinus(tenderId) {
  1852. const sql = `SELECT * FROM ${this.tableName} WHERE tid = ? AND negative_tp < 0 ORDER BY code asc`;
  1853. return this.db.query(sql, [tenderId]);
  1854. }
  1855. async getListByBudgetInfo(tenders) {
  1856. if (tenders) {
  1857. const sql = 'SELECT * FROM ?? WHERE `status` = ? AND `tid` in (' + this.ctx.helper.getInArrStrSqlFilter(tenders.split(',')) + ') ORDER BY `total_price` DESC LIMIT 0, 10';
  1858. const params = [this.tableName, audit.flow.status.checked];
  1859. return await this.db.query(sql, params);
  1860. }
  1861. return [];
  1862. }
  1863. async getTotalTpByBudgetInfo(tenders) {
  1864. if (tenders) {
  1865. const sql = 'SELECT SUM(`total_price`) AS tp FROM ?? WHERE `status` = ? AND `tid` in (' + this.ctx.helper.getInArrStrSqlFilter(tenders.split(',')) + ')';
  1866. const sqlParam = [this.tableName, audit.flow.status.checked];
  1867. const result = await this.db.queryOne(sql, sqlParam);
  1868. return result && result.tp ? result.tp : 0;
  1869. }
  1870. return 0;
  1871. }
  1872. async doCheckChangeCanCancel(change) {
  1873. // 获取当前审批人的上一个审批人,判断是否是当前登录人,并赋予撤回功能,(当审批人存在有审批过时,上一人不允许再撤回)
  1874. const status = audit.flow.status;
  1875. const auditStatus = audit.flow.auditStatus;
  1876. const accountId = this.ctx.session.sessionUser.accountId;
  1877. const auditors = await this.ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  1878. change.cancancel = 0;
  1879. if (change.status !== status.checked && change.status !== status.uncheck && change.status !== status.revise) {
  1880. if (change.status !== status.back) {
  1881. // 找出当前操作人上一个审批人,包括审批完成的和退回上一个审批人的,同时当前操作人为第一人时,就是则为原报
  1882. const onAuditor = this._.find(auditors, function(item) {
  1883. return item.uid === change.curAuditor.uid && item.status === auditStatus.checking;
  1884. });
  1885. const preAudit = onAuditor.usort >= 1 ? this._.find(auditors, { usort: onAuditor.usort - 1 }) : false;
  1886. const preAid = preAudit ? (preAudit.status !== auditStatus.checkAgain ? preAudit.uid : false) : change.uid;
  1887. // console.log(onAuditor, preAid);
  1888. if (!preAudit) {
  1889. return;// 应对于管理员修改审批流把退回人删除,不存在上一审批人,不可撤回
  1890. } else if (onAuditor.uid === preAid && preAudit.status === auditStatus.checkCancel) {
  1891. return;// 不可以多次撤回
  1892. } else if (preAid === accountId && (preAid !== change.uid || (preAid === change.uid && preAudit.usite !== 0))) {
  1893. if (preAudit.status === auditStatus.checked) {
  1894. change.cancancel = 2;// 审批人撤回审批通过
  1895. } else if (preAudit.status === auditStatus.backnew) {
  1896. change.cancancel = 3;// 审批人撤回审批退回上一人
  1897. }
  1898. change.preAudit = preAudit;
  1899. } else if (preAid === accountId && preAid === change.uid && preAudit.usite === 0) {
  1900. change.cancancel = 1;// 原报撤回
  1901. }
  1902. } else {
  1903. const lastAuditors = await this.service.changeAudit.getAuditors(change.cid, change.times - 1);
  1904. const onAuditor = this._.findLast(lastAuditors, { status: auditStatus.back });
  1905. if (onAuditor && onAuditor.uid === accountId) {
  1906. change.cancancel = 4;// 审批人撤回退回原报
  1907. }
  1908. }
  1909. }
  1910. }
  1911. async checkSettleUpdate(tid, settleInfo = null) {
  1912. const readySettle = settleInfo ? settleInfo : await this.ctx.service.settle.getReadySettle(tid);
  1913. if (readySettle && readySettle.settle_order !== this.ctx.tender.data.settle_order) {
  1914. // 更新tender里的settle_order值且更新变更数据
  1915. const transaction = await this.db.beginTransaction();
  1916. try {
  1917. const changeLedgerData = await this.ctx.service.changeLedger.getData(tid);
  1918. const changePosData = await this.ctx.service.changePos.getPosData({ tid });
  1919. // const changeSettleData = await this.ctx.service.changeSettleList.getAllDataByCondition({ where: { tid } });
  1920. if (changeLedgerData.length > 0 || changePosData.length > 0) {
  1921. const settleBills = await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } });
  1922. const removeLedgerList = [];
  1923. const settleStatus = this.ctx.service.settle.settleStatus;
  1924. for (const l of changeLedgerData) {
  1925. const parent = this._.find(settleBills, { tree_id: l.ledger_pid });
  1926. if (parent && parent.settle_status === settleStatus.finish) {
  1927. removeLedgerList.push(l);
  1928. }
  1929. }
  1930. // 移除计量单元
  1931. const removePosList = [];
  1932. for (const p of changePosData) {
  1933. const parent = this._.find(settleBills, { lid: p.lid });
  1934. if (parent && parent.settle_status === settleStatus.finish) {
  1935. removePosList.push(p);
  1936. }
  1937. }
  1938. // // 移除结算清单
  1939. // const removeSettleIdList = [];
  1940. // const settlePos = await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } });
  1941. // for (const s of changeSettleData) {
  1942. // const info = s.mx_id ? this._.find(settlePos, { lid: s.gcl_id, pid: s.mx_id }) : this._.find(settleBills, { lid: s.gcl_id });
  1943. // if (!info || info.settle_status !== settleStatus.finish) {
  1944. // removeSettleIdList.push(s.id);
  1945. // }
  1946. // }
  1947. if (removeLedgerList.length > 0) {
  1948. await this.ctx.service.changeLedger.deleteBySettle(transaction, tid, removeLedgerList);
  1949. }
  1950. if (removePosList.length > 0) {
  1951. await this.ctx.service.changePos.deleteBySettle(transaction, tid, removePosList);
  1952. }
  1953. // if (removeSettleIdList.length > 0) {
  1954. // await transaction.delete(this.ctx.service.changeSettleList.tableName, { id: removeSettleIdList });
  1955. // }
  1956. }
  1957. await transaction.update(this.ctx.service.tender.tableName, { id: tid, settle_order: readySettle.settle_order });
  1958. await transaction.commit();
  1959. return true;
  1960. } catch (err) {
  1961. console.log(err);
  1962. await transaction.rollback();
  1963. throw err;
  1964. }
  1965. }
  1966. }
  1967. }
  1968. return Change;
  1969. };