change.js 121 KB

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