quality_controller.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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 shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.inspection, sp_status: shenpiConst.sp_status.gdzs });
  775. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.inspection === shenpiConst.sp_status.gdzs ? 1 : 0;
  776. const result = await ctx.service.qualityInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times, is_gdzs);
  777. if (!result) {
  778. throw '添加审核人失败';
  779. }
  780. reponseData.data = await ctx.service.qualityInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  781. break;
  782. case 'del-audit':
  783. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  784. if (isNaN(id2) || id2 <= 0) {
  785. throw '参数错误';
  786. }
  787. const result2 = await ctx.service.qualityInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  788. if (!result2) {
  789. throw '移除审核人失败';
  790. }
  791. reponseData.data = await ctx.service.qualityInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  792. break;
  793. case 'start-inspection':
  794. if (ctx.inspection.readOnly) {
  795. throw '当前状态不可提交';
  796. }
  797. await ctx.service.qualityInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  798. break;
  799. case 'del-inspection':
  800. if (ctx.inspection.readOnly) {
  801. throw '当前状态不可删除';
  802. }
  803. await ctx.service.qualityInspection.delInspection(ctx.inspection.id);
  804. break;
  805. case 'check':
  806. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  807. throw '当前质量巡检数据有误';
  808. }
  809. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  810. throw '您无权进行该操作';
  811. }
  812. await ctx.service.qualityInspectionAudit.check(ctx.inspection, data);
  813. break;
  814. case 'rectification':
  815. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  816. throw '当前质量巡检数据有误';
  817. }
  818. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  819. throw '您无权进行该操作';
  820. }
  821. await ctx.service.qualityInspectionAudit.rectification(ctx.inspection, data);
  822. break;
  823. default:throw '参数有误';
  824. }
  825. ctx.body = reponseData;
  826. } catch (err) {
  827. this.log(err);
  828. ctx.body = { err: 1, msg: err.toString() };
  829. }
  830. }
  831. checkFieldExists(update, fields) {
  832. for (const field of Object.keys(update)) {
  833. if (!fields.includes(field)) {
  834. return false;
  835. }
  836. }
  837. return true;
  838. }
  839. /**
  840. * 上传附件
  841. * @param {*} ctx 上下文
  842. */
  843. async uploadInspectionFile(ctx) {
  844. let stream;
  845. try {
  846. // this._checkAdvanceFileCanModify(ctx);
  847. const parts = this.ctx.multipart({
  848. autoFields: true,
  849. });
  850. const files = [];
  851. const create_time = Date.parse(new Date()) / 1000;
  852. let idx = 0;
  853. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  854. while ((stream = await parts()) !== undefined) {
  855. if (!stream.filename) {
  856. // 如果没有传入直接返回
  857. return;
  858. }
  859. const fileInfo = path.parse(stream.filename);
  860. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/quality_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  861. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  862. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  863. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  864. ++idx;
  865. stream && (await sendToWormhole(stream));
  866. }
  867. const in_time = new Date();
  868. const payload = files.map(file => {
  869. let idx;
  870. if (Array.isArray(parts.field.name)) {
  871. idx = parts.field.name.findIndex(name => name === file.name);
  872. } else {
  873. idx = 'isString';
  874. }
  875. const newFile = {
  876. tid: ctx.tender.id,
  877. qiid: ctx.inspection.id,
  878. uid: ctx.session.sessionUser.accountId,
  879. filename: file.name,
  880. fileext: file.ext,
  881. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  882. filepath: file.filepath,
  883. upload_time: in_time,
  884. extra_upload,
  885. };
  886. return newFile;
  887. });
  888. // 执行文件信息写入数据库
  889. await ctx.service.qualityInspectionAtt.saveFileMsgToDb(payload);
  890. // 将最新的当前标段的所有文件信息返回
  891. const data = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  892. ctx.body = { err: 0, msg: '', data };
  893. } catch (err) {
  894. stream && (await sendToWormhole(stream));
  895. this.log(err);
  896. ctx.body = { err: 1, msg: err.toString(), data: null };
  897. }
  898. }
  899. /**
  900. * 删除附件
  901. * @param {Ojbect} ctx 上下文
  902. */
  903. async deleteInspectionFile(ctx) {
  904. try {
  905. const { id } = JSON.parse(ctx.request.body.data);
  906. const fileInfo = await ctx.service.qualityInspectionAtt.getDataById(id);
  907. if (fileInfo || Object.keys(fileInfo).length) {
  908. // 先删除文件
  909. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  910. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  911. // 再删除数据库
  912. await ctx.service.qualityInspectionAtt.delete(id);
  913. } else {
  914. throw '不存在该文件';
  915. }
  916. const data = await ctx.service.qualityInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  917. ctx.body = { err: 0, msg: '请求成功', data };
  918. } catch (err) {
  919. this.log(err);
  920. ctx.body = { err: 1, msg: err.toString(), data: null };
  921. }
  922. }
  923. /**
  924. * 下载附件
  925. * @param {Object} ctx - egg全局变量
  926. * @return {void}
  927. */
  928. async downloadInspectionFile(ctx) {
  929. const id = ctx.params.fid;
  930. if (id) {
  931. try {
  932. const fileInfo = await ctx.service.qualityInspectionAtt.getDataById(id);
  933. if (fileInfo !== undefined && fileInfo !== '') {
  934. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  935. // 解决中文无法下载问题
  936. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  937. let disposition = '';
  938. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  939. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  940. } else if (userAgent.indexOf('firefox') >= 0) {
  941. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  942. } else {
  943. /* safari等其他非主流浏览器只能自求多福了 */
  944. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  945. }
  946. ctx.response.set({
  947. 'Content-Type': 'application/octet-stream',
  948. 'Content-Disposition': disposition,
  949. 'Content-Length': fileInfo.filesize,
  950. });
  951. // ctx.body = await fs.createReadStream(fileName);
  952. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  953. } else {
  954. throw '不存在该文件';
  955. }
  956. } catch (err) {
  957. this.log(err);
  958. this.setMessage(err.toString(), this.messageType.ERROR);
  959. }
  960. }
  961. }
  962. }
  963. return QualityController;
  964. };