safe_controller.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. 'use strict';
  2. /**
  3. * 标段管理控制器
  4. *
  5. * @author Mai
  6. * @date 2025/7/17
  7. * @version
  8. */
  9. const auditConst = require('../const/audit');
  10. const safeInspectionConst = require('../const/safe_inspection');
  11. const auditType = require('../const/audit').auditType;
  12. const shenpiConst = require('../const/shenpi');
  13. const codeRuleConst = require('../const/code_rule');
  14. const contractConst = require('../const/contract');
  15. const moment = require('moment');
  16. const sendToWormhole = require('stream-wormhole');
  17. const fs = require('fs');
  18. const path = require('path');
  19. const PermissionCheck = require('../const/account_permission').PermissionCheck;
  20. module.exports = app => {
  21. class SafeController extends app.BaseController {
  22. constructor(ctx) {
  23. super(ctx);
  24. ctx.showProject = true;
  25. // ctx.showTitle = true;
  26. }
  27. loadMenu(ctx) {
  28. super.loadMenu(ctx);
  29. // 虚拟menu,以保证标题显示正确
  30. ctx.menu = {
  31. name: '安全管理',
  32. display: false,
  33. caption: '安全管理',
  34. controller: 'safe',
  35. };
  36. }
  37. async tender(ctx) {
  38. try {
  39. if (!ctx.subProject.page_show.safePayment) throw '该功能已关闭';
  40. const renderData = {
  41. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  42. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
  43. };
  44. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  45. renderData.accountList = accountList;
  46. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  47. const accountGroupList = unitList.map(item => {
  48. const groupList = accountList.filter(item1 => item1.company === item.name);
  49. return { groupName: item.name, groupList };
  50. }).filter(x => { return x.groupList.length > 0; });
  51. // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  52. // renderData.accountGroup = unitList.map(item => {
  53. // const groupList = accountList.filter(item1 => item1.company === item.name);
  54. // return { groupName: item.name, groupList };
  55. // });
  56. renderData.accountGroup = accountGroupList;
  57. renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  58. renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_payment', ctx.session.sessionUser.is_admin ? 'all' : '');
  59. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
  60. renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
  61. renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_payment');
  62. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_payment');
  63. await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
  64. } catch (err) {
  65. ctx.log(err);
  66. ctx.postError(err, '无法查看安全计量数据');
  67. ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
  68. }
  69. }
  70. async stage(ctx) {
  71. try {
  72. if (!ctx.subProject.page_show.safePayment) throw '该功能已关闭';
  73. const renderData = {
  74. auditType: auditConst.auditType,
  75. auditConst: auditConst.common,
  76. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.stage),
  77. };
  78. renderData.stages = await this.ctx.service.safeStage.getAllStages(ctx.tender.id, 'DESC');
  79. for (const s of renderData.stages) {
  80. if (s.audit_status !== auditConst.common.status.checked) await this.ctx.service.safeStage.loadUser(s);
  81. s.can_del = (s.create_user_id === ctx.session.sessionUser.accountId || ctx.session.sessionUser.is_admin)
  82. && (s.audit_status === auditConst.common.status.uncheck || s.audit_status === auditConst.common.status.checkNo);
  83. }
  84. await this.layout('safe_calc/stage.ejs', renderData, 'safe_calc/stage_modal.ejs');
  85. } catch (err) {
  86. ctx.log(err);
  87. ctx.postError(err, '查看安全计量数据错误');
  88. ctx.redirect(`/sp/${ctx.subProject.id}/safe`);
  89. }
  90. }
  91. async addStage(ctx) {
  92. try {
  93. if (!ctx.permission.safe_payment.add) throw '您无权创建计量期';
  94. const stage_date = ctx.request.body.stage_date;
  95. if (!stage_date) throw '请选择日期';
  96. const stage_code = ctx.request.body.stage_code;
  97. const stages = await ctx.service.safeStage.getAllStages(ctx.tender.id, 'DESC');
  98. const unCompleteCount = stages.filter(s => { return s.status !== auditConst.common.status.checked; }).length;
  99. if (unCompleteCount.length > 0) throw '最新一起未审批通过,请审批通过后再新增';
  100. const newStage = await ctx.service.safeStage.add(ctx.tender.id, stage_code, stage_date);
  101. const preStgId = stages.length > 0 ? stages[0].id : ''; // 这里排序是DESC,最前的那个是最后的期
  102. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(ctx.tender.id, '-150', newStage.id, preStgId);
  103. if (!newStage) throw '新增期失败';
  104. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${newStage.stage_order}/bills`);
  105. } catch (err) {
  106. ctx.log(err);
  107. ctx.postError(err, '新增期失败');
  108. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  109. }
  110. }
  111. async delStage(ctx) {
  112. try {
  113. // if (!ctx.session.sessionUser.is_admin && ctx.request.body.confirm !== '确认删除本期') throw '请输入文本确认删除本期';
  114. const stage_id = ctx.request.body.stage_id;
  115. const stage = await ctx.service.safeStage.getDataById(stage_id);
  116. if (!stage) throw '删除的期不存在,请刷新页面';
  117. if (!ctx.session.sessionUser.is_admin && stage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权删除本期';
  118. // 获取最新的期数
  119. const stageCount = await ctx.service.safeStage.count({ tid: ctx.tender.id });
  120. if (stage.stage_order !== stageCount) throw '非最新一期,不可删除';
  121. await ctx.service.safeStage.delete(stage_id);
  122. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  123. } catch (err) {
  124. ctx.log(err);
  125. ctx.postError(err, '删除期失败');
  126. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  127. }
  128. }
  129. async saveStage(ctx) {
  130. try {
  131. const stage_id = ctx.request.body.stage_id;
  132. const data = {
  133. stage_date: ctx.request.body.stage_date,
  134. stage_code: ctx.request.body.stage_code,
  135. };
  136. const stage = await ctx.service.safeStage.getStage(stage_id);
  137. if (!stage) throw '删除的期不存在,请刷新页面';
  138. if (!ctx.session.sessionUser.is_admin && stage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权修改该数据';
  139. await this.ctx.service.safeStage.save(stage, data);
  140. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  141. } catch (err) {
  142. ctx.log(err);
  143. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  144. }
  145. }
  146. async _getStageAuditViewData(ctx) {
  147. await this.ctx.service.safeStage.loadAuditViewData(ctx.safeStage);
  148. }
  149. async safeBills(ctx) {
  150. try {
  151. await this._getStageAuditViewData(ctx);
  152. // 获取附件列表
  153. const attList = await ctx.service.paymentDetailAtt.getPaymentDetailAttachment(ctx.safeStage.id, 'desc');
  154. const stdBills = await ctx.service.stdGclList.getSafeGcl();
  155. // 流程审批人相关数据
  156. // const accountList = await ctx.service.projectAccount.getAllSubProjectAccountByPermission(ctx.subProject, 'payment_permission');
  157. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  158. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  159. const accountGroup = unitList.map(item => {
  160. const groupList = accountList.filter(item1 => item1.company === item.name);
  161. return { groupName: item.name, groupList };
  162. }).filter(x => { return x.groupList.length > 0; });
  163. // 是否已验证手机短信
  164. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  165. const renderData = {
  166. auditConst: auditConst.common,
  167. accountList,
  168. accountGroup,
  169. shenpiConst,
  170. auditType: auditConst.auditType,
  171. authMobile: pa.auth_mobile,
  172. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.bills),
  173. stdBills,
  174. attList,
  175. };
  176. await this.layout('safe_calc/index.ejs', renderData, 'safe_calc/modal.ejs');
  177. } catch (err) {
  178. ctx.log(err);
  179. ctx.postError(err, '读取安全生产费错误');
  180. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  181. }
  182. }
  183. async safeCompare(ctx) {
  184. try {
  185. await this._getStageAuditViewData(ctx);
  186. // 流程审批人相关数据
  187. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  188. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  189. const accountGroup = unitList.map(item => {
  190. const groupList = accountList.filter(item1 => item1.company === item.name);
  191. return { groupName: item.name, groupList };
  192. }).filter(x => { return x.groupList.length > 0; });
  193. // 是否已验证手机短信
  194. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  195. const renderData = {
  196. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.compare),
  197. auditConst: auditConst.common,
  198. accountList,
  199. accountGroup,
  200. shenpiConst,
  201. auditType: auditConst.auditType,
  202. authMobile: pa.auth_mobile,
  203. };
  204. await this.layout('safe_calc/compare.ejs', renderData, 'safe_calc/audit_modal.ejs');
  205. } catch (err) {
  206. ctx.log(err);
  207. ctx.postError(err, '读取安全生产费错误');
  208. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
  209. }
  210. }
  211. async safeLoad(ctx) {
  212. try {
  213. const data = JSON.parse(ctx.request.body.data);
  214. const filter = data.filter.split(';');
  215. const responseData = { err: 0, msg: '', data: {}, hpack: [] };
  216. for (const f of filter) {
  217. switch (f) {
  218. case 'bills':
  219. responseData.data.bills = ctx.safeStage.readOnly
  220. ? await ctx.service.safeStageBills.getReadData(ctx.safeStage)
  221. : await ctx.service.safeStageBills.getEditData(ctx.safeStage);
  222. break;
  223. case 'billsCompare':
  224. responseData.data[f] = await ctx.service.safeStageBills.getCompareData(ctx.safeStage);
  225. break;
  226. case 'auditFlow':
  227. responseData.data[f] = await ctx.service.safeStageAudit.getViewFlow(ctx.safeStage);
  228. break;
  229. case 'att':
  230. responseData.data[f] = await ctx.service.safeStageFile.getData(ctx.safeStage.id, 'bills', 'DESC');
  231. break;
  232. default:
  233. responseData.data[f] = [];
  234. break;
  235. }
  236. }
  237. ctx.body = responseData;
  238. } catch (err) {
  239. this.log(err);
  240. ctx.body = { err: 1, msg: err.toString(), data: null };
  241. }
  242. }
  243. async _billsBase(stage, type, data) {
  244. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  245. if (type !== 'add') {
  246. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  247. }
  248. switch (type) {
  249. case 'add':
  250. return await this.ctx.service.safeStageBills.addSafeBillsNode(stage, data.id, data.count);
  251. case 'delete':
  252. return await this.ctx.service.safeStageBills.delete(stage.id, data.id, data.count);
  253. case 'up-move':
  254. return await this.ctx.service.safeStageBills.upMoveNode(stage.id, data.id, data.count);
  255. case 'down-move':
  256. return await this.ctx.service.safeStageBills.downMoveNode(stage.id, data.id, data.count);
  257. case 'up-level':
  258. return await this.ctx.service.safeStageBills.upLevelNode(stage.id, data.id, data.count);
  259. case 'down-level':
  260. return await this.ctx.service.safeStageBills.downLevelNode(stage.id, data.id, data.count);
  261. }
  262. }
  263. async safeUpdate(ctx) {
  264. try {
  265. const data = JSON.parse(ctx.request.body.data);
  266. if (!data.postType || !data.postData) throw '数据错误';
  267. const responseData = { err: 0, msg: '', data: {} };
  268. switch (data.postType) {
  269. case 'add':
  270. case 'delete':
  271. case 'up-move':
  272. case 'down-move':
  273. case 'up-level':
  274. case 'down-level':
  275. responseData.data = await this._billsBase(ctx.safeStage, data.postType, data.postData);
  276. break;
  277. case 'update':
  278. responseData.data = await this.ctx.service.safeStageBills.updateCalc(ctx.safeStage, data.postData);
  279. break;
  280. case 'add-std':
  281. responseData.data = await this.ctx.service.safeStageBills.addStdNodeWithParent(ctx.safeStage, data.postData.id, data.postData.stdData);
  282. break;
  283. default:
  284. throw '未知操作';
  285. }
  286. ctx.body = responseData;
  287. } catch (err) {
  288. this.log(err);
  289. ctx.body = this.ajaxErrorBody(err, '数据错误');
  290. }
  291. }
  292. async safeDecimal(ctx) {
  293. try {
  294. const data = JSON.parse(ctx.request.body.data);
  295. const result = await this.ctx.service.safeStageBills.setDecimal(data.decimal);
  296. ctx.body = { err: 0, msg: '', data: result };
  297. } catch (err) {
  298. this.log(err);
  299. ctx.body = this.ajaxErrorBody(err, '设置小数位数错误');
  300. }
  301. }
  302. async uploadStageFile(ctx) {
  303. let stream;
  304. try {
  305. const parts = ctx.multipart({ autoFields: true });
  306. let index = 0;
  307. const create_time = Date.parse(new Date()) / 1000;
  308. let stream = await parts();
  309. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  310. const rela_type = parts.fields.type;
  311. const rela_id = parts.field.rela_id;
  312. const uploadfiles = [];
  313. while (stream !== undefined) {
  314. if (!stream.filename) throw '未发现上传文件!';
  315. const fileInfo = path.parse(stream.filename);
  316. const filepath = `app/public/upload/${ctx.safeStage.tid}/safeStage/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  317. // 保存文件
  318. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  319. await sendToWormhole(stream);
  320. // 插入到stage_pay对应的附件列表中
  321. uploadfiles.push({
  322. rela_id,
  323. filename: fileInfo.name,
  324. fileext: fileInfo.ext,
  325. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  326. filepath,
  327. });
  328. ++index;
  329. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  330. stream = await parts();
  331. } else {
  332. stream = undefined;
  333. }
  334. }
  335. const result = await ctx.service.safeStageFile.addFiles(ctx.safeStage, 'bills', uploadfiles, user);
  336. ctx.body = { err: 0, msg: '', data: result };
  337. } catch (error) {
  338. ctx.log(error);
  339. // 失败需要消耗掉stream 以防卡死
  340. if (stream) await sendToWormhole(stream);
  341. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  342. }
  343. }
  344. async deleteStageFile(ctx) {
  345. try {
  346. const data = JSON.parse(ctx.request.body.data);
  347. if (!data && !data.id) throw '缺少参数';
  348. const result = await ctx.service.safeStageFile.delFiles(data.id);
  349. ctx.body = { err: 0, msg: '', data: result };
  350. } catch (error) {
  351. ctx.log(error);
  352. ctx.ajaxErrorBody(error, '删除附件失败');
  353. }
  354. }
  355. /**
  356. * 添加审批人
  357. * @param ctx
  358. * @return {Promise<void>}
  359. */
  360. async addStageAudit(ctx) {
  361. try {
  362. const data = JSON.parse(ctx.request.body.data);
  363. const id = this.app._.toInteger(data.auditorId);
  364. if (isNaN(id) || id <= 0) throw '参数错误';
  365. // 检查权限等
  366. if (ctx.safeStage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权添加审核人';
  367. if (ctx.safeStage.audit_status !== auditConst.common.status.uncheck && ctx.safeStage.audit_status !== auditConst.common.status.checkNo) {
  368. throw '当前不允许添加审核人';
  369. }
  370. // 检查审核人是否已存在
  371. const exist = await ctx.service.safeStageAudit.getDataByCondition({ stage_id: ctx.safeStage.id, audit_times: ctx.safeStage.audit_times, audit_id: id });
  372. if (exist) throw '该审核人已存在,请勿重复添加';
  373. const auditorInfo = await this.ctx.service.projectAccount.getDataById(id);
  374. if (!auditorInfo) throw '添加的审批人不存在';
  375. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.safe_payment, sp_status: shenpiConst.sp_status.gdzs });
  376. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.safe_payment === shenpiConst.sp_status.gdzs ? 1 : 0;
  377. const result = await ctx.service.safeStageAudit.addAuditor(ctx.safeStage.id, auditorInfo, ctx.safeStage.audit_times, is_gdzs);
  378. if (!result) throw '添加审核人失败';
  379. const auditors = await ctx.service.safeStageAudit.getAuditorGroup(ctx.safeStage.id, ctx.safeStage.audit_times);
  380. ctx.body = { err: 0, msg: '', data: auditors };
  381. } catch (err) {
  382. ctx.log(err);
  383. ctx.body = { err: 1, msg: err.toString(), data: null };
  384. }
  385. }
  386. /**
  387. * 移除审批人
  388. * @param ctx
  389. * @return {Promise<void>}
  390. */
  391. async deleteStageAudit(ctx) {
  392. try {
  393. const data = JSON.parse(ctx.request.body.data);
  394. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  395. if (isNaN(id) || id <= 0) throw '参数错误';
  396. const result = await ctx.service.safeStageAudit.deleteAuditor(ctx.safeStage.id, id, ctx.safeStage.audit_times);
  397. if (!result) throw '移除审核人失败';
  398. const auditors = await ctx.service.safeStageAudit.getAuditors(ctx.safeStage.id, ctx.safeStage.audit_times);
  399. ctx.body = { err: 0, msg: '', data: auditors };
  400. } catch (err) {
  401. ctx.log(err);
  402. ctx.body = { err: 1, msg: err.toString(), data: null };
  403. }
  404. }
  405. async stageAuditStart(ctx) {
  406. try {
  407. if (ctx.safeStage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权上报该期数据';
  408. if (ctx.safeStage.revising) throw '台账修订中,不可上报';
  409. if (ctx.safeStage.audit_status !== auditConst.common.status.uncheck && ctx.safeStage.audit_status !== auditConst.common.status.checkNo) throw '该期数据当前无法上报';
  410. await ctx.service.safeStageAudit.start(ctx.safeStage);
  411. ctx.redirect(ctx.request.header.referer);
  412. } catch (err) {
  413. ctx.log(err);
  414. ctx.postError(err, '上报失败');
  415. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${ctx.safeStage.stage_order}/bills`);
  416. }
  417. }
  418. async stageAuditCheck(ctx) {
  419. try {
  420. if (!ctx.safeStage || (ctx.safeStage.audit_status !== auditConst.common.status.checking && ctx.safeStage.audit_status !== auditConst.common.status.checkNoPre)) {
  421. throw '当前期数据有误';
  422. }
  423. if (ctx.safeStage.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) < 0) {
  424. throw '您无权进行该操作';
  425. }
  426. if (ctx.safeStage.revising) throw '台账修订中,不可审批';
  427. const checkType = parseInt(ctx.request.body.checkType);
  428. const opinion = ctx.request.body.opinion.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
  429. await ctx.service.safeStageAudit.check(ctx.safeStage, checkType, opinion);
  430. } catch (err) {
  431. ctx.log(err);
  432. ctx.postError(err, '审批失败');
  433. }
  434. ctx.redirect(ctx.request.header.referer);
  435. }
  436. async stageAuditCheckAgain(ctx) {
  437. try {
  438. if (!ctx.safeStage.isLatest) throw '非最新一期,不可重新审批';
  439. if (ctx.safeStage.audit_status !== auditConst.common.status.checked) throw '未审批完成,不可重新审批';
  440. if (ctx.safeStage.revising) throw '台账修订中,不可重审';
  441. if (ctx.session.sessionUser.loginStatus === 0) {
  442. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  443. if (!user.auth_mobile) throw '未绑定手机号';
  444. const code = ctx.request.body.code;
  445. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  446. const cacheCode = await app.redis.get(cacheKey);
  447. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  448. throw '验证码不正确!';
  449. }
  450. }
  451. const adminCheckAgain = ctx.request.body.confirm === '确认设置终审审批' && ctx.session.sessionUser.is_admin;
  452. if (ctx.safeStage.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) < 0 && !adminCheckAgain) throw '您无权重新审批';
  453. await ctx.service.safeStageAudit.checkAgain(ctx.safeStage, adminCheckAgain);
  454. } catch (err) {
  455. ctx.log(err);
  456. ctx.postError(err, '重新审批失败');
  457. }
  458. ctx.redirect(ctx.request.header.referer);
  459. }
  460. async stageAuditCheckCancel(ctx) {
  461. try {
  462. if (ctx.safeStage.revising) throw '台账修订中,不可撤回';
  463. if (!ctx.safeStage.cancancel) throw '您无权进行该操作';
  464. await ctx.service.safeStageAudit.checkCancel(ctx.safeStage);
  465. } catch (err) {
  466. ctx.log(err);
  467. ctx.postError(err, '撤回失败');
  468. }
  469. ctx.redirect(ctx.request.header.referer);
  470. }
  471. /**
  472. * 期审批流程(POST)
  473. * @param ctx
  474. * @return {Promise<void>}
  475. */
  476. async loadAuditors(ctx) {
  477. try {
  478. const order = JSON.parse(ctx.request.body.data).order;
  479. const tenderId = ctx.params.tid;
  480. const stage = await ctx.service.safeStage.getStageByOrder(tenderId, order);
  481. await ctx.service.safeStage.loadUser(stage);
  482. await ctx.service.safeStage.loadAuditViewData(stage);
  483. ctx.body = { err: 0, msg: '', data: stage };
  484. } catch (error) {
  485. ctx.log(error);
  486. ctx.body = { err: 1, msg: error.toString(), data: null };
  487. }
  488. }
  489. async loadPaySafeData(ctx) {
  490. try {
  491. // 先获取你创建的标段及参与的标段
  492. const tenderList = await ctx.service.paymentTender.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  493. // 获取你创建的目录及对应目录下的所有目录
  494. const folderList = await ctx.service.paymentFolder.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  495. for (const tender of tenderList) {
  496. tender.details = await ctx.service.paymentDetail.getAllDataByCondition({ where: { tender_id: tender.id, type: 1 } });
  497. }
  498. ctx.body = { err: 0, msg: '', data: { tenderList, folderList } };
  499. } catch (err) {
  500. ctx.log(error);
  501. ctx.ajaxErrorBody(err, '获取安全生产费旧数据失败');
  502. }
  503. }
  504. async copyPaySafeData(ctx) {
  505. try {
  506. const data = JSON.parse(ctx.request.body.data);
  507. if (!data.tid) throw '参数错误';
  508. await ctx.service.safeStage.copyPaySafeData(data.tid);
  509. ctx.body = { err: 0, msg: '迁移旧数据成功', data: null };
  510. } catch (err) {
  511. ctx.log(err);
  512. ctx.ajaxErrorBody(err, '迁移旧数据失败');
  513. }
  514. }
  515. async inspectionTender(ctx) {
  516. try {
  517. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  518. const renderData = {
  519. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  520. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
  521. };
  522. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  523. renderData.accountList = accountList;
  524. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  525. const accountGroupList = unitList.map(item => {
  526. const groupList = accountList.filter(item1 => item1.company === item.name);
  527. return { groupName: item.name, groupList };
  528. }).filter(x => { return x.groupList.length > 0; });
  529. // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  530. // renderData.accountGroup = unitList.map(item => {
  531. // const groupList = accountList.filter(item1 => item1.company === item.name);
  532. // return { groupName: item.name, groupList };
  533. // });
  534. renderData.accountGroup = accountGroupList;
  535. renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  536. renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_inspection', ctx.session.sessionUser.is_admin ? 'all' : '');
  537. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
  538. renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
  539. renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_inspection');
  540. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_inspection');
  541. await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
  542. } catch (err) {
  543. ctx.log(err);
  544. ctx.postError(err, '无法查看安全巡检数据');
  545. ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
  546. }
  547. }
  548. /**
  549. * 变更管理 页面 (Get)
  550. *
  551. * @param {Object} ctx - egg全局变量
  552. * @return {void}
  553. */
  554. async inspection(ctx) {
  555. try {
  556. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  557. const status = parseInt(ctx.query.status) || 0;
  558. await this._filterInspection(ctx, status);
  559. } catch (err) {
  560. ctx.log(err);
  561. ctx.postError(err, '无法查看质量管理数据');
  562. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  563. }
  564. }
  565. // 巡检概况
  566. async inspectionOverview(ctx) {
  567. try {
  568. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  569. const tender = await this.service.tender.getDataById(ctx.tender.id);
  570. const year = moment().year();
  571. const renderData = {
  572. moment,
  573. tender,
  574. permission: ctx.permission.safe_inspection,
  575. overview: await ctx.service.safeInspection.getOverviewData(ctx.tender.id, year),
  576. inspectionMenuCounts: await this._getInspectionMenuCounts(ctx),
  577. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection_overview),
  578. };
  579. await this.layout('safe/inspection_overview.ejs', renderData);
  580. } catch (err) {
  581. ctx.log(err);
  582. ctx.postError(err, '无法查看巡检概况数据');
  583. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  584. }
  585. }
  586. // 巡检整改
  587. async inspectionRectification(ctx) {
  588. try {
  589. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  590. const status = safeInspectionConst.filter.status.rectification; // 正在整改
  591. await this._filterInspection(ctx, status);
  592. } catch (err) {
  593. ctx.log(err);
  594. ctx.postError(err, '无法查看巡检整改数据');
  595. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  596. }
  597. }
  598. // 巡检批复
  599. async inspectionApproval(ctx) {
  600. try {
  601. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  602. const status = safeInspectionConst.filter.status.reply; // 正在批复
  603. await this._filterInspection(ctx, status);
  604. } catch (err) {
  605. ctx.log(err);
  606. ctx.postError(err, '无法查看巡检批复数据');
  607. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  608. }
  609. }
  610. // 质量巡检单功能
  611. async _filterInspection(ctx, status = 0) {
  612. try {
  613. ctx.session.sessionUser.tenderId = ctx.tender.id;
  614. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  615. const orders = ctx.query.order ? ctx.query.order : 0;
  616. const filter = JSON.parse(JSON.stringify(safeInspectionConst.filter));
  617. filter.count = [];
  618. filter.count[filter.status.pending] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.pending);
  619. filter.count[filter.status.uncheck] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.uncheck);
  620. filter.count[filter.status.checking] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checking);
  621. filter.count[filter.status.reply] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.reply);
  622. filter.count[filter.status.rectification] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.rectification);
  623. filter.count[filter.status.checked] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checked);
  624. filter.count[filter.status.checkStop] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checkStop);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  625. const inspectionList = await ctx.service.safeInspection.getListByStatus(ctx.tender.id, status, 1, sorts, orders);
  626. const total = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status);
  627. const allAttList = inspectionList.length > 0 ? await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.helper._.map(inspectionList, 'id')) : [];
  628. for (const c of inspectionList) {
  629. c.attList = ctx.helper._.filter(allAttList, { qiid: c.id });
  630. c.curAuditors = await ctx.service.safeInspectionAudit.getAuditorsByStatus(c.id, c.status, c.times);
  631. if (c.status === auditConst.inspection.status.checkNoPre) {
  632. c.curAuditors2 = await ctx.service.safeInspectionAudit.getAuditorsByStatus(c.id, auditConst.inspection.status.checking, c.times);
  633. }
  634. }
  635. // 分页相关
  636. const page = ctx.page;
  637. const pageSize = ctx.pageSize;
  638. const pageInfo = {
  639. page,
  640. pageSizeSelect: 1,
  641. pageSizeCacheKey: 'inspection-pageSize:' + ctx.session.sessionUser.accountId + ':' + ctx.path.replace(/\/$/, ''),
  642. pageSize,
  643. total_num: total,
  644. total: Math.ceil(total / pageSize),
  645. queryData: JSON.stringify(ctx.urlInfo.query),
  646. };
  647. let codeRule = [];
  648. let c_connector = '1';
  649. let c_rule_first = 1;
  650. const rule_type = 'safe_inspection';
  651. const tender = await this.service.tender.getDataById(ctx.tender.id);
  652. if (tender.c_code_rules) {
  653. const c_code_rules = JSON.parse(tender.c_code_rules);
  654. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  655. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  656. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  657. }
  658. for (const rule of codeRule) {
  659. switch (rule.rule_type) {
  660. case codeRuleConst.measure.ruleType.dealCode:
  661. rule.preview = ctx.tender.info.deal_info.dealCode;
  662. break;
  663. case codeRuleConst.measure.ruleType.tenderName:
  664. rule.preview = tender.name;
  665. break;
  666. case codeRuleConst.measure.ruleType.inDate:
  667. rule.preview = moment().format('YYYY');
  668. break;
  669. case codeRuleConst.measure.ruleType.text:
  670. rule.preview = rule.text;
  671. break;
  672. case codeRuleConst.measure.ruleType.addNo:
  673. const s = '0000000000';
  674. rule.preview = s.substr(s.length - rule.format);
  675. break;
  676. default: break;
  677. }
  678. }
  679. const renderData = {
  680. moment,
  681. tender,
  682. permission: ctx.permission.safe_inspection,
  683. rule_type,
  684. codeRule,
  685. dealCode: ctx.tender.info.deal_info.dealCode,
  686. c_connector,
  687. c_rule_first,
  688. ruleType: codeRuleConst.ruleType[rule_type],
  689. ruleConst: codeRuleConst.measure,
  690. filter,
  691. inspectionList,
  692. auditType,
  693. auditConst: safeInspectionConst,
  694. status,
  695. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection),
  696. pageInfo,
  697. };
  698. await this.layout('safe/inspection.ejs', renderData, 'safe/inspection_modal.ejs');
  699. } catch (err) {
  700. ctx.log(err);
  701. ctx.postError(err, '无法查看安全巡检数据');
  702. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  703. }
  704. }
  705. /**
  706. * 新增变更申请 (Post)
  707. *
  708. * @param {Object} ctx - egg全局变量
  709. * @return {void}
  710. */
  711. async inspectionSave(ctx) {
  712. try {
  713. const data = JSON.parse(ctx.request.body.data);
  714. const reponseData = {
  715. err: 0, msg: '', data: {},
  716. };
  717. switch (data.type) {
  718. case 'add':
  719. if (!data.code || data.code === '') {
  720. throw '编号不能为空';
  721. }
  722. if (!data.check_item || !data.check_date) {
  723. throw '请填写检查项和日期';
  724. }
  725. reponseData.data = await ctx.service.safeInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
  726. break;
  727. case 'addByWap':
  728. if (!data.code || data.code === '') {
  729. throw '编号不能为空';
  730. }
  731. if (!data.check_item || !data.check_date) {
  732. throw '请填写检查项';
  733. }
  734. reponseData.data = await ctx.service.safeInspection.addByWap(ctx.tender.id, data);
  735. break;
  736. default:throw '参数有误';
  737. }
  738. ctx.body = reponseData;
  739. } catch (err) {
  740. this.log(err);
  741. ctx.body = { err: 1, msg: err.toString() };
  742. }
  743. }
  744. /**
  745. * 获取审批界面所需的 原报、审批人数据等
  746. * @param ctx
  747. * @return {Promise<void>}
  748. * @private
  749. */
  750. async _getInspectionAuditViewData(ctx) {
  751. await ctx.service.safeInspection.loadAuditViewData(ctx.inspection);
  752. }
  753. async inspectionInformation(ctx) {
  754. try {
  755. const whiteList = this.ctx.app.config.multipart.whitelist;
  756. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  757. await this._getInspectionAuditViewData(ctx);
  758. // 获取附件列表
  759. const fileList = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  760. // 获取用户人验证手机号
  761. const renderData = {
  762. moment,
  763. tender,
  764. inspection: ctx.inspection,
  765. auditConst: safeInspectionConst,
  766. fileList,
  767. inspectionMenuCounts: await this._getInspectionMenuCounts(ctx),
  768. whiteList,
  769. auditType,
  770. shenpiConst,
  771. deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
  772. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection_information),
  773. preUrl: `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
  774. };
  775. // data.accountGroup = accountGroup;
  776. // 获取所有项目参与者
  777. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  778. renderData.accountList = accountList;
  779. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  780. renderData.accountGroup = unitList.map(item => {
  781. const groupList = accountList.filter(item1 => item1.company === item.name);
  782. return { groupName: item.name, groupList };
  783. }).filter(x => { return x.groupList.length > 0; });
  784. if (ctx.inspection.flow_version === 1) {
  785. const groupedIds = new Set(renderData.accountGroup.reduce((ids, group) => ids.concat(group.groupList.map(user => user.id)), []));
  786. const others = accountList.filter(user => !groupedIds.has(user.id));
  787. if (others.length) renderData.accountGroup.push({ groupName: '其他用户', groupList: others });
  788. }
  789. await this.layout('safe/inspection_information.ejs', renderData, 'safe/inspection_information_modal.ejs');
  790. } catch (err) {
  791. this.log(err);
  792. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  793. }
  794. }
  795. async inspectionInformationSave(ctx) {
  796. try {
  797. const data = JSON.parse(ctx.request.body.data);
  798. const reponseData = {
  799. err: 0, msg: '', data: {},
  800. };
  801. if (ctx.inspection.flow_version === 1) {
  802. reponseData.data = await ctx.service.safeInspectionAudit.processFlow(ctx.inspection, data);
  803. ctx.body = reponseData;
  804. return;
  805. }
  806. switch (data.type) {
  807. case 'update-field':
  808. if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
  809. throw '当前状态不可修改';
  810. }
  811. if (data.update.code !== undefined) {
  812. if (data.update.code === '') throw '巡检编号不能为空';
  813. const codeExist = await ctx.service.safeInspection.getDataByCondition({ code: data.update.code, tid: ctx.tender.id });
  814. if (codeExist) throw '该巡检编号已存在';
  815. }
  816. if (data.update.check_item !== undefined && data.update.check_item === '') {
  817. throw '检查项不能为空';
  818. }
  819. if (data.update.check_date !== undefined && data.update.check_date === '') {
  820. throw '请填写检查日期';
  821. }
  822. if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
  823. throw '整改情况不能为空';
  824. }
  825. if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
  826. throw '请填写整改日期';
  827. }
  828. const fields = ['id', 'code', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
  829. if (!this.checkFieldExists(data.update, fields)) {
  830. throw '参数有误';
  831. }
  832. reponseData.data = await ctx.service.safeInspection.defaultUpdate(data.update);
  833. break;
  834. case 'add-audit':
  835. const id = this.app._.toInteger(data.auditorId);
  836. if (isNaN(id) || id <= 0) {
  837. throw '参数错误';
  838. }
  839. // 检查权限等
  840. if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
  841. throw '您无权添加审核人';
  842. }
  843. if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
  844. throw '当前不允许添加审核人';
  845. }
  846. ctx.inspection.auditorList = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  847. // 检查审核人是否已存在
  848. const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
  849. if (exist) {
  850. throw '该审核人已存在,请勿重复添加';
  851. }
  852. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.safe_inspection, sp_status: shenpiConst.sp_status.gdzs });
  853. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.safe_inspection === shenpiConst.sp_status.gdzs ? 1 : 0;
  854. const result = await ctx.service.safeInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times, is_gdzs);
  855. if (!result) {
  856. throw '添加审核人失败';
  857. }
  858. reponseData.data = await ctx.service.safeInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  859. break;
  860. case 'del-audit':
  861. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  862. if (isNaN(id2) || id2 <= 0) {
  863. throw '参数错误';
  864. }
  865. const result2 = await ctx.service.safeInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  866. if (!result2) {
  867. throw '移除审核人失败';
  868. }
  869. reponseData.data = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  870. break;
  871. case 'start-inspection':
  872. if (ctx.inspection.readOnly) {
  873. throw '当前状态不可提交';
  874. }
  875. await ctx.service.safeInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  876. break;
  877. case 'del-inspection':
  878. if (ctx.inspection.readOnly) {
  879. throw '当前状态不可删除';
  880. }
  881. await ctx.service.safeInspection.delInspection(ctx.inspection.id);
  882. break;
  883. case 'check':
  884. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  885. throw '当前质量巡检数据有误';
  886. }
  887. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  888. throw '您无权进行该操作';
  889. }
  890. await ctx.service.safeInspectionAudit.check(ctx.inspection, data);
  891. break;
  892. case 'rectification':
  893. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  894. throw '当前质量巡检数据有误';
  895. }
  896. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  897. throw '您无权进行该操作';
  898. }
  899. await ctx.service.safeInspectionAudit.rectification(ctx.inspection, data);
  900. break;
  901. default:throw '参数有误';
  902. }
  903. ctx.body = reponseData;
  904. } catch (err) {
  905. this.log(err);
  906. ctx.body = { err: 1, msg: err.toString() };
  907. }
  908. }
  909. checkFieldExists(update, fields) {
  910. for (const field of Object.keys(update)) {
  911. if (!fields.includes(field)) {
  912. return false;
  913. }
  914. }
  915. return true;
  916. }
  917. /**
  918. * 上传附件
  919. * @param {*} ctx 上下文
  920. */
  921. async uploadInspectionFile(ctx) {
  922. let stream;
  923. try {
  924. if (ctx.inspection.flow_version === 1 && !ctx.inspection.canUpload) throw '当前不可上传附件';
  925. const parts = this.ctx.multipart({
  926. autoFields: true,
  927. });
  928. const files = [];
  929. const create_time = Date.parse(new Date()) / 1000;
  930. let idx = 0;
  931. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  932. while ((stream = await parts()) !== undefined) {
  933. if (!stream.filename) {
  934. // 如果没有传入直接返回
  935. return;
  936. }
  937. const fileInfo = path.parse(stream.filename);
  938. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/safe_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  939. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  940. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  941. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  942. ++idx;
  943. stream && (await sendToWormhole(stream));
  944. }
  945. const in_time = new Date();
  946. const payload = files.map(file => {
  947. let idx;
  948. if (Array.isArray(parts.field.name)) {
  949. idx = parts.field.name.findIndex(name => name === file.name);
  950. } else {
  951. idx = 'isString';
  952. }
  953. const newFile = {
  954. tid: ctx.tender.id,
  955. qiid: ctx.inspection.id,
  956. uid: ctx.session.sessionUser.accountId,
  957. filename: file.name,
  958. fileext: file.ext,
  959. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  960. filepath: file.filepath,
  961. upload_time: in_time,
  962. extra_upload,
  963. };
  964. return newFile;
  965. });
  966. // 执行文件信息写入数据库
  967. await ctx.service.safeInspectionAtt.saveFileMsgToDb(payload);
  968. // 将最新的当前标段的所有文件信息返回
  969. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  970. ctx.body = { err: 0, msg: '', data };
  971. } catch (err) {
  972. stream && (await sendToWormhole(stream));
  973. this.log(err);
  974. ctx.body = { err: 1, msg: err.toString(), data: null };
  975. }
  976. }
  977. /**
  978. * 删除附件
  979. * @param {Ojbect} ctx 上下文
  980. */
  981. async deleteInspectionFile(ctx) {
  982. try {
  983. const { id } = JSON.parse(ctx.request.body.data);
  984. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  985. if (ctx.inspection.flow_version === 1) {
  986. if (!fileInfo || fileInfo.qiid !== ctx.inspection.id || !ctx.inspection.canUpload || fileInfo.uid !== ctx.session.sessionUser.accountId) throw '您无权删除该附件';
  987. if (ctx.inspection.status === safeInspectionConst.status.checked && !fileInfo.extra_upload && !PermissionCheck.delFile(ctx.session.sessionUser.permission)) throw '该附件不可删除';
  988. }
  989. if (fileInfo && Object.keys(fileInfo).length) {
  990. // 先删除文件
  991. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  992. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  993. // 再删除数据库
  994. await ctx.service.safeInspectionAtt.delete(id);
  995. } else {
  996. throw '不存在该文件';
  997. }
  998. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  999. ctx.body = { err: 0, msg: '请求成功', data };
  1000. } catch (err) {
  1001. this.log(err);
  1002. ctx.body = { err: 1, msg: err.toString(), data: null };
  1003. }
  1004. }
  1005. /**
  1006. * 下载附件
  1007. * @param {Object} ctx - egg全局变量
  1008. * @return {void}
  1009. */
  1010. async downloadInspectionFile(ctx) {
  1011. const id = ctx.params.fid;
  1012. if (id) {
  1013. try {
  1014. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  1015. if (fileInfo !== undefined && fileInfo !== '') {
  1016. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  1017. // 解决中文无法下载问题
  1018. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1019. let disposition = '';
  1020. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1021. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  1022. } else if (userAgent.indexOf('firefox') >= 0) {
  1023. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  1024. } else {
  1025. /* safari等其他非主流浏览器只能自求多福了 */
  1026. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  1027. }
  1028. ctx.response.set({
  1029. 'Content-Type': 'application/octet-stream',
  1030. 'Content-Disposition': disposition,
  1031. 'Content-Length': fileInfo.filesize,
  1032. });
  1033. // ctx.body = await fs.createReadStream(fileName);
  1034. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1035. } else {
  1036. throw '不存在该文件';
  1037. }
  1038. } catch (err) {
  1039. this.log(err);
  1040. this.setMessage(err.toString(), this.messageType.ERROR);
  1041. }
  1042. }
  1043. }
  1044. async _getInspectionMenuCounts(ctx) {
  1045. const status = safeInspectionConst.filter.status;
  1046. const [rectification, reply] = await Promise.all([
  1047. ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status.rectification),
  1048. ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status.reply),
  1049. ]);
  1050. return { rectification, reply };
  1051. }
  1052. }
  1053. return SafeController;
  1054. };