change.js 85 KB

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