ration_item.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. // 定额xx下提示的次数
  793. let lastFailCount = 0;
  794. const rationData = [];
  795. // 编码列表,用于查找库中是否有对应数据
  796. let rationCodeList = [];
  797. let gljCodeList = [];
  798. // 插入失败的工料机列表(用于提示)
  799. let failGLJList = [];
  800. for (const tmp of data) {
  801. if (tmp.length <= 0) {
  802. continue;
  803. }
  804. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  805. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  806. // 如果不存在对应的工料机库数据则跳过
  807. if (stdGLJList[tmp[1]] === undefined) {
  808. if (lastFailCount === 0) {
  809. failGLJList.push('定额' + lastData.code + '下的');
  810. lastFailCount++;
  811. }
  812. //const failString = '定额' + lastData.code + '下的' + tmp[1];
  813. failGLJList.push(tmp[1]);
  814. continue;
  815. }
  816. const tmpRationGlj = {
  817. gljId: stdGLJList[tmp[1]],
  818. consumeAmt: tmp[4],
  819. proportion: 0,
  820. };
  821. lastData.rationGljList.push(tmpRationGlj);
  822. if (gljCodeList.indexOf(tmp[1]) < 0) {
  823. gljCodeList.push(tmp[1]);
  824. }
  825. continue;
  826. }
  827. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  828. rationData.push(lastData);
  829. }
  830. lastFailCount = 0;
  831. // 组装数据
  832. lastData = {
  833. code: tmp[1],
  834. name: tmp[2],
  835. unit: tmp[3],
  836. caption: tmp[2],
  837. rationRepId: rationRepId,
  838. sectionId: 0,
  839. labourPrice: '0',
  840. materialPrice: '0',
  841. machinePrice: '0',
  842. basePrice: '0',
  843. rationGljList: []
  844. };
  845. // 防止重复加入
  846. if (rationCodeList.indexOf(tmp[1]) < 0) {
  847. rationCodeList.push(tmp[1]);
  848. }
  849. }
  850. // 最后一个入数组
  851. rationData.push(lastData);
  852. // 查找数据库中是否已存在待插入数据
  853. const condition = {
  854. rationRepId: rationRepId,
  855. code: { $in: rationCodeList }
  856. };
  857. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  858. // 过滤插入数据
  859. let insertData = [];
  860. //已存在定额,则更新价格及rationGLjList字段
  861. let updateData = [];
  862. for (const ration of rationData) {
  863. if (existCodeList[ration.code] !== undefined) {
  864. updateData.push(ration);
  865. continue;
  866. }
  867. insertData.push(ration);
  868. }
  869. //更新定额
  870. let updateBulk = [];
  871. for(let ration of updateData){
  872. this.calcForRation(stdGLJListByID, ration);
  873. updateBulk.push({
  874. updateOne: {
  875. filter: {rationRepId: rationRepId, code: ration.code},
  876. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  877. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  878. }
  879. });
  880. }
  881. //更新数据库
  882. if(updateBulk.length > 0){
  883. await rationItemModel.bulkWrite(updateBulk);
  884. }
  885. // 如果都已经存在,直接返回
  886. if (insertData.length <= 0) {
  887. return failGLJList;
  888. }
  889. //计算价格
  890. for(let ration of insertData){
  891. this.calcForRation(stdGLJListByID, ration);
  892. }
  893. // 组织id
  894. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  895. let maxId = counterInfo.sequence_value;
  896. maxId = parseInt(maxId);
  897. let count = 0;
  898. for (const index in insertData) {
  899. insertData[index].ID = maxId - (insertData.length - 1) + count;
  900. count++;
  901. }
  902. // 插入数据库
  903. await rationItemModel.create(insertData);
  904. return failGLJList;
  905. };
  906. /**
  907. * 导出到excel的数据
  908. *
  909. * @param {Number} rationRepId
  910. * @return {Array}
  911. */
  912. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  913. const condition = {
  914. rationRepId: rationRepId
  915. };
  916. // @todo 限制导出的数量以防内存溢出
  917. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice']);
  918. // 整理数据
  919. let rationData = [];
  920. for (const tmp of rationDataList) {
  921. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  922. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  923. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice];
  924. rationData.push(ration);
  925. }
  926. //根据编号排序,优先级:number-number-..., number, Anumber....
  927. /*let regConnector = /-/g,
  928. regLetter = /[a-z,A-Z]/g,
  929. regNum = /\d+/g;
  930. rationData.sort(function (a, b) {
  931. let aCode = a[3],
  932. bCode = b[3],
  933. rst = 0;
  934. function compareConnector(arrA, arrB) {
  935. let lessArr = arrA.length <= arrB ? arrA : arrB;
  936. for (let i = 0; i < lessArr.length; i++) {
  937. let result = compareUnit(arrA[i], arrB[i]);
  938. if (result !== 0) {
  939. return result;
  940. } else {
  941. }
  942. }
  943. function compareUnit(uA, uB) {
  944. let uAV = parseFloat(uA),
  945. uBV = parseFloat(uB);
  946. if (uAV > uBV) {
  947. return 1;
  948. } else if (uAV < uBV) {
  949. return -1;
  950. }
  951. return 0;
  952. }
  953. }
  954. if (regConnector.test(a) && !regConnector.test(b)) {
  955. rst = -1;
  956. } else if (!regConnector.test(a) && regConnector.test(b)) {
  957. rst = 1;
  958. } else if (regConnector.test(a) && regConnector.test(b)) {
  959. }
  960. });
  961. rationData.sort(function (a, b) {
  962. let aCode = a[3],
  963. bCode = b[3],
  964. rst = 0,
  965. splitA = aCode.split('-'),
  966. splitB = bCode.split('-');
  967. if(splitA[0] > splitB[0]){
  968. rst = 1;
  969. }
  970. else if(splitA[0] < splitB[0]){
  971. rst = -1;
  972. }
  973. else {
  974. if(splitA[1] && splitB[1]){
  975. let floatA = parseFloat(splitA[1]),
  976. floatB = parseFloat(splitB[1]);
  977. if(floatA > floatB){
  978. rst = 1;
  979. }
  980. else if(floatA < floatB){
  981. rst = -1;
  982. }
  983. }
  984. }
  985. return rst;
  986. });*/
  987. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  988. excelData.push.apply(excelData, rationData);
  989. return excelData;
  990. };
  991. /**
  992. * 批量更改章节id
  993. *
  994. * @param {Object} data
  995. * @return {bool}
  996. */
  997. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  998. if (data.length <= 0) {
  999. return false;
  1000. }
  1001. // 批量执行update
  1002. let bulkOprs = [];
  1003. for (const tmp of data) {
  1004. let rationId = parseInt(tmp[2]);
  1005. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  1006. let sectionId = parseInt(tmp[0]);
  1007. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  1008. // 取费专业
  1009. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  1010. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  1011. let name = tmp[4];
  1012. name = name ? name : '';
  1013. let caption = tmp[5];
  1014. caption = caption ? caption : '';
  1015. if (sectionId <= 0 || rationId <= 0) {
  1016. continue;
  1017. }
  1018. bulkOprs.push({updateOne: {filter: {ID: rationId}, update: {$set: {sectionId: sectionId, feeType: feeType, name: name, caption: caption}}}});
  1019. }
  1020. if(bulkOprs.length <= 0){
  1021. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1022. }
  1023. await rationItemModel.bulkWrite(bulkOprs);
  1024. };
  1025. module.exports = new rationItemDAO();