123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700 |
- /**
- * Created by chen on 2017/6/29.
- */
- let mongoose = require('mongoose');
- const uuidV1 = require('uuid/v1');
- let consts = require('../../main/models/project_consts')
- let commonConsts = consts.commonConst;
- let _=require("lodash");
- let ration_glj = mongoose.model('ration_glj');
- import GLJListModel from '../../glj/models/glj_list_model';
- let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
- let async_n = require("async");
- let ration = mongoose.model('ration');
- let ration_coe_facade = require('./ration_coe_facade');
- let ration_coe = mongoose.model('ration_coe');
- let std_ration_lib_ration_items = mongoose.model('std_ration_lib_ration_items');
- let glj_calculate_facade = require('./glj_calculate_facade');
- let quantity_detail_facade = require('./quantity_detail_facade');
- let logger = require("../../../logs/log_helper").logger;
- import stdgljutil from "../../../public/cache/std_glj_type_util";
- import EngineeringLibModel from "../../users/models/engineering_lib_model";
- import GljDao from "../../complementary_glj_lib/models/gljModel";
- module.exports={
- save:save,
- getData:getData,
- deleteByRation:deleteByRation,
- getQuantityByProjectGLJ:getQuantityByProjectGLJ,
- getLibInfo:getLibInfo,
- getGLJData:getGLJData,
- addGLJ:addGLJ,
- replaceGLJ:replaceGLJ,
- mReplaceGLJ:mReplaceGLJ,
- updateRationGLJByEdit:updateRationGLJByEdit
- }
- let operationMap={
- 'ut_create':create_ration_glj,
- 'ut_update':update_ration_glj,
- 'ut_delete':delete_ration_glj
- };
- let updateFunctionMap = {
- 'normalUpdate':normalUpdate
- };
- /**
- * 根据项目工料机ID和项目ID取消耗量
- *
- * @param {object} condition
- * @return Array
- */
- async function getQuantityByProjectGLJ(condition) {
- let query ={
- $and:[
- {'projectID':condition.projectID},
- {'projectGLJID':{$in:condition.projectGLJIDList}}
- ]
- }
- let results = await ration_glj.find(query,['projectGLJID','quantity','rationID'],{sort: {projectGLJID: 1}});
- let rationList = _.uniq(_.map(results,'rationID'));
- let rationQuery={
- $and:[
- {'projectID':condition.projectID},
- {'ID':{$in:rationList}},
- {'deleteInfo': null}
- ]
- }
- let rations = await ration.find(rationQuery,['ID','quantity']);
- return combineQuantity(results,rations);
- }
- function combineQuantity(results,rations) {
- let resultList=[];
- _.forEach(results,function (data) {
- let tmp = {
- projectGLJID:data.projectGLJID,
- quantity: Number(data.quantity)
- }
- let ration=_.find(rations,{ID:data.rationID});
- if(ration){
- tmp.rationID=ration.ID;
- tmp.rationQuantity=ration.quantity?Number(ration.quantity):undefined;
- }
- resultList.push(tmp);
- /* if(resultMap.hasOwnProperty(data.projectGLJID)){
- resultMap[data.projectGLJID] += data.quantity;
- }else {
- resultMap[data.projectGLJID] = data.quantity;
- }*/
- });
- /* var resultList =[];
- for(let key in resultMap){
- let newObject = {
- 'projectGLJID':key,
- 'quantity':resultMap[key]
- }
- resultList.push(newObject)
- }*/
- return resultList;
- }
- function get_lib_glj_info(ration_glj) {
- return function (result,cb) {
- std_glj_lib_gljList_model.findOne({'ID':ration_glj.GLJID},(err,glj)=>{
- if(err){
- cb(err,'')
- }else if(glj){
- ration_glj.name = glj.name;
- ration_glj.code = glj.code;
- ration_glj.original_code=glj.code;
- ration_glj.unit = glj.unit;
- ration_glj.specs = glj.specs;
- ration_glj.basePrice = glj.basePrice;
- ration_glj.shortName = glj.shortName;
- ration_glj.type = glj.gljType;
- ration_glj.repositoryId = glj.repositoryId;
- getInfoFromProjectGLJ(ration_glj).then(function (info) {
- if(info){
- let tem={};
- tem.newRecode=createNewRecord(info);
- tem.showData=info;
- result.datas.push(tem);
- cb(null,result);
- }else {
- cb(new Error('get project glj error'),null);
- }
- });
- }else {
- cb(null,null);
- }
- })
- }
- }
- function createNewRecord(ration_glj) {
- let newRecoed={};
- newRecoed.ID=ration_glj.ID;
- newRecoed.projectID=ration_glj.projectID;
- newRecoed.GLJID=ration_glj.GLJID;
- newRecoed.rationID=ration_glj.rationID;
- newRecoed.rationItemQuantity=ration_glj.rationItemQuantity;
- newRecoed.quantity=ration_glj.quantity;
- newRecoed.name = ration_glj.name;
- newRecoed.code = ration_glj.code;
- newRecoed.original_code=ration_glj.original_code;
- newRecoed.unit = ration_glj.unit;
- newRecoed.specs = ration_glj.specs;
- newRecoed.from=ration_glj.from?ration_glj.from:undefined;
- newRecoed.createType=ration_glj.createType?ration_glj.createType:undefined;
- newRecoed.shortName = ration_glj.shortName;
- newRecoed.billsItemID=ration_glj.billsItemID,
- newRecoed.type = ration_glj.type;
- newRecoed.repositoryId = ration_glj.repositoryId;
- newRecoed.projectGLJID=ration_glj.projectGLJID;
- return newRecoed
- }
- async function getInfoFromProjectGLJ(ration_glj) {
- let data = getGLJSearchInfo(ration_glj);
- try {
- let projectGljModel = new GLJListModel();
- let result = await projectGljModel.addList(data);
- ration_glj.marketPrice=result.unit_price.market_price;
- ration_glj.adjustPrice=result.unit_price.base_price;
- ration_glj.basePrice=result.unit_price.base_price;
- ration_glj.projectGLJID=result.id;
- ration_glj.isEstimate=result.is_evaluate;
- if(result.hasOwnProperty('subList')&&result.subList.length>0){
- ration_glj.subList=getMixRatioShowDatas(result.subList);
- }
- return ration_glj;
- } catch (err) {
- logger.err(err);
- return null;
- }
- }
- function getMixRatioShowDatas(subList) {
- var temRationGLJs = [];
- for(let pg of subList){
- var tem = {
- code:pg.code,
- name:pg.name,
- specs:pg.specs,
- unit:pg.unit,
- shortName:pg.unit_price.short_name,
- rationItemQuantity:pg.ratio_data.consumption,
- basePrice:pg.unit_price.base_price,
- marketPrice:pg.unit_price.market_price,
- adjustPrice:pg.adjust_price,
- isEstimate:pg.is_evaluate,
- isMixRatio:true
- }
- temRationGLJs.push(tem);
- }
- temRationGLJs=_.sortBy(temRationGLJs,'code');
- return temRationGLJs;
- }
- function create_ration_glj(user_id,datas) {
- return function (callback) {
- let ration_glj_list=datas.ration_glj_list;
- var tasks=[];
- tasks.push(startingTask("get glj info"))
- for(let i =0;i<ration_glj_list.length;i++){
- ration_glj_list[i].ID = uuidV1();
- tasks.push(get_lib_glj_info(ration_glj_list[i]))
- }
- async_n.waterfall(tasks,(err,results)=>{
- if(err){
- callback(err,results)
- }else {
- let newRecords =[];
- let showDatas=[];
- for (let r of results.datas){
- if(r){
- newRecords.push(r.newRecode);
- showDatas.push(r.showData);
- }
- }
- if(newRecords.length>0){
- ration_glj.insertMany(newRecords,(err,doc)=>{
- if(err){
- callback(err,null);
- }else {
- let returndata ={
- updateTpye:commonConsts.UT_CREATE,
- moduleName:'ration_glj',
- data:{
- newRecords:newRecords,
- showDatas:showDatas
- }
- }
- callback(null,returndata)
- }
- });
- }else {
- logger.info("can't find gljs")
- callback(null,null)
- }
- }
- })
- }
- }
- function update_ration_glj(user_id,datas) {
- if(datas.updateFunction){
- return updateFunctionMap[datas.updateFunction](user_id,datas);
- }else {
- return normalUpdate(user_id,datas);
- }
- }
- function normalUpdate(user_id,datas){
- return function(callback) {
- ration_glj.update(datas.query,datas.doc,(err,result)=>{
- if(err){
- callback(err,'');
- }else {
- let returndata ={
- moduleName:'ration_glj',
- data:{
- updateTpye:commonConsts.UT_UPDATE,
- query:datas.query,
- doc:datas.doc
- }
- }
- callback(null,returndata)
- }
- })
- }
- }
- async function doCustomQuantityUpdate(datas){
- let result = await ration_glj.findOneAndUpdate(datas.query,datas.doc);
- let cal_result = await glj_calculate_facade.calculateQuantity({projectID:datas.query.projectID,rationID:datas.query.rationID});
- cal_result.glj_result.forEach(function (item) {
- if(!item.doc.hasOwnProperty('customQuantity')){
- item.doc.customQuantity=null;
- }
- });
- return cal_result;
- }
- function delete_ration_glj(user_id,datas) {
- return function (callback) {
- if(datas.deleteType=="RATION"){
- deleteByRation(datas,callback);
- }else if(datas.deleteType=="BILL"){
- deleteByBill(user_id,datas,callback);
- } else{
- deleteByID(datas,callback);
- }
- }
- }
- function deleteByRation(datas,callback) {
- let data = datas.updateData;
- let tasks=[];
- tasks.push(deleteGLJList(data));
- tasks.push(ration_coe_facade.delete_ration_coe(data));
- tasks.push(quantity_detail_facade.deleteByRation(data));
- async_n.parallel(tasks,function (err,result) {
- commonCallback(callback,result,err)
- })
- }
- function deleteGLJList(data) {
- return function (callback) {
- ration_glj.deleteMany({projectID: data.projectID, rationID: data.ID},(err,result)=>{
- commonCallback(callback,result,err)
- });
- }
- }
- function deleteByBill(user_id,datas,callback) {
- let tasks = [];
- tasks.push(startingTask("deleteByBill"));
- tasks.push(getRationsByBill(datas));
- tasks.push(deleteRationsbyBill(user_id,datas));
- tasks.push(deleteByMultiRations(datas));
- async_n.waterfall(tasks,function (err,results) {
- if(err){
- callback(err,'');
- }else {
- callback(null,results);
- }
- })
- }
- function deleteByID(datas,callback){
- deleteAndUpdateState(datas).then(function (result) {
- if(result.err){
- callback(result.err,'');
- }else {
- let returndata ={
- moduleName:'ration_glj',
- data:{
- updateTpye:commonConsts.UT_DELETE,
- query:datas.query,
- adjustState:result.adjustState
- }
- }
- callback(null,returndata)
- }
- })
- }
- async function deleteAndUpdateState(datas) {
- let result={
- err:null
- }
- try {
- await ration_glj.deleteOne(datas.query);
- let stateResult = await glj_calculate_facade.calculateQuantity({projectID:datas.query.projectID,rationID:datas.doc.rationID});
- result.adjustState=stateResult.adjustState;
- }catch (err){
- result.err=err;
- }
- return result;
- }
- function startingTask(processName){
- return function(asyncCallBack){
- var result = {
- processName : processName,
- datas:[]
- };
- asyncCallBack(null, result);
- };
- }
- function getRationsByBill(datas) {
- return function (results,callback) {
- ration.find({projectID:datas.updateData.projectID,billsItemID:datas.updateData.ID,deleteInfo: null},function (err,rations) {
- if(err){
- callback(err,'')
- }else {
- results.rations=rations;
- callback(null,results)
- }
- })
- }
- }
- function deleteRationsbyBill (user_id,datas){
- return function (results,callback) {
- let deleteInfo ={
- deleteInfo :{deleted: true, deleteDateTime: new Date(), deleteBy: user_id}
- };
- ration.update({projectID: datas.updateData.projectID, billsItemID:datas.updateData.ID},deleteInfo,{multi: true},(err,deleteresults)=>{
- if(err){
- callback(err,'');
- }else {
- callback(null,results);
- }
- });
- }
- }
- function deleteByMultiRations(datas) {
- return function (results,deleteCallBack) {
- var delete_tasks = [];
- var deleteOne=function (ration) {
- return function (callback) {
- ration_glj.deleteMany({projectID: ration.projectID, rationID: ration.ID},function (err,result) {
- commonCallback(callback,result,err)
- });
- }
- }
- let rations = results.rations;
- for(let i=0;i<rations.length;i++){
- delete_tasks.push(deleteOne(rations[i]._doc));
- delete_tasks.push(ration_coe_facade.delete_ration_coe(rations[i]._doc));
- delete_tasks.push(quantity_detail_facade.deleteByRation(rations[i]._doc));
- }
- delete_tasks.push(quantity_detail_facade.deleteByBill(datas.updateData));
- async_n.parallel(delete_tasks,(err,results)=>{
- if (err){
- deleteCallBack(err,'')
- }else {
- deleteCallBack(null,results)
- }
- })
- }
- }
- /*
- function deleteByRation(doc) {
- return function (callback){
- ration_glj.deleteMany({projectID: doc.updateData.projectID, rationID: doc.updateData.ID},callback);
- }
- }
- */
- function save (user_id, datas, callback) {
- let operations=[];
- if(_.isArray(datas)){
- for(let i=0;i<datas.length;i++){
- operations.push(operationMap[datas[i].updateType](user_id,datas[i]));
- }
- }else {
- operations.push(operationMap[datas.updateType](user_id,datas));
- }
- async_n.parallel(operations,function (err,results) {
- if(err){
- callback(err,'');
- }else {
- if(results.length==1){
- callback(null,results[0])
- }else {
- callback(null,results)
- }
- }
- })
- }
- async function getLibInfo(req){
- let gljLibId = null, engineeringId, sessionCompilation = req.session.sessionCompilation,
- rationValuation = sessionCompilation.ration_valuation,
- billValuation = sessionCompilation.bill_valuation,
- engineeringLibModel = new EngineeringLibModel();
- if(rationValuation[0]){
- let engineeringList = rationValuation[0].engineering_list;
- engineeringId = engineeringList.length > 0 ? engineeringList[0].engineering_id : null;
- let engineeringInfo = await engineeringLibModel.getEngineering(engineeringId);
- gljLibId = engineeringInfo.glj_lib.length > 0 && typeof engineeringInfo.glj_lib !== 'undefined' ? engineeringInfo.glj_lib[0].id : null;
- }
- else if(billValuation[0]){
- let engineeringList = billValuation[0].engineering_list;
- engineeringId = engineeringList.length > 0 ? engineeringList[0].engineering_id : null;
- let engineeringInfo = await engineeringLibModel.getEngineering(engineeringId);
- gljLibId = engineeringInfo.glj_lib.length > 0 && typeof engineeringInfo.glj_lib !== 'undefined' ? engineeringInfo.glj_lib[0].id : null;
- }
- let data = {
- userID: req.session.sessionUser.ssoId,
- gljLibId: gljLibId,
- compilationId: sessionCompilation._id
- };
- return data;
- }
- function getGLJData(info,callback) {
- let gljDao = new GljDao();
- let datas={};
- let gljDistTypeCache = stdgljutil.getStdGljTypeCacheObj().toArray();
- datas.distTypeTree=gljDistTypeCache;
- async_n.parallel([
- function (cb) {
- gljDao.getGljTypes(info.gljLibId,function (err,data) {
- if(err){
- cb(err);
- }else {
- datas.treeData=data;
- cb(null);
- }
- })
- },
- function (cb) {
- gljDao.getGljItems(info.gljLibId,info.userID,info.compilationId, function (err,data) {
- if(err){
- cb(err);
- }else {
- datas.stdGLJ=data.stdGljs;
- datas.complementaryGLJs=data.complementaryGljs;
- cb(null);
- }
- });
- }
- ], function (err) {
- if(err){
- callback(true, null);
- }
- else{
- callback(false, datas);
- }
- })
- }
- function getGLJSearchInfo(ration_glj) {
- let data = {
- glj_id: ration_glj.GLJID,
- project_id: ration_glj.projectID,
- code: ration_glj.code,
- original_code:ration_glj.original_code,
- name: ration_glj.name,
- shortName:ration_glj.shortName,
- specs: ration_glj.specs,
- unit: ration_glj.unit,
- type: ration_glj.type,
- type_of_work: ration_glj.type,
- base_price: ration_glj.basePrice,
- market_price: ration_glj.basePrice,
- repositoryId:ration_glj.repositoryId,
- from:ration_glj.from?ration_glj.from:'std'//std:标准工料机库, cpt:补充工料机库
- };
- if(data.from=='cpt'){//从补充工料机来的数据即为新增数据
- data.is_add = 1;
- }
- return data;
- }
- async function addGLJ(rgList) {
- let newRecodes = [];
- for(let g of rgList){
- let projectGljModel = new GLJListModel();
- let result = await projectGljModel.addList(getGLJSearchInfo(g));
- g.marketPrice=result.unit_price.market_price;
- g.adjustPrice=result.unit_price.base_price;
- g.basePrice=result.unit_price.base_price;
- g.projectGLJID=result.id;
- g.isEstimate=result.is_evaluate;
- g.ID=uuidV1();
- if(result.hasOwnProperty('subList')&&result.subList.length>0){
- g.subList=getMixRatioShowDatas(result.subList);
- }
- newRecodes.push(createNewRecord(g));
- }
- await ration_glj.insertMany(newRecodes);
- let stateResult = await glj_calculate_facade.calculateQuantity({projectID:rgList[0].projectID,rationID:rgList[0].rationID});
- let result={
- newRecodes:newRecodes,
- showData:rgList,
- adjustState:stateResult.adjustState
- }
- return result;
- }
- async function replaceGLJ(data) {
- let rdata={};
- let projectGljModel = new GLJListModel();
- let result = await projectGljModel.addList(getGLJSearchInfo(data));
- data.marketPrice=result.unit_price.market_price;
- data.adjustPrice=result.unit_price.base_price;
- data.basePrice=result.unit_price.base_price;
- data.projectGLJID=result.id;
- data.isEstimate=result.is_evaluate;
- let updateResult=await ration_glj.findOneAndUpdate({ID:data.ID,projectID:data.projectID},data);
- let stateResult = await glj_calculate_facade.calculateQuantity({projectID:data.projectID,rationID:data.rationID});
- rdata.data=data;
- rdata.adjustState=stateResult.adjustState;
- return rdata;
- }
- async function mReplaceGLJ(data) {
- let mresult={};
- let projectGljModel = new GLJListModel();
- let result = await projectGljModel.addList(getGLJSearchInfo(data.doc));
- data.doc.marketPrice=result.unit_price.market_price;
- data.doc.adjustPrice=result.unit_price.base_price;
- data.doc.basePrice=result.unit_price.base_price;
- data.doc.projectGLJID=result.id;
- data.doc.isEstimate=result.is_evaluate;
- let rationList=await ration_glj.distinct('rationID',data.query);
- let updateResult=await ration_glj.update(data.query,data.doc,{multi: true});
- let stateList= await changAdjustState(data,rationList);
- mresult.data=data;
- mresult.stateList=stateList;
- return mresult
- }
- async function updateRationGLJByEdit(data) {
- var doc = data.doc;
- var result;
- if(doc.hasOwnProperty('customQuantity')){
- result = await doCustomQuantityUpdate(data)
- }else {
- result = await doRationGLJUpdate(data);
- }
- return result;
- }
- async function doRationGLJUpdate(data){
- let resutl = {};
- let doc = data.doc;
- let priceInfo = data.priceInfo;
- let rg = await ration_glj.findOne(data.query);
- let gljListModel = new GLJListModel();
- let projectGLJ= getGLJSearchInfo(rg);
- for(let key in doc){
- projectGLJ[key]=doc[key]
- }
- projectGLJ.base_price = priceInfo.base_price;
- projectGLJ.market_price = priceInfo.market_price;
- let projcetGLJ_n = await gljListModel.modifyGLJ(projectGLJ,rg);
- doc.code = projcetGLJ_n.code;
- doc.projectGLJID=projcetGLJ_n.id;
- if(projcetGLJ_n.unit_price.is_add==1){
- doc.createType='replace';
- doc.rcode=projcetGLJ_n.original_code;
- }else {
- doc.createType='normal';
- doc.rcode='';
- }
- await ration_glj.findOneAndUpdate(data.query,doc);
- //取价格
- gljListModel.getGLJPrice(projcetGLJ_n);
- doc.basePrice=projcetGLJ_n.unit_price.base_price;
- doc.marketPrice=projcetGLJ_n.unit_price.market_price;
- doc.adjustPrice=projcetGLJ_n.adjust_price;
- doc.isAdd = projcetGLJ_n.unit_price.is_add;
- resutl.doc = doc;
- let stateResult = await glj_calculate_facade.calculateQuantity({projectID:data.query.projectID,rationID:data.query.rationID});
- resutl.adjustState= stateResult.adjustState;
- return resutl;
- }
- async function changAdjustState(data,rationList) {
- let stateList=[];
- for(let r of rationList){
- let stateResult = await glj_calculate_facade.calculateQuantity({projectID:data.query.projectID,rationID:r});
- stateList.push({rationID:r,adjustState:stateResult.adjustState});
- }
- return stateList;
- }
- async function testError() {
- throw new Error('test Error');
- }
- function getData(projectID, callback) {
- ration_glj.find({'projectID':projectID},(err,datas)=>{
- if(err){
- callback(1, '', null);
- }else {
- callback(0, consts.projectConst.RATION_GLJ, datas);
- }
- })
- }
- function commonCallback(callback,result,err) {
- if(err){
- callback(err,'');
- }else {
- callback(null,result);
- }
- }
|