ration_item.js 38 KB

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