ration_item.js 36 KB

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