'use strict'; /** * * * @author Mai * @date 2021/10/27 * @version */ const auditConst = require('../const/audit'); const sendToWormhole = require('stream-wormhole'); const path = require('path'); const advanceConst = require('../const/advance'); module.exports = app => { class BudgetController extends app.BaseController { /** * 概算投资 * * @param ctx * @returns {Promise} */ async index(ctx) { try { if (!ctx.session.sessionProject.page_show.openFile) { throw '该功能已关闭或无法查看'; } const renderData = { jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.index), auditConst, }; renderData.projectList = await ctx.service.subProject.getFileProject(ctx.session.sessionProject.id, ctx.session.sessionUser.accountId, ctx.session.sessionUser.is_admin); for (const p of renderData.projectList) { if (!p.is_folder) p.file_count = await this.service.filing.sumFileCount(p.id); } renderData.tenderList = await ctx.service.tender.getList4Select('stage'); renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.session.sessionProject.id); await this.layout('file/index.ejs', renderData, 'file/modal.ejs'); } catch (err) { ctx.log(err); ctx.session.postError = err.toString(); ctx.redirect(this.menu.menu.dashboard.url); } } async file(ctx) { try { const renderData = { jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.file), }; renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type); renderData.categoryData = await ctx.service.category.getAllCategory(ctx.session.sessionProject.id); renderData.canFiling = ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.filing.value) >= 0; renderData.canUpload = ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.upload.value) >= 0; renderData.filingTypes = ctx.service.filing.analysisFilingType(renderData.filing); await this.layout('file/file.ejs', renderData, 'file/file_modal.ejs'); } catch (err) { ctx.log(err); } } async getFilingTypePermission(ctx) { try { if (ctx.subProject.project_id !== this.ctx.session.sessionProject.id) throw '您无权操作该数据'; const filingType = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id); ctx.body = { err: 0, msg: '', data: filingType }; } catch(err) { ctx.log(err); ctx.ajaxErrorBody(err, '获取授权用户数据错误'); } } async saveFilingTypePermission(ctx) { try { const data = JSON.parse(ctx.request.body.data); await ctx.service.subProjPermission.saveFilingType(data); ctx.body = { err: 0, msg: '', data: '' }; } catch(err) { ctx.log(err); ctx.ajaxErrorBody(err, '保存授权用户信息错误'); } } async addFiling(ctx) { try { const data = JSON.parse(ctx.request.body.data); const result = await ctx.service.filing.add(data); ctx.body = { err: 0, msg: '', data: result }; } catch (err) { ctx.log(err); ctx.ajaxErrorBody(err, '新增分类失败'); } } async delFiling(ctx) { try { const data = JSON.parse(ctx.request.body.data); const result = await ctx.service.filing.del(data); ctx.body = { err: 0, msg: '', data: result }; } catch (err) { ctx.log(err); ctx.ajaxErrorBody(err, '删除分类失败'); } } async saveFiling(ctx) { try { const data = JSON.parse(ctx.request.body.data); const result = await ctx.service.filing.save(data); ctx.body = { err: 0, msg: '', data: result }; } catch (err) { ctx.log(err); ctx.ajaxErrorBody(err, '保存分类数据失败'); } } async moveFiling(ctx) { try { const data = JSON.parse(ctx.request.body.data); if (!data.id || !(data.tree_order >= 0)) throw '数据错误'; const result = await ctx.service.filing.move(data); ctx.body = { err: 0, msg: '', data: result }; } catch (err) { ctx.log(err); ctx.ajaxErrorBody(err, '移动分类失败'); } } async loadFile(ctx) { try { const data = JSON.parse(ctx.request.body.data); const order = data.order.split('|'); if (order.length !== 2) throw '加载文件错误'; if (order[0] !== 'filename' && order[0] !== 'create_time') throw '加载文件错误'; if (order[1] !== 'asc' && order[1] !== 'desc') throw '加载文件错误'; const result = await ctx.service.file.getFiles({ where: { filing_id: data.filing_id, is_deleted: 0 }, orders: [order], limit: data.count, offset: (data.page-1)*data.count, }, order); ctx.body = { err: 0, msg: '', data: result }; } catch (err) { ctx.log(err); ctx.ajaxErrorBody(err, '加载文件失败'); } } async checkCanUpload(ctx) { if (ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.upload.value) < 0) { throw '您无权上传、导入、删除文件'; } } async checkFiling(filing) { const child = await this.ctx.service.filing.getDataByCondition({ tree_pid: filing.id, is_deleted: 0 }); if (child) throw '该分类下存在子分类,请在子分类下上传、导入文件'; } async checkFiles(ctx) { try{ const data = JSON.parse(ctx.request.body.data); if (!data.filing_id || !data.files) throw '缺少参数'; const result = await ctx.service.file.checkFiles(data.filing_id, data.files); ctx.body = { err: 0, msg: '', data: result }; } catch(error) { this.log(error); ctx.ajaxErrorBody(error, '检查附件错误'); } } async uploadFile(ctx){ let stream; try { await this.checkCanUpload(ctx); const parts = ctx.multipart({ autoFields: true }); let index = 0; const create_time = Date.parse(new Date()) / 1000; let stream = await parts(); const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId); const filing = await ctx.service.filing.getDataById(parts.field.filing_id); if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试'; await this.checkFiling(filing); const uploadfiles = []; while (stream !== undefined) { if (!stream.filename) throw '未发现上传文件!'; const fileInfo = path.parse(stream.filename); const filepath = `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`; // 保存文件 await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream); await sendToWormhole(stream); // 插入到stage_pay对应的附件列表中 uploadfiles.push({ filename: fileInfo.name, fileext: fileInfo.ext, filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size, filepath, }); ++index; if (Array.isArray(parts.field.size) && index < parts.field.size.length) { stream = await parts(); } else { stream = undefined; } } const result = await ctx.service.file.addFiles(filing, uploadfiles, user); ctx.body = {err: 0, msg: '', data: result }; } catch (error) { ctx.helper.log(error); // 失败需要消耗掉stream 以防卡死 if (stream) await sendToWormhole(stream); ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试'); } } async delFile(ctx) { try{ const data = JSON.parse(ctx.request.body.data); if (!data.del) throw '缺少参数'; const result = await ctx.service.file.delFiles(data.del); ctx.body = { err: 0, msg: '', data: result }; } catch(error) { this.log(error); ctx.ajaxErrorBody(error, '删除附件失败'); } } async saveFile(ctx) { try { const data = JSON.parse(ctx.request.body.data); if (!data.id) throw '缺少参数'; const result = await ctx.service.file.saveFile(data.id, data.filename); ctx.body = { err: 0, msg: '', data: result }; } catch (error) { this.log(error); ctx.ajaxErrorBody(error, '编辑附件失败'); } } async uploadBigFile(ctx) { try { await this.checkCanUpload(ctx); const data = JSON.parse(ctx.request.body.data); if (!data.type || !data.filing_id || !data.fileInfo) throw '缺少参数'; const filing = await ctx.service.filing.getDataById(data.filing_id); if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试'; let result; const fileInfo = path.parse(data.fileInfo.filename); switch(data.type) { case 'begin': const create_time = Date.parse(new Date()) / 1000; result = { filename: `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + fileInfo.ext}`, }; result.filepath = ctx.app.config.fujianOssFolder + result.filename; // todo 写入ossToken result.oss = await ctx.helper.getOssToken(ctx.app.fujianOss); break; case 'end': const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId); const uploadFiles = [{ filepath: data.filepath, filename: fileInfo.name, fileext: fileInfo.ext, filesize: data.fileInfo.filesize, }]; result = await ctx.service.file.addFiles(filing, uploadFiles, user); break; } ctx.body = {err: 0, msg: '', data: result }; } catch (error) { ctx.log(error); ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试'); } } async loadValidRelaTender(ctx) { try { const data = JSON.parse(ctx.request.body.data); if (data.type) throw '参数错误'; const accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId); const userPermission = accountInfo !== undefined && accountInfo.permission !== '' ? JSON.parse(accountInfo.permission) : null; const tenderList = await ctx.service.tender.getList('', userPermission, ctx.session.sessionUser.is_admin); const rela_tender = await ctx.subProject.rela_tender.split(','); const result = tenderList.filter(x => { return rela_tender.indexOf(x.id + '') >= 0}); for (const r of result) { r.advance = await ctx.service.advance.getAllDataByCondition({ columns: ['id', 'order', 'type'], where: { tid: r.id }}); r.advance.forEach(a => { const type = advanceConst.typeCol.find(x => { return x.type === a.type }); if (type) a.type_str = type.name; }); r.stage = await ctx.service.stage.getAllDataByCondition({ columns: ['id', 'order'], where: { tid: r.id, status: auditConst.stage.status.checked } }); } ctx.body = {err: 0, msg: '', data: result }; } catch (error) { ctx.helper.log(error); ctx.body = this.ajaxErrorBody(error, '加载标段信息失败'); } } async _loadLedgerAtt(data) { if (!data.tender_id) throw '参数错误'; return await this.ctx.service.ledgerAtt.getAllDataByCondition({ where: { tid: data.tender_id }, order: [['id', 'desc']]}); } async _loadStageAtt(data) { if (!data.tender_id || !data.stage) throw '参数错误'; switch (data.sub_type) { case 'att': const stage = await this.ctx.service.stage.getDataById(data.stage); return await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: data.tender_id, sid: stage.order }, order: [['id', 'desc']]}); } } async _loadAdvanceAtt(data) { if (!data.stage) throw '参数错误'; const self = this; const result = await this.ctx.service.advanceFile.getAllDataByCondition({ where: { vid: data.stage }, order: [['id', 'desc']]}); result.forEach(x => { const info = path.parse(x.filename); x.filename = info.name; x.filesize = self.ctx.helper.sizeToBytes(x.filesize); }); return result; } async loadRelaFiles(ctx) { try { const data = JSON.parse(ctx.request.body.data); if (!data.type) throw '参数错误'; let files; switch(data.type) { case 'ledger': files = await this._loadLedgerAtt(data); break; case 'stage': files = await this._loadStageAtt(data); break; case 'advance': files = await this._loadAdvanceAtt(data); break; default: throw '未知文件类型'; } ctx.body = {err: 0, msg: '', data: files }; } catch (error) { ctx.helper.log(error); ctx.body = this.ajaxErrorBody(error, '加载附件失败,请重试'); } } async relaFile(ctx) { try { const data = JSON.parse(ctx.request.body.data); if (!data.filing_id || !data.files) throw '缺少参数'; const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId); const filing = await ctx.service.filing.getDataById(data.filing_id); if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试'; await this.checkFiling(filing); const result = await ctx.service.file.relaFiles(filing, data.files, user); ctx.body = {err: 0, msg: '', data: result }; } catch (error) { ctx.helper.log(error); ctx.body = this.ajaxErrorBody(error, '导入附件失败,请重试'); } } async template(ctx) { const defaultTemplate = await ctx.service.filingTemplateList.getOriginTemplate(); ctx.redirect('/file/template/' + defaultTemplate.id); } async templateDetail(ctx) { try { const renderData = { jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.template), }; renderData.templateList = await ctx.service.filingTemplateList.getAllTemplate(ctx.session.sessionProject.id); renderData.FtType = ctx.service.filingTemplateList.FtType; renderData.template = renderData.templateList.find(x => { return x.id === ctx.params.id }); if (!renderData.template) throw '查看的资料模板不存在'; renderData.templateData = await ctx.service.filingTemplate.getData(renderData.template.id); await this.layout('file/template.ejs', renderData); } catch (err) { ctx.log(err); ctx.session.postError = err.toString(); ctx.redirect(this.menu.menu.dashboard.url); } } async saveTemplate(ctx) { try { const id = ctx.query.id; const name = ctx.request.body.name; const [save, templateId] = await ctx.service.filingTemplateList.save(name, id); if (!save) throw '保存数据失败'; ctx.redirect('/file/template/' + templateId); } catch(err) { ctx.log(err); ctx.session.postError = err.toString(); ctx.redirect('/file/template'); } } async resetTemplate(ctx) { try { const id = ctx.query.id; await ctx.service.filingTemplateList.reset(id); ctx.redirect('/file/template/' + id); } catch (err) { ctx.log(err); ctx.postError(err, '重置模板失败'); ctx.redirect('/file/template'); } } async delTemplate(ctx) { try { const id = ctx.query.id; await ctx.service.filingTemplateList.delete(id); console.log(ctx.request.headers.referer, id); if (ctx.request.headers.referer.indexOf(id) > 0) { ctx.redirect('/file/template'); } else { ctx.redirect(ctx.request.headers.referer); } } catch (err) { ctx.log(err); ctx.postError(err, '删除模板失败'); ctx.redirect('/file/template'); } } async updateTemplate(ctx) { try { const data = JSON.parse(ctx.request.body.data); if (!data.updateType) throw '数据错误'; let result; if (data.updateType === 'add') { result = await ctx.service.filingTemplate.add(ctx.params.id, data); } else if (data.updateType === 'del') { result = await ctx.service.filingTemplate.del(ctx.params.id, data); } else if (data.updateType === 'save') { result = await ctx.service.filingTemplate.save(data); } else if (data.updateType === 'move') { if (!data.id || !(data.tree_order >= 0)) throw '数据错误'; result = await ctx.service.filingTemplate.move(ctx.params.id, data); } ctx.body = { err: 0, msg: '', data: result }; } catch (err) { ctx.log(err); ctx.ajaxErrorBody(err, '修改失败'); } } } return BudgetController; };