unit_price_model.js 14 KB

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