quality_controller.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 QualityController 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: 'quality',
  34. };
  35. }
  36. async tender(ctx) {
  37. try {
  38. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  39. const renderData = {
  40. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  41. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.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, 'quality', 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('quality');
  61. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('quality');
  62. await this.layout('quality/tender.ejs', renderData, 'quality/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.qualityInspection) throw '该功能已关闭';
  72. const renderData = {
  73. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  74. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.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, '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('inspection');
  94. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('inspection');
  95. await this.layout('quality/tender.ejs', renderData, 'quality/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. async member(ctx) {
  103. try {
  104. const data = JSON.parse(ctx.request.body.data);
  105. const result = await ctx.service.tenderPermission.getPartsPermission(data.tid, data.parts);
  106. ctx.body = { err: 0, msg: '', data: result };
  107. } catch (err) {
  108. ctx.log(err);
  109. ctx.ajaxErrorBody(err, '查询标段权限错误');
  110. }
  111. }
  112. async memberSave(ctx) {
  113. try {
  114. const data = JSON.parse(ctx.request.body.data);
  115. await ctx.service.tenderPermission.savePermission(data.tid, data.member, data.permissionBlock);
  116. ctx.body = { err: 0, msg: '', data: '' };
  117. } catch (err) {
  118. ctx.log(err);
  119. ctx.ajaxErrorBody(err, '保存标段权限错误');
  120. }
  121. }
  122. async auditSave(ctx) {
  123. try {
  124. if (ctx.session.sessionUser.is_admin === 0) throw '没有设置权限';
  125. const tid = parseInt(ctx.params.tid);
  126. const responseData = {
  127. err: 0, msg: '', data: null,
  128. };
  129. const tenderInfo = await ctx.service.tender.getDataById(tid);
  130. if (!tenderInfo) throw '标段不存在';
  131. const data = JSON.parse(ctx.request.body.data);
  132. if (!data.type) {
  133. throw '提交数据错误';
  134. }
  135. let uids;
  136. let auditList = [];
  137. const tenderPermissionKeys = ['quality', 'inspection', 'safe_inspection', 'safe_payment'];
  138. const tPsKeys = {
  139. quality: ['quality', 'inspection'],
  140. safe: ['safe_inspection', 'safe_payment'],
  141. };
  142. switch (data.type) {
  143. case 'add-audit':
  144. if (!data.key || !tenderPermissionKeys.includes(data.key) || !Object.keys(tPsKeys).includes(data.key)) throw '参数有误';
  145. // // 判断用户是单个还是数组
  146. uids = data.id instanceof Array ? data.id : [data.id];
  147. // // 判断该用户的组是否已加入到表中,已加入则提示无需添加
  148. const insertKeys = data.together ? tPsKeys[data.key] : [data.key];
  149. auditList = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, insertKeys);
  150. const addAidList = ctx.helper._.difference(uids, ctx.helper._.map(auditList, 'uid'));
  151. if (addAidList.length === 0) {
  152. throw '用户已存在成员管理中,无需重复添加';
  153. }
  154. const accountList = await ctx.service.projectAccount.getAllDataByCondition({ where: { id: addAidList } });
  155. const insert_members = [];
  156. for (const account of accountList) {
  157. const insert_member = { uid: account.id };
  158. for (const key of insertKeys) {
  159. insert_member[key] = ['1'];
  160. }
  161. insert_members.push(insert_member);
  162. }
  163. await ctx.service.tenderPermission.saveOnePermission(tenderInfo.id, ctx.helper._.map(accountList, 'id'), insert_members, insertKeys);
  164. responseData.data = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, insertKeys);
  165. break;
  166. case 'del-audit':
  167. if (!data.key || !tenderPermissionKeys.includes(data.key) || !Object.keys(tPsKeys).includes(data.key)) throw '参数有误';
  168. uids = data.id instanceof Array ? data.id : [data.id];
  169. if (uids.length === 0) throw '没有选择要移除的用户';
  170. const deleteKeys = data.together ? tPsKeys[data.key] : [data.key];
  171. auditList = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, deleteKeys);
  172. // 判断uids和auditList中是否有相同的uid
  173. const commonUids = ctx.helper._.intersection(uids, ctx.helper._.map(auditList, 'uid'));
  174. if (commonUids.length === 0) {
  175. throw '该用户已不在成员管理中,移除失败';
  176. }
  177. const del_members = [];
  178. for (const uid of uids) {
  179. const del_member = { uid };
  180. for (const key of deleteKeys) {
  181. del_member[key] = [];
  182. }
  183. del_members.push(del_member);
  184. }
  185. await ctx.service.tenderPermission.saveOnePermission(tenderInfo.id, uids, del_members, deleteKeys);
  186. responseData.data = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, deleteKeys);
  187. break;
  188. case 'save-permission':
  189. if (!data.key || !tenderPermissionKeys.includes(data.key)) throw '参数有误';
  190. uids = data.uid instanceof Array ? data.uid : [data.uid];
  191. await ctx.service.tenderPermission.saveOnePermission(tenderInfo.id, uids, data.members, [data.key]);
  192. break;
  193. case 'list':
  194. if (!data.key || !tenderPermissionKeys.includes(data.key)) throw '参数有误';
  195. responseData.data = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, [data.key]);
  196. break;
  197. default: throw '参数有误';
  198. }
  199. ctx.body = responseData;
  200. } catch (err) {
  201. this.log(err);
  202. ctx.body = { err: 1, msg: err.toString(), data: null };
  203. }
  204. }
  205. async info(ctx) {
  206. try {
  207. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  208. const renderData = {
  209. thirdParty: {
  210. gxby: ctx.session.sessionProject.gxby_status,
  211. dagl: ctx.session.sessionProject.dagl_status,
  212. },
  213. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.info),
  214. };
  215. await this.layout('quality/info.ejs', renderData, 'quality/info_modal.ejs');
  216. } catch (err) {
  217. ctx.log(err);
  218. ctx.postError(err, '无法查看质量管理数据');
  219. ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
  220. }
  221. }
  222. async flaw(ctx) {
  223. try {
  224. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  225. const renderData = {
  226. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.flaw),
  227. };
  228. await this.layout('quality/flaw.ejs', renderData, 'quality/flaw_modal.ejs');
  229. } catch (err) {
  230. ctx.log(err);
  231. ctx.postError(err, '无法查看质量管理数据');
  232. ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
  233. }
  234. }
  235. async lab(ctx) {
  236. try {
  237. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  238. const renderData = {
  239. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.lab),
  240. };
  241. await this.layout('quality/lab.ejs', renderData, 'quality/lab_modal.ejs');
  242. } catch (err) {
  243. ctx.log(err);
  244. ctx.postError(err, '无法查看质量管理数据');
  245. ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
  246. }
  247. }
  248. async _loadXmjData(spec) {
  249. const xmj = await this.ctx.service.ledger.getAllDataByCondition({
  250. where: { tender_id: this.ctx.tender.id },
  251. columns: ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name'],
  252. });
  253. // const quality = spec && spec.loadStatus ? await this.ctx.service.quality.getAllDataByCondition({
  254. // where: { tid: this.ctx.tender.id, rela_type: 'xmj' },
  255. // columns: ['rela_id', 'gxby_status', 'gxby_date', 'dagl_status'],
  256. // }) : [];
  257. // this.ctx.helper.assignRelaData(xmj, [
  258. // { data: quality, fields: ['gxby_status', 'gxby_date', 'dagl_status'], prefix: '', relaId: 'rela_id' },
  259. // ]);
  260. return xmj; // .filter(x => { return !x.b_code; });
  261. }
  262. async _loadPosData(condition, spec) {
  263. const pos = await this.ctx.service.pos.getAllDataByCondition({
  264. where: condition,
  265. columns: ['id', 'tid', 'lid', 'name'],
  266. orders: [['porder', 'ASC']],
  267. });
  268. // const quality = spec && spec.loadStatus ? await this.ctx.service.quality.getAllDataByCondition({
  269. // where: { tid: this.ctx.tender.id, rela_type: 'pos' },
  270. // columns: ['rela_id', 'gxby_status', 'gxby_date', 'dagl_status'],
  271. // }) : [];
  272. // this.ctx.helper.assignRelaData(pos, [
  273. // { data: quality, fields: ['gxby_status', 'gxby_date', 'dagl_status'], prefix: '', relaId: 'rela_id' },
  274. // ]);
  275. return pos;
  276. }
  277. async _loadDetailData(rela_type, rela_id, rela_name) {
  278. const result = await this.ctx.service.quality.getDataByCondition({ tid: this.ctx.tender.id, rela_type, rela_id, rela_name });
  279. if (!result) return result;
  280. await this.ctx.service.quality.loadQualityDetail(result);
  281. await this.ctx.service.quality.checkQualityStatusAndSave(result);
  282. return result;
  283. }
  284. async _loadData(type, data, result) {
  285. if (result[type]) return result[type];
  286. switch (type) {
  287. case 'xmj':
  288. return this._loadXmjData(data.spec);
  289. case 'pos':
  290. return this._loadPosData({ tid: this.ctx.tender.id }, data.spec);
  291. case 'detail':
  292. if (!data.rela_id && !data.rela_type) throw '缺少参数';
  293. return this._loadDetailData(data.rela_type, data.rela_id, data.rela_name);
  294. case 'quality':
  295. return await this.ctx.service.quality.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
  296. case 'lab':
  297. return await this.ctx.service.qualityLab.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
  298. default: throw '未知数据类型';
  299. }
  300. }
  301. async _load(data) {
  302. if (!data.filter) throw '参数错误';
  303. const filter = data.filter.split(';');
  304. const result = {};
  305. for (const f of filter) {
  306. result[f] = await this._loadData(f, data, result);
  307. }
  308. return result;
  309. }
  310. async load(ctx) {
  311. try {
  312. const data = JSON.parse(ctx.request.body.data);
  313. const result = await this._load(data);
  314. ctx.body = { err: 0, msg: '', data: result };
  315. } catch (err) {
  316. ctx.log(err);
  317. ctx.ajaxErrorBody(err, '获取数据错误');
  318. }
  319. }
  320. async _saveKaigong(ctx, data) {
  321. if (data.add) {
  322. if (!ctx.permission.quality.add) throw '您无权新增开工';
  323. await ctx.service.quality.kaigong(data, data.add.name, data.add.date);
  324. } else if (data.update) {
  325. await ctx.service.quality.kaigong(data, data.update.name, data.update.date);
  326. } else if (data.del) {
  327. await ctx.service.quality.delKaigong(data);
  328. }
  329. }
  330. async _saveGongxu(ctx, data) {
  331. if (data.add) {
  332. if (!ctx.permission.quality.add) throw '您无权新增工序';
  333. await ctx.service.qualityGongxu.add(data, data.add.name);
  334. } else if (data.update) {
  335. await ctx.service.qualityGongxu.update(data.update.id, data.update.name);
  336. } else if (data.del) {
  337. await ctx.service.qualityGongxu.del(data.del);
  338. }
  339. }
  340. async _saveYinbi(ctx, data) {
  341. if (data.add) {
  342. if (!ctx.permission.quality.add) throw '您无权新增隐蔽工程';
  343. await ctx.service.qualityYinbi.add(data, data.add);
  344. } else if (data.update) {
  345. await ctx.service.qualityYinbi.update(data.update.id, data.update);
  346. } else if (data.del) {
  347. await ctx.service.qualityYinbi.del(data.del);
  348. }
  349. }
  350. async save(ctx) {
  351. try {
  352. const data = JSON.parse(ctx.request.body.data);
  353. if (!data.quality_id && (!data.rela_type && !data.rela_id)) throw '参数错误';
  354. switch (ctx.params.type) {
  355. case 'kaigong':
  356. await this._saveKaigong(ctx, data);
  357. break;
  358. case 'gongxu':
  359. await this._saveGongxu(ctx, data);
  360. break;
  361. case 'yinbi':
  362. await this._saveYinbi(ctx, data);
  363. break;
  364. default: throw '请求错误';
  365. }
  366. const quality = await this._loadDetailData(data.rela_type, data.rela_id, data.rela_name);
  367. ctx.body = { err: 0, msg: '', data: quality };
  368. } catch (err) {
  369. ctx.log(err);
  370. ctx.ajaxErrorBody(err, '保存数据错误');
  371. }
  372. }
  373. async checkCanUpload(ctx) {
  374. if (!ctx.permission.quality.upload) {
  375. throw '您无权上传、删除文件';
  376. }
  377. }
  378. async uploadFile(ctx) {
  379. let stream;
  380. try {
  381. await this.checkCanUpload(ctx);
  382. const parts = ctx.multipart({ autoFields: true });
  383. let index = 0;
  384. const create_time = Date.parse(new Date()) / 1000;
  385. let stream = await parts();
  386. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  387. const quality = await ctx.service.quality.getDataById(parts.field.quality_id);
  388. if (!quality) throw '工程未开工';
  389. const blockType = parts.field.block_type;
  390. const blockId = parts.field.block_id || '';
  391. const specType = parts.field.spec_type || '';
  392. if (!blockType) throw '参数错误';
  393. const uploadfiles = [];
  394. while (stream !== undefined) {
  395. if (!stream.filename) throw '未发现上传文件!';
  396. const fileInfo = path.parse(stream.filename);
  397. const filepath = `${ctx.session.sessionProject.id}/${ctx.tender.id}/quality/${blockType}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  398. // 保存文件
  399. await ctx.fujianOss.put(ctx.fujianOssPath + filepath, stream);
  400. await sendToWormhole(stream);
  401. // 插入到stage_pay对应的附件列表中
  402. uploadfiles.push({
  403. filename: fileInfo.name,
  404. fileext: fileInfo.ext,
  405. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  406. filepath,
  407. });
  408. ++index;
  409. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  410. stream = await parts();
  411. } else {
  412. stream = undefined;
  413. }
  414. }
  415. const result = await ctx.service.qualityFile.addFiles(user, quality, uploadfiles, blockType, blockId, specType);
  416. ctx.body = { err: 0, msg: '', data: result };
  417. } catch (error) {
  418. ctx.log(error);
  419. // 失败需要消耗掉stream 以防卡死
  420. if (stream) await sendToWormhole(stream);
  421. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  422. }
  423. }
  424. async delFile(ctx) {
  425. try {
  426. const data = JSON.parse(ctx.request.body.data);
  427. if (!data.del) throw '缺少参数';
  428. const result = await ctx.service.qualityFile.delFiles(data.del);
  429. ctx.body = { err: 0, msg: '', data: result };
  430. } catch (error) {
  431. this.log(error);
  432. ctx.ajaxErrorBody(error, '删除附件失败');
  433. }
  434. }
  435. async saveFile(ctx) {
  436. try {
  437. const data = JSON.parse(ctx.request.body.data);
  438. if (!data.id) throw '缺少参数';
  439. const result = await ctx.service.file.qualityFile(data.id, data.filename);
  440. ctx.body = { err: 0, msg: '', data: result };
  441. } catch (error) {
  442. this.log(error);
  443. ctx.ajaxErrorBody(error, '编辑附件失败');
  444. }
  445. }
  446. async rule(ctx) {
  447. try {
  448. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  449. const ruleGroups = await ctx.service.qualityRule.getRuleGroups(ctx.subProject.id);
  450. const tenderList = await ctx.service.tender.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  451. const renderData = {
  452. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.rule),
  453. ruleGroups,
  454. thirdParty: {
  455. gxby: ctx.session.sessionProject.gxby_status,
  456. dagl: ctx.session.sessionProject.dagl_status,
  457. },
  458. tenderList,
  459. };
  460. await this.layout('quality/rule.ejs', renderData, 'quality/rule_modal.ejs');
  461. } catch (err) {
  462. ctx.log(err);
  463. ctx.postError(err, '无法查看质量管理数据');
  464. ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
  465. }
  466. }
  467. async ruleSave(ctx) {
  468. try {
  469. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  470. const data = JSON.parse(ctx.request.body.data);
  471. if (!data.group && !data.rule && !data.quality) throw '参数错误';
  472. if (data.group) {
  473. const result = await ctx.service.qualityRule.saveGroup(data.group);
  474. ctx.body = { err: 0, msg: '', data: result };
  475. } else if (data.rule) {
  476. const result = await ctx.service.qualityRule.saveRule(data.rule);
  477. ctx.body = { err: 0, msg: '', data: result };
  478. } else if (data.quality) {
  479. const result = await ctx.service.quality.saveQualityManage(this.ctx.tender.id, data.quality);
  480. ctx.body = { err: 0, msg: '', data: result };
  481. }
  482. } catch (err) {
  483. ctx.log(err);
  484. ctx.ajaxErrorBody(err, '保存状态推送规则错误');
  485. }
  486. }
  487. async _pushIncStatus(select) {
  488. // todo 向其他系统推送
  489. return await this.ctx.service.quality.pushIncStatus(select);
  490. }
  491. async _pushAllStatus(select) {
  492. // todo 向其他系统推送
  493. return await this.ctx.service.quality.pushAllStatus(select);
  494. }
  495. async pushStatus(ctx) {
  496. try {
  497. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  498. const data = JSON.parse(ctx.request.body.data);
  499. if (!data.push_type) throw '参数错误';
  500. let count;
  501. switch (data.push_type) {
  502. case 'inc':
  503. count = await this._pushIncStatus(data.select);
  504. break;
  505. case 'all':
  506. count = await this._pushAllStatus();
  507. break;
  508. default: throw '参数错误';
  509. }
  510. ctx.body = { err: 0, msg: '', data: count };
  511. } catch (err) {
  512. ctx.log(err);
  513. ctx.ajaxErrorBody(err, '推送失败');
  514. }
  515. }
  516. async _forceRefreshStatus() {
  517. const qualities = await this.ctx.service.quality.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
  518. for (const q of qualities) {
  519. await this.ctx.service.quality.loadQualityDetail(q);
  520. await this.ctx.service.quality.checkQualityStatusAndSave(q);
  521. }
  522. }
  523. async force(ctx) {
  524. try {
  525. if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
  526. const data = JSON.parse(ctx.request.body.data);
  527. if (!data.type) throw '参数错误';
  528. switch (data.type) {
  529. case 'all':
  530. await this._forceRefreshStatus();
  531. break;
  532. default: throw '参数错误';
  533. }
  534. const result = data.load ? this._load(data.load) : {};
  535. ctx.body = { err: 0, msg: '', data: result };
  536. } catch (err) {
  537. console.log(err);
  538. ctx.log(err);
  539. ctx.ajaxErrorBody(err, '操作失败');
  540. }
  541. }
  542. /**
  543. * 变更管理 页面 (Get)
  544. *
  545. * @param {Object} ctx - egg全局变量
  546. * @return {void}
  547. */
  548. async inspection(ctx) {
  549. try {
  550. if (!ctx.subProject.page_show.qualityInspection) throw '该功能已关闭';
  551. const status = parseInt(ctx.query.status) || 0;
  552. await this._filterInspection(ctx, status);
  553. } catch (err) {
  554. ctx.log(err);
  555. ctx.postError(err, '无法查看质量管理数据');
  556. ctx.redirect(`/sp/${ctx.subProject.id}/quality/tender`);
  557. }
  558. }
  559. // 质量巡检单功能
  560. async _filterInspection(ctx, status = 0) {
  561. try {
  562. ctx.session.sessionUser.tenderId = ctx.tender.id;
  563. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  564. const orders = ctx.query.order ? ctx.query.order : 0;
  565. const filter = JSON.parse(JSON.stringify(auditConst.inspection.filter));
  566. filter.count = [];
  567. filter.count[filter.status.pending] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.pending);
  568. filter.count[filter.status.uncheck] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.uncheck);
  569. filter.count[filter.status.checking] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.checking);
  570. filter.count[filter.status.rectification] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.rectification);
  571. filter.count[filter.status.checked] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.checked);
  572. filter.count[filter.status.checkStop] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.checkStop);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  573. const inspectionList = await ctx.service.qualityInspection.getListByStatus(ctx.tender.id, status, 1, sorts, orders);
  574. const total = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, status);
  575. const allAttList = inspectionList.length > 0 ? await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.helper._.map(inspectionList, 'id')) : [];
  576. for (const c of inspectionList) {
  577. c.attList = ctx.helper._.filter(allAttList, { qiid: c.id });
  578. c.curAuditors = await ctx.service.qualityInspectionAudit.getAuditorsByStatus(c.id, c.status, c.times);
  579. if (c.status === auditConst.inspection.status.checkNoPre) {
  580. c.curAuditors2 = await ctx.service.qualityInspectionAudit.getAuditorsByStatus(c.id, auditConst.inspection.status.checking, c.times);
  581. }
  582. }
  583. // 分页相关
  584. const page = ctx.page;
  585. const pageSize = ctx.pageSize;
  586. const pageInfo = {
  587. page,
  588. pageSizeSelect: 1,
  589. pageSize,
  590. total_num: total,
  591. total: Math.ceil(total / pageSize),
  592. queryData: JSON.stringify(ctx.urlInfo.query),
  593. };
  594. let codeRule = [];
  595. let c_connector = '1';
  596. let c_rule_first = 1;
  597. const rule_type = 'inspection';
  598. const tender = await this.service.tender.getDataById(ctx.tender.id);
  599. if (tender.c_code_rules) {
  600. const c_code_rules = JSON.parse(tender.c_code_rules);
  601. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  602. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  603. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  604. }
  605. for (const rule of codeRule) {
  606. switch (rule.rule_type) {
  607. case codeRuleConst.measure.ruleType.dealCode:
  608. rule.preview = ctx.tender.info.deal_info.dealCode;
  609. break;
  610. case codeRuleConst.measure.ruleType.tenderName:
  611. rule.preview = tender.name;
  612. break;
  613. case codeRuleConst.measure.ruleType.inDate:
  614. rule.preview = moment().format('YYYY');
  615. break;
  616. case codeRuleConst.measure.ruleType.text:
  617. rule.preview = rule.text;
  618. break;
  619. case codeRuleConst.measure.ruleType.addNo:
  620. const s = '0000000000';
  621. rule.preview = s.substr(s.length - rule.format);
  622. break;
  623. default: break;
  624. }
  625. }
  626. const renderData = {
  627. moment,
  628. tender,
  629. permission: ctx.permission.inspection,
  630. rule_type,
  631. codeRule,
  632. dealCode: ctx.tender.info.deal_info.dealCode,
  633. c_connector,
  634. c_rule_first,
  635. ruleType: codeRuleConst.ruleType[rule_type],
  636. ruleConst: codeRuleConst.measure,
  637. filter,
  638. inspectionList,
  639. auditType,
  640. auditConst: auditConst.inspection,
  641. status,
  642. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.inspection),
  643. pageInfo,
  644. };
  645. await this.layout('quality/inspection.ejs', renderData, 'quality/inspection_modal.ejs');
  646. } catch (err) {
  647. ctx.log(err);
  648. ctx.postError(err, '无法查看质量巡检数据');
  649. ctx.redirect(`/sp/${ctx.subProject.id}/quality/inspection`);
  650. }
  651. }
  652. /**
  653. * 新增变更申请 (Post)
  654. *
  655. * @param {Object} ctx - egg全局变量
  656. * @return {void}
  657. */
  658. async inspectionSave(ctx) {
  659. try {
  660. const data = JSON.parse(ctx.request.body.data);
  661. const reponseData = {
  662. err: 0, msg: '', data: {},
  663. };
  664. switch (data.type) {
  665. case 'add':
  666. if (!data.code || data.code === '') {
  667. throw '编号不能为空';
  668. }
  669. if (!data.check_item || !data.check_date) {
  670. throw '请填写检查项和日期';
  671. }
  672. reponseData.data = await ctx.service.qualityInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
  673. break;
  674. default:throw '参数有误';
  675. }
  676. ctx.body = reponseData;
  677. } catch (err) {
  678. this.log(err);
  679. ctx.body = { err: 1, msg: err.toString() };
  680. }
  681. }
  682. /**
  683. * 获取审批界面所需的 原报、审批人数据等
  684. * @param ctx
  685. * @return {Promise<void>}
  686. * @private
  687. */
  688. async _getInspectionAuditViewData(ctx) {
  689. await ctx.service.qualityInspection.loadAuditViewData(ctx.inspection);
  690. }
  691. async inspectionInformation(ctx) {
  692. try {
  693. const whiteList = this.ctx.app.config.multipart.whitelist;
  694. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  695. await this._getInspectionAuditViewData(ctx);
  696. // 获取附件列表
  697. const fileList = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  698. // 获取用户人验证手机号
  699. const renderData = {
  700. moment,
  701. tender,
  702. inspection: ctx.inspection,
  703. auditConst: auditConst.inspection,
  704. fileList,
  705. whiteList,
  706. auditType,
  707. shenpiConst,
  708. deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
  709. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.inspection_information),
  710. preUrl: `/sp/${ctx.subProject.id}/quality/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
  711. };
  712. // data.accountGroup = accountGroup;
  713. // 获取所有项目参与者
  714. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  715. renderData.accountList = accountList;
  716. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  717. renderData.accountGroup = unitList.map(item => {
  718. const groupList = accountList.filter(item1 => item1.company === item.name);
  719. return { groupName: item.name, groupList };
  720. }).filter(x => { return x.groupList.length > 0; });
  721. await this.layout('quality/inspection_information.ejs', renderData, 'quality/inspection_information_modal.ejs');
  722. } catch (err) {
  723. this.log(err);
  724. ctx.redirect(`/sp/${ctx.subProject.id}/quality/tender/${ctx.tender.id}/inspection`);
  725. }
  726. }
  727. async inspectionInformationSave(ctx) {
  728. try {
  729. const data = JSON.parse(ctx.request.body.data);
  730. const reponseData = {
  731. err: 0, msg: '', data: {},
  732. };
  733. switch (data.type) {
  734. case 'update-field':
  735. if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
  736. throw '当前状态不可修改';
  737. }
  738. if (data.update.check_item !== undefined && data.update.check_item === '') {
  739. throw '检查项不能为空';
  740. }
  741. if (data.update.check_date !== undefined && data.update.check_date === '') {
  742. throw '请填写检查日期';
  743. }
  744. if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
  745. throw '整改情况不能为空';
  746. }
  747. if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
  748. throw '请填写整改日期';
  749. }
  750. const fields = ['id', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
  751. if (!this.checkFieldExists(data.update, fields)) {
  752. throw '参数有误';
  753. }
  754. reponseData.data = await ctx.service.qualityInspection.defaultUpdate(data.update);
  755. break;
  756. case 'add-audit':
  757. const id = this.app._.toInteger(data.auditorId);
  758. if (isNaN(id) || id <= 0) {
  759. throw '参数错误';
  760. }
  761. // 检查权限等
  762. if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
  763. throw '您无权添加审核人';
  764. }
  765. if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
  766. throw '当前不允许添加审核人';
  767. }
  768. ctx.inspection.auditorList = await ctx.service.qualityInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  769. // 检查审核人是否已存在
  770. const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
  771. if (exist) {
  772. throw '该审核人已存在,请勿重复添加';
  773. }
  774. const result = await ctx.service.qualityInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times);
  775. if (!result) {
  776. throw '添加审核人失败';
  777. }
  778. reponseData.data = await ctx.service.qualityInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  779. break;
  780. case 'del-audit':
  781. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  782. if (isNaN(id2) || id2 <= 0) {
  783. throw '参数错误';
  784. }
  785. const result2 = await ctx.service.qualityInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  786. if (!result2) {
  787. throw '移除审核人失败';
  788. }
  789. reponseData.data = await ctx.service.qualityInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  790. break;
  791. case 'start-inspection':
  792. if (ctx.inspection.readOnly) {
  793. throw '当前状态不可提交';
  794. }
  795. await ctx.service.qualityInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  796. break;
  797. case 'del-inspection':
  798. if (ctx.inspection.readOnly) {
  799. throw '当前状态不可删除';
  800. }
  801. await ctx.service.qualityInspection.delInspection(ctx.inspection.id);
  802. break;
  803. case 'check':
  804. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  805. throw '当前质量巡检数据有误';
  806. }
  807. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  808. throw '您无权进行该操作';
  809. }
  810. await ctx.service.qualityInspectionAudit.check(ctx.inspection, data);
  811. break;
  812. case 'rectification':
  813. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  814. throw '当前质量巡检数据有误';
  815. }
  816. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  817. throw '您无权进行该操作';
  818. }
  819. await ctx.service.qualityInspectionAudit.rectification(ctx.inspection, data);
  820. break;
  821. default:throw '参数有误';
  822. }
  823. ctx.body = reponseData;
  824. } catch (err) {
  825. this.log(err);
  826. ctx.body = { err: 1, msg: err.toString() };
  827. }
  828. }
  829. checkFieldExists(update, fields) {
  830. for (const field of Object.keys(update)) {
  831. if (!fields.includes(field)) {
  832. return false;
  833. }
  834. }
  835. return true;
  836. }
  837. /**
  838. * 上传附件
  839. * @param {*} ctx 上下文
  840. */
  841. async uploadInspectionFile(ctx) {
  842. let stream;
  843. try {
  844. // this._checkAdvanceFileCanModify(ctx);
  845. const parts = this.ctx.multipart({
  846. autoFields: true,
  847. });
  848. const files = [];
  849. const create_time = Date.parse(new Date()) / 1000;
  850. let idx = 0;
  851. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  852. while ((stream = await parts()) !== undefined) {
  853. if (!stream.filename) {
  854. // 如果没有传入直接返回
  855. return;
  856. }
  857. const fileInfo = path.parse(stream.filename);
  858. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/quality_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  859. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  860. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  861. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  862. ++idx;
  863. stream && (await sendToWormhole(stream));
  864. }
  865. const in_time = new Date();
  866. const payload = files.map(file => {
  867. let idx;
  868. if (Array.isArray(parts.field.name)) {
  869. idx = parts.field.name.findIndex(name => name === file.name);
  870. } else {
  871. idx = 'isString';
  872. }
  873. const newFile = {
  874. tid: ctx.tender.id,
  875. qiid: ctx.inspection.id,
  876. uid: ctx.session.sessionUser.accountId,
  877. filename: file.name,
  878. fileext: file.ext,
  879. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  880. filepath: file.filepath,
  881. upload_time: in_time,
  882. extra_upload,
  883. };
  884. return newFile;
  885. });
  886. // 执行文件信息写入数据库
  887. await ctx.service.qualityInspectionAtt.saveFileMsgToDb(payload);
  888. // 将最新的当前标段的所有文件信息返回
  889. const data = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  890. ctx.body = { err: 0, msg: '', data };
  891. } catch (err) {
  892. stream && (await sendToWormhole(stream));
  893. this.log(err);
  894. ctx.body = { err: 1, msg: err.toString(), data: null };
  895. }
  896. }
  897. /**
  898. * 删除附件
  899. * @param {Ojbect} ctx 上下文
  900. */
  901. async deleteInspectionFile(ctx) {
  902. try {
  903. const { id } = JSON.parse(ctx.request.body.data);
  904. const fileInfo = await ctx.service.qualityInspectionAtt.getDataById(id);
  905. if (fileInfo || Object.keys(fileInfo).length) {
  906. // 先删除文件
  907. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  908. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  909. // 再删除数据库
  910. await ctx.service.qualityInspectionAtt.delete(id);
  911. } else {
  912. throw '不存在该文件';
  913. }
  914. const data = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  915. ctx.body = { err: 0, msg: '请求成功', data };
  916. } catch (err) {
  917. this.log(err);
  918. ctx.body = { err: 1, msg: err.toString(), data: null };
  919. }
  920. }
  921. /**
  922. * 下载附件
  923. * @param {Object} ctx - egg全局变量
  924. * @return {void}
  925. */
  926. async downloadInspectionFile(ctx) {
  927. const id = ctx.params.fid;
  928. if (id) {
  929. try {
  930. const fileInfo = await ctx.service.qualityInspectionAtt.getDataById(id);
  931. if (fileInfo !== undefined && fileInfo !== '') {
  932. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  933. // 解决中文无法下载问题
  934. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  935. let disposition = '';
  936. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  937. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  938. } else if (userAgent.indexOf('firefox') >= 0) {
  939. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  940. } else {
  941. /* safari等其他非主流浏览器只能自求多福了 */
  942. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  943. }
  944. ctx.response.set({
  945. 'Content-Type': 'application/octet-stream',
  946. 'Content-Disposition': disposition,
  947. 'Content-Length': fileInfo.filesize,
  948. });
  949. // ctx.body = await fs.createReadStream(fileName);
  950. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  951. } else {
  952. throw '不存在该文件';
  953. }
  954. } catch (err) {
  955. this.log(err);
  956. this.setMessage(err.toString(), this.messageType.ERROR);
  957. }
  958. }
  959. }
  960. }
  961. return QualityController;
  962. };