ration_item.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. if(err){
  390. cb(err);
  391. }
  392. else {
  393. let gljIndex = {};
  394. for(let glj of allGljs){
  395. gljIndex[glj.ID] = glj;
  396. }
  397. async.each(result, function (rationItem, ecb) {
  398. let rationGljList = rationItem.rationGljList;
  399. let gljArr = [];
  400. for(let i=0; i<rationGljList.length; i++){
  401. let theGlj = gljIndex[rationGljList[i].gljId];
  402. if(theGlj !== undefined && theGlj){
  403. if(theGlj.ID === adjGljId){
  404. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, consumeAmt: rationGljList[i].consumeAmt});
  405. } else {
  406. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  407. let priceKeys = Object.keys(theGlj.priceProperty);
  408. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.priceProperty[priceKeys[0]]), consumeAmt: rationGljList[i].consumeAmt});
  409. } else {
  410. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), consumeAmt: rationGljList[i].consumeAmt});
  411. }
  412. }
  413. }
  414. }
  415. //recalculate the price of ration
  416. let basePrice = 0;
  417. gljArr.forEach(function (gljItem) {
  418. basePrice += gljItem.basePrice * gljItem.consumeAmt;
  419. });
  420. basePrice = scMathUtil.roundTo(basePrice, 0);
  421. let task = {
  422. updateOne: {
  423. filter: {
  424. ID: rationItem.ID
  425. },
  426. update: {
  427. basePrice: basePrice.toString()
  428. }
  429. }
  430. };
  431. //updateDataBase
  432. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  433. compleRTasks.push(task);
  434. ecb(null);
  435. }
  436. else {
  437. stdRTasks.push(task);
  438. ecb(null);
  439. }
  440. }, async function(err){
  441. if(err){
  442. cb(err);
  443. }
  444. else {
  445. //do sth
  446. try{
  447. if(compleRTasks.length > 0){
  448. await compleRationModel.bulkWrite(compleRTasks);
  449. }
  450. if(stdRTasks.length > 0){
  451. await rationItemModel.bulkWrite(stdRTasks);
  452. }
  453. }
  454. catch(e){
  455. cb(err);
  456. }
  457. cb(null);
  458. }
  459. });
  460. }
  461. });
  462. },
  463. ], function (err) {
  464. if(err){
  465. finalCb(err);
  466. }
  467. else{
  468. finalCb(null);
  469. }
  470. });
  471. }, function (err) {
  472. if(err){
  473. callback(err, 'Error');
  474. }
  475. else{
  476. callback(null, '');
  477. }
  478. });
  479. };
  480. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  481. let repId = data.repId;
  482. rationItemModel.find({rationRepId: repId}, function (err, result) {
  483. if(err){
  484. callback(err, 'Error', null);
  485. }
  486. else{
  487. let rstIds = [], newRst = [];
  488. result.forEach(function (data) {
  489. if(data.rationGljList.length >0){
  490. data.rationGljList.forEach(function (gljObj) {
  491. rstIds.push(gljObj.gljId);
  492. })
  493. }
  494. });
  495. for(let i= 0; i< rstIds.length; i++){
  496. if(newRst.indexOf(rstIds[i]) === -1){
  497. newRst.push(rstIds[i]);
  498. }
  499. }
  500. callback(null, '', newRst);
  501. }
  502. });
  503. };
  504. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  505. let repId = data.repId;
  506. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  507. if(err){
  508. callback(err, 'Error', null);
  509. }
  510. else{
  511. let rstCodes = [];
  512. result.forEach(function (rationItem) {
  513. rstCodes.push(rationItem.code);
  514. });
  515. callback(null, 'get all rationCodes success', rstCodes);
  516. }
  517. })
  518. };
  519. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  520. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  521. async.each(updateArr, function (obj, cb) {
  522. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  523. if(err){
  524. cb(err);
  525. }
  526. else{
  527. cb(null);
  528. }
  529. })
  530. }, function (err) {
  531. if(err){
  532. callback(err);
  533. }
  534. else{
  535. callback(null);
  536. }
  537. });
  538. });
  539. }
  540. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  541. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  542. async.each(updateArr, function (obj, cb) {
  543. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  544. if(err){
  545. cb(err);
  546. }
  547. else{
  548. cb(null);
  549. }
  550. })
  551. }, function (err) {
  552. if(err){
  553. callback(err);
  554. }
  555. else{
  556. callback(null);
  557. }
  558. });
  559. });
  560. };
  561. //更新定额下模板关联
  562. rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  563. //自动匹配定额
  564. let matachCodes = [],
  565. matchRations = [];
  566. //要保存的数据
  567. let saveData = [];
  568. for (let data of templateData) {
  569. if (data.code) {
  570. matachCodes.push(data.code);
  571. }
  572. }
  573. matachCodes = Array.from(new Set(matachCodes));
  574. if (matachCodes.length > 0) {
  575. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  576. }
  577. let validData = [];
  578. //设置展示数据
  579. for (let data of templateData) {
  580. let match = false;
  581. for (let ration of matchRations) {
  582. if (data.code && data.code === ration.code) {
  583. match = true;
  584. data.name = ration.name;
  585. data.rationID = ration.ID;
  586. break;
  587. }
  588. }
  589. if (!match) {
  590. data.code = '';
  591. data.name = '';
  592. }
  593. if (data.type || data.code || data.name || data.billsLocation) {
  594. validData.push(data);
  595. }
  596. }
  597. for (let data of validData) {
  598. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  599. }
  600. //更新
  601. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  602. return validData;
  603. };
  604. //计算导入数据的价格
  605. rationItemDAO.prototype.calcForRation = function (stdGljList, ration) {
  606. let rationGljList = ration.rationGljList;
  607. let basePrice = 0;
  608. for(let rationGlj of rationGljList) {
  609. let glj = stdGljList[rationGlj.gljId];
  610. if (glj) {
  611. basePrice += glj.basePrice * rationGlj.consumeAmt;
  612. }
  613. }
  614. ration.basePrice = scMathUtil.roundTo(basePrice, 0).toString();
  615. };
  616. /**
  617. * 根据条件获取定额数据
  618. *
  619. * @param {Object} condition
  620. * @param {Object} fields
  621. * @param {String} indexBy
  622. * @return {Promise|Array}
  623. */
  624. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  625. let result = [];
  626. if (Object.keys(condition).length <= 0) {
  627. return result;
  628. }
  629. result = await rationItemModel.find(condition, fields).sort({code: 1});
  630. if (indexBy !== null && result.length > 0) {
  631. let tmpResult = {};
  632. for(let tmp of result) {
  633. tmpResult[tmp[indexBy]] = tmp;
  634. }
  635. result = tmpResult;
  636. }
  637. return result;
  638. };
  639. /**
  640. * 从excel中批量新增数据
  641. *
  642. * @param {Number} rationRepId
  643. * @param {Array} data
  644. * @return {bool}
  645. */
  646. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  647. if (data.length <= 0) {
  648. return false;
  649. }
  650. // 获取定额库相关数据
  651. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  652. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  653. return false;
  654. }
  655. // 获取标准工料机库数据
  656. const stdBillsLibListsModel = new STDGLJListModel();
  657. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  658. // 整理标准工料机库数据
  659. let stdGLJList = {};
  660. let stdGLJListByID = {};
  661. for (const tmp of stdGLJData) {
  662. stdGLJList[tmp.code.toString()] = tmp.ID;
  663. stdGLJListByID[tmp.ID] = tmp;
  664. }
  665. let lastData = {};
  666. const rationData = [];
  667. // 编码列表,用于查找库中是否有对应数据
  668. let rationCodeList = [];
  669. let gljCodeList = [];
  670. // 插入失败的工料机列表(用于提示)
  671. this.failGLJList = [];
  672. for (const tmp of data) {
  673. if (tmp.length <= 0) {
  674. continue;
  675. }
  676. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  677. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  678. // 如果不存在对应的工料机库数据则跳过
  679. if (stdGLJList[tmp[1]] === undefined) {
  680. const failString = '定额' + lastData.code + '下的' + tmp[1];
  681. this.failGLJList.push(failString);
  682. continue;
  683. }
  684. const tmpRationGlj = {
  685. gljId: stdGLJList[tmp[1]],
  686. consumeAmt: tmp[4],
  687. proportion: 0,
  688. };
  689. lastData.rationGljList.push(tmpRationGlj);
  690. if (gljCodeList.indexOf(tmp[1]) < 0) {
  691. gljCodeList.push(tmp[1]);
  692. }
  693. continue;
  694. }
  695. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  696. rationData.push(lastData);
  697. }
  698. // 组装数据
  699. lastData = {
  700. code: tmp[1],
  701. name: tmp[2],
  702. unit: tmp[3],
  703. caption: tmp[2],
  704. rationRepId: rationRepId,
  705. sectionId: 0,
  706. labourPrice: '0',
  707. materialPrice: '0',
  708. machinePrice: '0',
  709. basePrice: '0',
  710. rationGljList: []
  711. };
  712. // 防止重复加入
  713. if (rationCodeList.indexOf(tmp[1]) < 0) {
  714. rationCodeList.push(tmp[1]);
  715. }
  716. }
  717. // 最后一个入数组
  718. rationData.push(lastData);
  719. // 查找数据库中是否已存在待插入数据
  720. const condition = {
  721. rationRepId: rationRepId,
  722. code: { $in: rationCodeList }
  723. };
  724. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  725. // 过滤插入数据
  726. let insertData = [];
  727. //已存在定额,则更新价格及rationGLjList字段
  728. let updateData = [];
  729. for (const ration of rationData) {
  730. if (existCodeList[ration.code] !== undefined) {
  731. updateData.push(ration);
  732. continue;
  733. }
  734. insertData.push(ration);
  735. }
  736. //更新定额
  737. let updateBulk = [];
  738. for(let ration of updateData){
  739. this.calcForRation(stdGLJListByID, ration);
  740. updateBulk.push({
  741. updateOne: {
  742. filter: {rationRepId: rationRepId, code: ration.code},
  743. update: {$set: {rationGljList: ration.rationGljList, basePrice: ration.basePrice}}
  744. }
  745. });
  746. }
  747. //更新数据库
  748. if(updateBulk.length > 0){
  749. await rationItemModel.bulkWrite(updateBulk);
  750. }
  751. // 如果都已经存在,直接返回
  752. if (insertData.length <= 0) {
  753. return true;
  754. }
  755. //计算价格
  756. for(let ration of insertData){
  757. this.calcForRation(stdGLJListByID, ration);
  758. }
  759. // 组织id
  760. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  761. let maxId = counterInfo.sequence_value;
  762. maxId = parseInt(maxId);
  763. let count = 0;
  764. for (const index in insertData) {
  765. insertData[index].ID = maxId - (insertData.length - 1) + count;
  766. count++;
  767. }
  768. // 插入数据库
  769. const result = await rationItemModel.create(insertData);
  770. return result.length > 0;
  771. };
  772. /**
  773. * 导出到excel的数据
  774. *
  775. * @param {Number} rationRepId
  776. * @return {Array}
  777. */
  778. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  779. const condition = {
  780. rationRepId: rationRepId
  781. };
  782. // @todo 限制导出的数量以防内存溢出
  783. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice']);
  784. // 整理数据
  785. let rationData = [];
  786. for (const tmp of rationDataList) {
  787. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  788. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  789. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice];
  790. rationData.push(ration);
  791. }
  792. //根据编号排序,优先级:number-number-..., number, Anumber....
  793. /*let regConnector = /-/g,
  794. regLetter = /[a-z,A-Z]/g,
  795. regNum = /\d+/g;
  796. rationData.sort(function (a, b) {
  797. let aCode = a[3],
  798. bCode = b[3],
  799. rst = 0;
  800. function compareConnector(arrA, arrB) {
  801. let lessArr = arrA.length <= arrB ? arrA : arrB;
  802. for (let i = 0; i < lessArr.length; i++) {
  803. let result = compareUnit(arrA[i], arrB[i]);
  804. if (result !== 0) {
  805. return result;
  806. } else {
  807. }
  808. }
  809. function compareUnit(uA, uB) {
  810. let uAV = parseFloat(uA),
  811. uBV = parseFloat(uB);
  812. if (uAV > uBV) {
  813. return 1;
  814. } else if (uAV < uBV) {
  815. return -1;
  816. }
  817. return 0;
  818. }
  819. }
  820. if (regConnector.test(a) && !regConnector.test(b)) {
  821. rst = -1;
  822. } else if (!regConnector.test(a) && regConnector.test(b)) {
  823. rst = 1;
  824. } else if (regConnector.test(a) && regConnector.test(b)) {
  825. }
  826. });
  827. rationData.sort(function (a, b) {
  828. let aCode = a[3],
  829. bCode = b[3],
  830. rst = 0,
  831. splitA = aCode.split('-'),
  832. splitB = bCode.split('-');
  833. if(splitA[0] > splitB[0]){
  834. rst = 1;
  835. }
  836. else if(splitA[0] < splitB[0]){
  837. rst = -1;
  838. }
  839. else {
  840. if(splitA[1] && splitB[1]){
  841. let floatA = parseFloat(splitA[1]),
  842. floatB = parseFloat(splitB[1]);
  843. if(floatA > floatB){
  844. rst = 1;
  845. }
  846. else if(floatA < floatB){
  847. rst = -1;
  848. }
  849. }
  850. }
  851. return rst;
  852. });*/
  853. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  854. excelData.push.apply(excelData, rationData);
  855. return excelData;
  856. };
  857. /**
  858. * 批量更改章节id
  859. *
  860. * @param {Object} data
  861. * @return {bool}
  862. */
  863. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  864. if (data.length <= 0) {
  865. return false;
  866. }
  867. // 批量执行update
  868. let bulkOprs = [];
  869. for (const tmp of data) {
  870. let rationId = parseInt(tmp[2]);
  871. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  872. let sectionId = parseInt(tmp[0]);
  873. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  874. // 取费专业
  875. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  876. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  877. let name = tmp[4];
  878. name = name ? name : '';
  879. let caption = tmp[5];
  880. caption = caption ? caption : '';
  881. if (sectionId <= 0 || rationId <= 0) {
  882. continue;
  883. }
  884. bulkOprs.push({updateOne: {filter: {ID: rationId}, update: {$set: {sectionId: sectionId, feeType: feeType, name: name, caption: caption}}}});
  885. }
  886. if(bulkOprs.length <= 0){
  887. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  888. }
  889. await rationItemModel.bulkWrite(bulkOprs);
  890. };
  891. module.exports = new rationItemDAO();