ration_item.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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 compleRationModel = mongoose.model('complementary_ration_items');
  13. import STDGLJListModel from '../../std_glj_lib/models/gljModel';
  14. var rationItemDAO = function(){};
  15. rationItemDAO.prototype.sortToNumber = function (datas) {
  16. for(let i = 0, len = datas.length; i < len; i++){
  17. let data = datas[i]._doc;
  18. if(_exist(data, 'labourPrice')){
  19. data['labourPrice'] = parseFloat(data['labourPrice']);
  20. }
  21. if(_exist(data, 'materialPrice')){
  22. data['materialPrice'] = parseFloat(data['materialPrice']);
  23. }
  24. if(_exist(data, 'machinePrice')){
  25. data['machinePrice'] = parseFloat(data['machinePrice']);
  26. }
  27. if(_exist(data, 'basePrice')){
  28. data['basePrice'] = parseFloat(data['basePrice']);
  29. }
  30. if(_exist(data, 'rationGljList')){
  31. for(let j = 0, jLen = data['rationGljList'].length; j < jLen; j++){
  32. let raGljObj = data['rationGljList'][j]._doc;
  33. if(_exist(raGljObj, 'consumeAmt')){
  34. raGljObj['consumeAmt'] = parseFloat(raGljObj['consumeAmt']);
  35. }
  36. }
  37. }
  38. }
  39. function _exist(data, attr){
  40. return data && data[attr] !== undefined && data[attr];
  41. }
  42. };
  43. rationItemDAO.prototype.getRationItemsBySection = function(rationRepId, sectionId,callback){
  44. let me = this;
  45. rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
  46. if(err) callback(true, "Fail to get items", "");
  47. else {
  48. me.sortToNumber(data);
  49. callback(false,"Get items successfully", data);
  50. }
  51. })
  52. };
  53. rationItemDAO.prototype.mixUpdateRationItems = function(rationLibId, lastOpr, sectionId, updateItems, addItems, rIds, callback){
  54. var me = this;
  55. if (updateItems.length == 0 && rIds.length == 0) {
  56. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  57. } else {
  58. me.removeRationItems(rationLibId, lastOpr, rIds, function(err, message, docs) {
  59. if (err) {
  60. callback(true, "Fail to remove", false);
  61. } else {
  62. me.updateRationItems(rationLibId, lastOpr, sectionId, updateItems, function(err, results){
  63. if (err) {
  64. callback(true, "Fail to save", false);
  65. } else {
  66. if (addItems && addItems.length > 0) {
  67. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  68. } else {
  69. callback(false, "Save successfully", results);
  70. }
  71. }
  72. });
  73. }
  74. })
  75. }
  76. };
  77. rationItemDAO.prototype.removeRationItems = function(rationLibId, lastOpr, rIds,callback){
  78. if (rIds.length > 0) {
  79. rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
  80. if (err) {
  81. callback(true, "Fail to remove", false);
  82. } else {
  83. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  84. if(!err){
  85. callback(false, "Remove successfully", docs);
  86. }
  87. })
  88. }
  89. })
  90. } else {
  91. callback(false, "No records were deleted!", null);
  92. }
  93. };
  94. rationItemDAO.prototype.getRationItemsByCode = function(repId, code,callback){
  95. rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$or": [{"isDeleted": null}, {"isDeleted": false}]},function(err,data){
  96. if(err) callback(true, "Fail to get items", "")
  97. else callback(false,"Get items successfully", data);
  98. })
  99. };
  100. rationItemDAO.prototype.findRation = function (repId, keyword, callback) {
  101. var filter = {
  102. 'rationRepId': repId,
  103. '$and': [{
  104. '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
  105. }, {
  106. '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
  107. }]
  108. };
  109. rationItemModel.find(filter, function (err, data) {
  110. if (err) {
  111. callback(true, 'Fail to find ration', null);
  112. } else {
  113. callback(false, '', data);
  114. }
  115. })
  116. }
  117. rationItemDAO.prototype.getRationItem = function (repId, code, callback) {
  118. if (callback) {
  119. rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec()
  120. .then(function (result, err) {
  121. if (err) {
  122. callback(1, '找不到定额“' + code +'”' , null);
  123. } else {
  124. callback(0, '', result);
  125. }
  126. });
  127. return null;
  128. } else {
  129. return rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec();
  130. }
  131. };
  132. rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  133. if (items && items.length > 0) {
  134. counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
  135. var maxId = result.sequence_value;
  136. var arr = [];
  137. for (var i = 0; i < items.length; i++) {
  138. var obj = new rationItemModel(items[i]);
  139. obj.ID = (maxId - (items.length - 1) + i);
  140. obj.sectionId = sectionId;
  141. obj.rationRepId = rationLibId;
  142. arr.push(obj);
  143. }
  144. rationItemModel.collection.insert(arr, null, function(err, docs){
  145. if (err) {
  146. callback(true, "Fail to save", false);
  147. } else {
  148. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  149. if(err){
  150. callback(true, "Fail to sava operator", false);
  151. }
  152. else{
  153. callback(false, "Save successfully", docs);
  154. }
  155. })
  156. }
  157. })
  158. });
  159. } else {
  160. callback(true, "Source error!", false);
  161. }
  162. };
  163. rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  164. var functions = [];
  165. for (var i=0; i < items.length; i++) {
  166. functions.push((function(doc) {
  167. return function(cb) {
  168. var filter = {};
  169. if (doc.ID) {
  170. filter.ID = doc.ID;
  171. } else {
  172. filter.sectionId = sectionId;
  173. if (rationLibId) filter.rationRepId = rationLibId;
  174. filter.code = doc.code;
  175. }
  176. rationItemModel.update(filter, doc, cb);
  177. };
  178. })(items[i]));
  179. }
  180. functions.push((function () {
  181. return function (cb) {
  182. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  183. if(err){
  184. cb(err);
  185. }
  186. else{
  187. cb(null);
  188. }
  189. });
  190. }
  191. })());
  192. async.parallel(functions, function(err, results) {
  193. callback(err, results);
  194. });
  195. };
  196. //ration round func
  197. function round(v,e){
  198. var t=1;
  199. for(;e>0;t*=10,e--);
  200. for(;e<0;t/=10,e++);
  201. return Math.round(v*t)/t;
  202. }
  203. rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, callback) {
  204. async.each(basePrcArr, function (basePrcObj, finalCb) {
  205. let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
  206. async.waterfall([
  207. function (cb) {
  208. if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
  209. rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
  210. if(err){
  211. cb(err);
  212. }
  213. else{
  214. //删除
  215. rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  216. if(err){
  217. cb(err);
  218. }
  219. else{
  220. //补充定额
  221. compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
  222. if(err){
  223. cb(err);
  224. }
  225. else {
  226. compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  227. if(err){
  228. cb(err);
  229. }
  230. else {
  231. for(let i = 0, len = compleRst.length; i < len; i++){
  232. compleRst[i]._doc.type = 'complementary';
  233. }
  234. cb(null, result.concat(compleRst));
  235. }
  236. });
  237. }
  238. });
  239. }
  240. });
  241. }
  242. });
  243. }
  244. else{
  245. rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
  246. if(err){
  247. cb(err);
  248. }
  249. else{
  250. compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
  251. if(err){
  252. cb(err);
  253. }
  254. else {
  255. for(let i = 0, len = compleRst.length; i < len; i++){
  256. compleRst[i]._doc.type = 'complementary';
  257. }
  258. cb(null, result.concat(compleRst));
  259. }
  260. });
  261. }
  262. });
  263. }
  264. },
  265. function (result, cb) {
  266. let compleRTasks = [], stdRTasks = [];
  267. //重算时需要用到的所有工料机,一次性取
  268. let compleGljIds = [], stdGljIds = [];
  269. for(let ration of result){
  270. for(let glj of ration.rationGljList){
  271. if(glj.type !== undefined && glj.type === 'complementary'){
  272. compleGljIds.push(glj.gljId);
  273. }
  274. else {
  275. stdGljIds.push(glj.gljId);
  276. }
  277. }
  278. }
  279. gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
  280. const processDecimal = -6;
  281. if(err){
  282. cb(err);
  283. }
  284. else {
  285. let gljIndex = {};
  286. for(let glj of allGljs){
  287. gljIndex[glj.ID] = glj;
  288. }
  289. async.each(result, function (rationItem, ecb) {
  290. let rationGljList = rationItem.rationGljList;
  291. let gljArr = [];
  292. for(let i=0; i<rationGljList.length; i++){
  293. let theGlj = gljIndex[rationGljList[i].gljId];
  294. if(theGlj !== undefined && theGlj){
  295. let gljParentType = -1;
  296. if(theGlj.ID === adjGljId){
  297. theGlj.gljType = adjGljType;
  298. }
  299. if(theGlj.gljType <= 3){
  300. gljParentType = theGlj.gljType;
  301. }
  302. if(theGlj.gljType > 200 && theGlj.gljType < 300){
  303. gljParentType = 2;
  304. }
  305. if(theGlj.gljType > 300 && theGlj.gljType < 400){
  306. gljParentType = 3;
  307. }
  308. if(theGlj.ID === adjGljId){
  309. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, gljParentType: gljParentType});
  310. }
  311. else {
  312. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), gljParentType: gljParentType});
  313. }
  314. }
  315. }
  316. gljArr.forEach(function (gljItem) {
  317. rationGljList.forEach(function (rationGlj) {
  318. if(gljItem.gljId === rationGlj.gljId){
  319. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  320. }
  321. })
  322. });
  323. //recalculate the price of ration
  324. let labourPrc = [], materialPrc = [], machinePrc = [], singlePrc, updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, basePrice: 0};
  325. gljArr.forEach(function (gljItem) {
  326. if(gljItem.gljParentType !== -1){
  327. singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3);
  328. if(gljItem.gljParentType === 1){
  329. labourPrc.push(singlePrc);
  330. }
  331. else if(gljItem.gljParentType ===2){
  332. materialPrc.push(singlePrc);
  333. }
  334. else{
  335. machinePrc.push(singlePrc);
  336. }
  337. }
  338. });
  339. if(labourPrc.length > 0){
  340. let sumLaP = 0;
  341. for(let i=0; i<labourPrc.length; i++){
  342. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], processDecimal);
  343. }
  344. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  345. }
  346. if(materialPrc.length > 0){
  347. let sumMtP = 0;
  348. for(let i= 0; i<materialPrc.length; i++){
  349. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], processDecimal);
  350. }
  351. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  352. }
  353. if(machinePrc.length > 0){
  354. let sumMaP = 0;
  355. for(let i =0; i< machinePrc.length; i++){
  356. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], processDecimal);
  357. }
  358. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  359. }
  360. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice, -2);
  361. let task = {
  362. updateOne: {
  363. filter: {
  364. ID: rationItem.ID
  365. },
  366. update: {
  367. labourPrice: updatePrc.labourPrice.toString(),
  368. materialPrice: updatePrc.materialPrice.toString(),
  369. machinePrice: updatePrc.machinePrice.toString(),
  370. basePrice: updatePrc.basePrice.toString()
  371. }
  372. }
  373. };
  374. //updateDataBase
  375. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  376. compleRTasks.push(task);
  377. ecb(null);
  378. }
  379. else {
  380. stdRTasks.push(task);
  381. ecb(null);
  382. }
  383. }, async function(err){
  384. if(err){
  385. cb(err);
  386. }
  387. else {
  388. //do sth
  389. try{
  390. if(compleRTasks.length > 0){
  391. await compleRationModel.bulkWrite(compleRTasks);
  392. }
  393. if(stdRTasks.length > 0){
  394. await rationItemModel.bulkWrite(stdRTasks);
  395. }
  396. }
  397. catch(e){
  398. cb(err);
  399. }
  400. cb(null);
  401. }
  402. });
  403. }
  404. });
  405. },
  406. ], function (err) {
  407. if(err){
  408. finalCb(err);
  409. }
  410. else{
  411. finalCb(null);
  412. }
  413. });
  414. }, function (err) {
  415. if(err){
  416. callback(err, 'Error');
  417. }
  418. else{
  419. callback(null, '');
  420. }
  421. });
  422. };
  423. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  424. let repId = data.repId;
  425. rationItemModel.find({rationRepId: repId}, function (err, result) {
  426. if(err){
  427. callback(err, 'Error', null);
  428. }
  429. else{
  430. let rstIds = [], newRst = [];
  431. result.forEach(function (data) {
  432. if(data.rationGljList.length >0){
  433. data.rationGljList.forEach(function (gljObj) {
  434. rstIds.push(gljObj.gljId);
  435. })
  436. }
  437. });
  438. for(let i= 0; i< rstIds.length; i++){
  439. if(newRst.indexOf(rstIds[i]) === -1){
  440. newRst.push(rstIds[i]);
  441. }
  442. }
  443. callback(null, '', newRst);
  444. }
  445. });
  446. };
  447. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  448. let repId = data.repId;
  449. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  450. if(err){
  451. callback(err, 'Error', null);
  452. }
  453. else{
  454. let rstCodes = [];
  455. result.forEach(function (rationItem) {
  456. rstCodes.push(rationItem.code);
  457. });
  458. callback(null, 'get all rationCodes success', rstCodes);
  459. }
  460. })
  461. };
  462. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  463. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  464. async.each(updateArr, function (obj, cb) {
  465. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  466. if(err){
  467. cb(err);
  468. }
  469. else{
  470. cb(null);
  471. }
  472. })
  473. }, function (err) {
  474. if(err){
  475. callback(err);
  476. }
  477. else{
  478. callback(null);
  479. }
  480. });
  481. });
  482. }
  483. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  484. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  485. async.each(updateArr, function (obj, cb) {
  486. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  487. if(err){
  488. cb(err);
  489. }
  490. else{
  491. cb(null);
  492. }
  493. })
  494. }, function (err) {
  495. if(err){
  496. callback(err);
  497. }
  498. else{
  499. callback(null);
  500. }
  501. });
  502. });
  503. };
  504. //计算导入数据的价格
  505. rationItemDAO.prototype.calcForRation = function (stdGljList, ration) {
  506. const processDecimal = -6;
  507. //根据工料机类型划分价格
  508. const labour = [1], material = [201, 202, 203, 204, 205, 206], machine = [301, 302, 303];
  509. let labourPrc = [], materialPrc = [], machinePrc = [], singlePrc, updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, basePrice: 0};
  510. let rationGljList = ration.rationGljList;
  511. for(let rationGlj of rationGljList){
  512. let glj = stdGljList[rationGlj.gljId];
  513. let prcType = isDef(glj) ? getParentType(glj.gljType) : null;
  514. if(isDef(prcType)){
  515. singlePrc = scMathUtil.roundTo(parseFloat(glj.basePrice) * parseFloat(rationGlj.consumeAmt), -3);
  516. if(prcType === 'labour'){
  517. labourPrc.push(singlePrc);
  518. }
  519. else if(prcType === 'material'){
  520. materialPrc.push(singlePrc);
  521. }
  522. else if(prcType === 'machine'){
  523. machinePrc.push(singlePrc);
  524. }
  525. }
  526. }
  527. //计算人工费
  528. if(labourPrc.length > 0){
  529. let sumLaP = 0;
  530. for(let i = 0, len = labourPrc.length; i < len; i++){
  531. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], processDecimal);
  532. }
  533. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  534. }
  535. //材料费
  536. if(materialPrc.length > 0){
  537. let sumMtP = 0;
  538. for(let i = 0, len = materialPrc.length; i < len; i++){
  539. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], processDecimal);
  540. }
  541. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  542. }
  543. //机械费
  544. if(machinePrc.length > 0){
  545. let sumMaP = 0;
  546. for(let i = 0, len = machinePrc.length; i < len; i++){
  547. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], processDecimal);
  548. }
  549. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  550. }
  551. //基价
  552. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice, -2);
  553. //更新定额数据
  554. ration.labourPrice = updatePrc.labourPrice.toString();
  555. ration.materialPrice = updatePrc.materialPrice.toString();
  556. ration.machinePrice = updatePrc.machinePrice.toString();
  557. ration.basePrice = updatePrc.basePrice.toString();
  558. function isDef(v){
  559. return v !== undefined && v !== null;
  560. }
  561. //是否属于人工、材料、机械类型
  562. function getParentType(type){
  563. if(labour.indexOf(type) !== -1){
  564. return 'labour';
  565. }
  566. if(material.indexOf(type) !== -1){
  567. return 'material';
  568. }
  569. if(machine.indexOf(type) !== -1){
  570. return 'machine';
  571. }
  572. return null;
  573. }
  574. };
  575. /**
  576. * 根据条件获取定额数据
  577. *
  578. * @param {Object} condition
  579. * @param {Object} fields
  580. * @param {String} indexBy
  581. * @return {Promise|Array}
  582. */
  583. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  584. let result = [];
  585. if (Object.keys(condition).length <= 0) {
  586. return result;
  587. }
  588. result = await rationItemModel.find(condition, fields).sort({code: 1});
  589. if (indexBy !== null && result.length > 0) {
  590. let tmpResult = {};
  591. for(let tmp of result) {
  592. tmpResult[tmp[indexBy]] = tmp;
  593. }
  594. result = tmpResult;
  595. }
  596. return result;
  597. };
  598. /**
  599. * 从excel中批量新增数据
  600. *
  601. * @param {Number} rationRepId
  602. * @param {Array} data
  603. * @return {bool}
  604. */
  605. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  606. if (data.length <= 0) {
  607. return false;
  608. }
  609. // 获取定额库相关数据
  610. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  611. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  612. return false;
  613. }
  614. // 获取标准工料机库数据
  615. const stdBillsLibListsModel = new STDGLJListModel();
  616. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  617. // 整理标准工料机库数据
  618. let stdGLJList = {};
  619. let stdGLJListByID = {};
  620. for (const tmp of stdGLJData) {
  621. stdGLJList[tmp.code.toString()] = tmp.ID;
  622. stdGLJListByID[tmp.ID] = tmp;
  623. }
  624. let lastData = {};
  625. const rationData = [];
  626. // 编码列表,用于查找库中是否有对应数据
  627. let rationCodeList = [];
  628. let gljCodeList = [];
  629. // 插入失败的工料机列表(用于提示)
  630. this.failGLJList = [];
  631. for (const tmp of data) {
  632. if (tmp.length <= 0) {
  633. continue;
  634. }
  635. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  636. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  637. // 如果不存在对应的工料机库数据则跳过
  638. if (stdGLJList[tmp[1]] === undefined) {
  639. const failString = '定额' + lastData.code + '下的' + tmp[1];
  640. this.failGLJList.push(failString);
  641. continue;
  642. }
  643. const tmpRationGlj = {
  644. gljId: stdGLJList[tmp[1]],
  645. consumeAmt: tmp[4],
  646. proportion: 0,
  647. };
  648. lastData.rationGljList.push(tmpRationGlj);
  649. if (gljCodeList.indexOf(tmp[1]) < 0) {
  650. gljCodeList.push(tmp[1]);
  651. }
  652. continue;
  653. }
  654. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  655. rationData.push(lastData);
  656. }
  657. // 组装数据
  658. lastData = {
  659. code: tmp[1],
  660. name: tmp[2],
  661. unit: tmp[3],
  662. caption: tmp[2],
  663. rationRepId: rationRepId,
  664. sectionId: 0,
  665. labourPrice: '0',
  666. materialPrice: '0',
  667. machinePrice: '0',
  668. basePrice: '0',
  669. rationGljList: []
  670. };
  671. // 防止重复加入
  672. if (rationCodeList.indexOf(tmp[1]) < 0) {
  673. rationCodeList.push(tmp[1]);
  674. }
  675. }
  676. // 最后一个入数组
  677. rationData.push(lastData);
  678. // 查找数据库中是否已存在待插入数据
  679. const condition = {
  680. rationRepId: rationRepId,
  681. code: { $in: rationCodeList }
  682. };
  683. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  684. // 过滤插入数据
  685. let insertData = [];
  686. for (const ration of rationData) {
  687. if (existCodeList[ration.code] !== undefined) {
  688. continue;
  689. }
  690. insertData.push(ration);
  691. }
  692. // 如果都已经存在,直接返回
  693. if (insertData.length <= 0) {
  694. return true;
  695. }
  696. //计算价格
  697. for(let ration of insertData){
  698. this.calcForRation(stdGLJListByID, ration);
  699. }
  700. // 组织id
  701. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  702. let maxId = counterInfo.sequence_value;
  703. maxId = parseInt(maxId);
  704. let count = 0;
  705. for (const index in insertData) {
  706. insertData[index].ID = maxId - (insertData.length - 1) + count;
  707. count++;
  708. }
  709. // 插入数据库
  710. const result = await rationItemModel.create(insertData);
  711. return result.length > 0;
  712. };
  713. /**
  714. * 导出到excel的数据
  715. *
  716. * @param {Number} rationRepId
  717. * @return {Array}
  718. */
  719. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  720. const condition = {
  721. rationRepId: rationRepId
  722. };
  723. // @todo 限制导出的数量以防内存溢出
  724. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType']);
  725. // 整理数据
  726. let rationData = [];
  727. for (const tmp of rationDataList) {
  728. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  729. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  730. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name];
  731. rationData.push(ration);
  732. }
  733. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名']];
  734. excelData.push.apply(excelData, rationData);
  735. return excelData;
  736. };
  737. /**
  738. * 批量更改章节id
  739. *
  740. * @param {Object} data
  741. * @return {bool}
  742. */
  743. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  744. if (data.length <= 0) {
  745. return false;
  746. }
  747. // 批量执行update
  748. const bulk = rationItemModel.collection.initializeOrderedBulkOp();
  749. for (const tmp of data) {
  750. let rationId = parseInt(tmp[2]);
  751. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  752. let sectionId = parseInt(tmp[0]);
  753. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  754. // 取费专业
  755. let feeType = parseInt(tmp[1]);
  756. feeType = isNaN(feeType) || feeType <= 0 ? 0 : feeType;
  757. if (sectionId <= 0 || rationId <= 0 || feeType <= 0) {
  758. continue;
  759. }
  760. bulk.find({"ID": rationId}).update({$set: { sectionId: sectionId, feeType: feeType }});
  761. }
  762. const result = await bulk.execute();
  763. return result.isOk();
  764. };
  765. module.exports = new rationItemDAO();