ration_item.js 39 KB

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