quality_controller.js 48 KB

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