ration_item.js 31 KB

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