ration_item.js 45 KB

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