ration_item.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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, unit: theGlj.unit});
  485. } else {
  486. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  487. let priceKeys = Object.keys(theGlj.priceProperty);
  488. gljArr.push({
  489. gljId: theGlj.ID,
  490. basePrice: parseFloat(theGlj.priceProperty[priceKeys[0]]),
  491. gljParentType: gljParentType,
  492. unit: theGlj.unit});
  493. } else {
  494. gljArr.push({
  495. gljId: theGlj.ID,
  496. basePrice: parseFloat(theGlj.basePrice),
  497. gljParentType: gljParentType,
  498. unit: theGlj.unit});
  499. }
  500. }
  501. }
  502. }
  503. gljArr.forEach(function (gljItem) {
  504. rationGljList.forEach(function (rationGlj) {
  505. if(gljItem.gljId === rationGlj.gljId){
  506. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  507. }
  508. })
  509. });
  510. let updatePrc = null;
  511. let overWriteCalc = false; //需要重写算法
  512. if (overWriteUrl) {
  513. let overWriteExports = require(overWriteUrl);
  514. if (typeof overWriteExports.calcRation !== 'undefined') {
  515. overWriteCalc = true;
  516. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  517. }
  518. }
  519. if (!overWriteCalc) {
  520. updatePrc = calcRation(gljArr);
  521. }
  522. let task = {
  523. updateOne: {
  524. filter: {
  525. ID: rationItem.ID
  526. },
  527. update: {
  528. labourPrice: updatePrc.labourPrice.toString(),
  529. materialPrice: updatePrc.materialPrice.toString(),
  530. machinePrice: updatePrc.machinePrice.toString(),
  531. basePrice: updatePrc.basePrice.toString()
  532. }
  533. }
  534. };
  535. //updateDataBase
  536. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  537. compleRTasks.push(task);
  538. ecb(null);
  539. }
  540. else {
  541. stdRTasks.push(task);
  542. ecb(null);
  543. }
  544. }, async function(err){
  545. if(err){
  546. cb(err);
  547. }
  548. else {
  549. //do sth
  550. try{
  551. if(compleRTasks.length > 0){
  552. await compleRationModel.bulkWrite(compleRTasks);
  553. }
  554. if(stdRTasks.length > 0){
  555. await rationItemModel.bulkWrite(stdRTasks);
  556. }
  557. }
  558. catch(e){
  559. cb(err);
  560. }
  561. cb(null);
  562. }
  563. });
  564. }
  565. });
  566. },
  567. ], function (err) {
  568. if(err){
  569. finalCb(err);
  570. }
  571. else{
  572. finalCb(null);
  573. }
  574. });
  575. }, function (err) {
  576. if(err){
  577. callback(err, 'Error');
  578. }
  579. else{
  580. callback(null, '');
  581. }
  582. });
  583. };
  584. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  585. let repId = data.repId;
  586. rationItemModel.find({rationRepId: repId}, function (err, result) {
  587. if(err){
  588. callback(err, 'Error', null);
  589. }
  590. else{
  591. let rstIds = [], newRst = [];
  592. result.forEach(function (data) {
  593. if(data.rationGljList.length >0){
  594. data.rationGljList.forEach(function (gljObj) {
  595. rstIds.push(gljObj.gljId);
  596. })
  597. }
  598. });
  599. for(let i= 0; i< rstIds.length; i++){
  600. if(newRst.indexOf(rstIds[i]) === -1){
  601. newRst.push(rstIds[i]);
  602. }
  603. }
  604. callback(null, '', newRst);
  605. }
  606. });
  607. };
  608. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  609. let repId = data.repId;
  610. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  611. if(err){
  612. callback(err, 'Error', null);
  613. }
  614. else{
  615. let rstCodes = [];
  616. result.forEach(function (rationItem) {
  617. rstCodes.push(rationItem.code);
  618. });
  619. callback(null, 'get all rationCodes success', rstCodes);
  620. }
  621. })
  622. };
  623. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  624. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  625. async.each(updateArr, function (obj, cb) {
  626. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  627. if(err){
  628. cb(err);
  629. }
  630. else{
  631. cb(null);
  632. }
  633. })
  634. }, function (err) {
  635. if(err){
  636. callback(err);
  637. }
  638. else{
  639. callback(null);
  640. }
  641. });
  642. });
  643. }
  644. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  645. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  646. async.each(updateArr, function (obj, cb) {
  647. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  648. if(err){
  649. cb(err);
  650. }
  651. else{
  652. cb(null);
  653. }
  654. })
  655. }, function (err) {
  656. if(err){
  657. callback(err);
  658. }
  659. else{
  660. callback(null);
  661. }
  662. });
  663. });
  664. };
  665. //更新定额下模板关联
  666. rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  667. //自动匹配定额
  668. let matachCodes = [],
  669. matchRations = [];
  670. //要保存的数据
  671. let saveData = [];
  672. for (let data of templateData) {
  673. if (data.code) {
  674. matachCodes.push(data.code);
  675. }
  676. }
  677. matachCodes = Array.from(new Set(matachCodes));
  678. if (matachCodes.length > 0) {
  679. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  680. }
  681. let validData = [];
  682. //设置展示数据
  683. for (let data of templateData) {
  684. let match = false;
  685. for (let ration of matchRations) {
  686. if (data.code && data.code === ration.code) {
  687. match = true;
  688. data.name = ration.name;
  689. data.rationID = ration.ID;
  690. break;
  691. }
  692. }
  693. if (!match) {
  694. data.code = '';
  695. data.name = '';
  696. }
  697. if (data.type || data.code || data.name || data.billsLocation) {
  698. validData.push(data);
  699. }
  700. }
  701. for (let data of validData) {
  702. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  703. }
  704. //更新
  705. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  706. return validData;
  707. };
  708. //计算导入数据的价格
  709. rationItemDAO.prototype.calcForRation = function (stdGljList, ration, overWriteUrl) {
  710. let rationGljList = ration.rationGljList,
  711. gljArr = [];
  712. for(let rationGlj of rationGljList) {
  713. let glj = stdGljList[rationGlj.gljId];
  714. let gljPType = parseInt(glj.gljType.toString().match(/\d+?/)[0]);
  715. if (glj.priceProperty && Object.keys(glj.priceProperty).length > 0) {
  716. let priceKeys = Object.keys(glj.priceProperty);
  717. gljArr.push({
  718. gljId: glj.ID,
  719. basePrice: parseFloat(glj.priceProperty[priceKeys[0]]),
  720. consumeAmt: rationGlj.consumeAmt,
  721. gljParentType: gljPType,
  722. unit: glj.unit
  723. });
  724. } else {
  725. gljArr.push({gljId: glj.ID, basePrice: parseFloat(glj.basePrice), consumeAmt: rationGlj.consumeAmt, gljParentType: gljPType, unit: glj.unit});
  726. }
  727. let updatePrc = null;
  728. let overWriteCalc = false; //需要重写算法
  729. if (overWriteUrl) {
  730. let overWriteExports = require(overWriteUrl);
  731. if (typeof overWriteExports.calcRation !== 'undefined') {
  732. overWriteCalc = true;
  733. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  734. }
  735. }
  736. if (!overWriteCalc) {
  737. updatePrc = calcRation(gljArr);
  738. }
  739. ration.labourPrice = updatePrc.labourPrice.toString();
  740. ration.materialPrice = updatePrc.materialPrice.toString();
  741. ration.machinePrice = updatePrc.machinePrice.toString();
  742. ration.basePrice = updatePrc.basePrice.toString();
  743. }
  744. };
  745. /**
  746. * 根据条件获取定额数据
  747. *
  748. * @param {Object} condition
  749. * @param {Object} fields
  750. * @param {String} indexBy
  751. * @return {Promise|Array}
  752. */
  753. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  754. let result = [];
  755. if (Object.keys(condition).length <= 0) {
  756. return result;
  757. }
  758. result = await rationItemModel.find(condition, fields).sort({code: 1});
  759. if (indexBy !== null && result.length > 0) {
  760. let tmpResult = {};
  761. for(let tmp of result) {
  762. tmpResult[tmp[indexBy]] = tmp;
  763. }
  764. result = tmpResult;
  765. }
  766. return result;
  767. };
  768. /**
  769. * 从excel中批量新增数据
  770. *
  771. * @param {Number} rationRepId
  772. * @param {Array} data
  773. * @return {bool}
  774. */
  775. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  776. if (data.length <= 0) {
  777. return false;
  778. }
  779. // 获取定额库相关数据
  780. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  781. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  782. return false;
  783. }
  784. // 获取标准工料机库数据
  785. const stdBillsLibListsModel = new STDGLJListModel();
  786. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  787. // 整理标准工料机库数据
  788. let stdGLJList = {};
  789. let stdGLJListByID = {};
  790. for (const tmp of stdGLJData) {
  791. stdGLJList[tmp.code.toString()] = tmp.ID;
  792. stdGLJListByID[tmp.ID] = tmp;
  793. }
  794. let lastData = {};
  795. const rationData = [];
  796. // 编码列表,用于查找库中是否有对应数据
  797. let rationCodeList = [];
  798. let gljCodeList = [];
  799. // 插入失败的工料机列表(用于提示)
  800. this.failGLJList = [];
  801. for (const tmp of data) {
  802. if (tmp.length <= 0) {
  803. continue;
  804. }
  805. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  806. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  807. // 如果不存在对应的工料机库数据则跳过
  808. if (stdGLJList[tmp[1]] === undefined) {
  809. const failString = '定额' + lastData.code + '下的' + tmp[1];
  810. this.failGLJList.push(failString);
  811. continue;
  812. }
  813. const tmpRationGlj = {
  814. gljId: stdGLJList[tmp[1]],
  815. consumeAmt: tmp[4],
  816. proportion: 0,
  817. };
  818. lastData.rationGljList.push(tmpRationGlj);
  819. if (gljCodeList.indexOf(tmp[1]) < 0) {
  820. gljCodeList.push(tmp[1]);
  821. }
  822. continue;
  823. }
  824. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  825. rationData.push(lastData);
  826. }
  827. // 组装数据
  828. lastData = {
  829. code: tmp[1],
  830. name: tmp[2],
  831. unit: tmp[3],
  832. caption: tmp[2],
  833. rationRepId: rationRepId,
  834. sectionId: 0,
  835. labourPrice: '0',
  836. materialPrice: '0',
  837. machinePrice: '0',
  838. basePrice: '0',
  839. rationGljList: []
  840. };
  841. // 防止重复加入
  842. if (rationCodeList.indexOf(tmp[1]) < 0) {
  843. rationCodeList.push(tmp[1]);
  844. }
  845. }
  846. // 最后一个入数组
  847. rationData.push(lastData);
  848. // 查找数据库中是否已存在待插入数据
  849. const condition = {
  850. rationRepId: rationRepId,
  851. code: { $in: rationCodeList }
  852. };
  853. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  854. // 过滤插入数据
  855. let insertData = [];
  856. //已存在定额,则更新价格及rationGLjList字段
  857. let updateData = [];
  858. for (const ration of rationData) {
  859. if (existCodeList[ration.code] !== undefined) {
  860. updateData.push(ration);
  861. continue;
  862. }
  863. insertData.push(ration);
  864. }
  865. //更新定额
  866. let updateBulk = [];
  867. for(let ration of updateData){
  868. this.calcForRation(stdGLJListByID, ration);
  869. updateBulk.push({
  870. updateOne: {
  871. filter: {rationRepId: rationRepId, code: ration.code},
  872. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  873. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  874. }
  875. });
  876. }
  877. //更新数据库
  878. if(updateBulk.length > 0){
  879. await rationItemModel.bulkWrite(updateBulk);
  880. }
  881. // 如果都已经存在,直接返回
  882. if (insertData.length <= 0) {
  883. return true;
  884. }
  885. //计算价格
  886. for(let ration of insertData){
  887. this.calcForRation(stdGLJListByID, ration);
  888. }
  889. // 组织id
  890. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  891. let maxId = counterInfo.sequence_value;
  892. maxId = parseInt(maxId);
  893. let count = 0;
  894. for (const index in insertData) {
  895. insertData[index].ID = maxId - (insertData.length - 1) + count;
  896. count++;
  897. }
  898. // 插入数据库
  899. const result = await rationItemModel.create(insertData);
  900. return result.length > 0;
  901. };
  902. /**
  903. * 导出到excel的数据
  904. *
  905. * @param {Number} rationRepId
  906. * @return {Array}
  907. */
  908. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  909. const condition = {
  910. rationRepId: rationRepId
  911. };
  912. // @todo 限制导出的数量以防内存溢出
  913. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice']);
  914. // 整理数据
  915. let rationData = [];
  916. for (const tmp of rationDataList) {
  917. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  918. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  919. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice];
  920. rationData.push(ration);
  921. }
  922. //根据编号排序,优先级:number-number-..., number, Anumber....
  923. /*let regConnector = /-/g,
  924. regLetter = /[a-z,A-Z]/g,
  925. regNum = /\d+/g;
  926. rationData.sort(function (a, b) {
  927. let aCode = a[3],
  928. bCode = b[3],
  929. rst = 0;
  930. function compareConnector(arrA, arrB) {
  931. let lessArr = arrA.length <= arrB ? arrA : arrB;
  932. for (let i = 0; i < lessArr.length; i++) {
  933. let result = compareUnit(arrA[i], arrB[i]);
  934. if (result !== 0) {
  935. return result;
  936. } else {
  937. }
  938. }
  939. function compareUnit(uA, uB) {
  940. let uAV = parseFloat(uA),
  941. uBV = parseFloat(uB);
  942. if (uAV > uBV) {
  943. return 1;
  944. } else if (uAV < uBV) {
  945. return -1;
  946. }
  947. return 0;
  948. }
  949. }
  950. if (regConnector.test(a) && !regConnector.test(b)) {
  951. rst = -1;
  952. } else if (!regConnector.test(a) && regConnector.test(b)) {
  953. rst = 1;
  954. } else if (regConnector.test(a) && regConnector.test(b)) {
  955. }
  956. });
  957. rationData.sort(function (a, b) {
  958. let aCode = a[3],
  959. bCode = b[3],
  960. rst = 0,
  961. splitA = aCode.split('-'),
  962. splitB = bCode.split('-');
  963. if(splitA[0] > splitB[0]){
  964. rst = 1;
  965. }
  966. else if(splitA[0] < splitB[0]){
  967. rst = -1;
  968. }
  969. else {
  970. if(splitA[1] && splitB[1]){
  971. let floatA = parseFloat(splitA[1]),
  972. floatB = parseFloat(splitB[1]);
  973. if(floatA > floatB){
  974. rst = 1;
  975. }
  976. else if(floatA < floatB){
  977. rst = -1;
  978. }
  979. }
  980. }
  981. return rst;
  982. });*/
  983. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  984. excelData.push.apply(excelData, rationData);
  985. return excelData;
  986. };
  987. /**
  988. * 批量更改章节id
  989. *
  990. * @param {Object} data
  991. * @return {bool}
  992. */
  993. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  994. if (data.length <= 0) {
  995. return false;
  996. }
  997. // 批量执行update
  998. let bulkOprs = [];
  999. for (const tmp of data) {
  1000. let rationId = parseInt(tmp[2]);
  1001. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  1002. let sectionId = parseInt(tmp[0]);
  1003. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  1004. // 取费专业
  1005. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  1006. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  1007. let name = tmp[4];
  1008. name = name ? name : '';
  1009. let caption = tmp[5];
  1010. caption = caption ? caption : '';
  1011. if (sectionId <= 0 || rationId <= 0) {
  1012. continue;
  1013. }
  1014. bulkOprs.push({updateOne: {filter: {ID: rationId}, update: {$set: {sectionId: sectionId, feeType: feeType, name: name, caption: caption}}}});
  1015. }
  1016. if(bulkOprs.length <= 0){
  1017. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1018. }
  1019. await rationItemModel.bulkWrite(bulkOprs);
  1020. };
  1021. module.exports = new rationItemDAO();