ration_item.js 31 KB

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