ration_item.js 40 KB

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