unit_price_model.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /**
  2. * 单价业务模型
  3. *
  4. * @author CaiAoLin
  5. * @date 2017/6/30
  6. * @version
  7. */
  8. import mongoose from "mongoose";
  9. import BaseModel from "../../common/base/base_model"
  10. import GLJTypeConst from "../../common/const/glj_type_const"
  11. import CounterModel from "./counter_model"
  12. import MixRatioModel from "./mix_ratio_model";
  13. import _ from "lodash";
  14. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  15. let collectionName = 'unit_price';
  16. let decimal_facade = require('../../main/facade/decimal_facade');
  17. class UnitPriceModel extends BaseModel {
  18. /**
  19. * 构造函数
  20. *
  21. * @return {void}
  22. */
  23. constructor() {
  24. let parent = super();
  25. parent.model = mongoose.model(collectionName);
  26. parent.init();
  27. }
  28. /**
  29. * 根据单价文件id获取单价数据
  30. *
  31. * @param {Number} fileId
  32. * @return {Promise}
  33. */
  34. async getDataByFileId(fileId) {
  35. fileId = parseInt(fileId);
  36. if (isNaN(fileId) || fileId <= 0) {
  37. return null;
  38. }
  39. let unitPriceList = await this.db.model.find({unit_price_file_id: fileId});
  40. if (unitPriceList.length <= 0) {
  41. return null;
  42. }
  43. // 整理数据
  44. let result = {};
  45. for(let tmp of unitPriceList) {
  46. let index = this.getIndex(tmp,['code','name','specs','unit','type'])
  47. result[index] = tmp;
  48. }
  49. return result;
  50. }
  51. /**
  52. * 设置场景
  53. *
  54. * @param {string} scene
  55. * @return {void}
  56. */
  57. setScene(scene = '') {
  58. switch (scene) {
  59. // 新增数据的验证规则
  60. case 'add':
  61. this.model.schema.path('base_price').required(true);
  62. this.model.schema.path('market_price').required(true);
  63. this.model.schema.path('name').required(true);
  64. this.model.schema.path('code').required(true);
  65. // this.model.schema.path('unit').required(true);
  66. this.model.schema.path('type').required(true);
  67. this.model.schema.path('unit_price_file_id').required(true);
  68. }
  69. }
  70. /**
  71. * 新增单价数据
  72. *
  73. * @param {Object} data
  74. * @param {Number} unitPriceFileId
  75. * @param {Number} gljCount
  76. * @return {Promise} 返回数据以及是否新增
  77. */
  78. async addUnitPrice(data, unitPriceFileId,operation='add', gljCount = 0) {
  79. if (data.original_code===undefined||data.code === undefined || data.project_id === undefined || data.name === undefined
  80. || data.market_price === undefined) {
  81. return [null, false];
  82. }
  83. // 先查找是否有原始code相同的记录
  84. let unitPriceData = await this.db.model.find({original_code: data.original_code, unit_price_file_id: unitPriceFileId}).sort('code').exec();
  85. // 如果有记录,判断是否存在一样的名称,单位...等,有则直接返回数据
  86. let unitPrice=null;
  87. if(operation=='add'){//新增操作时,要把code也一起判断,是否完全一样。(新增的时候有可能存在编码一样,但是名称规格等不一样的情况,这种情况的话编码不用改变)
  88. unitPrice = this.isPropertyInclude(unitPriceData,['code','name','specs','unit','type'],data);
  89. }else {//修改操作时,code不用加入判断,因为code是需要改变的
  90. unitPrice = this.isPropertyInclude(unitPriceData,['name','specs','unit','type'],data);
  91. }
  92. if(unitPrice){
  93. return [unitPrice, false];
  94. }
  95. // 如果不存在基价单价,则在数据源中获取
  96. if (data.base_price === undefined) {
  97. let firstUnitPrice = unitPriceData[0] !== undefined ? unitPriceData[0] : [];
  98. data.base_price = firstUnitPrice.base_price !== undefined ? firstUnitPrice.base_price : 0;
  99. data.type = firstUnitPrice.type !== undefined ? firstUnitPrice.type : 0;
  100. }
  101. let insertData = {
  102. code: data.code,
  103. base_price: data.base_price,
  104. market_price: data.market_price,
  105. unit_price_file_id: unitPriceFileId,
  106. name: data.name,
  107. specs:data.specs,
  108. original_code:data.original_code,
  109. unit:data.unit,
  110. type: data.type,
  111. short_name: data.shortName !== undefined ? data.shortName : '',
  112. glj_id: data.glj_id,
  113. is_add:0
  114. };
  115. if(data.from=='cpt'){//如果是来自补充工料机,则都添加新增标记
  116. insertData.is_add=1;
  117. }
  118. if (unitPriceData&&unitPriceData.length>0&&operation!='add') {// 如果原始编码能找到,但不存在一样的编号,名称,单位.型号等,更改code和添加新增标记,新增的时候除外。新增的情况下能到这一步说明有存在编码一致但其它属性不一致的情况,所以不用更改编码
  119. insertData.code = data.original_code+"-"+unitPriceData.length;
  120. insertData.is_add=1;
  121. }
  122. let addPriceResult = await this.add(insertData);
  123. return [addPriceResult, true];
  124. }
  125. /**
  126. * 新增记录
  127. *
  128. * @param {object} data
  129. * @return {Promise}
  130. */
  131. async add(data) {
  132. let counterModel = new CounterModel();
  133. if (data instanceof Array) {
  134. // 如果是批量新增
  135. for(let tmp in data) {
  136. data[tmp].id = await counterModel.getId(collectionName);
  137. }
  138. } else {
  139. data.id = await counterModel.getId(collectionName);
  140. }
  141. this.setScene('add');
  142. return this.db.model.create(data);
  143. }
  144. /**
  145. * 判断数据中是否包含某个市场价格的记录
  146. *
  147. * @param {Array} data
  148. * @param {Number} price
  149. * @return {Number}
  150. */
  151. isPriceIncluded(data, price) {
  152. let index = -1;
  153. if (data.length <= 0) {
  154. return index;
  155. }
  156. for(let tmp in data) {
  157. if (data[tmp].market_price === price) {
  158. index = tmp;
  159. break;
  160. }
  161. }
  162. return index;
  163. }
  164. isPropertyInclude(data,pops,obj){
  165. let condition={};
  166. if (data.length <= 0) {
  167. return null;
  168. }
  169. if(pops instanceof Array){
  170. for(let p of pops){
  171. if(obj[p]){
  172. condition[p]=obj[p]
  173. }
  174. }
  175. }else {
  176. condition[pops]=obj[pops]
  177. }
  178. return _.find(data,condition);
  179. }
  180. /**
  181. * 更新市场单价
  182. *
  183. * @param {Object} condition
  184. * @param {Object} updateData
  185. * @param {String} extend
  186. * @return {Promise}
  187. */
  188. async updatePrice(condition, updateData, extend = '') {
  189. if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
  190. return false;
  191. }
  192. // 首先查找相应的数据判断工料机类型
  193. let unitPriceData = await this.findDataByCondition(condition);
  194. if (!unitPriceData) {
  195. throw '找不到对应的单价数据';
  196. }
  197. /* // 基价单价的计算-----先不考虑同步
  198. switch (unitPriceData.type) {
  199. // 主材、设备自动赋值基价单价=市场单价
  200. case GLJTypeConst.MAIN_MATERIAL:
  201. case GLJTypeConst.EQUIPMENT:
  202. updateData.base_price = updateData.market_price;
  203. break;
  204. }*/
  205. // 额外更新数据
  206. if (extend !== '') {
  207. extend = JSON.parse(extend);
  208. let indexList = ['code','name','specs','unit','type'];
  209. for (let conKey in extend) {
  210. let extendUpdateData = {
  211. market_price: extend[conKey].market_price,
  212. };
  213. let tmpCondition = {
  214. unit_price_file_id: unitPriceData.unit_price_file_id,
  215. };
  216. let keyList = conKey.split("|-|");
  217. for(let i = 1;i<keyList.length;i++){
  218. if(keyList[i]!='null'){
  219. tmpCondition[indexList[i]]=keyList[i];
  220. }
  221. }
  222. let extendResult = await this.db.update(tmpCondition, extendUpdateData);
  223. if (!extendResult) {
  224. throw '更新额外数据,编码为' + code + '的数据失败!';
  225. }
  226. }
  227. }
  228. let result = await this.db.update(condition, updateData);
  229. return result.ok !== undefined && result.ok === 1;
  230. }
  231. async updateUnitPrice(data){
  232. //查找并更新单价
  233. let doc={};
  234. doc[data.field]=data.newval;
  235. let unitPrice = await this.db.findAndModify({id:data.id},doc);
  236. if(!unitPrice){
  237. throw "没有找到对应的单价";
  238. }
  239. //查找是否是属于某个项目工料机的组成物
  240. let mixRatioModel = new MixRatioModel();
  241. 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};
  242. let mixRatioList = await mixRatioModel.findDataByCondition(condition, null, false);
  243. let connectKeyMap={};
  244. //找到则计算项目工料机组成物的价格并更新
  245. let rList= [];
  246. if(mixRatioList&&mixRatioList.length>0){
  247. for(let m of mixRatioList){
  248. if(!connectKeyMap.hasOwnProperty(m.connect_key)){//为了去重复,组成物会与其它项目同步,所以有可能重复。
  249. rList.push(await this.updateParentUnitPrice(m,data.field,data.project_id));
  250. connectKeyMap[m.connect_key]=true;
  251. }
  252. }
  253. }
  254. return rList;
  255. }
  256. async updateParentUnitPrice(mixRatio,fieid,project_id){
  257. let decimalObject =await decimal_facade.getProjectDecimal(project_id);
  258. let quantity_decimal = (decimalObject&&decimalObject.glj&&decimalObject.glj.quantity)?decimalObject.glj.quantity:3;
  259. let price_decimal = (decimalObject&&decimalObject.glj&&decimalObject.glj.unitPrice)?decimalObject.glj.unitPrice:2;
  260. //查找该工料机所有组成物
  261. let indexList = ['code','name','specs','unit','type'];
  262. let mixRatioModel = new MixRatioModel();
  263. let mixRatioMap = await mixRatioModel.findDataByCondition({unit_price_file_id:mixRatio.unit_price_file_id,connect_key:mixRatio.connect_key}, null, false,indexList);
  264. //查找对应的价格
  265. let codeList = [];
  266. let nameList = [];
  267. let specsList= [];
  268. let typeList = [];
  269. let unitList = [];
  270. for(let mk in mixRatioMap){
  271. codeList.push(mixRatioMap[mk].code);
  272. nameList.push(mixRatioMap[mk].name);
  273. specsList.push(mixRatioMap[mk].specs);
  274. typeList.push(mixRatioMap[mk].type);
  275. unitList.push(mixRatioMap[mk].unit);
  276. }
  277. 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}};
  278. let priceMap = await this.findDataByCondition(condition, {_id: 0}, false, indexList);
  279. let sumPrice=0;
  280. for(let pk in priceMap){
  281. let price = scMathUtil.roundForObj(priceMap[pk][fieid],price_decimal);
  282. let consumption = scMathUtil.roundForObj(mixRatioMap[pk].consumption,quantity_decimal);
  283. sumPrice +=scMathUtil.roundForObj(price*consumption,price_decimal);
  284. }
  285. sumPrice= scMathUtil.roundForObj(sumPrice,price_decimal);
  286. if(sumPrice<=0){
  287. return null;
  288. }
  289. //更新父价格
  290. let keyList = mixRatio.connect_key.split("|-|");
  291. let pcondition = {
  292. unit_price_file_id:mixRatio.unit_price_file_id,
  293. code:keyList[0]
  294. };
  295. for(let i = 1;i<keyList.length;i++){
  296. if(keyList[i]!='null'){
  297. pcondition[indexList[i]]=keyList[i];
  298. }
  299. }
  300. let doc={};
  301. doc[fieid]=sumPrice;
  302. let uprice = await this.db.findAndModify(pcondition,doc);
  303. uprice[fieid]=sumPrice;
  304. return uprice;
  305. }
  306. /**
  307. * 复制单价文件数据
  308. *
  309. * @param {Number} currentUnitPriceId
  310. * @param {Number} changeUnitPriceId
  311. * @return {Promise}
  312. */
  313. async copyNotExist(currentUnitPriceId, changeUnitPriceId) {
  314. let result = false;
  315. // 首先查找原单价文件id下的数据
  316. let currentUnitList = await this.findDataByCondition({unit_price_file_id: currentUnitPriceId}, null, false);
  317. if (currentUnitList === null) {
  318. return result;
  319. }
  320. // 过滤mongoose格式
  321. currentUnitList = JSON.stringify(currentUnitList);
  322. currentUnitList = JSON.parse(currentUnitList);
  323. let codeList = [];
  324. let nameList =[];
  325. for (let tmp of currentUnitList) {
  326. if (codeList.indexOf(tmp.code) >= 0) {
  327. continue;
  328. }
  329. codeList.push(tmp.code);
  330. if(nameList.indexOf(tmp.name)>=0){
  331. continue
  332. }
  333. nameList.push(tmp.name);
  334. }
  335. // 查找即将更替的单价文件是否存在对应的工料机数据 -- (这里只根据code和名称初步过滤,因为其它的几项更改的概率不大,在下一步的比较中再精确匹配)
  336. let condition = {unit_price_file_id: changeUnitPriceId, code: {"$in": codeList},name:{"$in": nameList}};
  337. let targetUnitList = await this.findDataByCondition(condition, null, false, ['code','name','specs','unit','type']);
  338. // 如果没有重叠的数据则原有的数据都复制一份
  339. let insertData = [];
  340. for (let tmp of currentUnitList) {
  341. let t_index = this.getIndex(tmp,['code','name','specs','unit','type']);
  342. if (targetUnitList !== null && targetUnitList[t_index] !== undefined) {
  343. continue;
  344. }
  345. // 删除原有id信息
  346. delete tmp._id;
  347. delete tmp.id;
  348. tmp.unit_price_file_id = changeUnitPriceId;
  349. insertData.push(tmp);
  350. }
  351. return insertData.length > 0 ? this.add(insertData) : true;
  352. }
  353. }
  354. export default UnitPriceModel;