/** * Created by Tony on 2017/4/28. */ let async = require("async"); let moment = require('moment'); let counter = require('../../../public/counter/counter'); let gljDao = require('./glj_repository'); let rationRepositoryDao = require('./repository_map'); const scMathUtil = require('../../../public/scMathUtil').getUtil(); import {rationItemModel, compleRationModel} from './schemas'; import STDGLJListModel from '../../std_glj_lib/models/gljModel'; var rationItemDAO = function(){}; rationItemDAO.prototype.sortToNumber = function (datas) { for(let i = 0, len = datas.length; i < len; i++){ let data = datas[i]._doc; if(_exist(data, 'labourPrice')){ data['labourPrice'] = parseFloat(data['labourPrice']); } if(_exist(data, 'materialPrice')){ data['materialPrice'] = parseFloat(data['materialPrice']); } if(_exist(data, 'machinePrice')){ data['machinePrice'] = parseFloat(data['machinePrice']); } if(_exist(data, 'basePrice')){ data['basePrice'] = parseFloat(data['basePrice']); } if(_exist(data, 'rationGljList')){ for(let j = 0, jLen = data['rationGljList'].length; j < jLen; j++){ let raGljObj = data['rationGljList'][j]._doc; if(_exist(raGljObj, 'consumeAmt')){ raGljObj['consumeAmt'] = parseFloat(raGljObj['consumeAmt']); } } } } function _exist(data, attr){ return data && data[attr] !== undefined && data[attr]; } }; rationItemDAO.prototype.getRationItemsBySection = function(rationRepId, sectionId,callback){ let me = this; rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){ if(err) callback(true, "Fail to get items", ""); else { me.sortToNumber(data); callback(false,"Get items successfully", data); } }) }; rationItemDAO.prototype.mixUpdateRationItems = function(rationLibId, lastOpr, sectionId, updateItems, addItems, rIds, callback){ var me = this; if (updateItems.length == 0 && rIds.length == 0) { me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback); } else { me.removeRationItems(rationLibId, lastOpr, rIds, function(err, message, docs) { if (err) { callback(true, "Fail to remove", false); } else { me.updateRationItems(rationLibId, lastOpr, sectionId, updateItems, function(err, results){ if (err) { callback(true, "Fail to save", false); } else { if (addItems && addItems.length > 0) { me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback); } else { callback(false, "Save successfully", results); } } }); } }) } }; rationItemDAO.prototype.removeRationItems = function(rationLibId, lastOpr, rIds,callback){ if (rIds.length > 0) { rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){ if (err) { callback(true, "Fail to remove", false); } else { rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) { if(!err){ callback(false, "Remove successfully", docs); } }) } }) } else { callback(false, "No records were deleted!", null); } }; rationItemDAO.prototype.getRationItemsByCode = function(repId, code,callback){ rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$or": [{"isDeleted": null}, {"isDeleted": false}]},function(err,data){ if(err) callback(true, "Fail to get items", "") else callback(false,"Get items successfully", data); }) }; rationItemDAO.prototype.findRation = function (repId, keyword, callback) { var filter = { 'rationRepId': repId, '$and': [{ '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}] }, { '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}] }] }; rationItemModel.find(filter, function (err, data) { if (err) { callback(true, 'Fail to find ration', null); } else { callback(false, '', data); } }) } rationItemDAO.prototype.getRationItem = function (repId, code, callback) { if (callback) { rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec() .then(function (result, err) { if (err) { callback(1, '找不到定额“' + code +'”' , null); } else { callback(0, '', result); } }); return null; } else { return rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec(); } }; rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){ if (items && items.length > 0) { counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){ var maxId = result.value.sequence_value; var arr = []; for (var i = 0; i < items.length; i++) { var obj = new rationItemModel(items[i]); obj.ID = (maxId - (items.length - 1) + i); obj.sectionId = sectionId; obj.rationRepId = rationLibId; arr.push(obj); } rationItemModel.collection.insert(arr, null, function(err, docs){ if (err) { callback(true, "Fail to save", false); } else { rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) { if(err){ callback(true, "Fail to sava operator", false); } else{ callback(false, "Save successfully", docs); } }) } }) }); } else { callback(true, "Source error!", false); } }; rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){ var functions = []; for (var i=0; i < items.length; i++) { functions.push((function(doc) { return function(cb) { var filter = {}; if (doc.ID) { filter.ID = doc.ID; } else { filter.sectionId = sectionId; if (rationLibId) filter.rationRepId = rationLibId; filter.code = doc.code; } rationItemModel.update(filter, doc, cb); }; })(items[i])); } functions.push((function () { return function (cb) { rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) { if(err){ cb(err); } else{ cb(null); } }); } })()); async.parallel(functions, function(err, results) { callback(err, results); }); }; //ration round func function round(v,e){ var t=1; for(;e>0;t*=10,e--); for(;e<0;t/=10,e++); return Math.round(v*t)/t; } rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, callback) { async.each(basePrcArr, function (basePrcObj, finalCb) { let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType; async.waterfall([ function (cb) { if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){ rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) { if(err){ cb(err); } else{ //删除 rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) { if(err){ cb(err); } else{ //补充定额 compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) { if(err){ cb(err); } else { compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) { if(err){ cb(err); } else { for(let i = 0, len = compleRst.length; i < len; i++){ compleRst[i]._doc.type = 'complementary'; } cb(null, result.concat(compleRst)); } }); } }); } }); } }); } else{ rationItemModel.find({'rationGljList.gljId': adjGljId}, function (err, result) { if(err){ cb(err); } else{ compleRationModel.find({'rationGljList.gljId': adjGljId}, function (err, compleRst) { if(err){ cb(err); } else { for(let i = 0, len = compleRst.length; i < len; i++){ compleRst[i]._doc.type = 'complementary'; } cb(null, result.concat(compleRst)); } }); } }); } }, function (result, cb) { async.each(result, function (rationItem, ecb) { let rationGljList = rationItem.rationGljList, gljIds = []; gljDao.getStdCompleGljItems(rationGljList, function(err, gljItems){ if(err){ ecb(err); } else{ let gljArr = []; for(let i=0; i 200 && gljItems[i].gljType < 300){ gljParentType = 2; } if(gljItems[i].gljType > 300 && gljItems[i].gljType < 400){ gljParentType = 3; } if(gljItems[i].ID === adjGljId){ gljArr.push({gljId: gljItems[i].ID, basePrice: adjBasePrice, gljParentType: gljParentType}); } else { gljArr.push({gljId: gljItems[i].ID, basePrice: parseFloat(gljItems[i].basePrice), gljParentType: gljParentType}); } } gljArr.forEach(function (gljItem) { rationGljList.forEach(function (rationGlj) { if(gljItem.gljId === rationGlj.gljId){ gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt); } }) }); //recalculate the price of ration let labourPrc = [], materialPrc = [], machinePrc = [], singlePrc, updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, basePrice: 0}; gljArr.forEach(function (gljItem) { if(gljItem.gljParentType !== -1){ singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3); if(gljItem.gljParentType === 1){ labourPrc.push(singlePrc); } else if(gljItem.gljParentType ===2){ materialPrc.push(singlePrc); } else{ machinePrc.push(singlePrc); } } }); if(labourPrc.length > 0){ let sumLaP = 0; for(let i=0; i 0){ let sumMtP = 0; for(let i= 0; i 0){ let sumMaP = 0; for(let i =0; i< machinePrc.length; i++){ sumMaP += machinePrc[i]; } updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2); } updatePrc.basePrice = scMathUtil.roundTo(updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice, -2); //updateDataBase if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){ compleRationModel.update({ID: rationItem.ID}, {$set: {labourPrice: updatePrc.labourPrice.toString(), materialPrice: updatePrc.materialPrice.toString(), machinePrice: updatePrc.machinePrice.toString(), basePrice: updatePrc.basePrice.toString()}}, function (err, result) { if(err){ ecb(err); } else { ecb(null); } }); } else { rationItemModel.update({ID: rationItem.ID}, {$set: {labourPrice: updatePrc.labourPrice.toString(), materialPrice: updatePrc.materialPrice.toString(), machinePrice: updatePrc.machinePrice.toString(), basePrice: updatePrc.basePrice.toString()}}, function (err, result) { if(err){ ecb(err); } else { ecb(null); } }); } } }); }, function(err){ if(err){ cb(err); } else { cb(null); } }); }, ], function (err) { if(err){ finalCb(err); } else{ finalCb(null); } }); }, function (err) { if(err){ callback(err, 'Error'); } else{ callback(null, ''); } }); }; rationItemDAO.prototype.getRationGljIds = function (data, callback) { let repId = data.repId; rationItemModel.find({rationRepId: repId}, function (err, result) { if(err){ callback(err, 'Error', null); } else{ let rstIds = [], newRst = []; result.forEach(function (data) { if(data.rationGljList.length >0){ data.rationGljList.forEach(function (gljObj) { rstIds.push(gljObj.gljId); }) } }); for(let i= 0; i< rstIds.length; i++){ if(newRst.indexOf(rstIds[i]) === -1){ newRst.push(rstIds[i]); } } callback(null, '', newRst); } }); }; rationItemDAO.prototype.getRationsCodes = function (data, callback) { let repId = data.repId; rationItemModel.find({rationRepId: repId}, function (err, result) { if(err){ callback(err, 'Error', null); } else{ let rstCodes = []; result.forEach(function (rationItem) { rstCodes.push(rationItem.code); }); callback(null, 'get all rationCodes success', rstCodes); } }) }; rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) { rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) { async.each(updateArr, function (obj, cb) { rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) { if(err){ cb(err); } else{ cb(null); } }) }, function (err) { if(err){ callback(err); } else{ callback(null); } }); }); } rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) { rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) { async.each(updateArr, function (obj, cb) { rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) { if(err){ cb(err); } else{ cb(null); } }) }, function (err) { if(err){ callback(err); } else{ callback(null); } }); }); }; /** * 根据条件获取定额数据 * * @param {Object} condition * @param {Object} fields * @param {String} indexBy * @return {Promise|Array} */ rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) { let result = []; if (Object.keys(condition).length <= 0) { return result; } result = await rationItemModel.find(condition, fields).sort({code: 1}); if (indexBy !== null && result.length > 0) { let tmpResult = {}; for(let tmp of result) { tmpResult[tmp[indexBy]] = tmp; } result = tmpResult; } return result; }; /** * 从excel中批量新增数据 * * @param {Number} rationRepId * @param {Array} data * @return {bool} */ rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) { if (data.length <= 0) { return false; } // 获取定额库相关数据 const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId); if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) { return false; } // 获取标准工料机库数据 const stdBillsLibListsModel = new STDGLJListModel(); const stdGLJData = await stdBillsLibListsModel.getGljItemsByRep(rationRepository[0].gljLib); // 整理标准工料机库数据 let stdGLJList = {}; for (const tmp of stdGLJData) { stdGLJList[tmp.code.toString()] = tmp.ID; } let lastData = {}; const rationData = []; // 编码列表,用于查找库中是否有对应数据 let rationCodeList = []; let gljCodeList = []; // 插入失败的工料机列表(用于提示) this.failGLJList = []; for (const tmp of data) { if (tmp.length <= 0) { continue; } // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段 if (tmp[0] === undefined && Object.keys(lastData).length > 0) { // 如果不存在对应的工料机库数据则跳过 if (stdGLJList[tmp[1]] === undefined) { const failString = '定额' + lastData.code + '下的' + tmp[1]; this.failGLJList.push(failString); continue; } const tmpRationGlj = { gljId: stdGLJList[tmp[1]], consumeAmt: tmp[4], proportion: 0, }; lastData.rationGljList.push(tmpRationGlj); if (gljCodeList.indexOf(tmp[1]) < 0) { gljCodeList.push(tmp[1]); } continue; } if (tmp[0] === '定额' && Object.keys(lastData).length > 0) { rationData.push(lastData); } // 组装数据 lastData = { code: tmp[1], name: tmp[2], unit: tmp[3], caption: tmp[2], rationRepId: rationRepId, sectionId: 0, rationGljList: [] }; // 防止重复加入 if (rationCodeList.indexOf(tmp[1]) < 0) { rationCodeList.push(tmp[1]); } } // 最后一个入数组 rationData.push(lastData); // 查找数据库中是否已存在待插入数据 const condition = { rationRepId: rationRepId, code: { $in: rationCodeList } }; const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code'); // 过滤插入数据 let insertData = []; for (const ration of rationData) { if (existCodeList[ration.code] !== undefined) { continue; } insertData.push(ration); } // 如果都已经存在,直接返回 if (insertData.length <= 0) { return true; } // 组织id const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length); let maxId = counterInfo.value.sequence_value; maxId = parseInt(maxId); let count = 0; for (const index in insertData) { insertData[index].ID = maxId - (insertData.length - 1) + count; count++; } // 插入数据库 const result = await rationItemModel.create(insertData); return result.length > 0; }; /** * 导出到excel的数据 * * @param {Number} rationRepId * @return {Array} */ rationItemDAO.prototype.exportExcelData = async function(rationRepId) { const condition = { rationRepId: rationRepId }; // @todo 限制导出的数量以防内存溢出 const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType']); // 整理数据 let rationData = []; for (const tmp of rationDataList) { const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId; const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType; const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name]; rationData.push(ration); } const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名']]; excelData.push.apply(excelData, rationData); return excelData; }; /** * 批量更改章节id * * @param {Object} data * @return {bool} */ rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) { if (data.length <= 0) { return false; } // 批量执行update const bulk = rationItemModel.collection.initializeOrderedBulkOp(); for (const tmp of data) { let rationId = parseInt(tmp[2]); rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId; let sectionId = parseInt(tmp[0]); sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId; // 取费专业 let feeType = parseInt(tmp[1]); feeType = isNaN(feeType) || feeType <= 0 ? 0 : feeType; if (sectionId <= 0 || rationId <= 0 || feeType <= 0) { continue; } bulk.find({"ID": rationId}).update({$set: { sectionId: sectionId, feeType: feeType }}); } const result = await bulk.execute(); return result.isOk(); }; module.exports = new rationItemDAO();