safe_controller.js 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. pageSize,
  642. total_num: total,
  643. total: Math.ceil(total / pageSize),
  644. queryData: JSON.stringify(ctx.urlInfo.query),
  645. };
  646. let codeRule = [];
  647. let c_connector = '1';
  648. let c_rule_first = 1;
  649. const rule_type = 'safe_inspection';
  650. const tender = await this.service.tender.getDataById(ctx.tender.id);
  651. if (tender.c_code_rules) {
  652. const c_code_rules = JSON.parse(tender.c_code_rules);
  653. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  654. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  655. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  656. }
  657. for (const rule of codeRule) {
  658. switch (rule.rule_type) {
  659. case codeRuleConst.measure.ruleType.dealCode:
  660. rule.preview = ctx.tender.info.deal_info.dealCode;
  661. break;
  662. case codeRuleConst.measure.ruleType.tenderName:
  663. rule.preview = tender.name;
  664. break;
  665. case codeRuleConst.measure.ruleType.inDate:
  666. rule.preview = moment().format('YYYY');
  667. break;
  668. case codeRuleConst.measure.ruleType.text:
  669. rule.preview = rule.text;
  670. break;
  671. case codeRuleConst.measure.ruleType.addNo:
  672. const s = '0000000000';
  673. rule.preview = s.substr(s.length - rule.format);
  674. break;
  675. default: break;
  676. }
  677. }
  678. const renderData = {
  679. moment,
  680. tender,
  681. permission: ctx.permission.safe_inspection,
  682. rule_type,
  683. codeRule,
  684. dealCode: ctx.tender.info.deal_info.dealCode,
  685. c_connector,
  686. c_rule_first,
  687. ruleType: codeRuleConst.ruleType[rule_type],
  688. ruleConst: codeRuleConst.measure,
  689. filter,
  690. inspectionList,
  691. auditType,
  692. auditConst: safeInspectionConst,
  693. status,
  694. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection),
  695. pageInfo,
  696. };
  697. await this.layout('safe/inspection.ejs', renderData, 'safe/inspection_modal.ejs');
  698. } catch (err) {
  699. ctx.log(err);
  700. ctx.postError(err, '无法查看安全巡检数据');
  701. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  702. }
  703. }
  704. /**
  705. * 新增变更申请 (Post)
  706. *
  707. * @param {Object} ctx - egg全局变量
  708. * @return {void}
  709. */
  710. async inspectionSave(ctx) {
  711. try {
  712. const data = JSON.parse(ctx.request.body.data);
  713. const reponseData = {
  714. err: 0, msg: '', data: {},
  715. };
  716. switch (data.type) {
  717. case 'add':
  718. if (!data.code || data.code === '') {
  719. throw '编号不能为空';
  720. }
  721. if (!data.check_item || !data.check_date) {
  722. throw '请填写检查项和日期';
  723. }
  724. reponseData.data = await ctx.service.safeInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
  725. break;
  726. case 'addByWap':
  727. if (!data.code || data.code === '') {
  728. throw '编号不能为空';
  729. }
  730. if (!data.check_item || !data.check_date) {
  731. throw '请填写检查项';
  732. }
  733. reponseData.data = await ctx.service.safeInspection.addByWap(ctx.tender.id, data);
  734. break;
  735. default:throw '参数有误';
  736. }
  737. ctx.body = reponseData;
  738. } catch (err) {
  739. this.log(err);
  740. ctx.body = { err: 1, msg: err.toString() };
  741. }
  742. }
  743. /**
  744. * 获取审批界面所需的 原报、审批人数据等
  745. * @param ctx
  746. * @return {Promise<void>}
  747. * @private
  748. */
  749. async _getInspectionAuditViewData(ctx) {
  750. await ctx.service.safeInspection.loadAuditViewData(ctx.inspection);
  751. }
  752. async inspectionInformation(ctx) {
  753. try {
  754. const whiteList = this.ctx.app.config.multipart.whitelist;
  755. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  756. await this._getInspectionAuditViewData(ctx);
  757. // 获取附件列表
  758. const fileList = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  759. // 获取用户人验证手机号
  760. const renderData = {
  761. moment,
  762. tender,
  763. inspection: ctx.inspection,
  764. auditConst: safeInspectionConst,
  765. fileList,
  766. inspectionMenuCounts: await this._getInspectionMenuCounts(ctx),
  767. whiteList,
  768. auditType,
  769. shenpiConst,
  770. deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
  771. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection_information),
  772. preUrl: `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
  773. };
  774. // data.accountGroup = accountGroup;
  775. // 获取所有项目参与者
  776. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  777. renderData.accountList = accountList;
  778. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  779. renderData.accountGroup = unitList.map(item => {
  780. const groupList = accountList.filter(item1 => item1.company === item.name);
  781. return { groupName: item.name, groupList };
  782. }).filter(x => { return x.groupList.length > 0; });
  783. if (ctx.inspection.flow_version === 1) {
  784. const groupedIds = new Set(renderData.accountGroup.reduce((ids, group) => ids.concat(group.groupList.map(user => user.id)), []));
  785. const others = accountList.filter(user => !groupedIds.has(user.id));
  786. if (others.length) renderData.accountGroup.push({ groupName: '其他用户', groupList: others });
  787. }
  788. await this.layout('safe/inspection_information.ejs', renderData, 'safe/inspection_information_modal.ejs');
  789. } catch (err) {
  790. this.log(err);
  791. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  792. }
  793. }
  794. async inspectionInformationSave(ctx) {
  795. try {
  796. const data = JSON.parse(ctx.request.body.data);
  797. const reponseData = {
  798. err: 0, msg: '', data: {},
  799. };
  800. if (ctx.inspection.flow_version === 1) {
  801. reponseData.data = await ctx.service.safeInspectionAudit.processFlow(ctx.inspection, data);
  802. ctx.body = reponseData;
  803. return;
  804. }
  805. switch (data.type) {
  806. case 'update-field':
  807. if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
  808. throw '当前状态不可修改';
  809. }
  810. if (data.update.code !== undefined) {
  811. if (data.update.code === '') throw '巡检编号不能为空';
  812. const codeExist = await ctx.service.safeInspection.getDataByCondition({ code: data.update.code, tid: ctx.tender.id });
  813. if (codeExist) throw '该巡检编号已存在';
  814. }
  815. if (data.update.check_item !== undefined && data.update.check_item === '') {
  816. throw '检查项不能为空';
  817. }
  818. if (data.update.check_date !== undefined && data.update.check_date === '') {
  819. throw '请填写检查日期';
  820. }
  821. if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
  822. throw '整改情况不能为空';
  823. }
  824. if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
  825. throw '请填写整改日期';
  826. }
  827. const fields = ['id', 'code', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
  828. if (!this.checkFieldExists(data.update, fields)) {
  829. throw '参数有误';
  830. }
  831. reponseData.data = await ctx.service.safeInspection.defaultUpdate(data.update);
  832. break;
  833. case 'add-audit':
  834. const id = this.app._.toInteger(data.auditorId);
  835. if (isNaN(id) || id <= 0) {
  836. throw '参数错误';
  837. }
  838. // 检查权限等
  839. if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
  840. throw '您无权添加审核人';
  841. }
  842. if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
  843. throw '当前不允许添加审核人';
  844. }
  845. ctx.inspection.auditorList = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  846. // 检查审核人是否已存在
  847. const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
  848. if (exist) {
  849. throw '该审核人已存在,请勿重复添加';
  850. }
  851. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.safe_inspection, sp_status: shenpiConst.sp_status.gdzs });
  852. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.safe_inspection === shenpiConst.sp_status.gdzs ? 1 : 0;
  853. const result = await ctx.service.safeInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times, is_gdzs);
  854. if (!result) {
  855. throw '添加审核人失败';
  856. }
  857. reponseData.data = await ctx.service.safeInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  858. break;
  859. case 'del-audit':
  860. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  861. if (isNaN(id2) || id2 <= 0) {
  862. throw '参数错误';
  863. }
  864. const result2 = await ctx.service.safeInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  865. if (!result2) {
  866. throw '移除审核人失败';
  867. }
  868. reponseData.data = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  869. break;
  870. case 'start-inspection':
  871. if (ctx.inspection.readOnly) {
  872. throw '当前状态不可提交';
  873. }
  874. await ctx.service.safeInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  875. break;
  876. case 'del-inspection':
  877. if (ctx.inspection.readOnly) {
  878. throw '当前状态不可删除';
  879. }
  880. await ctx.service.safeInspection.delInspection(ctx.inspection.id);
  881. break;
  882. case 'check':
  883. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  884. throw '当前质量巡检数据有误';
  885. }
  886. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  887. throw '您无权进行该操作';
  888. }
  889. await ctx.service.safeInspectionAudit.check(ctx.inspection, data);
  890. break;
  891. case 'rectification':
  892. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  893. throw '当前质量巡检数据有误';
  894. }
  895. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  896. throw '您无权进行该操作';
  897. }
  898. await ctx.service.safeInspectionAudit.rectification(ctx.inspection, data);
  899. break;
  900. default:throw '参数有误';
  901. }
  902. ctx.body = reponseData;
  903. } catch (err) {
  904. this.log(err);
  905. ctx.body = { err: 1, msg: err.toString() };
  906. }
  907. }
  908. checkFieldExists(update, fields) {
  909. for (const field of Object.keys(update)) {
  910. if (!fields.includes(field)) {
  911. return false;
  912. }
  913. }
  914. return true;
  915. }
  916. /**
  917. * 上传附件
  918. * @param {*} ctx 上下文
  919. */
  920. async uploadInspectionFile(ctx) {
  921. let stream;
  922. try {
  923. if (ctx.inspection.flow_version === 1 && !ctx.inspection.canUpload) throw '当前不可上传附件';
  924. const parts = this.ctx.multipart({
  925. autoFields: true,
  926. });
  927. const files = [];
  928. const create_time = Date.parse(new Date()) / 1000;
  929. let idx = 0;
  930. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  931. while ((stream = await parts()) !== undefined) {
  932. if (!stream.filename) {
  933. // 如果没有传入直接返回
  934. return;
  935. }
  936. const fileInfo = path.parse(stream.filename);
  937. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/safe_inspection/fujian_${create_time + idx.toString() + 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. ++idx;
  942. stream && (await sendToWormhole(stream));
  943. }
  944. const in_time = new Date();
  945. const payload = files.map(file => {
  946. let idx;
  947. if (Array.isArray(parts.field.name)) {
  948. idx = parts.field.name.findIndex(name => name === file.name);
  949. } else {
  950. idx = 'isString';
  951. }
  952. const newFile = {
  953. tid: ctx.tender.id,
  954. qiid: ctx.inspection.id,
  955. uid: ctx.session.sessionUser.accountId,
  956. filename: file.name,
  957. fileext: file.ext,
  958. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  959. filepath: file.filepath,
  960. upload_time: in_time,
  961. extra_upload,
  962. };
  963. return newFile;
  964. });
  965. // 执行文件信息写入数据库
  966. await ctx.service.safeInspectionAtt.saveFileMsgToDb(payload);
  967. // 将最新的当前标段的所有文件信息返回
  968. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  969. ctx.body = { err: 0, msg: '', data };
  970. } catch (err) {
  971. stream && (await sendToWormhole(stream));
  972. this.log(err);
  973. ctx.body = { err: 1, msg: err.toString(), data: null };
  974. }
  975. }
  976. /**
  977. * 删除附件
  978. * @param {Ojbect} ctx 上下文
  979. */
  980. async deleteInspectionFile(ctx) {
  981. try {
  982. const { id } = JSON.parse(ctx.request.body.data);
  983. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  984. if (ctx.inspection.flow_version === 1) {
  985. if (!fileInfo || fileInfo.qiid !== ctx.inspection.id || !ctx.inspection.canUpload || fileInfo.uid !== ctx.session.sessionUser.accountId) throw '您无权删除该附件';
  986. if (ctx.inspection.status === safeInspectionConst.status.checked && !fileInfo.extra_upload && !PermissionCheck.delFile(ctx.session.sessionUser.permission)) throw '该附件不可删除';
  987. }
  988. if (fileInfo && Object.keys(fileInfo).length) {
  989. // 先删除文件
  990. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  991. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  992. // 再删除数据库
  993. await ctx.service.safeInspectionAtt.delete(id);
  994. } else {
  995. throw '不存在该文件';
  996. }
  997. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  998. ctx.body = { err: 0, msg: '请求成功', data };
  999. } catch (err) {
  1000. this.log(err);
  1001. ctx.body = { err: 1, msg: err.toString(), data: null };
  1002. }
  1003. }
  1004. /**
  1005. * 下载附件
  1006. * @param {Object} ctx - egg全局变量
  1007. * @return {void}
  1008. */
  1009. async downloadInspectionFile(ctx) {
  1010. const id = ctx.params.fid;
  1011. if (id) {
  1012. try {
  1013. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  1014. if (fileInfo !== undefined && fileInfo !== '') {
  1015. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  1016. // 解决中文无法下载问题
  1017. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1018. let disposition = '';
  1019. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1020. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  1021. } else if (userAgent.indexOf('firefox') >= 0) {
  1022. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  1023. } else {
  1024. /* safari等其他非主流浏览器只能自求多福了 */
  1025. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  1026. }
  1027. ctx.response.set({
  1028. 'Content-Type': 'application/octet-stream',
  1029. 'Content-Disposition': disposition,
  1030. 'Content-Length': fileInfo.filesize,
  1031. });
  1032. // ctx.body = await fs.createReadStream(fileName);
  1033. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1034. } else {
  1035. throw '不存在该文件';
  1036. }
  1037. } catch (err) {
  1038. this.log(err);
  1039. this.setMessage(err.toString(), this.messageType.ERROR);
  1040. }
  1041. }
  1042. }
  1043. async _getInspectionMenuCounts(ctx) {
  1044. const status = safeInspectionConst.filter.status;
  1045. const [rectification, reply] = await Promise.all([
  1046. ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status.rectification),
  1047. ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status.reply),
  1048. ]);
  1049. return { rectification, reply };
  1050. }
  1051. }
  1052. return SafeController;
  1053. };