/** * 配合比业务模型 * * @author CaiAoLin * @date 2017/7/12 * @version */ const mongoose = require("mongoose"); const BaseModel = require("../../common/base/base_model"); const CounterModel = require("./counter_model"); let collectionName = 'mix_ratio'; class MixRatioModel extends BaseModel { /** * 构造函数 * * @return {void} */ constructor() { let parent = super(); parent.model = mongoose.model(collectionName); parent.init(); } /** * 设置场景 * * @param {string} scene * @return {void} */ setScene(scene = '') { switch (scene) { // 新增数据的验证规则 case 'add': //this.model.schema.path('glj_id').required(true); this.model.schema.path('consumption').required(true); this.model.schema.path('unit_price_file_id').required(true); this.model.schema.path('connect_key').required(true); break; } } /** * 新增配合比数据(自动判断是否存在) * * @param {object} data * @return {Promise} */ async add(data) { let counterModel = new CounterModel(); if (data instanceof Array) { await this.setIDfromCounter(collectionName,data); /* for(let tmp in data) { data[tmp].id = await counterModel.getId(collectionName); } */ } else { data.id = await counterModel.getId(collectionName); } return await this.db.model.create(data); } /** * 更新数据 * * @param {Number} id * @param {Object} updateData * @return {Promise} */ async updateById(id, updateData) { id = parseInt(id); if (isNaN(id) || id <= 0 || Object.keys(updateData).length <= 0) { return false; } let result = await this.db.update({id: id}, updateData); return result.ok !== undefined && result.ok === 1; } //复制组成物到切换后的组成物映射表 async copyNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,newFile = false){ let currentMap = {},targetMap = {}, insertData = []; //取原单价文件所有的的组成物 let currentList = await this.model.find({'unit_price_file_id':currentUnitPriceId}).lean();; this.getConnectionMap(currentMap,currentList); //切换后的单价文件所有的的组成物 let targetList = await this.model.find({'unit_price_file_id':changeUnitPriceId}).lean(); this.getConnectionMap(targetMap,targetList); for(let ckey in currentMap){ if(targetMap[ckey]){//如果切换后的单价文件已经存在,则不用复 continue; } if(gljMap[ckey] || newFile == true){//在本项目中有用到 for(let ratio of currentMap[ckey]){ delete ratio._id; // 删除原有id信息 delete ratio.id; ratio.unit_price_file_id = changeUnitPriceId; insertData.push(ratio); } } } return insertData.length > 0 ? await this.add(insertData) : true; } getConnectionMap(map,list){ for(let l of list){ if(map[l.connect_key]){ map[l.connect_key].push(l); }else { map[l.connect_key] = [l]; } } } } module.exports = MixRatioModel;