123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333 |
- /**
- * Created by Tony on 2017/4/20.
- */
- const mongoose = require('mongoose');
- var rationRepository = require("../models/repository_map");
- import baseController from "../../common/base/base_controller";
- import CompilationModel from "../../users/models/compilation_model";
- const gljMapModel = mongoose.model('std_glj_lib_map');
- const compilationModel = mongoose.model('compilation');
- import async from "async";
- var callback = function(req, res, err, message, data){
- res.json({error: err, message: message, data: data});
- };
- // 上传控件
- const multiparty = require("multiparty");
- const fs = require("fs");
- // excel解析
- const excel = require("node-xlsx");
- const rationItem = require("../models/ration_item");
- const rationSectionTree = require('../models/ration_section_tree');
- const rationLibModel = mongoose.model('std_ration_lib_map');
- const rationItemModel = mongoose.model('std_ration_lib_ration_items');
- import STDGLJListModel from '../../std_glj_lib/models/gljModel';
- let logger = require('../../../logs/log_helper').logger;
- class RationRepositoryController extends baseController {
- // 定额页面初始化数据
- async prepareInitData(req, res) {
- try {
- const data = JSON.parse(req.body.data);
- const rst = await rationItem.prepareInitData(data.rationRepId);
- res.json({error: 0, message: 'success', data: rst});
- } catch (err) {
- console.log(err);
- res.json({error: 1, message: 'fail', data: null});
- }
- }
- async getRationLibsByCompilation(req, res){
- try{
- let data = JSON.parse(req.body.data);
- let rationLibs = await rationRepository.getRationLibsByCompilation(data.compilationId);
- callback(req, res, 0, '', rationLibs);
- }
- catch(err){
- callback(req, res, 1, err, null);
- }
- }
- async getCompilationList(req, res) {
- try {
- let compilationModel = new CompilationModel(), rst = [];
- let compilationList = await compilationModel.getCompilationList();
- if (compilationList.length <= 0) {
- throw '没有数据';
- }
- else {
- compilationList.forEach(function (compilation) {
- rst.push({_id: compilation._id, name: compilation.name});
- });
- //获得相关编办下的工料机库
- let parallelFucs = [];
- for (let i = 0; i < rst.length; i++) {
- parallelFucs.push((function (obj) {
- return function (cb) {
- gljMapModel.find({compilationId: obj._id, deleted: false}, function (err, result) {
- if (err) {
- cb(err);
- }
- else {
- cb(null, result);
- }
- })
- }
- })(rst[i]));
- }
- async.parallel(parallelFucs, function (err, result) {
- if (err) {
- callback(req, res, err, '没有数据', null);
- }
- else {
- let gljLibsRst = [];
- for (let i = 0; i < result.length; i++) {
- for (let j = 0; j < result[i].length; j++) {
- gljLibsRst.push(result[i][j]);
- }
- }
- callback(req, res, false, '', {compilation: rst, gljLibs: gljLibsRst});
- }
- })
- }
- }
- catch (err) {
- callback(req, res, err, '没有数据', null);
- }
- }
- addRationRepository(req, res) {
- var rationObj = JSON.parse(req.body.rationRepObj);
- rationRepository.addRationRepository(rationObj, function (err, data) {
- if (data) {
- callback(req, res, err, "has data", data);
- } else {
- callback(req, res, err, "no data", null);
- }
- })
- }
- getRationLib(req, res){
- let data = JSON.parse(req.body.data);
- let libId = data.libId;
- rationRepository.getRationLib(libId, function(err, data){
- if (data) {
- callback(req, res, err, "has data", data);
- } else {
- callback(req, res, err, "no data", null);
- }
- });
- }
- async getDisPlayRationLibs(req, res) {
- rationRepository.getDisplayRationLibs(function (err, data) {
- if (data) {
- callback(req, res, err, "has data", data);
- } else {
- callback(req, res, err, "no data", null);
- }
- });
- }
- getRealLibName(req, res) {
- var libName = req.body.rationName;
- rationRepository.getRealLibName(libName, function (err, data) {
- if (data) {
- callback(req, res, err, "has data", data);
- } else {
- callback(req, res, err, "no data", null);
- }
- })
- }
- getLibIDByName(req, res) {
- rationRepository.getLibIDByName(req.body.libName, function (err, data) {
- if (data) {
- callback(req, res, err, "has ID", data);
- } else {
- callback(req, res, err, "no ID", null);
- }
- })
- }
- deleteRationLib(req, res) {
- logger.info(`deleteRationLib ${req.ip}`);
- let oprtor = req.body.oprtor,
- libId = req.body.libId;
- rationRepository.deleteRationLib(oprtor, libId, function (err, message) {
- callback(req, res, err, message, null);
- });
- }
- updateRationRepositoryName(req, res) {
- let oprtor = req.body.oprtor,
- renameObj = JSON.parse(req.body.renameObj);
- rationRepository.updateName(oprtor, renameObj, function (err, message) {
- callback(req, res, err, message, null);
- })
- }
- /**
- * 上传定额库原始数据
- *
- * @param {Object} request
- * @param {Object} response
- * @return {void}
- */
- async uploadSourceData(request, response) {
- let responseData = {
- err: 0,
- msg: ''
- };
- const allowHeader = [
- 'application/vnd.ms-excel',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'application/octet-stream'
- ];
- const uploadOption = {
- uploadDir: './public'
- };
- const form = new multiparty.Form(uploadOption);
- let uploadFullName
- form.parse(request, async function(err, fields, files) {
- try{
- const rationRepId = fields.rationRepId !== undefined && fields.rationRepId.length > 0 ?
- fields.rationRepId[0] : 0;
- const type = fields.type !== undefined && fields.type.length > 0 ?
- fields.type[0] : '';
- if (rationRepId <= 0 || type === '') {
- throw '参数错误';
- }
- const file = files.file !== undefined ? files.file[0] : null;
- if (err || file === null) {
- throw '上传失败';
- }
- console.log(file.headers['content-type']);
- // 判断类型
- if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
- throw `不支持该类型:${file.headers['content-type']}`;
- }
- // 重命名文件名
- uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
- fs.renameSync(file.path, uploadFullName);
- const sheet = excel.parse(uploadFullName);
- if (sheet[0] === undefined || sheet[0].data === undefined) {
- throw 'excel没有对应数据';
- }
- let failGLJList;
- switch (type) {
- // 导入原始数据
- case 'source_file':
- failGLJList = await rationItem.batchAddFromExcel(rationRepId, sheet[0].data);
- break;
- // 导入内部数据
- case 'import_data':
- failGLJList = await rationItem.batchUpdateSectionIdFromExcel(sheet[0].data);
- break;
- // 导入章节数据(一列文本,生成兄弟节点树)
- case 'section_file':
- await rationSectionTree.importSection(rationRepId, sheet[0].data);
- break;
- }
- if (Array.isArray(failGLJList) && failGLJList.length > 0) {
- responseData.msg = failGLJList.join("<br/>");
- }
- // 删除文件
- if(uploadFullName && fs.existsSync(uploadFullName)){
- fs.unlink(uploadFullName);
- }
- response.json(responseData);
- }
- catch (error){
- console.log(error);
- if(uploadFullName && fs.existsSync(uploadFullName)){
- fs.unlink(uploadFullName);
- }
- responseData.err = 1;
- responseData.msg = error;
- response.json(responseData);
- }
- });
- return;
- }
- /**
- * 导出内部数据
- *
- * @param {Object} request
- * @param {Object} response
- * @return {void}
- */
- async exportRationData(request, response) {
- let rationRepId = request.query.rationRepId;
- rationRepId = parseInt(rationRepId);
- try {
- if (isNaN(rationRepId) || rationRepId <= 0) {
- throw '参数错误';
- }
- const excelData = await rationItem.exportExcelData(rationRepId);
- const buffer = excel.build([{name: "sheet", data: excelData}]);
- const filePath = './public/export.xlsx';
- fs.writeFileSync(filePath, buffer, 'binary');
- const stats = fs.statSync(filePath);
- // 下载相关header
- response.set({
- 'Content-Type': 'application/octet-stream',
- 'Content-Disposition': 'attachment; filename=ration.xlsx',
- 'Content-Length': stats.size
- });
- fs.createReadStream(filePath).pipe(response);
- fs.unlink(filePath);
- } catch (error) {
- response.end(error);
- }
- }
- //一键重新计算所有定额数据
- async reCalcAll(req, res){
- try{
- let data = JSON.parse(req.body.data);
- let rationRepId = data.rationRepId;
- let rationLib = await rationLibModel.findOne({ID: rationRepId, $or: [{deleted: null},{deleted: false}]});
- if(!rationLib){
- throw '不存在此定额库';
- }
- let task = [];
- // 获取标准工料机库数据
- const stdBillsLibListsModel = new STDGLJListModel();
- const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib);
- // 整理标准工料机库数据
- let stdGLJList = {};
- let stdGLJListByID = {};
- for (const tmp of stdGLJData) {
- if (tmp.priceProperty && Object.keys(tmp.priceProperty).length) {
- tmp.basePrice = tmp.priceProperty.price1;
- }
- stdGLJList[tmp.code.toString()] = tmp.ID;
- stdGLJListByID[tmp.ID] = tmp;
- }
- //获取所有的定额
- let allRations = await rationItemModel.find({rationRepId: rationRepId, $or: [{isDeleted: false}, {isDeleted: null}]});
- let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(rationLib.compilationId)});
- let tempUrl = compilation.overWriteUrl ? req.app.locals.rootDir + compilation.overWriteUrl : req.app.locals.rootDir;
- let absoluteUrl = fs.existsSync(tempUrl) && fs.statSync(tempUrl).isFile()? tempUrl : null;
- for(let ration of allRations){
- rationItem.calcForRation(stdGLJListByID, ration, absoluteUrl);
- task.push({
- updateOne: {
- filter: {ID: ration.ID},
- update: {$set: {labourPrice: ration.labourPrice, materialPrice: ration.materialPrice, machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
- }
- });
- }
- if(task.length > 0){
- await rationItemModel.bulkWrite(task);
- }
- res.json({error: 0, message: 'success', data: null});
- }
- catch (err){
- res.json({error: 1, message: err, data: null});
- }
- }
- }
- export default RationRepositoryController;
|