quality_controller.js 45 KB

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