safe_controller.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 auditType = require('../const/audit').auditType;
  11. const shenpiConst = require('../const/shenpi');
  12. const codeRuleConst = require('../const/code_rule');
  13. const contractConst = require('../const/contract');
  14. const moment = require('moment');
  15. const sendToWormhole = require('stream-wormhole');
  16. const fs = require('fs');
  17. const path = require('path');
  18. const PermissionCheck = require('../const/account_permission').PermissionCheck;
  19. module.exports = app => {
  20. class SafeController extends app.BaseController {
  21. constructor(ctx) {
  22. super(ctx);
  23. ctx.showProject = true;
  24. // ctx.showTitle = true;
  25. }
  26. loadMenu(ctx) {
  27. super.loadMenu(ctx);
  28. // 虚拟menu,以保证标题显示正确
  29. ctx.menu = {
  30. name: '安全管理',
  31. display: false,
  32. caption: '安全管理',
  33. controller: 'safe',
  34. };
  35. }
  36. async tender(ctx) {
  37. try {
  38. if (!ctx.subProject.page_show.safePayment) throw '该功能已关闭';
  39. const renderData = {
  40. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  41. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
  42. };
  43. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  44. renderData.accountList = accountList;
  45. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  46. const accountGroupList = unitList.map(item => {
  47. const groupList = accountList.filter(item1 => item1.company === item.name);
  48. return { groupName: item.name, groupList };
  49. }).filter(x => { return x.groupList.length > 0; });
  50. // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  51. // renderData.accountGroup = unitList.map(item => {
  52. // const groupList = accountList.filter(item1 => item1.company === item.name);
  53. // return { groupName: item.name, groupList };
  54. // });
  55. renderData.accountGroup = accountGroupList;
  56. renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  57. renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_payment', ctx.session.sessionUser.is_admin ? 'all' : '');
  58. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
  59. renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
  60. renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_payment');
  61. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_payment');
  62. await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
  63. } catch (err) {
  64. ctx.log(err);
  65. ctx.postError(err, '无法查看安全计量数据');
  66. ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
  67. }
  68. }
  69. async inspectionTender(ctx) {
  70. try {
  71. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  72. const renderData = {
  73. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  74. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
  75. };
  76. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  77. renderData.accountList = accountList;
  78. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  79. const accountGroupList = unitList.map(item => {
  80. const groupList = accountList.filter(item1 => item1.company === item.name);
  81. return { groupName: item.name, groupList };
  82. }).filter(x => { return x.groupList.length > 0; });
  83. // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  84. // renderData.accountGroup = unitList.map(item => {
  85. // const groupList = accountList.filter(item1 => item1.company === item.name);
  86. // return { groupName: item.name, groupList };
  87. // });
  88. renderData.accountGroup = accountGroupList;
  89. renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  90. renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_inspection', ctx.session.sessionUser.is_admin ? 'all' : '');
  91. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
  92. renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
  93. renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_inspection');
  94. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_inspection');
  95. await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
  96. } catch (err) {
  97. ctx.log(err);
  98. ctx.postError(err, '无法查看安全巡检数据');
  99. ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
  100. }
  101. }
  102. /**
  103. * 变更管理 页面 (Get)
  104. *
  105. * @param {Object} ctx - egg全局变量
  106. * @return {void}
  107. */
  108. async inspection(ctx) {
  109. try {
  110. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  111. const status = parseInt(ctx.query.status) || 0;
  112. await this._filterInspection(ctx, status);
  113. } catch (err) {
  114. ctx.log(err);
  115. ctx.postError(err, '无法查看质量管理数据');
  116. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  117. }
  118. }
  119. // 质量巡检单功能
  120. async _filterInspection(ctx, status = 0) {
  121. try {
  122. ctx.session.sessionUser.tenderId = ctx.tender.id;
  123. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  124. const orders = ctx.query.order ? ctx.query.order : 0;
  125. const filter = JSON.parse(JSON.stringify(auditConst.inspection.filter));
  126. filter.count = [];
  127. filter.count[filter.status.pending] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.pending);
  128. filter.count[filter.status.uncheck] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.uncheck);
  129. filter.count[filter.status.checking] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checking);
  130. filter.count[filter.status.rectification] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.rectification);
  131. filter.count[filter.status.checked] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checked);
  132. 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);
  133. const inspectionList = await ctx.service.safeInspection.getListByStatus(ctx.tender.id, status, 1, sorts, orders);
  134. const total = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status);
  135. const allAttList = inspectionList.length > 0 ? await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.helper._.map(inspectionList, 'id')) : [];
  136. for (const c of inspectionList) {
  137. c.attList = ctx.helper._.filter(allAttList, { qiid: c.id });
  138. c.curAuditors = await ctx.service.safeInspectionAudit.getAuditorsByStatus(c.id, c.status, c.times);
  139. if (c.status === auditConst.inspection.status.checkNoPre) {
  140. c.curAuditors2 = await ctx.service.safeInspectionAudit.getAuditorsByStatus(c.id, auditConst.inspection.status.checking, c.times);
  141. }
  142. }
  143. // 分页相关
  144. const page = ctx.page;
  145. const pageSize = ctx.pageSize;
  146. const pageInfo = {
  147. page,
  148. pageSizeSelect: 1,
  149. pageSize,
  150. total_num: total,
  151. total: Math.ceil(total / pageSize),
  152. queryData: JSON.stringify(ctx.urlInfo.query),
  153. };
  154. let codeRule = [];
  155. let c_connector = '1';
  156. let c_rule_first = 1;
  157. const rule_type = 'safe_inspection';
  158. const tender = await this.service.tender.getDataById(ctx.tender.id);
  159. if (tender.c_code_rules) {
  160. const c_code_rules = JSON.parse(tender.c_code_rules);
  161. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  162. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  163. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  164. }
  165. for (const rule of codeRule) {
  166. switch (rule.rule_type) {
  167. case codeRuleConst.measure.ruleType.dealCode:
  168. rule.preview = ctx.tender.info.deal_info.dealCode;
  169. break;
  170. case codeRuleConst.measure.ruleType.tenderName:
  171. rule.preview = tender.name;
  172. break;
  173. case codeRuleConst.measure.ruleType.inDate:
  174. rule.preview = moment().format('YYYY');
  175. break;
  176. case codeRuleConst.measure.ruleType.text:
  177. rule.preview = rule.text;
  178. break;
  179. case codeRuleConst.measure.ruleType.addNo:
  180. const s = '0000000000';
  181. rule.preview = s.substr(s.length - rule.format);
  182. break;
  183. default: break;
  184. }
  185. }
  186. const renderData = {
  187. moment,
  188. tender,
  189. permission: ctx.permission.safe_inspection,
  190. rule_type,
  191. codeRule,
  192. dealCode: ctx.tender.info.deal_info.dealCode,
  193. c_connector,
  194. c_rule_first,
  195. ruleType: codeRuleConst.ruleType[rule_type],
  196. ruleConst: codeRuleConst.measure,
  197. filter,
  198. inspectionList,
  199. auditType,
  200. auditConst: auditConst.inspection,
  201. status,
  202. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection),
  203. pageInfo,
  204. };
  205. await this.layout('safe/inspection.ejs', renderData, 'safe/inspection_modal.ejs');
  206. } catch (err) {
  207. ctx.log(err);
  208. ctx.postError(err, '无法查看安全巡检数据');
  209. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  210. }
  211. }
  212. /**
  213. * 新增变更申请 (Post)
  214. *
  215. * @param {Object} ctx - egg全局变量
  216. * @return {void}
  217. */
  218. async inspectionSave(ctx) {
  219. try {
  220. const data = JSON.parse(ctx.request.body.data);
  221. const reponseData = {
  222. err: 0, msg: '', data: {},
  223. };
  224. switch (data.type) {
  225. case 'add':
  226. if (!data.code || data.code === '') {
  227. throw '编号不能为空';
  228. }
  229. if (!data.check_item || !data.check_date) {
  230. throw '请填写检查项和日期';
  231. }
  232. reponseData.data = await ctx.service.safeInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
  233. break;
  234. default:throw '参数有误';
  235. }
  236. ctx.body = reponseData;
  237. } catch (err) {
  238. this.log(err);
  239. ctx.body = { err: 1, msg: err.toString() };
  240. }
  241. }
  242. /**
  243. * 获取审批界面所需的 原报、审批人数据等
  244. * @param ctx
  245. * @return {Promise<void>}
  246. * @private
  247. */
  248. async _getInspectionAuditViewData(ctx) {
  249. await ctx.service.safeInspection.loadAuditViewData(ctx.inspection);
  250. }
  251. async inspectionInformation(ctx) {
  252. try {
  253. const whiteList = this.ctx.app.config.multipart.whitelist;
  254. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  255. await this._getInspectionAuditViewData(ctx);
  256. // 获取附件列表
  257. const fileList = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  258. // 获取用户人验证手机号
  259. const renderData = {
  260. moment,
  261. tender,
  262. inspection: ctx.inspection,
  263. auditConst: auditConst.inspection,
  264. fileList,
  265. whiteList,
  266. auditType,
  267. shenpiConst,
  268. deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
  269. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection_information),
  270. preUrl: `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
  271. };
  272. // data.accountGroup = accountGroup;
  273. // 获取所有项目参与者
  274. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  275. renderData.accountList = accountList;
  276. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  277. renderData.accountGroup = unitList.map(item => {
  278. const groupList = accountList.filter(item1 => item1.company === item.name);
  279. return { groupName: item.name, groupList };
  280. }).filter(x => { return x.groupList.length > 0; });
  281. await this.layout('safe/inspection_information.ejs', renderData, 'safe/inspection_information_modal.ejs');
  282. } catch (err) {
  283. this.log(err);
  284. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  285. }
  286. }
  287. async inspectionInformationSave(ctx) {
  288. try {
  289. const data = JSON.parse(ctx.request.body.data);
  290. const reponseData = {
  291. err: 0, msg: '', data: {},
  292. };
  293. switch (data.type) {
  294. case 'update-field':
  295. if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
  296. throw '当前状态不可修改';
  297. }
  298. if (data.update.check_item !== undefined && data.update.check_item === '') {
  299. throw '检查项不能为空';
  300. }
  301. if (data.update.check_date !== undefined && data.update.check_date === '') {
  302. throw '请填写检查日期';
  303. }
  304. if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
  305. throw '整改情况不能为空';
  306. }
  307. if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
  308. throw '请填写整改日期';
  309. }
  310. const fields = ['id', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
  311. if (!this.checkFieldExists(data.update, fields)) {
  312. throw '参数有误';
  313. }
  314. reponseData.data = await ctx.service.safeInspection.defaultUpdate(data.update);
  315. break;
  316. case 'add-audit':
  317. const id = this.app._.toInteger(data.auditorId);
  318. if (isNaN(id) || id <= 0) {
  319. throw '参数错误';
  320. }
  321. // 检查权限等
  322. if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
  323. throw '您无权添加审核人';
  324. }
  325. if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
  326. throw '当前不允许添加审核人';
  327. }
  328. ctx.inspection.auditorList = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  329. // 检查审核人是否已存在
  330. const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
  331. if (exist) {
  332. throw '该审核人已存在,请勿重复添加';
  333. }
  334. const result = await ctx.service.safeInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times);
  335. if (!result) {
  336. throw '添加审核人失败';
  337. }
  338. reponseData.data = await ctx.service.safeInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  339. break;
  340. case 'del-audit':
  341. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  342. if (isNaN(id2) || id2 <= 0) {
  343. throw '参数错误';
  344. }
  345. const result2 = await ctx.service.safeInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  346. if (!result2) {
  347. throw '移除审核人失败';
  348. }
  349. reponseData.data = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  350. break;
  351. case 'start-inspection':
  352. if (ctx.inspection.readOnly) {
  353. throw '当前状态不可提交';
  354. }
  355. await ctx.service.safeInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  356. break;
  357. case 'del-inspection':
  358. if (ctx.inspection.readOnly) {
  359. throw '当前状态不可删除';
  360. }
  361. await ctx.service.safeInspection.delInspection(ctx.inspection.id);
  362. break;
  363. case 'check':
  364. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  365. throw '当前质量巡检数据有误';
  366. }
  367. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  368. throw '您无权进行该操作';
  369. }
  370. await ctx.service.safeInspectionAudit.check(ctx.inspection, data);
  371. break;
  372. case 'rectification':
  373. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  374. throw '当前质量巡检数据有误';
  375. }
  376. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  377. throw '您无权进行该操作';
  378. }
  379. await ctx.service.safeInspectionAudit.rectification(ctx.inspection, data);
  380. break;
  381. default:throw '参数有误';
  382. }
  383. ctx.body = reponseData;
  384. } catch (err) {
  385. this.log(err);
  386. ctx.body = { err: 1, msg: err.toString() };
  387. }
  388. }
  389. checkFieldExists(update, fields) {
  390. for (const field of Object.keys(update)) {
  391. if (!fields.includes(field)) {
  392. return false;
  393. }
  394. }
  395. return true;
  396. }
  397. /**
  398. * 上传附件
  399. * @param {*} ctx 上下文
  400. */
  401. async uploadInspectionFile(ctx) {
  402. let stream;
  403. try {
  404. // this._checkAdvanceFileCanModify(ctx);
  405. const parts = this.ctx.multipart({
  406. autoFields: true,
  407. });
  408. const files = [];
  409. const create_time = Date.parse(new Date()) / 1000;
  410. let idx = 0;
  411. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  412. while ((stream = await parts()) !== undefined) {
  413. if (!stream.filename) {
  414. // 如果没有传入直接返回
  415. return;
  416. }
  417. const fileInfo = path.parse(stream.filename);
  418. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/safe_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  419. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  420. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  421. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  422. ++idx;
  423. stream && (await sendToWormhole(stream));
  424. }
  425. const in_time = new Date();
  426. const payload = files.map(file => {
  427. let idx;
  428. if (Array.isArray(parts.field.name)) {
  429. idx = parts.field.name.findIndex(name => name === file.name);
  430. } else {
  431. idx = 'isString';
  432. }
  433. const newFile = {
  434. tid: ctx.tender.id,
  435. qiid: ctx.inspection.id,
  436. uid: ctx.session.sessionUser.accountId,
  437. filename: file.name,
  438. fileext: file.ext,
  439. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  440. filepath: file.filepath,
  441. upload_time: in_time,
  442. extra_upload,
  443. };
  444. return newFile;
  445. });
  446. // 执行文件信息写入数据库
  447. await ctx.service.safeInspectionAtt.saveFileMsgToDb(payload);
  448. // 将最新的当前标段的所有文件信息返回
  449. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  450. ctx.body = { err: 0, msg: '', data };
  451. } catch (err) {
  452. stream && (await sendToWormhole(stream));
  453. this.log(err);
  454. ctx.body = { err: 1, msg: err.toString(), data: null };
  455. }
  456. }
  457. /**
  458. * 删除附件
  459. * @param {Ojbect} ctx 上下文
  460. */
  461. async deleteInspectionFile(ctx) {
  462. try {
  463. const { id } = JSON.parse(ctx.request.body.data);
  464. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  465. if (fileInfo || Object.keys(fileInfo).length) {
  466. // 先删除文件
  467. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  468. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  469. // 再删除数据库
  470. await ctx.service.safeInspectionAtt.delete(id);
  471. } else {
  472. throw '不存在该文件';
  473. }
  474. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  475. ctx.body = { err: 0, msg: '请求成功', data };
  476. } catch (err) {
  477. this.log(err);
  478. ctx.body = { err: 1, msg: err.toString(), data: null };
  479. }
  480. }
  481. /**
  482. * 下载附件
  483. * @param {Object} ctx - egg全局变量
  484. * @return {void}
  485. */
  486. async downloadInspectionFile(ctx) {
  487. const id = ctx.params.fid;
  488. if (id) {
  489. try {
  490. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  491. if (fileInfo !== undefined && fileInfo !== '') {
  492. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  493. // 解决中文无法下载问题
  494. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  495. let disposition = '';
  496. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  497. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  498. } else if (userAgent.indexOf('firefox') >= 0) {
  499. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  500. } else {
  501. /* safari等其他非主流浏览器只能自求多福了 */
  502. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  503. }
  504. ctx.response.set({
  505. 'Content-Type': 'application/octet-stream',
  506. 'Content-Disposition': disposition,
  507. 'Content-Length': fileInfo.filesize,
  508. });
  509. // ctx.body = await fs.createReadStream(fileName);
  510. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  511. } else {
  512. throw '不存在该文件';
  513. }
  514. } catch (err) {
  515. this.log(err);
  516. this.setMessage(err.toString(), this.messageType.ERROR);
  517. }
  518. }
  519. }
  520. }
  521. return SafeController;
  522. };