ration_item.js 30 KB

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