change.js 111 KB

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