ration_item.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. if(err){
  281. cb(err);
  282. }
  283. else {
  284. let gljIndex = {};
  285. for(let glj of allGljs){
  286. gljIndex[glj.ID] = glj;
  287. }
  288. async.each(result, function (rationItem, ecb) {
  289. let rationGljList = rationItem.rationGljList;
  290. let gljArr = [];
  291. for(let i=0; i<rationGljList.length; i++){
  292. let theGlj = gljIndex[rationGljList[i].gljId];
  293. if(theGlj !== undefined && theGlj){
  294. let gljParentType = -1;
  295. if(theGlj.ID === adjGljId){
  296. theGlj.gljType = adjGljType;
  297. }
  298. if(theGlj.gljType <= 3){
  299. gljParentType = theGlj.gljType;
  300. }
  301. if(theGlj.gljType > 200 && theGlj.gljType < 300){
  302. gljParentType = 2;
  303. }
  304. if(theGlj.gljType > 300 && theGlj.gljType < 400){
  305. gljParentType = 3;
  306. }
  307. if(theGlj.ID === adjGljId){
  308. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, gljParentType: gljParentType});
  309. }
  310. else {
  311. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), gljParentType: gljParentType});
  312. }
  313. }
  314. }
  315. gljArr.forEach(function (gljItem) {
  316. rationGljList.forEach(function (rationGlj) {
  317. if(gljItem.gljId === rationGlj.gljId){
  318. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  319. }
  320. })
  321. });
  322. //recalculate the price of ration
  323. let labourPrc = [], materialPrc = [], machinePrc = [], singlePrc, updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, basePrice: 0};
  324. gljArr.forEach(function (gljItem) {
  325. if(gljItem.gljParentType !== -1){
  326. singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3);
  327. if(gljItem.gljParentType === 1){
  328. labourPrc.push(singlePrc);
  329. }
  330. else if(gljItem.gljParentType ===2){
  331. materialPrc.push(singlePrc);
  332. }
  333. else{
  334. machinePrc.push(singlePrc);
  335. }
  336. }
  337. });
  338. if(labourPrc.length > 0){
  339. let sumLaP = 0;
  340. for(let i=0; i<labourPrc.length; i++){
  341. sumLaP += labourPrc[i];
  342. }
  343. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  344. }
  345. if(materialPrc.length > 0){
  346. let sumMtP = 0;
  347. for(let i= 0; i<materialPrc.length; i++){
  348. sumMtP += materialPrc[i];
  349. }
  350. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  351. }
  352. if(machinePrc.length > 0){
  353. let sumMaP = 0;
  354. for(let i =0; i< machinePrc.length; i++){
  355. sumMaP += machinePrc[i];
  356. }
  357. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  358. }
  359. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice, -2);
  360. let task = {
  361. updateOne: {
  362. filter: {
  363. ID: rationItem.ID
  364. },
  365. update: {
  366. labourPrice: updatePrc.labourPrice.toString(),
  367. materialPrice: updatePrc.materialPrice.toString(),
  368. machinePrice: updatePrc.machinePrice.toString(),
  369. basePrice: updatePrc.basePrice.toString()
  370. }
  371. }
  372. };
  373. //updateDataBase
  374. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  375. compleRTasks.push(task);
  376. ecb(null);
  377. }
  378. else {
  379. stdRTasks.push(task);
  380. ecb(null);
  381. }
  382. }, async function(err){
  383. if(err){
  384. cb(err);
  385. }
  386. else {
  387. //do sth
  388. try{
  389. if(compleRTasks.length > 0){
  390. await compleRationModel.bulkWrite(compleRTasks);
  391. }
  392. if(stdRTasks.length > 0){
  393. await rationItemModel.bulkWrite(stdRTasks);
  394. }
  395. }
  396. catch(e){
  397. cb(err);
  398. }
  399. cb(null);
  400. }
  401. });
  402. }
  403. });
  404. },
  405. ], function (err) {
  406. if(err){
  407. finalCb(err);
  408. }
  409. else{
  410. finalCb(null);
  411. }
  412. });
  413. }, function (err) {
  414. if(err){
  415. callback(err, 'Error');
  416. }
  417. else{
  418. callback(null, '');
  419. }
  420. });
  421. };
  422. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  423. let repId = data.repId;
  424. rationItemModel.find({rationRepId: repId}, function (err, result) {
  425. if(err){
  426. callback(err, 'Error', null);
  427. }
  428. else{
  429. let rstIds = [], newRst = [];
  430. result.forEach(function (data) {
  431. if(data.rationGljList.length >0){
  432. data.rationGljList.forEach(function (gljObj) {
  433. rstIds.push(gljObj.gljId);
  434. })
  435. }
  436. });
  437. for(let i= 0; i< rstIds.length; i++){
  438. if(newRst.indexOf(rstIds[i]) === -1){
  439. newRst.push(rstIds[i]);
  440. }
  441. }
  442. callback(null, '', newRst);
  443. }
  444. });
  445. };
  446. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  447. let repId = data.repId;
  448. rationItemModel.find({rationRepId: repId}, function (err, result) {
  449. if(err){
  450. callback(err, 'Error', null);
  451. }
  452. else{
  453. let rstCodes = [];
  454. result.forEach(function (rationItem) {
  455. rstCodes.push(rationItem.code);
  456. });
  457. callback(null, 'get all rationCodes success', rstCodes);
  458. }
  459. })
  460. };
  461. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  462. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  463. async.each(updateArr, function (obj, cb) {
  464. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  465. if(err){
  466. cb(err);
  467. }
  468. else{
  469. cb(null);
  470. }
  471. })
  472. }, function (err) {
  473. if(err){
  474. callback(err);
  475. }
  476. else{
  477. callback(null);
  478. }
  479. });
  480. });
  481. }
  482. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  483. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  484. async.each(updateArr, function (obj, cb) {
  485. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  486. if(err){
  487. cb(err);
  488. }
  489. else{
  490. cb(null);
  491. }
  492. })
  493. }, function (err) {
  494. if(err){
  495. callback(err);
  496. }
  497. else{
  498. callback(null);
  499. }
  500. });
  501. });
  502. };
  503. //计算导入数据的价格
  504. rationItemDAO.prototype.calcForRation = function (stdGljList, ration) {
  505. //根据工料机类型划分价格
  506. const labour = [1], material = [201, 202, 203, 204, 205, 206], machine = [301, 302, 303];
  507. let labourPrc = [], materialPrc = [], machinePrc = [], singlePrc, updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, basePrice: 0};
  508. let rationGljList = ration.rationGljList;
  509. for(let rationGlj of rationGljList){
  510. let glj = stdGljList[rationGlj.gljId];
  511. let prcType = isDef(glj) ? getParentType(glj.gljType) : null;
  512. if(isDef(prcType)){
  513. singlePrc = scMathUtil.roundTo(parseFloat(glj.basePrice) * parseFloat(rationGlj.consumeAmt), -3);
  514. if(prcType === 'labour'){
  515. labourPrc.push(singlePrc);
  516. }
  517. else if(prcType === 'material'){
  518. materialPrc.push(singlePrc);
  519. }
  520. else if(prcType === 'machine'){
  521. machinePrc.push(singlePrc);
  522. }
  523. }
  524. }
  525. //计算人工费
  526. if(labourPrc.length > 0){
  527. let sumLaP = 0;
  528. for(let i = 0, len = labourPrc.length; i < len; i++){
  529. sumLaP += labourPrc[i];
  530. }
  531. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  532. }
  533. //材料费
  534. if(materialPrc.length > 0){
  535. let sumLaP = 0;
  536. for(let i = 0, len = materialPrc.length; i < len; i++){
  537. sumLaP += materialPrc[i];
  538. }
  539. updatePrc.materialPrice = scMathUtil.roundTo(sumLaP, -2);
  540. }
  541. //机械费
  542. if(machinePrc.length > 0){
  543. let sumLaP = 0;
  544. for(let i = 0, len = machinePrc.length; i < len; i++){
  545. sumLaP += machinePrc[i];
  546. }
  547. updatePrc.machinePrice = scMathUtil.roundTo(sumLaP, -2);
  548. }
  549. //基价
  550. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.labourPrice + updatePrc.materialPrice + updatePrc.machinePrice, -2);
  551. //更新定额数据
  552. ration.labourPrice = updatePrc.labourPrice.toString();
  553. ration.materialPrice = updatePrc.materialPrice.toString();
  554. ration.machinePrice = updatePrc.machinePrice.toString();
  555. ration.basePrice = updatePrc.basePrice.toString();
  556. function isDef(v){
  557. return v !== undefined && v !== null;
  558. }
  559. //是否属于人工、材料、机械类型
  560. function getParentType(type){
  561. if(labour.indexOf(type) !== -1){
  562. return 'labour';
  563. }
  564. if(material.indexOf(type) !== -1){
  565. return 'material';
  566. }
  567. if(machine.indexOf(type) !== -1){
  568. return 'machine';
  569. }
  570. return null;
  571. }
  572. };
  573. /**
  574. * 根据条件获取定额数据
  575. *
  576. * @param {Object} condition
  577. * @param {Object} fields
  578. * @param {String} indexBy
  579. * @return {Promise|Array}
  580. */
  581. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  582. let result = [];
  583. if (Object.keys(condition).length <= 0) {
  584. return result;
  585. }
  586. result = await rationItemModel.find(condition, fields).sort({code: 1});
  587. if (indexBy !== null && result.length > 0) {
  588. let tmpResult = {};
  589. for(let tmp of result) {
  590. tmpResult[tmp[indexBy]] = tmp;
  591. }
  592. result = tmpResult;
  593. }
  594. return result;
  595. };
  596. /**
  597. * 从excel中批量新增数据
  598. *
  599. * @param {Number} rationRepId
  600. * @param {Array} data
  601. * @return {bool}
  602. */
  603. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  604. if (data.length <= 0) {
  605. return false;
  606. }
  607. // 获取定额库相关数据
  608. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  609. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  610. return false;
  611. }
  612. // 获取标准工料机库数据
  613. const stdBillsLibListsModel = new STDGLJListModel();
  614. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  615. // 整理标准工料机库数据
  616. let stdGLJList = {};
  617. let stdGLJListByID = {};
  618. for (const tmp of stdGLJData) {
  619. stdGLJList[tmp.code.toString()] = tmp.ID;
  620. stdGLJListByID[tmp.ID] = tmp;
  621. }
  622. let lastData = {};
  623. const rationData = [];
  624. // 编码列表,用于查找库中是否有对应数据
  625. let rationCodeList = [];
  626. let gljCodeList = [];
  627. // 插入失败的工料机列表(用于提示)
  628. this.failGLJList = [];
  629. for (const tmp of data) {
  630. if (tmp.length <= 0) {
  631. continue;
  632. }
  633. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  634. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  635. // 如果不存在对应的工料机库数据则跳过
  636. if (stdGLJList[tmp[1]] === undefined) {
  637. const failString = '定额' + lastData.code + '下的' + tmp[1];
  638. this.failGLJList.push(failString);
  639. continue;
  640. }
  641. const tmpRationGlj = {
  642. gljId: stdGLJList[tmp[1]],
  643. consumeAmt: tmp[4],
  644. proportion: 0,
  645. };
  646. lastData.rationGljList.push(tmpRationGlj);
  647. if (gljCodeList.indexOf(tmp[1]) < 0) {
  648. gljCodeList.push(tmp[1]);
  649. }
  650. continue;
  651. }
  652. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  653. rationData.push(lastData);
  654. }
  655. // 组装数据
  656. lastData = {
  657. code: tmp[1],
  658. name: tmp[2],
  659. unit: tmp[3],
  660. caption: tmp[2],
  661. rationRepId: rationRepId,
  662. sectionId: 0,
  663. labourPrice: '0',
  664. materialPrice: '0',
  665. machinePrice: '0',
  666. basePrice: '0',
  667. rationGljList: []
  668. };
  669. // 防止重复加入
  670. if (rationCodeList.indexOf(tmp[1]) < 0) {
  671. rationCodeList.push(tmp[1]);
  672. }
  673. }
  674. // 最后一个入数组
  675. rationData.push(lastData);
  676. // 查找数据库中是否已存在待插入数据
  677. const condition = {
  678. rationRepId: rationRepId,
  679. code: { $in: rationCodeList }
  680. };
  681. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  682. // 过滤插入数据
  683. let insertData = [];
  684. for (const ration of rationData) {
  685. if (existCodeList[ration.code] !== undefined) {
  686. continue;
  687. }
  688. insertData.push(ration);
  689. }
  690. // 如果都已经存在,直接返回
  691. if (insertData.length <= 0) {
  692. return true;
  693. }
  694. //计算价格
  695. for(let ration of insertData){
  696. this.calcForRation(stdGLJListByID, ration);
  697. }
  698. // 组织id
  699. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  700. let maxId = counterInfo.sequence_value;
  701. maxId = parseInt(maxId);
  702. let count = 0;
  703. for (const index in insertData) {
  704. insertData[index].ID = maxId - (insertData.length - 1) + count;
  705. count++;
  706. }
  707. // 插入数据库
  708. const result = await rationItemModel.create(insertData);
  709. return result.length > 0;
  710. };
  711. /**
  712. * 导出到excel的数据
  713. *
  714. * @param {Number} rationRepId
  715. * @return {Array}
  716. */
  717. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  718. const condition = {
  719. rationRepId: rationRepId
  720. };
  721. // @todo 限制导出的数量以防内存溢出
  722. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType']);
  723. // 整理数据
  724. let rationData = [];
  725. for (const tmp of rationDataList) {
  726. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  727. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  728. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name];
  729. rationData.push(ration);
  730. }
  731. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名']];
  732. excelData.push.apply(excelData, rationData);
  733. return excelData;
  734. };
  735. /**
  736. * 批量更改章节id
  737. *
  738. * @param {Object} data
  739. * @return {bool}
  740. */
  741. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  742. if (data.length <= 0) {
  743. return false;
  744. }
  745. // 批量执行update
  746. const bulk = rationItemModel.collection.initializeOrderedBulkOp();
  747. for (const tmp of data) {
  748. let rationId = parseInt(tmp[2]);
  749. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  750. let sectionId = parseInt(tmp[0]);
  751. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  752. // 取费专业
  753. let feeType = parseInt(tmp[1]);
  754. feeType = isNaN(feeType) || feeType <= 0 ? 0 : feeType;
  755. if (sectionId <= 0 || rationId <= 0 || feeType <= 0) {
  756. continue;
  757. }
  758. bulk.find({"ID": rationId}).update({$set: { sectionId: sectionId, feeType: feeType }});
  759. }
  760. const result = await bulk.execute();
  761. return result.isOk();
  762. };
  763. module.exports = new rationItemDAO();