safe_controller.js 57 KB

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