ration_item.js 42 KB

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