ration_item.js 35 KB

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