ration_item.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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 = function (repId, code, callback) {
  217. if (callback) {
  218. rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec()
  219. .then(function (result, err) {
  220. if (err) {
  221. callback(1, '找不到定额“' + code +'”' , null);
  222. } else {
  223. callback(0, '', result);
  224. }
  225. });
  226. return null;
  227. } else {
  228. return rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec();
  229. }
  230. };
  231. rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  232. if (items && items.length > 0) {
  233. counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
  234. var maxId = result.sequence_value;
  235. var arr = [];
  236. for (var i = 0; i < items.length; i++) {
  237. var obj = new rationItemModel(items[i]);
  238. obj.ID = (maxId - (items.length - 1) + i);
  239. obj.sectionId = sectionId;
  240. obj.rationRepId = rationLibId;
  241. arr.push(obj);
  242. }
  243. rationItemModel.collection.insert(arr, null, function(err, docs){
  244. if (err) {
  245. callback(true, "Fail to save", false);
  246. } else {
  247. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  248. if(err){
  249. callback(true, "Fail to sava operator", false);
  250. }
  251. else{
  252. callback(false, "Save successfully", docs);
  253. }
  254. })
  255. }
  256. })
  257. });
  258. } else {
  259. callback(true, "Source error!", false);
  260. }
  261. };
  262. rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  263. console.log('enter============');
  264. var functions = [];
  265. for (var i=0; i < items.length; i++) {
  266. functions.push((function(doc) {
  267. return function(cb) {
  268. var filter = {};
  269. if (doc.ID) {
  270. filter.ID = doc.ID;
  271. } else {
  272. filter.sectionId = sectionId;
  273. if (rationLibId) filter.rationRepId = rationLibId;
  274. filter.code = doc.code;
  275. }
  276. rationItemModel.update(filter, doc, cb);
  277. };
  278. })(items[i]));
  279. }
  280. functions.push((function () {
  281. return function (cb) {
  282. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  283. if(err){
  284. cb(err);
  285. }
  286. else{
  287. cb(null);
  288. }
  289. });
  290. }
  291. })());
  292. async.parallel(functions, function(err, results) {
  293. callback(err, results);
  294. });
  295. };
  296. //ration round func
  297. function round(v,e){
  298. var t=1;
  299. for(;e>0;t*=10,e--);
  300. for(;e<0;t/=10,e++);
  301. return Math.round(v*t)/t;
  302. }
  303. rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, callback) {
  304. async.each(basePrcArr, function (basePrcObj, finalCb) {
  305. let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
  306. async.waterfall([
  307. function (cb) {
  308. if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
  309. rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
  310. if(err){
  311. cb(err);
  312. }
  313. else{
  314. //删除
  315. rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  316. if(err){
  317. cb(err);
  318. }
  319. else{
  320. //补充定额
  321. compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
  322. if(err){
  323. cb(err);
  324. }
  325. else {
  326. compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  327. if(err){
  328. cb(err);
  329. }
  330. else {
  331. for(let i = 0, len = compleRst.length; i < len; i++){
  332. compleRst[i]._doc.type = 'complementary';
  333. }
  334. cb(null, result.concat(compleRst));
  335. }
  336. });
  337. }
  338. });
  339. }
  340. });
  341. }
  342. });
  343. }
  344. else{
  345. rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
  346. if(err){
  347. cb(err);
  348. }
  349. else{
  350. compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
  351. if(err){
  352. cb(err);
  353. }
  354. else {
  355. for(let i = 0, len = compleRst.length; i < len; i++){
  356. compleRst[i]._doc.type = 'complementary';
  357. }
  358. cb(null, result.concat(compleRst));
  359. }
  360. });
  361. }
  362. });
  363. }
  364. },
  365. function (result, cb) {
  366. let compleRTasks = [], stdRTasks = [];
  367. //重算时需要用到的所有工料机,一次性取
  368. let compleGljIds = [], stdGljIds = [];
  369. for(let ration of result){
  370. for(let glj of ration.rationGljList){
  371. if(glj.type !== undefined && glj.type === 'complementary'){
  372. compleGljIds.push(glj.gljId);
  373. }
  374. else {
  375. stdGljIds.push(glj.gljId);
  376. }
  377. }
  378. }
  379. gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
  380. const processDecimal = -6;
  381. if(err){
  382. cb(err);
  383. }
  384. else {
  385. let gljIndex = {};
  386. for(let glj of allGljs){
  387. gljIndex[glj.ID] = glj;
  388. }
  389. async.each(result, function (rationItem, ecb) {
  390. let rationGljList = rationItem.rationGljList;
  391. let gljArr = [];
  392. for(let i=0; i<rationGljList.length; i++){
  393. let theGlj = gljIndex[rationGljList[i].gljId];
  394. if(theGlj !== undefined && theGlj){
  395. let gljParentType = -1;
  396. if(theGlj.ID === adjGljId){
  397. theGlj.gljType = adjGljType;
  398. }
  399. if(theGlj.gljType <= 3){
  400. gljParentType = theGlj.gljType;
  401. }
  402. if(theGlj.gljType > 200 && theGlj.gljType < 300){
  403. gljParentType = 2;
  404. }
  405. if(theGlj.gljType > 300 && theGlj.gljType < 400){
  406. gljParentType = 3;
  407. }
  408. //管理费
  409. if(theGlj.gljType === 6){
  410. gljParentType = 6;
  411. }
  412. //利润
  413. if(theGlj.gljType === 7){
  414. gljParentType = 7;
  415. }
  416. //风险费
  417. if(theGlj.gljType === 8){
  418. gljParentType = 8;
  419. }
  420. if(theGlj)
  421. if(theGlj.ID === adjGljId){
  422. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, gljParentType: gljParentType});
  423. }
  424. else {
  425. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  426. let priceKeys = Object.keys(theGlj.priceProperty);
  427. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.priceProperty[priceKeys[0]]), gljParentType: gljParentType});
  428. }
  429. else {
  430. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), gljParentType: gljParentType});
  431. }
  432. }
  433. }
  434. }
  435. gljArr.forEach(function (gljItem) {
  436. rationGljList.forEach(function (rationGlj) {
  437. if(gljItem.gljId === rationGlj.gljId){
  438. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  439. }
  440. })
  441. });
  442. //recalculate the price of ration
  443. let labourPrc = [],
  444. materialPrc = [],
  445. machinePrc = [],
  446. managePrc = [],
  447. profitPrc = [],
  448. riskPrc = [],
  449. singlePrc,
  450. updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, managePrice: 0, profitPrice: 0, riskPrice: 0, basePrice: 0};
  451. gljArr.forEach(function (gljItem) {
  452. if(gljItem.gljParentType !== -1){
  453. singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3);
  454. if(gljItem.gljParentType === 1){
  455. labourPrc.push(singlePrc);
  456. }
  457. else if(gljItem.gljParentType ===2){
  458. materialPrc.push(singlePrc);
  459. }
  460. else if(gljItem.gljParentType === 3){
  461. machinePrc.push(singlePrc);
  462. }
  463. else if(gljItem.gljParentType === 6){
  464. managePrc.push(singlePrc);
  465. }
  466. else if(gljItem.gljParentType === 7){
  467. profitPrc.push(singlePrc);
  468. }
  469. else if(gljItem.gljParentType === 8){
  470. riskPrc.push(singlePrc);
  471. }
  472. }
  473. });
  474. if(labourPrc.length > 0){
  475. let sumLaP = 0;
  476. for(let i=0; i<labourPrc.length; i++){
  477. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], processDecimal);
  478. }
  479. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  480. }
  481. if(materialPrc.length > 0){
  482. let sumMtP = 0;
  483. for(let i= 0; i<materialPrc.length; i++){
  484. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], processDecimal);
  485. }
  486. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  487. }
  488. if(machinePrc.length > 0){
  489. let sumMaP = 0;
  490. for(let i =0; i< machinePrc.length; i++){
  491. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], processDecimal);
  492. }
  493. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  494. }
  495. if(managePrc.length > 0){
  496. let sumMgP = 0;
  497. for(let i =0; i< managePrc.length; i++){
  498. sumMgP = scMathUtil.roundTo(sumMgP + managePrc[i], processDecimal);
  499. }
  500. updatePrc.managePrice = scMathUtil.roundTo(sumMgP, -2);
  501. }
  502. if(profitPrc.length > 0){
  503. let sumPfP = 0;
  504. for(let i =0; i< profitPrc.length; i++){
  505. sumPfP = scMathUtil.roundTo(sumPfP + profitPrc[i], processDecimal);
  506. }
  507. updatePrc.profitPrice = scMathUtil.roundTo(sumPfP, -2);
  508. }
  509. if(riskPrc.length > 0){
  510. let sumRkP = 0;
  511. for(let i =0; i< riskPrc.length; i++){
  512. sumRkP = scMathUtil.roundTo(sumRkP + riskPrc[i], processDecimal);
  513. }
  514. updatePrc.riskPrice = scMathUtil.roundTo(sumRkP, -2);
  515. }
  516. updatePrc.basePrice = scMathUtil.roundTo(
  517. updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice + updatePrc.managePrice + updatePrc.profitPrice + updatePrc.riskPrice, -2);
  518. let task = {
  519. updateOne: {
  520. filter: {
  521. ID: rationItem.ID
  522. },
  523. update: {
  524. labourPrice: updatePrc.labourPrice.toString(),
  525. materialPrice: updatePrc.materialPrice.toString(),
  526. machinePrice: updatePrc.machinePrice.toString(),
  527. basePrice: updatePrc.basePrice.toString()
  528. }
  529. }
  530. };
  531. //updateDataBase
  532. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  533. compleRTasks.push(task);
  534. ecb(null);
  535. }
  536. else {
  537. stdRTasks.push(task);
  538. ecb(null);
  539. }
  540. }, async function(err){
  541. if(err){
  542. cb(err);
  543. }
  544. else {
  545. //do sth
  546. try{
  547. if(compleRTasks.length > 0){
  548. await compleRationModel.bulkWrite(compleRTasks);
  549. }
  550. if(stdRTasks.length > 0){
  551. await rationItemModel.bulkWrite(stdRTasks);
  552. }
  553. }
  554. catch(e){
  555. cb(err);
  556. }
  557. cb(null);
  558. }
  559. });
  560. }
  561. });
  562. },
  563. ], function (err) {
  564. if(err){
  565. finalCb(err);
  566. }
  567. else{
  568. finalCb(null);
  569. }
  570. });
  571. }, function (err) {
  572. if(err){
  573. callback(err, 'Error');
  574. }
  575. else{
  576. callback(null, '');
  577. }
  578. });
  579. };
  580. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  581. let repId = data.repId;
  582. rationItemModel.find({rationRepId: repId}, function (err, result) {
  583. if(err){
  584. callback(err, 'Error', null);
  585. }
  586. else{
  587. let rstIds = [], newRst = [];
  588. result.forEach(function (data) {
  589. if(data.rationGljList.length >0){
  590. data.rationGljList.forEach(function (gljObj) {
  591. rstIds.push(gljObj.gljId);
  592. })
  593. }
  594. });
  595. for(let i= 0; i< rstIds.length; i++){
  596. if(newRst.indexOf(rstIds[i]) === -1){
  597. newRst.push(rstIds[i]);
  598. }
  599. }
  600. callback(null, '', newRst);
  601. }
  602. });
  603. };
  604. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  605. let repId = data.repId;
  606. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  607. if(err){
  608. callback(err, 'Error', null);
  609. }
  610. else{
  611. let rstCodes = [];
  612. result.forEach(function (rationItem) {
  613. rstCodes.push(rationItem.code);
  614. });
  615. callback(null, 'get all rationCodes success', rstCodes);
  616. }
  617. })
  618. };
  619. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  620. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  621. async.each(updateArr, function (obj, cb) {
  622. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  623. if(err){
  624. cb(err);
  625. }
  626. else{
  627. cb(null);
  628. }
  629. })
  630. }, function (err) {
  631. if(err){
  632. callback(err);
  633. }
  634. else{
  635. callback(null);
  636. }
  637. });
  638. });
  639. }
  640. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  641. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  642. async.each(updateArr, function (obj, cb) {
  643. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  644. if(err){
  645. cb(err);
  646. }
  647. else{
  648. cb(null);
  649. }
  650. })
  651. }, function (err) {
  652. if(err){
  653. callback(err);
  654. }
  655. else{
  656. callback(null);
  657. }
  658. });
  659. });
  660. };
  661. //更新定额下模板关联
  662. rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  663. //自动匹配定额
  664. let matachCodes = [],
  665. matchRations = [];
  666. //要保存的数据
  667. let saveData = [];
  668. for (let data of templateData) {
  669. if (data.code) {
  670. matachCodes.push(data.code);
  671. }
  672. }
  673. matachCodes = Array.from(new Set(matachCodes));
  674. if (matachCodes.length > 0) {
  675. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  676. }
  677. let validData = [];
  678. //设置展示数据
  679. for (let data of templateData) {
  680. let match = false;
  681. for (let ration of matchRations) {
  682. if (data.code && data.code === ration.code) {
  683. match = true;
  684. data.name = ration.name;
  685. data.rationID = ration.ID;
  686. break;
  687. }
  688. }
  689. if (!match) {
  690. data.code = '';
  691. data.name = '';
  692. }
  693. if (data.type || data.code || data.name || data.billsLocation) {
  694. validData.push(data);
  695. }
  696. }
  697. for (let data of validData) {
  698. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  699. }
  700. //更新
  701. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  702. return validData;
  703. };
  704. //计算导入数据的价格
  705. rationItemDAO.prototype.calcForRation = function (stdGljList, ration) {
  706. const processDecimal = -6;
  707. //根据工料机类型划分价格
  708. const labour = [1],
  709. material = [201, 202, 203, 204, 205, 206, 207],
  710. machine = [301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312],
  711. manage = [6],
  712. profit = [7],
  713. risk = [8];
  714. let labourPrc = [], materialPrc = [], machinePrc = [], managePrc = [], profitPrc = [], riskPrc = [],
  715. singlePrc, updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, basePrice: 0, managePrice: 0, profitPrice: 0, riskPrice: 0};
  716. let rationGljList = ration.rationGljList;
  717. for(let rationGlj of rationGljList){
  718. let glj = stdGljList[rationGlj.gljId];
  719. let prcType = isDef(glj) ? getParentType(glj.gljType) : null;
  720. if(isDef(prcType)){
  721. singlePrc = scMathUtil.roundTo(parseFloat(glj.basePrice) * parseFloat(rationGlj.consumeAmt), -3);
  722. if(prcType === 'labour'){
  723. labourPrc.push(singlePrc);
  724. }
  725. else if(prcType === 'material'){
  726. materialPrc.push(singlePrc);
  727. }
  728. else if(prcType === 'machine'){
  729. machinePrc.push(singlePrc);
  730. }
  731. else if(prcType === 'manage'){
  732. managePrc.push(singlePrc);
  733. }
  734. else if(prcType === 'profit'){
  735. profitPrc.push(singlePrc);
  736. }
  737. else if(prcType === 'risk'){
  738. riskPrc.push(singlePrc);
  739. }
  740. }
  741. }
  742. //计算人工费
  743. if(labourPrc.length > 0){
  744. let sumLaP = 0;
  745. for(let i = 0, len = labourPrc.length; i < len; i++){
  746. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], processDecimal);
  747. }
  748. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  749. }
  750. //材料费
  751. if(materialPrc.length > 0){
  752. let sumMtP = 0;
  753. for(let i = 0, len = materialPrc.length; i < len; i++){
  754. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], processDecimal);
  755. }
  756. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  757. }
  758. //机械费
  759. if(machinePrc.length > 0){
  760. let sumMaP = 0;
  761. for(let i = 0, len = machinePrc.length; i < len; i++){
  762. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], processDecimal);
  763. }
  764. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  765. }
  766. //管理费
  767. if(managePrc.length > 0){
  768. let sumMgP = 0;
  769. for(let i = 0, len = managePrc.length; i < len; i++){
  770. sumMgP = scMathUtil.roundTo(sumMgP + managePrc[i], processDecimal);
  771. }
  772. updatePrc.managePrice = scMathUtil.roundTo(sumMgP, -2);
  773. }
  774. //利润
  775. if(profitPrc.length > 0){
  776. let sumPfP = 0;
  777. for(let i = 0, len = profitPrc.length; i < len; i++){
  778. sumPfP = scMathUtil.roundTo(sumPfP + profitPrc[i], processDecimal);
  779. }
  780. updatePrc.profitPrice = scMathUtil.roundTo(sumPfP, -2);
  781. }
  782. //风险费
  783. if(riskPrc.length > 0){
  784. let sumRkP = 0;
  785. for(let i = 0, len = riskPrc.length; i < len; i++){
  786. sumRkP = scMathUtil.roundTo(sumRkP + riskPrc[i], processDecimal);
  787. }
  788. updatePrc.riskPrice = scMathUtil.roundTo(sumRkP, -2);
  789. }
  790. //基价
  791. updatePrc.basePrice = scMathUtil.roundTo(
  792. updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice + updatePrc.managePrice + updatePrc.profitPrice + updatePrc.riskPrice, -2);
  793. //更新定额数据
  794. ration.labourPrice = updatePrc.labourPrice.toString();
  795. ration.materialPrice = updatePrc.materialPrice.toString();
  796. ration.machinePrice = updatePrc.machinePrice.toString();
  797. ration.basePrice = updatePrc.basePrice.toString();
  798. function isDef(v){
  799. return v !== undefined && v !== null;
  800. }
  801. //是否属于人工、材料、机械类型
  802. function getParentType(type){
  803. if(labour.includes(type)){
  804. return 'labour';
  805. }
  806. if(material.includes(type)){
  807. return 'material';
  808. }
  809. if(machine.includes(type)){
  810. return 'machine';
  811. }
  812. if(manage.includes(type)){
  813. return 'manage';
  814. }
  815. if(profit.includes(type)){
  816. return 'profit';
  817. }
  818. if(risk.includes(type)){
  819. return 'risk'
  820. }
  821. return null;
  822. }
  823. };
  824. /**
  825. * 根据条件获取定额数据
  826. *
  827. * @param {Object} condition
  828. * @param {Object} fields
  829. * @param {String} indexBy
  830. * @return {Promise|Array}
  831. */
  832. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  833. let result = [];
  834. if (Object.keys(condition).length <= 0) {
  835. return result;
  836. }
  837. result = await rationItemModel.find(condition, fields).sort({code: 1});
  838. if (indexBy !== null && result.length > 0) {
  839. let tmpResult = {};
  840. for(let tmp of result) {
  841. tmpResult[tmp[indexBy]] = tmp;
  842. }
  843. result = tmpResult;
  844. }
  845. return result;
  846. };
  847. /**
  848. * 从excel中批量新增数据
  849. *
  850. * @param {Number} rationRepId
  851. * @param {Array} data
  852. * @return {bool}
  853. */
  854. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  855. if (data.length <= 0) {
  856. return false;
  857. }
  858. // 获取定额库相关数据
  859. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  860. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  861. return false;
  862. }
  863. // 获取标准工料机库数据
  864. const stdBillsLibListsModel = new STDGLJListModel();
  865. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  866. // 整理标准工料机库数据
  867. let stdGLJList = {};
  868. let stdGLJListByID = {};
  869. for (const tmp of stdGLJData) {
  870. stdGLJList[tmp.code.toString()] = tmp.ID;
  871. stdGLJListByID[tmp.ID] = tmp;
  872. }
  873. let lastData = {};
  874. const rationData = [];
  875. // 编码列表,用于查找库中是否有对应数据
  876. let rationCodeList = [];
  877. let gljCodeList = [];
  878. // 插入失败的工料机列表(用于提示)
  879. this.failGLJList = [];
  880. for (const tmp of data) {
  881. if (tmp.length <= 0) {
  882. continue;
  883. }
  884. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  885. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  886. // 如果不存在对应的工料机库数据则跳过
  887. if (stdGLJList[tmp[1]] === undefined) {
  888. const failString = '定额' + lastData.code + '下的' + tmp[1];
  889. this.failGLJList.push(failString);
  890. continue;
  891. }
  892. const tmpRationGlj = {
  893. gljId: stdGLJList[tmp[1]],
  894. consumeAmt: tmp[4],
  895. proportion: 0,
  896. };
  897. lastData.rationGljList.push(tmpRationGlj);
  898. if (gljCodeList.indexOf(tmp[1]) < 0) {
  899. gljCodeList.push(tmp[1]);
  900. }
  901. continue;
  902. }
  903. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  904. rationData.push(lastData);
  905. }
  906. // 组装数据
  907. lastData = {
  908. code: tmp[1],
  909. name: tmp[2],
  910. unit: tmp[3],
  911. caption: tmp[2],
  912. rationRepId: rationRepId,
  913. sectionId: 0,
  914. labourPrice: '0',
  915. materialPrice: '0',
  916. machinePrice: '0',
  917. basePrice: '0',
  918. rationGljList: []
  919. };
  920. // 防止重复加入
  921. if (rationCodeList.indexOf(tmp[1]) < 0) {
  922. rationCodeList.push(tmp[1]);
  923. }
  924. }
  925. // 最后一个入数组
  926. rationData.push(lastData);
  927. // 查找数据库中是否已存在待插入数据
  928. const condition = {
  929. rationRepId: rationRepId,
  930. code: { $in: rationCodeList }
  931. };
  932. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  933. // 过滤插入数据
  934. let insertData = [];
  935. //已存在定额,则更新价格及rationGLjList字段
  936. let updateData = [];
  937. for (const ration of rationData) {
  938. if (existCodeList[ration.code] !== undefined) {
  939. updateData.push(ration);
  940. continue;
  941. }
  942. insertData.push(ration);
  943. }
  944. //更新定额
  945. let updateBulk = [];
  946. for(let ration of updateData){
  947. this.calcForRation(stdGLJListByID, ration);
  948. updateBulk.push({
  949. updateOne: {
  950. filter: {rationRepId: rationRepId, code: ration.code},
  951. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  952. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  953. }
  954. });
  955. }
  956. //更新数据库
  957. if(updateBulk.length > 0){
  958. await rationItemModel.bulkWrite(updateBulk);
  959. }
  960. // 如果都已经存在,直接返回
  961. if (insertData.length <= 0) {
  962. return true;
  963. }
  964. //计算价格
  965. for(let ration of insertData){
  966. this.calcForRation(stdGLJListByID, ration);
  967. }
  968. // 组织id
  969. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  970. let maxId = counterInfo.sequence_value;
  971. maxId = parseInt(maxId);
  972. let count = 0;
  973. for (const index in insertData) {
  974. insertData[index].ID = maxId - (insertData.length - 1) + count;
  975. count++;
  976. }
  977. // 插入数据库
  978. const result = await rationItemModel.create(insertData);
  979. return result.length > 0;
  980. };
  981. /**
  982. * 导出到excel的数据
  983. *
  984. * @param {Number} rationRepId
  985. * @return {Array}
  986. */
  987. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  988. const condition = {
  989. rationRepId: rationRepId
  990. };
  991. // @todo 限制导出的数量以防内存溢出
  992. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice']);
  993. // 整理数据
  994. let rationData = [];
  995. for (const tmp of rationDataList) {
  996. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  997. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  998. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice];
  999. rationData.push(ration);
  1000. }
  1001. //根据编号排序,优先级:number-number-..., number, Anumber....
  1002. /*let regConnector = /-/g,
  1003. regLetter = /[a-z,A-Z]/g,
  1004. regNum = /\d+/g;
  1005. rationData.sort(function (a, b) {
  1006. let aCode = a[3],
  1007. bCode = b[3],
  1008. rst = 0;
  1009. function compareConnector(arrA, arrB) {
  1010. let lessArr = arrA.length <= arrB ? arrA : arrB;
  1011. for (let i = 0; i < lessArr.length; i++) {
  1012. let result = compareUnit(arrA[i], arrB[i]);
  1013. if (result !== 0) {
  1014. return result;
  1015. } else {
  1016. }
  1017. }
  1018. function compareUnit(uA, uB) {
  1019. let uAV = parseFloat(uA),
  1020. uBV = parseFloat(uB);
  1021. if (uAV > uBV) {
  1022. return 1;
  1023. } else if (uAV < uBV) {
  1024. return -1;
  1025. }
  1026. return 0;
  1027. }
  1028. }
  1029. if (regConnector.test(a) && !regConnector.test(b)) {
  1030. rst = -1;
  1031. } else if (!regConnector.test(a) && regConnector.test(b)) {
  1032. rst = 1;
  1033. } else if (regConnector.test(a) && regConnector.test(b)) {
  1034. }
  1035. });
  1036. rationData.sort(function (a, b) {
  1037. let aCode = a[3],
  1038. bCode = b[3],
  1039. rst = 0,
  1040. splitA = aCode.split('-'),
  1041. splitB = bCode.split('-');
  1042. if(splitA[0] > splitB[0]){
  1043. rst = 1;
  1044. }
  1045. else if(splitA[0] < splitB[0]){
  1046. rst = -1;
  1047. }
  1048. else {
  1049. if(splitA[1] && splitB[1]){
  1050. let floatA = parseFloat(splitA[1]),
  1051. floatB = parseFloat(splitB[1]);
  1052. if(floatA > floatB){
  1053. rst = 1;
  1054. }
  1055. else if(floatA < floatB){
  1056. rst = -1;
  1057. }
  1058. }
  1059. }
  1060. return rst;
  1061. });*/
  1062. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  1063. excelData.push.apply(excelData, rationData);
  1064. return excelData;
  1065. };
  1066. /**
  1067. * 批量更改章节id
  1068. *
  1069. * @param {Object} data
  1070. * @return {bool}
  1071. */
  1072. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  1073. if (data.length <= 0) {
  1074. return false;
  1075. }
  1076. // 批量执行update
  1077. let bulkOprs = [];
  1078. for (const tmp of data) {
  1079. let rationId = parseInt(tmp[2]);
  1080. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  1081. let sectionId = parseInt(tmp[0]);
  1082. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  1083. // 取费专业
  1084. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  1085. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  1086. let name = tmp[4];
  1087. name = name ? name : '';
  1088. let caption = tmp[5];
  1089. caption = caption ? caption : '';
  1090. if (sectionId <= 0 || rationId <= 0) {
  1091. continue;
  1092. }
  1093. bulkOprs.push({updateOne: {filter: {ID: rationId}, update: {$set: {sectionId: sectionId, feeType: feeType, name: name, caption: caption}}}});
  1094. }
  1095. if(bulkOprs.length <= 0){
  1096. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1097. }
  1098. await rationItemModel.bulkWrite(bulkOprs);
  1099. };
  1100. module.exports = new rationItemDAO();