ration_item.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. /**
  2. * Created by Tony on 2017/4/28.
  3. */
  4. const mongoose = require('mongoose');
  5. let async = require("async");
  6. let moment = require('moment');
  7. let counter = require('../../../public/counter/counter');
  8. let gljDao = require('./glj_repository');
  9. let rationRepositoryDao = require('./repository_map');
  10. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  11. const rationItemModel = mongoose.model('std_ration_lib_ration_items');
  12. const stdRationLibModel = mongoose.model('std_ration_lib_map');
  13. const compleRationModel = mongoose.model('complementary_ration_items');
  14. import STDGLJListModel from '../../std_glj_lib/models/gljModel';
  15. var rationItemDAO = function(){};
  16. rationItemDAO.prototype.getRationItemsByLib = async function (rationRepId, showHint = null, returnFields = '') {
  17. let rationLib = await stdRationLibModel.findOne({ID: rationRepId, deleted: false});
  18. if(!rationLib){
  19. return [];
  20. }
  21. let startDate = new Date();
  22. let rations = await rationItemModel.find({rationRepId: rationRepId}, returnFields);
  23. console.log(`Date: ${new Date() - startDate}====================================`);
  24. if(!showHint){
  25. return rations;
  26. }
  27. else {
  28. const stdBillsLibListsModel = new STDGLJListModel();
  29. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib, '-_id ID code name unit gljType');
  30. let gljMapping = {};
  31. for(let glj of stdGLJData){
  32. gljMapping[glj.ID] = glj;
  33. }
  34. //设置悬浮
  35. for(let ration of rations){
  36. let hintsArr = [];
  37. //对人材机进行排序
  38. ration.rationGljList.sort(function (a, b) {
  39. let gljA = gljMapping[a.gljId],
  40. gljB = gljMapping[b.gljId];
  41. if(gljA && gljB){
  42. let aV = gljA.gljType + gljA.code,
  43. bV = gljB.gljType + gljB.code;
  44. if(aV > bV) {
  45. return 1;
  46. } else if(aV < bV) {
  47. return -1;
  48. }
  49. }
  50. return 0;
  51. });
  52. for(let rationGlj of ration.rationGljList){
  53. let subGlj = gljMapping[rationGlj.gljId];
  54. if(subGlj){
  55. hintsArr.push(` ${subGlj.code} ${subGlj.name}${subGlj.specs ? '&nbsp;&nbsp;&nbsp;' + subGlj.specs : ''}&nbsp;&nbsp&nbsp;${subGlj.unit}&nbsp;&nbsp;&nbsp;${rationGlj.consumeAmt}`);
  56. }
  57. }
  58. hintsArr.push(`基价 元 ${ration.basePrice}`);
  59. if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
  60. hintsArr.push(`工作内容:`);
  61. hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
  62. }
  63. if(ration.annotation && ration.annotation.toString().trim() !== ''){
  64. hintsArr.push(`附注:`);
  65. hintsArr = hintsArr.concat(ration.annotation.split('\n'));
  66. }
  67. ration._doc.hint = hintsArr.join('<br>');
  68. }
  69. return rations;
  70. }
  71. };
  72. rationItemDAO.prototype.sortToNumber = function (datas) {
  73. for(let i = 0, len = datas.length; i < len; i++){
  74. let data = datas[i]._doc;
  75. if(_exist(data, 'labourPrice')){
  76. data['labourPrice'] = parseFloat(data['labourPrice']);
  77. }
  78. if(_exist(data, 'materialPrice')){
  79. data['materialPrice'] = parseFloat(data['materialPrice']);
  80. }
  81. if(_exist(data, 'machinePrice')){
  82. data['machinePrice'] = parseFloat(data['machinePrice']);
  83. }
  84. if(_exist(data, 'basePrice')){
  85. data['basePrice'] = parseFloat(data['basePrice']);
  86. }
  87. if(_exist(data, 'rationGljList')){
  88. for(let j = 0, jLen = data['rationGljList'].length; j < jLen; j++){
  89. let raGljObj = data['rationGljList'][j]._doc;
  90. if(_exist(raGljObj, 'consumeAmt')){
  91. raGljObj['consumeAmt'] = parseFloat(raGljObj['consumeAmt']);
  92. }
  93. }
  94. }
  95. }
  96. function _exist(data, attr){
  97. return data && data[attr] !== undefined && data[attr];
  98. }
  99. };
  100. rationItemDAO.prototype.getRationItemsBySection = async function(rationRepId, sectionId,callback){
  101. let me = this;
  102. try {
  103. let rations = await rationItemModel.find({rationRepId: rationRepId, sectionId: sectionId});
  104. me.sortToNumber(rations);
  105. let matchRationIDs = [],
  106. matchRations = [];
  107. for (let ration of rations) {
  108. if (ration.rationTemplateList) {
  109. for (let rt of ration.rationTemplateList) {
  110. if (rt.rationID) {
  111. matchRationIDs.push(rt.rationID);
  112. }
  113. }
  114. }
  115. }
  116. if (matchRationIDs.length > 0) {
  117. matchRations = await rationItemModel.find({ID: {$in: matchRationIDs}}, '-_id ID code name');
  118. }
  119. for (let mr of matchRations) {
  120. for (let ration of rations) {
  121. if (ration.rationTemplateList) {
  122. for (let rt of ration.rationTemplateList) {
  123. if (rt.rationID && rt.rationID === mr.ID) {
  124. rt.code = mr.code ? mr.code : '';
  125. rt.name = mr.name ? mr.name : '';
  126. }
  127. }
  128. }
  129. }
  130. }
  131. callback(false,"Get items successfully", rations);
  132. } catch (err) {
  133. console.log(err);
  134. callback(true, "Fail to get items", "");
  135. }
  136. /* rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
  137. if(err) callback(true, "Fail to get items", "");
  138. else {
  139. me.sortToNumber(data);
  140. callback(false,"Get items successfully", data);
  141. }
  142. })*/
  143. };
  144. rationItemDAO.prototype.mixUpdateRationItems = function(rationLibId, lastOpr, sectionId, updateItems, addItems, rIds, callback){
  145. var me = this;
  146. if (updateItems.length == 0 && rIds.length == 0) {
  147. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  148. } else {
  149. me.removeRationItems(rationLibId, lastOpr, rIds, function(err, message, docs) {
  150. if (err) {
  151. callback(true, "Fail to remove", false);
  152. } else {
  153. me.updateRationItems(rationLibId, lastOpr, sectionId, updateItems, function(err, results){
  154. if (err) {
  155. callback(true, "Fail to save", false);
  156. } else {
  157. if (addItems && addItems.length > 0) {
  158. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  159. } else {
  160. callback(false, "Save successfully", results);
  161. }
  162. }
  163. });
  164. }
  165. })
  166. }
  167. };
  168. rationItemDAO.prototype.removeRationItems = function(rationLibId, lastOpr, rIds,callback){
  169. if (rIds.length > 0) {
  170. rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
  171. if (err) {
  172. callback(true, "Fail to remove", false);
  173. } else {
  174. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  175. if(!err){
  176. rationItemModel.update({rationRepId: rationLibId}, {$pull: {rationTemplateList: {rationID: {$in: rIds}}}}, function (theErr) {
  177. if (!theErr) {
  178. callback(false, "Remove successfully", docs);
  179. } else {
  180. callback(true, "Fail to remove", false);
  181. }
  182. });
  183. } else {
  184. callback(true, "Fail to remove", false);
  185. }
  186. })
  187. }
  188. })
  189. } else {
  190. callback(false, "No records were deleted!", null);
  191. }
  192. };
  193. rationItemDAO.prototype.getRationItemsByCode = function(repId, code,callback){
  194. rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$or": [{"isDeleted": null}, {"isDeleted": false}]},function(err,data){
  195. if(err) callback(true, "Fail to get items", "")
  196. else callback(false,"Get items successfully", data);
  197. })
  198. };
  199. rationItemDAO.prototype.findRation = function (repId, keyword, callback) {
  200. var filter = {
  201. 'rationRepId': repId,
  202. '$and': [{
  203. '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
  204. }, {
  205. '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
  206. }]
  207. };
  208. rationItemModel.find(filter, function (err, data) {
  209. if (err) {
  210. callback(true, 'Fail to find ration', null);
  211. } else {
  212. callback(false, '', data);
  213. }
  214. })
  215. }
  216. rationItemDAO.prototype.getRationItem = async function (repId, code) {
  217. let ration = await rationItemModel.findOne({rationRepId: repId, code: code});
  218. return ration;
  219. };
  220. rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  221. if (items && items.length > 0) {
  222. counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
  223. var maxId = result.sequence_value;
  224. var arr = [];
  225. for (var i = 0; i < items.length; i++) {
  226. var obj = new rationItemModel(items[i]);
  227. obj.ID = (maxId - (items.length - 1) + i);
  228. obj.sectionId = sectionId;
  229. obj.rationRepId = rationLibId;
  230. arr.push(obj);
  231. }
  232. rationItemModel.collection.insert(arr, null, function(err, docs){
  233. if (err) {
  234. callback(true, "Fail to save", false);
  235. } else {
  236. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  237. if(err){
  238. callback(true, "Fail to sava operator", false);
  239. }
  240. else{
  241. callback(false, "Save successfully", docs);
  242. }
  243. })
  244. }
  245. })
  246. });
  247. } else {
  248. callback(true, "Source error!", false);
  249. }
  250. };
  251. rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  252. console.log('enter============');
  253. var functions = [];
  254. for (var i=0; i < items.length; i++) {
  255. functions.push((function(doc) {
  256. return function(cb) {
  257. var filter = {};
  258. if (doc.ID) {
  259. filter.ID = doc.ID;
  260. } else {
  261. filter.sectionId = sectionId;
  262. if (rationLibId) filter.rationRepId = rationLibId;
  263. filter.code = doc.code;
  264. }
  265. rationItemModel.update(filter, doc, cb);
  266. };
  267. })(items[i]));
  268. }
  269. functions.push((function () {
  270. return function (cb) {
  271. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  272. if(err){
  273. cb(err);
  274. }
  275. else{
  276. cb(null);
  277. }
  278. });
  279. }
  280. })());
  281. async.parallel(functions, function(err, results) {
  282. callback(err, results);
  283. });
  284. };
  285. //ration round func
  286. function round(v,e){
  287. var t=1;
  288. for(;e>0;t*=10,e--);
  289. for(;e<0;t/=10,e++);
  290. return Math.round(v*t)/t;
  291. }
  292. function calcRation(gljArr) {
  293. let labourPrc = [],
  294. materialPrc = [],
  295. machinePrc = [],
  296. managePrc = [],
  297. profitPrc = [],
  298. riskPrc = [],
  299. singlePrc,
  300. updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, managePrice: 0, profitPrice: 0, riskPrice: 0, basePrice: 0};
  301. gljArr.forEach(function (gljItem) {
  302. if(gljItem.gljParentType !== -1){
  303. singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3);
  304. if(gljItem.gljParentType === 1){
  305. labourPrc.push(singlePrc);
  306. }
  307. else if(gljItem.gljParentType ===2){
  308. materialPrc.push(singlePrc);
  309. }
  310. else if(gljItem.gljParentType === 3){
  311. machinePrc.push(singlePrc);
  312. }
  313. else if(gljItem.gljParentType === 6){
  314. managePrc.push(singlePrc);
  315. }
  316. else if(gljItem.gljParentType === 7){
  317. profitPrc.push(singlePrc);
  318. }
  319. else if(gljItem.gljParentType === 8){
  320. riskPrc.push(singlePrc);
  321. }
  322. }
  323. });
  324. if(labourPrc.length > 0){
  325. let sumLaP = 0;
  326. for(let i=0; i<labourPrc.length; i++){
  327. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], -6);
  328. }
  329. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  330. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.labourPrice, -2);
  331. }
  332. if(materialPrc.length > 0){
  333. let sumMtP = 0;
  334. for(let i= 0; i<materialPrc.length; i++){
  335. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], -6);
  336. }
  337. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  338. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.materialPrice, -2);
  339. }
  340. if(machinePrc.length > 0){
  341. let sumMaP = 0;
  342. for(let i =0; i< machinePrc.length; i++){
  343. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], -6);
  344. }
  345. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  346. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.machinePrice, -2);
  347. }
  348. if(managePrc.length > 0){
  349. let sumMgP = 0;
  350. for(let i =0; i< managePrc.length; i++){
  351. sumMgP = scMathUtil.roundTo(sumMgP + managePrc[i], -6);
  352. }
  353. updatePrc.managePrice = scMathUtil.roundTo(sumMgP, -2);
  354. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.managePrice, -2);
  355. }
  356. if(profitPrc.length > 0){
  357. let sumPfP = 0;
  358. for(let i =0; i< profitPrc.length; i++){
  359. sumPfP = scMathUtil.roundTo(sumPfP + profitPrc[i], -6);
  360. }
  361. updatePrc.profitPrice = scMathUtil.roundTo(sumPfP, -2);
  362. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.profitPrice, -2);
  363. }
  364. if(riskPrc.length > 0){
  365. let sumRkP = 0;
  366. for(let i =0; i< riskPrc.length; i++){
  367. sumRkP = scMathUtil.roundTo(sumRkP + riskPrc[i], -6);
  368. }
  369. updatePrc.riskPrice = scMathUtil.roundTo(sumRkP, -2);
  370. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.riskPrice, -2);
  371. }
  372. return updatePrc;
  373. }
  374. rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, overWriteUrl, callback) {
  375. async.each(basePrcArr, function (basePrcObj, finalCb) {
  376. let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
  377. async.waterfall([
  378. function (cb) {
  379. if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
  380. rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
  381. if(err){
  382. cb(err);
  383. }
  384. else{
  385. //删除
  386. rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  387. if(err){
  388. cb(err);
  389. }
  390. else{
  391. //补充定额
  392. compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
  393. if(err){
  394. cb(err);
  395. }
  396. else {
  397. compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  398. if(err){
  399. cb(err);
  400. }
  401. else {
  402. for(let i = 0, len = compleRst.length; i < len; i++){
  403. compleRst[i]._doc.type = 'complementary';
  404. }
  405. cb(null, result.concat(compleRst));
  406. }
  407. });
  408. }
  409. });
  410. }
  411. });
  412. }
  413. });
  414. }
  415. else{
  416. rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
  417. if(err){
  418. cb(err);
  419. }
  420. else{
  421. compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
  422. if(err){
  423. cb(err);
  424. }
  425. else {
  426. for(let i = 0, len = compleRst.length; i < len; i++){
  427. compleRst[i]._doc.type = 'complementary';
  428. }
  429. cb(null, result.concat(compleRst));
  430. }
  431. });
  432. }
  433. });
  434. }
  435. },
  436. function (result, cb) {
  437. let compleRTasks = [], stdRTasks = [];
  438. //重算时需要用到的所有工料机,一次性取
  439. let compleGljIds = [], stdGljIds = [];
  440. for(let ration of result){
  441. for(let glj of ration.rationGljList){
  442. if(glj.type !== undefined && glj.type === 'complementary'){
  443. compleGljIds.push(glj.gljId);
  444. }
  445. else {
  446. stdGljIds.push(glj.gljId);
  447. }
  448. }
  449. }
  450. gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
  451. if(err){
  452. cb(err);
  453. }
  454. else {
  455. let gljIndex = {};
  456. for(let glj of allGljs){
  457. gljIndex[glj.ID] = glj;
  458. }
  459. async.each(result, function (rationItem, ecb) {
  460. let rationGljList = rationItem.rationGljList;
  461. let gljArr = [];
  462. for(let i=0; i<rationGljList.length; i++){
  463. let theGlj = gljIndex[rationGljList[i].gljId];
  464. if(theGlj !== undefined && theGlj){
  465. let gljParentType = -1;
  466. if(theGlj.ID === adjGljId){
  467. theGlj.gljType = adjGljType;
  468. }
  469. if(theGlj.gljType <= 3){
  470. gljParentType = theGlj.gljType;
  471. } else if(theGlj.gljType > 200 && theGlj.gljType < 300){
  472. gljParentType = 2;
  473. } else if(theGlj.gljType > 300 && theGlj.gljType < 400){
  474. gljParentType = 3;
  475. } else if(theGlj.gljType === 6){ //管理费
  476. gljParentType = 6;
  477. } else if(theGlj.gljType === 7){ //利润
  478. gljParentType = 7;
  479. } else if(theGlj.gljType === 8){ //风险费
  480. gljParentType = 8;
  481. }
  482. if(theGlj)
  483. if(theGlj.ID === adjGljId){
  484. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, gljParentType: gljParentType});
  485. } else {
  486. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  487. let priceKeys = Object.keys(theGlj.priceProperty);
  488. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.priceProperty[priceKeys[0]]), gljParentType: gljParentType});
  489. } else {
  490. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), gljParentType: gljParentType});
  491. }
  492. }
  493. }
  494. }
  495. gljArr.forEach(function (gljItem) {
  496. rationGljList.forEach(function (rationGlj) {
  497. if(gljItem.gljId === rationGlj.gljId){
  498. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  499. }
  500. })
  501. });
  502. let updatePrc = null;
  503. let overWriteCalc = false; //需要重写算法
  504. if (overWriteUrl) {
  505. let overWriteExports = require(overWriteUrl);
  506. if (typeof overWriteExports.calcRation !== 'undefined') {
  507. overWriteCalc = true;
  508. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  509. }
  510. }
  511. if (!overWriteCalc) {
  512. updatePrc = calcRation(gljArr);
  513. }
  514. let task = {
  515. updateOne: {
  516. filter: {
  517. ID: rationItem.ID
  518. },
  519. update: {
  520. labourPrice: updatePrc.labourPrice.toString(),
  521. materialPrice: updatePrc.materialPrice.toString(),
  522. machinePrice: updatePrc.machinePrice.toString(),
  523. basePrice: updatePrc.basePrice.toString()
  524. }
  525. }
  526. };
  527. //updateDataBase
  528. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  529. compleRTasks.push(task);
  530. ecb(null);
  531. }
  532. else {
  533. stdRTasks.push(task);
  534. ecb(null);
  535. }
  536. }, async function(err){
  537. if(err){
  538. cb(err);
  539. }
  540. else {
  541. //do sth
  542. try{
  543. if(compleRTasks.length > 0){
  544. await compleRationModel.bulkWrite(compleRTasks);
  545. }
  546. if(stdRTasks.length > 0){
  547. await rationItemModel.bulkWrite(stdRTasks);
  548. }
  549. }
  550. catch(e){
  551. cb(err);
  552. }
  553. cb(null);
  554. }
  555. });
  556. }
  557. });
  558. },
  559. ], function (err) {
  560. if(err){
  561. finalCb(err);
  562. }
  563. else{
  564. finalCb(null);
  565. }
  566. });
  567. }, function (err) {
  568. if(err){
  569. callback(err, 'Error');
  570. }
  571. else{
  572. callback(null, '');
  573. }
  574. });
  575. };
  576. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  577. let repId = data.repId;
  578. rationItemModel.find({rationRepId: repId}, function (err, result) {
  579. if(err){
  580. callback(err, 'Error', null);
  581. }
  582. else{
  583. let rstIds = [], newRst = [];
  584. result.forEach(function (data) {
  585. if(data.rationGljList.length >0){
  586. data.rationGljList.forEach(function (gljObj) {
  587. rstIds.push(gljObj.gljId);
  588. })
  589. }
  590. });
  591. for(let i= 0; i< rstIds.length; i++){
  592. if(newRst.indexOf(rstIds[i]) === -1){
  593. newRst.push(rstIds[i]);
  594. }
  595. }
  596. callback(null, '', newRst);
  597. }
  598. });
  599. };
  600. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  601. let repId = data.repId;
  602. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  603. if(err){
  604. callback(err, 'Error', null);
  605. }
  606. else{
  607. let rstCodes = [];
  608. result.forEach(function (rationItem) {
  609. rstCodes.push(rationItem.code);
  610. });
  611. callback(null, 'get all rationCodes success', rstCodes);
  612. }
  613. })
  614. };
  615. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  616. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  617. async.each(updateArr, function (obj, cb) {
  618. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  619. if(err){
  620. cb(err);
  621. }
  622. else{
  623. cb(null);
  624. }
  625. })
  626. }, function (err) {
  627. if(err){
  628. callback(err);
  629. }
  630. else{
  631. callback(null);
  632. }
  633. });
  634. });
  635. }
  636. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  637. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  638. async.each(updateArr, function (obj, cb) {
  639. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  640. if(err){
  641. cb(err);
  642. }
  643. else{
  644. cb(null);
  645. }
  646. })
  647. }, function (err) {
  648. if(err){
  649. callback(err);
  650. }
  651. else{
  652. callback(null);
  653. }
  654. });
  655. });
  656. };
  657. //更新定额下模板关联
  658. rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  659. //自动匹配定额
  660. let matachCodes = [],
  661. matchRations = [];
  662. //要保存的数据
  663. let saveData = [];
  664. for (let data of templateData) {
  665. if (data.code) {
  666. matachCodes.push(data.code);
  667. }
  668. }
  669. matachCodes = Array.from(new Set(matachCodes));
  670. if (matachCodes.length > 0) {
  671. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  672. }
  673. let validData = [];
  674. //设置展示数据
  675. for (let data of templateData) {
  676. let match = false;
  677. for (let ration of matchRations) {
  678. if (data.code && data.code === ration.code) {
  679. match = true;
  680. data.name = ration.name;
  681. data.rationID = ration.ID;
  682. break;
  683. }
  684. }
  685. if (!match) {
  686. data.code = '';
  687. data.name = '';
  688. }
  689. if (data.type || data.code || data.name || data.billsLocation) {
  690. validData.push(data);
  691. }
  692. }
  693. for (let data of validData) {
  694. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  695. }
  696. //更新
  697. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  698. return validData;
  699. };
  700. //计算导入数据的价格
  701. rationItemDAO.prototype.calcForRation = function (stdGljList, ration, overWriteUrl) {
  702. let rationGljList = ration.rationGljList,
  703. gljArr = [];
  704. for(let rationGlj of rationGljList) {
  705. let glj = stdGljList[rationGlj.gljId];
  706. let gljPType = parseInt(glj.gljType.toString().match(/\d+?/)[0]);
  707. if (glj.priceProperty && Object.keys(glj.priceProperty).length > 0) {
  708. let priceKeys = Object.keys(glj.priceProperty);
  709. gljArr.push({
  710. gljId: glj.ID,
  711. basePrice: parseFloat(glj.priceProperty[priceKeys[0]]),
  712. consumeAmt: rationGlj.consumeAmt,
  713. gljParentType: gljPType
  714. });
  715. } else {
  716. gljArr.push({gljId: glj.ID, basePrice: parseFloat(glj.basePrice), consumeAmt: rationGlj.consumeAmt, gljParentType: gljPType});
  717. }
  718. let updatePrc = null;
  719. let overWriteCalc = false; //需要重写算法
  720. if (overWriteUrl) {
  721. let overWriteExports = require(overWriteUrl);
  722. if (typeof overWriteExports.calcRation !== 'undefined') {
  723. overWriteCalc = true;
  724. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  725. }
  726. }
  727. if (!overWriteCalc) {
  728. updatePrc = calcRation(gljArr);
  729. }
  730. ration.labourPrice = updatePrc.labourPrice.toString();
  731. ration.materialPrice = updatePrc.materialPrice.toString();
  732. ration.machinePrice = updatePrc.machinePrice.toString();
  733. ration.basePrice = updatePrc.basePrice.toString();
  734. }
  735. };
  736. /**
  737. * 根据条件获取定额数据
  738. *
  739. * @param {Object} condition
  740. * @param {Object} fields
  741. * @param {String} indexBy
  742. * @return {Promise|Array}
  743. */
  744. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  745. let result = [];
  746. if (Object.keys(condition).length <= 0) {
  747. return result;
  748. }
  749. result = await rationItemModel.find(condition, fields).sort({code: 1});
  750. if (indexBy !== null && result.length > 0) {
  751. let tmpResult = {};
  752. for(let tmp of result) {
  753. tmpResult[tmp[indexBy]] = tmp;
  754. }
  755. result = tmpResult;
  756. }
  757. return result;
  758. };
  759. /**
  760. * 从excel中批量新增数据
  761. *
  762. * @param {Number} rationRepId
  763. * @param {Array} data
  764. * @return {bool}
  765. */
  766. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  767. if (data.length <= 0) {
  768. return false;
  769. }
  770. // 获取定额库相关数据
  771. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  772. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  773. return false;
  774. }
  775. // 获取标准工料机库数据
  776. const stdBillsLibListsModel = new STDGLJListModel();
  777. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  778. // 整理标准工料机库数据
  779. let stdGLJList = {};
  780. let stdGLJListByID = {};
  781. for (const tmp of stdGLJData) {
  782. stdGLJList[tmp.code.toString()] = tmp.ID;
  783. stdGLJListByID[tmp.ID] = tmp;
  784. }
  785. let lastData = {};
  786. const rationData = [];
  787. // 编码列表,用于查找库中是否有对应数据
  788. let rationCodeList = [];
  789. let gljCodeList = [];
  790. // 插入失败的工料机列表(用于提示)
  791. this.failGLJList = [];
  792. for (const tmp of data) {
  793. if (tmp.length <= 0) {
  794. continue;
  795. }
  796. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  797. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  798. // 如果不存在对应的工料机库数据则跳过
  799. if (stdGLJList[tmp[1]] === undefined) {
  800. const failString = '定额' + lastData.code + '下的' + tmp[1];
  801. this.failGLJList.push(failString);
  802. continue;
  803. }
  804. const tmpRationGlj = {
  805. gljId: stdGLJList[tmp[1]],
  806. consumeAmt: tmp[4],
  807. proportion: 0,
  808. };
  809. lastData.rationGljList.push(tmpRationGlj);
  810. if (gljCodeList.indexOf(tmp[1]) < 0) {
  811. gljCodeList.push(tmp[1]);
  812. }
  813. continue;
  814. }
  815. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  816. rationData.push(lastData);
  817. }
  818. // 组装数据
  819. lastData = {
  820. code: tmp[1],
  821. name: tmp[2],
  822. unit: tmp[3],
  823. caption: tmp[2],
  824. rationRepId: rationRepId,
  825. sectionId: 0,
  826. labourPrice: '0',
  827. materialPrice: '0',
  828. machinePrice: '0',
  829. basePrice: '0',
  830. rationGljList: []
  831. };
  832. // 防止重复加入
  833. if (rationCodeList.indexOf(tmp[1]) < 0) {
  834. rationCodeList.push(tmp[1]);
  835. }
  836. }
  837. // 最后一个入数组
  838. rationData.push(lastData);
  839. // 查找数据库中是否已存在待插入数据
  840. const condition = {
  841. rationRepId: rationRepId,
  842. code: { $in: rationCodeList }
  843. };
  844. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  845. // 过滤插入数据
  846. let insertData = [];
  847. //已存在定额,则更新价格及rationGLjList字段
  848. let updateData = [];
  849. for (const ration of rationData) {
  850. if (existCodeList[ration.code] !== undefined) {
  851. updateData.push(ration);
  852. continue;
  853. }
  854. insertData.push(ration);
  855. }
  856. //更新定额
  857. let updateBulk = [];
  858. for(let ration of updateData){
  859. this.calcForRation(stdGLJListByID, ration);
  860. updateBulk.push({
  861. updateOne: {
  862. filter: {rationRepId: rationRepId, code: ration.code},
  863. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  864. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  865. }
  866. });
  867. }
  868. //更新数据库
  869. if(updateBulk.length > 0){
  870. await rationItemModel.bulkWrite(updateBulk);
  871. }
  872. // 如果都已经存在,直接返回
  873. if (insertData.length <= 0) {
  874. return true;
  875. }
  876. //计算价格
  877. for(let ration of insertData){
  878. this.calcForRation(stdGLJListByID, ration);
  879. }
  880. // 组织id
  881. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  882. let maxId = counterInfo.sequence_value;
  883. maxId = parseInt(maxId);
  884. let count = 0;
  885. for (const index in insertData) {
  886. insertData[index].ID = maxId - (insertData.length - 1) + count;
  887. count++;
  888. }
  889. // 插入数据库
  890. const result = await rationItemModel.create(insertData);
  891. return result.length > 0;
  892. };
  893. /**
  894. * 导出到excel的数据
  895. *
  896. * @param {Number} rationRepId
  897. * @return {Array}
  898. */
  899. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  900. const condition = {
  901. rationRepId: rationRepId
  902. };
  903. // @todo 限制导出的数量以防内存溢出
  904. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice']);
  905. // 整理数据
  906. let rationData = [];
  907. for (const tmp of rationDataList) {
  908. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  909. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  910. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice];
  911. rationData.push(ration);
  912. }
  913. //根据编号排序,优先级:number-number-..., number, Anumber....
  914. /*let regConnector = /-/g,
  915. regLetter = /[a-z,A-Z]/g,
  916. regNum = /\d+/g;
  917. rationData.sort(function (a, b) {
  918. let aCode = a[3],
  919. bCode = b[3],
  920. rst = 0;
  921. function compareConnector(arrA, arrB) {
  922. let lessArr = arrA.length <= arrB ? arrA : arrB;
  923. for (let i = 0; i < lessArr.length; i++) {
  924. let result = compareUnit(arrA[i], arrB[i]);
  925. if (result !== 0) {
  926. return result;
  927. } else {
  928. }
  929. }
  930. function compareUnit(uA, uB) {
  931. let uAV = parseFloat(uA),
  932. uBV = parseFloat(uB);
  933. if (uAV > uBV) {
  934. return 1;
  935. } else if (uAV < uBV) {
  936. return -1;
  937. }
  938. return 0;
  939. }
  940. }
  941. if (regConnector.test(a) && !regConnector.test(b)) {
  942. rst = -1;
  943. } else if (!regConnector.test(a) && regConnector.test(b)) {
  944. rst = 1;
  945. } else if (regConnector.test(a) && regConnector.test(b)) {
  946. }
  947. });
  948. rationData.sort(function (a, b) {
  949. let aCode = a[3],
  950. bCode = b[3],
  951. rst = 0,
  952. splitA = aCode.split('-'),
  953. splitB = bCode.split('-');
  954. if(splitA[0] > splitB[0]){
  955. rst = 1;
  956. }
  957. else if(splitA[0] < splitB[0]){
  958. rst = -1;
  959. }
  960. else {
  961. if(splitA[1] && splitB[1]){
  962. let floatA = parseFloat(splitA[1]),
  963. floatB = parseFloat(splitB[1]);
  964. if(floatA > floatB){
  965. rst = 1;
  966. }
  967. else if(floatA < floatB){
  968. rst = -1;
  969. }
  970. }
  971. }
  972. return rst;
  973. });*/
  974. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  975. excelData.push.apply(excelData, rationData);
  976. return excelData;
  977. };
  978. /**
  979. * 批量更改章节id
  980. *
  981. * @param {Object} data
  982. * @return {bool}
  983. */
  984. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  985. if (data.length <= 0) {
  986. return false;
  987. }
  988. // 批量执行update
  989. let bulkOprs = [];
  990. for (const tmp of data) {
  991. let rationId = parseInt(tmp[2]);
  992. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  993. let sectionId = parseInt(tmp[0]);
  994. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  995. // 取费专业
  996. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  997. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  998. let name = tmp[4];
  999. name = name ? name : '';
  1000. let caption = tmp[5];
  1001. caption = caption ? caption : '';
  1002. if (sectionId <= 0 || rationId <= 0) {
  1003. continue;
  1004. }
  1005. bulkOprs.push({updateOne: {filter: {ID: rationId}, update: {$set: {sectionId: sectionId, feeType: feeType, name: name, caption: caption}}}});
  1006. }
  1007. if(bulkOprs.length <= 0){
  1008. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1009. }
  1010. await rationItemModel.bulkWrite(bulkOprs);
  1011. };
  1012. module.exports = new rationItemDAO();