change.js 121 KB

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