change.js 85 KB

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