quality_controller.js 45 KB

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