unit_price_model.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. * 单价业务模型
  3. *
  4. * @author CaiAoLin
  5. * @date 2017/6/30
  6. * @version
  7. */
  8. const mongoose = require("mongoose");
  9. const BaseModel = require("../../common/base/base_model");
  10. const CounterModel = require("./counter_model")
  11. const MixRatioModel = require("./mix_ratio_model");
  12. const _ = require("lodash");
  13. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  14. let collectionName = 'unit_price';
  15. let decimal_facade = require('../../main/facade/decimal_facade');
  16. let gljListModel = mongoose.model("glj_list");
  17. let original_calc_model = mongoose.model('original_calc');
  18. let freight_calc_model = mongoose.model('freight_calc');
  19. let gljUtil = require('../../../public/gljUtil');
  20. const uuidV1 = require('uuid/v1');
  21. class UnitPriceModel extends BaseModel {
  22. /**
  23. * 构造函数
  24. *
  25. * @return {void}
  26. */
  27. constructor() {
  28. let parent = super();
  29. parent.model = mongoose.model(collectionName);
  30. parent.init();
  31. }
  32. /**
  33. * 根据单价文件id获取单价数据
  34. *
  35. * @param {Number} fileId
  36. * @return {Promise}
  37. */
  38. async getDataByFileId(fileId) {
  39. fileId = parseInt(fileId);
  40. if (isNaN(fileId) || fileId <= 0) {
  41. return null;
  42. }
  43. let unitPriceList = await this.db.model.find({unit_price_file_id: fileId});
  44. if (unitPriceList.length <= 0) {
  45. return null;
  46. }
  47. // 整理数据
  48. let result = {};
  49. for(let tmp of unitPriceList) {
  50. let index = this.getIndex(tmp,['code','name','specs','unit','type'])
  51. result[index] = tmp;
  52. }
  53. return result;
  54. }
  55. /**
  56. * 设置场景
  57. *
  58. * @param {string} scene
  59. * @return {void}
  60. */
  61. setScene(scene = '') {
  62. switch (scene) {
  63. // 新增数据的验证规则
  64. case 'add':
  65. this.model.schema.path('base_price').required(true);
  66. this.model.schema.path('market_price').required(true);
  67. this.model.schema.path('name').required(true);
  68. this.model.schema.path('code').required(true);
  69. // this.model.schema.path('unit').required(true);
  70. this.model.schema.path('type').required(true);
  71. this.model.schema.path('unit_price_file_id').required(true);
  72. }
  73. }
  74. /**
  75. * 新增单价数据
  76. *
  77. * @param {Object} data
  78. * @param {Number} unitPriceFileId
  79. * @param {Number} gljCount
  80. * @return {Promise} 返回数据以及是否新增
  81. */
  82. async addUnitPrice(data, unitPriceFileId,operation='add', gljCount = 0) {
  83. if (data.original_code===undefined||data.code === undefined || data.project_id === undefined || data.name === undefined
  84. || data.market_price === undefined) {
  85. return [null, false];
  86. }
  87. // 先查找是否有原始code相同的记录
  88. let unitPriceData = await this.db.model.find({original_code: data.original_code, unit_price_file_id: unitPriceFileId}).sort('code').exec();
  89. // 如果有记录,判断是否存在一样的名称,单位...等,有则直接返回数据
  90. let unitPrice=null;
  91. if(operation=='add'){//新增操作时,要把code也一起判断,是否完全一样。(新增的时候有可能存在编码一样,但是名称规格等不一样的情况,这种情况的话编码不用改变)
  92. unitPrice = this.isPropertyInclude(unitPriceData,['code','name','specs','unit','type'],data);
  93. }else {//修改操作时,code不用加入判断,因为code是需要改变的
  94. unitPrice = this.isPropertyInclude(unitPriceData,['name','specs','unit','type'],data);
  95. }
  96. if(unitPrice){
  97. return [unitPrice, false];
  98. }
  99. // 如果不存在基价单价,则在数据源中获取
  100. if (data.base_price === undefined) {
  101. let firstUnitPrice = unitPriceData[0] !== undefined ? unitPriceData[0] : [];
  102. data.base_price = firstUnitPrice.base_price !== undefined ? firstUnitPrice.base_price : 0;
  103. data.type = firstUnitPrice.type !== undefined ? firstUnitPrice.type : 0;
  104. }
  105. let insertData = {
  106. code: data.code,
  107. base_price: data.base_price,
  108. market_price: data.market_price,
  109. unit_price_file_id: unitPriceFileId,
  110. name: data.name,
  111. specs:data.specs?data.specs:'',
  112. original_code:data.original_code,
  113. unit:data.unit?data.unit:'',
  114. type: data.type,
  115. short_name: data.shortName !== undefined ? data.shortName : '',
  116. glj_id: data.glj_id,
  117. is_add:0,
  118. grossWeightCoe:data.grossWeightCoe,
  119. purchaseStorageRate:data.purchaseStorageRate,
  120. offSiteTransportLossRate:data.offSiteTransportLossRate,
  121. handlingLossRate:data.handlingLossRate
  122. };
  123. if(data.from=='cpt') insertData.is_add=1;//如果是来自补充工料机,则都添加新增标记
  124. if(operation=='add' && insertData.code != insertData.original_code) insertData.is_add=1;//添加的时候如果是复制整块来的,可能在源项目中是新增的工料机,这里也要添上
  125. if (unitPriceData&&unitPriceData.length>0&&operation!='add') {// 如果原始编码能找到,但不存在一样的编号,名称,单位.型号等,更改code和添加新增标记,新增的时候除外。新增的情况下能到这一步说明有存在编码一致但其它属性不一致的情况,所以不用更改编码
  126. //insertData.code = data.original_code+"-"+unitPriceData.length;
  127. insertData.code = data.original_code+"-"+this.getLastNumber(data.original_code,unitPriceData);
  128. insertData.is_add=1;
  129. }
  130. let addPriceResult = await this.add(insertData);
  131. return [addPriceResult, true];
  132. }
  133. getLastNumber(original_code,unitPriceData){
  134. let codeArray = _.map(unitPriceData,'code');
  135. let last = 1;
  136. while (true){
  137. if(_.includes(codeArray,original_code+"-"+last)){
  138. last +=1
  139. }else {
  140. break;
  141. }
  142. }
  143. return last;
  144. }
  145. /**
  146. * 新增记录
  147. *
  148. * @param {object} data
  149. * @return {Promise}
  150. */
  151. async add(data) {
  152. let counterModel = new CounterModel();
  153. if (data instanceof Array) {
  154. // 如果是批量新增
  155. await this.setIDfromCounter(collectionName,data);
  156. /* for(let tmp in data) {
  157. data[tmp].id = await counterModel.getId(collectionName);
  158. } */
  159. } else {
  160. data.id = await counterModel.getId(collectionName);
  161. }
  162. this.setScene('add');
  163. return await this.db.model.create(data);
  164. }
  165. /**
  166. * 判断数据中是否包含某个市场价格的记录
  167. *
  168. * @param {Array} data
  169. * @param {Number} price
  170. * @return {Number}
  171. */
  172. isPriceIncluded(data, price) {
  173. let index = -1;
  174. if (data.length <= 0) {
  175. return index;
  176. }
  177. for(let tmp in data) {
  178. if (data[tmp].market_price === price) {
  179. index = tmp;
  180. break;
  181. }
  182. }
  183. return index;
  184. }
  185. isPropertyInclude(data,pops,obj){
  186. let condition={},me = this;
  187. if (data.length <= 0) {
  188. return null;
  189. }
  190. if(pops instanceof Array){
  191. return _.find(data,function (d) {
  192. return me.getIndex(d,pops) == me.getIndex(obj,pops)
  193. });
  194. }else {
  195. condition[pops]=obj[pops];
  196. return _.find(data,condition);
  197. }
  198. }
  199. /**
  200. * 更新市场单价
  201. *
  202. * @param {Object} condition
  203. * @param {Object} updateData
  204. * @param {String} extend
  205. * @return {Promise}
  206. */
  207. async updatePrice(condition, updateData, extend = '') {
  208. if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
  209. return false;
  210. }
  211. // 首先查找相应的数据判断工料机类型
  212. let unitPriceData = await this.findDataByCondition(condition);
  213. if (!unitPriceData) {
  214. throw '找不到对应的单价数据';
  215. }
  216. /* // 基价单价的计算-----先不考虑同步
  217. switch (unitPriceData.type) {
  218. // 主材、设备自动赋值基价单价=市场单价
  219. case GLJTypeConst.MAIN_MATERIAL:
  220. case GLJTypeConst.EQUIPMENT:
  221. updateData.base_price = updateData.market_price;
  222. break;
  223. }*/
  224. // 额外更新数据
  225. if (extend !== '') {
  226. extend = JSON.parse(extend);
  227. let indexList = ['code','name','specs','unit','type'];
  228. for (let conKey in extend) {
  229. let extendUpdateData = {
  230. market_price: extend[conKey].market_price,
  231. };
  232. let tmpCondition = {
  233. unit_price_file_id: unitPriceData.unit_price_file_id,
  234. };
  235. let keyList = conKey.split("|-|");
  236. for(let i = 1;i<keyList.length;i++){
  237. if(keyList[i]!='null'){
  238. tmpCondition[indexList[i]]=keyList[i];
  239. }
  240. }
  241. let extendResult = await this.db.update(tmpCondition, extendUpdateData);
  242. if (!extendResult) {
  243. throw '更新额外数据,编码为' + code + '的数据失败!';
  244. }
  245. }
  246. }
  247. let result = await this.db.update(condition, updateData);
  248. return result.ok !== undefined && result.ok === 1;
  249. }
  250. async updateUnitPrice(data){
  251. //查找并更新单价
  252. let doc={},newValueMap={};
  253. doc[data.field]=data.newval;
  254. newValueMap[data.id]=doc;
  255. let unitPrice = await this.db.findAndModify({id:data.id,unit_price_file_id:data.unit_price_file_id},doc);
  256. if(!unitPrice){
  257. throw "没有找到对应的单价";
  258. }
  259. let rList=await this.checkAndUpdateParent(unitPrice,data.field,data.project_id,newValueMap);
  260. if(data.ext){
  261. let elecPrice = await this.db.findAndModify({id:data.ext.id,unit_price_file_id:data.ext.unit_price_file_id},data.ext.doc);
  262. let nm = {};
  263. nm[data.ext.id] = data.ext.doc;
  264. let erList=await this.checkAndUpdateParent(elecPrice,"market_price",data.project_id,nm);
  265. rList = rList.concat(erList);
  266. }
  267. return rList;
  268. }
  269. async updateCalcMaterial(datas){
  270. for(let data of datas){
  271. let doc = data.ext?data.ext:{};
  272. doc[data.updateField] = data.value;
  273. let unitPrice = await this.db.findAndModify({id:data.id,unit_price_file_id:data.unit_price_file_id},doc);
  274. if(data.updateField == 'calcMaterial' && doc['calcMaterial'] == 0){//标记为0即删除材料计算标记,要删除其下挂的原价计算,运费计算,定额计算
  275. let connect_key = gljUtil.getIndex(unitPrice);
  276. await original_calc_model.deleteMany({unit_price_file_id:data.unit_price_file_id,connect_key:connect_key});
  277. await freight_calc_model.deleteMany({unit_price_file_id:data.unit_price_file_id,connect_key:connect_key});
  278. //to do 删除定额计算
  279. }
  280. if(!unitPrice){
  281. throw "没有找到对应的单价";
  282. }
  283. }
  284. return datas;
  285. }
  286. needUpdateParent(connect_key){
  287. let noNeedUpdateType = ["202","203","204"];//父类型为混凝土、砂浆,配合比,类型的,不用更新价格
  288. let keyList = connect_key.split("|-|");
  289. return noNeedUpdateType.indexOf(keyList[4]) == -1
  290. }
  291. async checkAndUpdateParent(unitPrice,field,project_id,newValueMap,batchUpdate=false){//检查是否属于某个工料机的组成物,如果是,并且不是批量更新的情况下,直接更新,如果是批量更新,返回更新任务
  292. //查找是否是属于某个项目工料机的组成物
  293. let mixRatioModel = new MixRatioModel();
  294. let condition = {unit_price_file_id:unitPrice.unit_price_file_id, code:unitPrice.code,name: unitPrice.name, specs: unitPrice.specs,unit:unitPrice.unit,type:unitPrice.type};
  295. let mixRatioList = await mixRatioModel.findDataByCondition(condition, null, false);
  296. let connectKeyMap={};
  297. //找到则计算项目工料机组成物的价格并更新
  298. let rList= [];
  299. if(mixRatioList&&mixRatioList.length>0){
  300. for(let m of mixRatioList){
  301. // 父类型不为混凝土、砂浆,配合比,类型的,才要更新价格
  302. if(this.needUpdateParent(m.connect_key) && !connectKeyMap.hasOwnProperty(m.connect_key)){//为了去重复,组成物会与其它项目同步,所以有可能重复。
  303. rList.push(await this.updateParentUnitPrice(m,field,project_id,newValueMap,batchUpdate));
  304. connectKeyMap[m.connect_key]=true;
  305. }
  306. }
  307. }
  308. return rList;
  309. }
  310. async batchUpdatePrices(data){//批量更新
  311. let tasks = [];
  312. let parentTask = [];
  313. let newValueMap = {};
  314. let needCheckDatas= [];
  315. for(let d of data){//第一次循环生成更新提交的记录,并生成一个新值的映射表,为更新父节点使用
  316. let condition = {id:d.unit_price.id,unit_price_file_id:d.unit_price.unit_price_file_id};
  317. let doc = d.ext?d.ext:{};
  318. if(d.field){//共用接口后有可能只更新其它属性,不更新价格
  319. doc[d.field]=d.newval;
  320. newValueMap[d.unit_price.id] = doc;
  321. needCheckDatas.push(d);
  322. }
  323. tasks.push(this.generateUpdateTask(condition,doc));
  324. }
  325. for(let d of needCheckDatas){//第二次更新父节点
  326. let rList = await this.checkAndUpdateParent(d.unit_price,d.field,d.project_id,newValueMap,true);
  327. parentTask = parentTask.concat(rList);
  328. }
  329. tasks = tasks.concat(parentTask);
  330. tasks.length>0?this.model.bulkWrite(tasks):'';
  331. return parentTask;
  332. }
  333. async updateParentUnitPrice(mixRatio,fieid,project_id,newValueMap,batchUpdate){//batchUpdate 批量更新标记,如果true,只生成task
  334. let decimalObject =project_id?await decimal_facade.getProjectDecimal(project_id):null;
  335. let quantity_decimal = (decimalObject&&decimalObject.glj&&decimalObject.glj.quantity)?decimalObject.glj.quantity:3;
  336. let price_decimal = (decimalObject&&decimalObject.glj&&decimalObject.glj.unitPrice)?decimalObject.glj.unitPrice:2;
  337. //查找该工料机所有组成物
  338. let indexList = ['code','name','specs','unit','type'];
  339. let mixRatioModel = new MixRatioModel();
  340. let mixRatioMap = await mixRatioModel.findDataByCondition({unit_price_file_id:mixRatio.unit_price_file_id,connect_key:mixRatio.connect_key}, null, false,indexList);
  341. //查找对应的价格
  342. let codeList = [];
  343. let nameList = [];
  344. let specsList= [];
  345. let typeList = [];
  346. let unitList = [];
  347. for(let mk in mixRatioMap){
  348. codeList.push(mixRatioMap[mk].code);
  349. nameList.push(mixRatioMap[mk].name);
  350. specsList.push(mixRatioMap[mk].specs);
  351. typeList.push(mixRatioMap[mk].type);
  352. unitList.push(mixRatioMap[mk].unit);
  353. }
  354. let condition = {unit_price_file_id: mixRatio.unit_price_file_id,code: {"$in": codeList}, name: {"$in": nameList},specs:{"$in": specsList},type:{"$in": typeList},unit:{"$in": unitList}};
  355. let priceMap = await this.findDataByCondition(condition, {_id: 0}, false, indexList);
  356. let sumPrice=0;
  357. for(let pk in priceMap){
  358. let price = scMathUtil.roundForObj(priceMap[pk][fieid],price_decimal);
  359. let consumption = scMathUtil.roundForObj(mixRatioMap[pk].consumption,quantity_decimal);
  360. if(newValueMap[priceMap[pk].id]){//是需要更新的记录,取当前新的值
  361. price = scMathUtil.roundForObj(newValueMap[priceMap[pk].id][fieid],price_decimal);
  362. }
  363. sumPrice +=scMathUtil.roundForObj(price*consumption,price_decimal);
  364. }
  365. sumPrice= scMathUtil.roundForObj(sumPrice,price_decimal);
  366. if(sumPrice<=0){
  367. return null;
  368. }
  369. //更新父价格
  370. let keyList = mixRatio.connect_key.split("|-|");
  371. let pcondition = {
  372. unit_price_file_id:mixRatio.unit_price_file_id,
  373. code:keyList[0]
  374. };
  375. for(let i = 1;i<keyList.length;i++){
  376. if(keyList[i]!='null'){
  377. pcondition[indexList[i]]=keyList[i];
  378. }
  379. }
  380. let doc={};
  381. doc[fieid]=sumPrice;
  382. if(batchUpdate == true){
  383. return this.generateUpdateTask(pcondition,doc);
  384. }else {
  385. let uprice = await this.db.findAndModify(pcondition,doc,{new: true});
  386. //uprice[fieid]=sumPrice;
  387. return uprice;
  388. }
  389. }
  390. generateUpdateTask(condition,doc) {
  391. let task = {
  392. updateOne:{
  393. filter:condition,
  394. update:doc
  395. }
  396. };
  397. return task
  398. }
  399. /**
  400. * 复制单价文件数据
  401. *
  402. * @param {Number} currentUnitPriceId
  403. * @param {Number} changeUnitPriceId
  404. * @return {Promise}
  405. */
  406. async copyNotExist(currentUnitPriceId, changeUnitPriceId,projectId) {
  407. let result = false;
  408. // 首先查找原单价文件id下的数据
  409. let currentUnitList = await this.model.find({unit_price_file_id: currentUnitPriceId}).lean();
  410. if (currentUnitList === null) {
  411. return result;
  412. }
  413. let gljList = await gljListModel.find({'project_id':projectId}).lean();
  414. let gljMap = {};//用来记录glj的映射表,本项目有使用的工料机才需要copy过去
  415. for(let g of gljList){
  416. let g_index = this.getIndex(g,['code','name','specs','unit','type']);
  417. gljMap[g_index] = g;
  418. }
  419. let codeList = [];
  420. let nameList =[];
  421. for (let tmp of currentUnitList) {
  422. if (codeList.indexOf(tmp.code) >= 0) {
  423. continue;
  424. }
  425. codeList.push(tmp.code);
  426. if(nameList.indexOf(tmp.name)>=0){
  427. continue
  428. }
  429. nameList.push(tmp.name);
  430. }
  431. // 查找即将更替的单价文件是否存在对应的工料机数据 -- (这里只根据code和名称初步过滤,因为其它的几项更改的概率不大,在下一步的比较中再精确匹配)
  432. let condition = {unit_price_file_id: changeUnitPriceId, code: {"$in": codeList},name:{"$in": nameList}};
  433. let targetUnitList = await this.findDataByCondition(condition, null, false, ['code','name','specs','unit','type']);
  434. // 如果没有重叠的数据则原有的数据都复制一份
  435. let insertData = [];
  436. for (let tmp of currentUnitList) {
  437. let t_index = this.getIndex(tmp,['code','name','specs','unit','type']);
  438. if (targetUnitList !== null && targetUnitList[t_index] !== undefined) {
  439. continue;
  440. }
  441. if(gljMap[t_index]){//如果本项目有用到才复制
  442. delete tmp._id; // 删除原有id信息
  443. delete tmp.id;
  444. tmp.unit_price_file_id = changeUnitPriceId;
  445. insertData.push(tmp);
  446. }
  447. }
  448. let uResult = insertData.length > 0 ? await this.add(insertData) : true;
  449. let mixRatioModel = new MixRatioModel();
  450. let mResult = await mixRatioModel.copyNotExist(currentUnitPriceId, changeUnitPriceId,gljMap);//复制组成物
  451. let cResult = await this.copyMaterialNotExist(currentUnitPriceId, changeUnitPriceId,gljMap);
  452. return uResult&&mResult&&cResult;
  453. }
  454. async copyMaterialNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,newFile = false){
  455. await this.copyCalcNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,original_calc_model,newFile);//复制原价计算
  456. await this.copyCalcNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,freight_calc_model,newFile);//复制运费计算
  457. return true;
  458. }
  459. async copyCalcNotExist(currentUnitPriceId, changeUnitPriceId,gljMap,model,newFile){
  460. let currentMap = {},targetMap = {}, insertData = [];
  461. //取原单价文件所有的原价、运费计算计录
  462. let currentList = await model.find({'unit_price_file_id':currentUnitPriceId}).lean();
  463. currentMap = _.groupBy(currentList,"connect_key");
  464. //切换后的单价文件所有的的组成物
  465. let targetList = await model.find({'unit_price_file_id':changeUnitPriceId});
  466. targetMap = _.groupBy(targetList,"connect_key");
  467. for(let ckey in currentMap){
  468. if(targetMap[ckey]){//如果切换后已经存在,则不用复制
  469. continue;
  470. }
  471. if(gljMap[ckey] || newFile == true){//在本项目中有用到 或者 新建的文件
  472. for(let c of currentMap[ckey]){
  473. delete c._id; // 删除原有id信息
  474. c.ID = uuidV1();
  475. c.unit_price_file_id = changeUnitPriceId;
  476. //更改下挂的定额工料机与项目工料机的关联关系
  477. if(c.ration_gljs){
  478. for(let rg of c.ration_gljs){
  479. rg.ID = uuidV1();
  480. }
  481. }
  482. if(c.rations){
  483. for(let r of c.rations){
  484. r.ID = uuidV1();
  485. }
  486. }
  487. insertData.push(c);
  488. }
  489. }
  490. }
  491. if(insertData.length > 0) await model.create(insertData);
  492. }
  493. }
  494. module.exports = UnitPriceModel;