quality_controller.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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 item of inspectionList) {
  577. item.attList = ctx.helper._.filter(allAttList, { qiid: item.id });
  578. }
  579. // 分页相关
  580. const page = ctx.page;
  581. const pageSize = ctx.pageSize;
  582. const pageInfo = {
  583. page,
  584. pageSizeSelect: 1,
  585. pageSize,
  586. total_num: total,
  587. total: Math.ceil(total / pageSize),
  588. queryData: JSON.stringify(ctx.urlInfo.query),
  589. };
  590. let codeRule = [];
  591. let c_connector = '1';
  592. let c_rule_first = 1;
  593. const rule_type = 'inspection';
  594. const tender = await this.service.tender.getDataById(ctx.tender.id);
  595. if (tender.c_code_rules) {
  596. const c_code_rules = JSON.parse(tender.c_code_rules);
  597. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  598. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  599. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  600. }
  601. for (const rule of codeRule) {
  602. switch (rule.rule_type) {
  603. case codeRuleConst.measure.ruleType.dealCode:
  604. rule.preview = ctx.tender.info.deal_info.dealCode;
  605. break;
  606. case codeRuleConst.measure.ruleType.tenderName:
  607. rule.preview = tender.name;
  608. break;
  609. case codeRuleConst.measure.ruleType.inDate:
  610. rule.preview = moment().format('YYYY');
  611. break;
  612. case codeRuleConst.measure.ruleType.text:
  613. rule.preview = rule.text;
  614. break;
  615. case codeRuleConst.measure.ruleType.addNo:
  616. const s = '0000000000';
  617. rule.preview = s.substr(s.length - rule.format);
  618. break;
  619. default: break;
  620. }
  621. }
  622. const renderData = {
  623. moment,
  624. tender,
  625. permission: ctx.permission.inspection,
  626. rule_type,
  627. codeRule,
  628. dealCode: ctx.tender.info.deal_info.dealCode,
  629. c_connector,
  630. c_rule_first,
  631. ruleType: codeRuleConst.ruleType[rule_type],
  632. ruleConst: codeRuleConst.measure,
  633. filter,
  634. inspectionList,
  635. auditType,
  636. auditConst: auditConst.inspection,
  637. status,
  638. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.inspection),
  639. pageInfo,
  640. };
  641. await this.layout('quality/inspection.ejs', renderData, 'quality/inspection_modal.ejs');
  642. } catch (err) {
  643. ctx.log(err);
  644. ctx.postError(err, '无法查看质量管理数据');
  645. ctx.redirect(`/sp/${ctx.subProject.id}/quality/tender`);
  646. }
  647. }
  648. /**
  649. * 新增变更申请 (Post)
  650. *
  651. * @param {Object} ctx - egg全局变量
  652. * @return {void}
  653. */
  654. async inspectionSave(ctx) {
  655. try {
  656. const data = JSON.parse(ctx.request.body.data);
  657. const reponseData = {
  658. err: 0, msg: '', data: {},
  659. };
  660. switch (data.type) {
  661. case 'add':
  662. if (!data.code || data.code === '') {
  663. throw '编号不能为空';
  664. }
  665. if (!data.check_item || !data.check_date) {
  666. throw '请填写检查项和日期';
  667. }
  668. reponseData.data = await ctx.service.qualityInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
  669. break;
  670. default:throw '参数有误';
  671. }
  672. ctx.body = reponseData;
  673. } catch (err) {
  674. this.log(err);
  675. ctx.body = { err: 1, msg: err.toString() };
  676. }
  677. }
  678. /**
  679. * 获取审批界面所需的 原报、审批人数据等
  680. * @param ctx
  681. * @return {Promise<void>}
  682. * @private
  683. */
  684. async _getInspectionAuditViewData(ctx) {
  685. await ctx.service.qualityInspection.loadAuditViewData(ctx.inspection);
  686. }
  687. async inspectionInformation(ctx) {
  688. try {
  689. const whiteList = this.ctx.app.config.multipart.whitelist;
  690. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  691. await this._getInspectionAuditViewData(ctx);
  692. // 获取附件列表
  693. const fileList = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  694. // 获取用户人验证手机号
  695. const renderData = {
  696. moment,
  697. tender,
  698. inspection: ctx.inspection,
  699. auditConst: auditConst.inspection,
  700. fileList,
  701. whiteList,
  702. auditType,
  703. shenpiConst,
  704. deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
  705. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.inspection_information),
  706. preUrl: `/sp/${ctx.subProject.id}/quality/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
  707. };
  708. // data.accountGroup = accountGroup;
  709. // 获取所有项目参与者
  710. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  711. renderData.accountList = accountList;
  712. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  713. renderData.accountGroup = unitList.map(item => {
  714. const groupList = accountList.filter(item1 => item1.company === item.name);
  715. return { groupName: item.name, groupList };
  716. }).filter(x => { return x.groupList.length > 0; });
  717. await this.layout('quality/inspection_information.ejs', renderData, 'quality/inspection_information_modal.ejs');
  718. } catch (err) {
  719. this.log(err);
  720. ctx.redirect(`/sp/${ctx.subProject.id}/quality/tender/${ctx.tender.id}/inspection`);
  721. }
  722. }
  723. async inspectionInformationSave(ctx) {
  724. try {
  725. const data = JSON.parse(ctx.request.body.data);
  726. const reponseData = {
  727. err: 0, msg: '', data: {},
  728. };
  729. switch (data.type) {
  730. case 'update-field':
  731. if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
  732. throw '当前状态不可修改';
  733. }
  734. if (data.update.check_item !== undefined && data.update.check_item === '') {
  735. throw '检查项不能为空';
  736. }
  737. if (data.update.check_date !== undefined && data.update.check_date === '') {
  738. throw '请填写检查日期';
  739. }
  740. if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
  741. throw '整改情况不能为空';
  742. }
  743. if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
  744. throw '请填写整改日期';
  745. }
  746. const fields = ['id', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
  747. if (!this.checkFieldExists(data.update, fields)) {
  748. throw '参数有误';
  749. }
  750. reponseData.data = await ctx.service.qualityInspection.defaultUpdate(data.update);
  751. break;
  752. case 'add-audit':
  753. const id = this.app._.toInteger(data.auditorId);
  754. if (isNaN(id) || id <= 0) {
  755. throw '参数错误';
  756. }
  757. // 检查权限等
  758. if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
  759. throw '您无权添加审核人';
  760. }
  761. if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
  762. throw '当前不允许添加审核人';
  763. }
  764. ctx.inspection.auditorList = await ctx.service.qualityInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  765. // 检查审核人是否已存在
  766. const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
  767. if (exist) {
  768. throw '该审核人已存在,请勿重复添加';
  769. }
  770. const result = await ctx.service.qualityInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times);
  771. if (!result) {
  772. throw '添加审核人失败';
  773. }
  774. reponseData.data = await ctx.service.qualityInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  775. break;
  776. case 'del-audit':
  777. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  778. if (isNaN(id2) || id2 <= 0) {
  779. throw '参数错误';
  780. }
  781. const result2 = await ctx.service.qualityInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  782. if (!result2) {
  783. throw '移除审核人失败';
  784. }
  785. reponseData.data = await ctx.service.qualityInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  786. break;
  787. case 'start-inspection':
  788. if (ctx.inspection.readOnly) {
  789. throw '当前状态不可提交';
  790. }
  791. await ctx.service.qualityInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  792. break;
  793. case 'del-inspection':
  794. if (ctx.inspection.readOnly) {
  795. throw '当前状态不可删除';
  796. }
  797. await ctx.service.qualityInspection.delInspection(ctx.inspection.id);
  798. break;
  799. case 'check':
  800. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  801. throw '当前质量巡检数据有误';
  802. }
  803. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  804. throw '您无权进行该操作';
  805. }
  806. await ctx.service.qualityInspectionAudit.check(ctx.inspection, data);
  807. break;
  808. case 'rectification':
  809. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  810. throw '当前质量巡检数据有误';
  811. }
  812. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  813. throw '您无权进行该操作';
  814. }
  815. await ctx.service.qualityInspectionAudit.rectification(ctx.inspection, data);
  816. break;
  817. default:throw '参数有误';
  818. }
  819. ctx.body = reponseData;
  820. } catch (err) {
  821. this.log(err);
  822. ctx.body = { err: 1, msg: err.toString() };
  823. }
  824. }
  825. checkFieldExists(update, fields) {
  826. for (const field of Object.keys(update)) {
  827. if (!fields.includes(field)) {
  828. return false;
  829. }
  830. }
  831. return true;
  832. }
  833. /**
  834. * 上传附件
  835. * @param {*} ctx 上下文
  836. */
  837. async uploadInspectionFile(ctx) {
  838. let stream;
  839. try {
  840. // this._checkAdvanceFileCanModify(ctx);
  841. const parts = this.ctx.multipart({
  842. autoFields: true,
  843. });
  844. const files = [];
  845. const create_time = Date.parse(new Date()) / 1000;
  846. let idx = 0;
  847. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  848. while ((stream = await parts()) !== undefined) {
  849. if (!stream.filename) {
  850. // 如果没有传入直接返回
  851. return;
  852. }
  853. const fileInfo = path.parse(stream.filename);
  854. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/quality_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  855. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  856. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  857. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  858. ++idx;
  859. stream && (await sendToWormhole(stream));
  860. }
  861. const in_time = new Date();
  862. const payload = files.map(file => {
  863. let idx;
  864. if (Array.isArray(parts.field.name)) {
  865. idx = parts.field.name.findIndex(name => name === file.name);
  866. } else {
  867. idx = 'isString';
  868. }
  869. const newFile = {
  870. tid: ctx.tender.id,
  871. qiid: ctx.inspection.id,
  872. uid: ctx.session.sessionUser.accountId,
  873. filename: file.name,
  874. fileext: file.ext,
  875. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  876. filepath: file.filepath,
  877. upload_time: in_time,
  878. extra_upload,
  879. };
  880. return newFile;
  881. });
  882. // 执行文件信息写入数据库
  883. await ctx.service.qualityInspectionAtt.saveFileMsgToDb(payload);
  884. // 将最新的当前标段的所有文件信息返回
  885. const data = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  886. ctx.body = { err: 0, msg: '', data };
  887. } catch (err) {
  888. stream && (await sendToWormhole(stream));
  889. this.log(err);
  890. ctx.body = { err: 1, msg: err.toString(), data: null };
  891. }
  892. }
  893. /**
  894. * 删除附件
  895. * @param {Ojbect} ctx 上下文
  896. */
  897. async deleteInspectionFile(ctx) {
  898. try {
  899. const { id } = JSON.parse(ctx.request.body.data);
  900. const fileInfo = await ctx.service.qualityInspectionAtt.getDataById(id);
  901. if (fileInfo || Object.keys(fileInfo).length) {
  902. // 先删除文件
  903. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  904. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  905. // 再删除数据库
  906. await ctx.service.qualityInspectionAtt.delete(id);
  907. } else {
  908. throw '不存在该文件';
  909. }
  910. const data = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  911. ctx.body = { err: 0, msg: '请求成功', data };
  912. } catch (err) {
  913. this.log(err);
  914. ctx.body = { err: 1, msg: err.toString(), data: null };
  915. }
  916. }
  917. /**
  918. * 下载附件
  919. * @param {Object} ctx - egg全局变量
  920. * @return {void}
  921. */
  922. async downloadInspectionFile(ctx) {
  923. const id = ctx.params.fid;
  924. if (id) {
  925. try {
  926. const fileInfo = await ctx.service.qualityInspectionAtt.getDataById(id);
  927. if (fileInfo !== undefined && fileInfo !== '') {
  928. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  929. // 解决中文无法下载问题
  930. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  931. let disposition = '';
  932. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  933. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  934. } else if (userAgent.indexOf('firefox') >= 0) {
  935. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  936. } else {
  937. /* safari等其他非主流浏览器只能自求多福了 */
  938. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  939. }
  940. ctx.response.set({
  941. 'Content-Type': 'application/octet-stream',
  942. 'Content-Disposition': disposition,
  943. 'Content-Length': fileInfo.filesize,
  944. });
  945. // ctx.body = await fs.createReadStream(fileName);
  946. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  947. } else {
  948. throw '不存在该文件';
  949. }
  950. } catch (err) {
  951. this.log(err);
  952. this.setMessage(err.toString(), this.messageType.ERROR);
  953. }
  954. }
  955. }
  956. }
  957. return QualityController;
  958. };