ration_item.js 44 KB

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