unit_price_model.js 21 KB

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