quality_controller.js 48 KB

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