ration_item.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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 stdRationSectionModel = mongoose.model('std_ration_lib_ration_chapter_trees');
  14. const compleRationModel = mongoose.model('complementary_ration_items');
  15. import STDGLJListModel from '../../std_glj_lib/models/gljModel';
  16. import InstallationDao from '../models/installation';
  17. const installationDao = new InstallationDao();
  18. import GljDao from "../../std_glj_lib/models/gljModel";
  19. const stdGljDao = new GljDao();
  20. import stdgljutil from "../../../public/cache/std_glj_type_util";
  21. var rationItemDAO = function(){};
  22. rationItemDAO.prototype.prepareInitData = async function (rationRepId) {
  23. // 定额库
  24. const libTask = stdRationLibModel.findOne({ID: rationRepId}, '-_id ID dispName gljLib');
  25. // 定额编码
  26. const codesTask = rationItemModel.find({rationRepId}, '-_id code', {lean: true});
  27. // 定额章节树
  28. const sectionTreeTask = stdRationSectionModel.find({rationRepId}, '-_id', {lean: true});
  29. // 安装增加费
  30. const installationTask = installationDao.getInstallation(rationRepId);
  31. const [libInfo, codesArr, sectionTree, installationList] = await Promise.all([libTask, codesTask, sectionTreeTask, installationTask]);
  32. const rationsCodes = codesArr.reduce((acc, cur) => {
  33. acc.push(cur.code);
  34. return acc;
  35. }, []);
  36. // 人材机分类树
  37. const gljLibId = libInfo.gljLib;
  38. const gljTreeTask = stdGljDao.getGljTreeSync(gljLibId);
  39. const gljTask = stdGljDao.getGljItemsSync(gljLibId);
  40. const [gljTree, gljList] = await Promise.all([gljTreeTask, gljTask]);
  41. const gljDistTypeList = stdgljutil.getStdGljTypeCacheObj().toArray();
  42. return {
  43. libInfo,
  44. rationsCodes,
  45. sectionTree,
  46. installationList,
  47. gljTree,
  48. gljList,
  49. gljDistTypeList
  50. };
  51. };
  52. //将消耗量为负的人材机改为正的
  53. rationItemDAO.prototype.toPositive = async function (rationRepId) {
  54. let rations = await rationItemModel.find({rationRepId: rationRepId, 'rationGljList.consumeAmt': {$lt: 0}});
  55. let task = [];
  56. for (let ration of rations) {
  57. let update = false;
  58. for (let rGlj of ration.rationGljList) {
  59. if (rGlj.consumeAmt < 0) {
  60. update = true;
  61. rGlj.consumeAmt = Math.abs(rGlj.consumeAmt);
  62. }
  63. }
  64. if (update) {
  65. task.push({updateOne: {filter: {ID: ration.ID}, update: {rationGljList: ration.rationGljList}}});
  66. }
  67. }
  68. if (task.length > 0) {
  69. await rationItemModel.bulkWrite(task);
  70. }
  71. };
  72. rationItemDAO.prototype.getRationItemsByLib = async function (rationRepId, showHint = null, returnFields = '') {
  73. let rationLib = await stdRationLibModel.findOne({ID: rationRepId, deleted: false});
  74. if(!rationLib){
  75. return [];
  76. }
  77. let startDate = new Date();
  78. let rations = await rationItemModel.find({rationRepId: rationRepId}, returnFields);
  79. console.log(`Date: ${new Date() - startDate}====================================`);
  80. if(!showHint){
  81. return rations;
  82. }
  83. else {
  84. const stdBillsLibListsModel = new STDGLJListModel();
  85. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib, '-_id ID code name unit gljType');
  86. let gljMapping = {};
  87. for(let glj of stdGLJData){
  88. gljMapping[glj.ID] = glj;
  89. }
  90. //设置悬浮
  91. for(let ration of rations){
  92. let hintsArr = [];
  93. //对人材机进行排序
  94. ration.rationGljList.sort(function (a, b) {
  95. let gljA = gljMapping[a.gljId],
  96. gljB = gljMapping[b.gljId];
  97. if(gljA && gljB){
  98. let aV = gljA.gljType + gljA.code,
  99. bV = gljB.gljType + gljB.code;
  100. if(aV > bV) {
  101. return 1;
  102. } else if(aV < bV) {
  103. return -1;
  104. }
  105. }
  106. return 0;
  107. });
  108. for(let rationGlj of ration.rationGljList){
  109. let subGlj = gljMapping[rationGlj.gljId];
  110. if(subGlj){
  111. hintsArr.push(` ${subGlj.code} ${subGlj.name}${subGlj.specs ? '&nbsp;&nbsp;&nbsp;' + subGlj.specs : ''}&nbsp;&nbsp&nbsp;${subGlj.unit}&nbsp;&nbsp;&nbsp;${rationGlj.consumeAmt}`);
  112. }
  113. }
  114. hintsArr.push(`基价 元 ${ration.basePrice}`);
  115. if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
  116. hintsArr.push(`工作内容:`);
  117. hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
  118. }
  119. if(ration.annotation && ration.annotation.toString().trim() !== ''){
  120. hintsArr.push(`附注:`);
  121. hintsArr = hintsArr.concat(ration.annotation.split('\n'));
  122. }
  123. ration._doc.hint = hintsArr.join('<br>');
  124. }
  125. return rations;
  126. }
  127. };
  128. rationItemDAO.prototype.sortToNumber = function (datas) {
  129. for(let i = 0, len = datas.length; i < len; i++){
  130. let data = datas[i]._doc;
  131. if(_exist(data, 'labourPrice')){
  132. data['labourPrice'] = parseFloat(data['labourPrice']);
  133. }
  134. if(_exist(data, 'materialPrice')){
  135. data['materialPrice'] = parseFloat(data['materialPrice']);
  136. }
  137. if(_exist(data, 'machinePrice')){
  138. data['machinePrice'] = parseFloat(data['machinePrice']);
  139. }
  140. if(_exist(data, 'basePrice')){
  141. data['basePrice'] = parseFloat(data['basePrice']);
  142. }
  143. if(_exist(data, 'rationGljList')){
  144. for(let j = 0, jLen = data['rationGljList'].length; j < jLen; j++){
  145. let raGljObj = data['rationGljList'][j]._doc;
  146. if(_exist(raGljObj, 'consumeAmt')){
  147. raGljObj['consumeAmt'] = parseFloat(raGljObj['consumeAmt']);
  148. }
  149. }
  150. }
  151. }
  152. function _exist(data, attr){
  153. return data && data[attr] !== undefined && data[attr];
  154. }
  155. };
  156. rationItemDAO.prototype.getRationItemsBySection = async function(rationRepId, sectionId,callback){
  157. let me = this;
  158. try {
  159. let rations = await rationItemModel.find({rationRepId: rationRepId, sectionId: sectionId});
  160. me.sortToNumber(rations);
  161. let matchRationIDs = [],
  162. matchRations = [];
  163. for (let ration of rations) {
  164. if (ration.rationTemplateList) {
  165. for (let rt of ration.rationTemplateList) {
  166. if (rt.rationID) {
  167. matchRationIDs.push(rt.rationID);
  168. }
  169. }
  170. }
  171. }
  172. if (matchRationIDs.length > 0) {
  173. matchRations = await rationItemModel.find({ID: {$in: matchRationIDs}}, '-_id ID code name');
  174. }
  175. for (let mr of matchRations) {
  176. for (let ration of rations) {
  177. if (ration.rationTemplateList) {
  178. for (let rt of ration.rationTemplateList) {
  179. if (rt.rationID && rt.rationID === mr.ID) {
  180. rt.code = mr.code ? mr.code : '';
  181. rt.name = mr.name ? mr.name : '';
  182. }
  183. }
  184. }
  185. }
  186. }
  187. callback(false,"Get items successfully", rations);
  188. } catch (err) {
  189. console.log(err);
  190. callback(true, "Fail to get items", "");
  191. }
  192. /* rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
  193. if(err) callback(true, "Fail to get items", "");
  194. else {
  195. me.sortToNumber(data);
  196. callback(false,"Get items successfully", data);
  197. }
  198. })*/
  199. };
  200. rationItemDAO.prototype.mixUpdateRationItems = function(rationLibId, lastOpr, sectionId, updateItems, addItems, rIds, callback){
  201. var me = this;
  202. if (updateItems.length == 0 && rIds.length == 0) {
  203. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  204. } else {
  205. me.removeRationItems(rationLibId, lastOpr, rIds, function(err, message, docs) {
  206. if (err) {
  207. callback(true, "Fail to remove", false);
  208. } else {
  209. me.updateRationItems(rationLibId, lastOpr, sectionId, updateItems, function(err, results){
  210. if (err) {
  211. callback(true, "Fail to save", false);
  212. } else {
  213. if (addItems && addItems.length > 0) {
  214. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  215. } else {
  216. callback(false, "Save successfully", results);
  217. }
  218. }
  219. });
  220. }
  221. })
  222. }
  223. };
  224. rationItemDAO.prototype.removeRationItems = function(rationLibId, lastOpr, rIds,callback){
  225. if (rIds.length > 0) {
  226. rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
  227. if (err) {
  228. callback(true, "Fail to remove", false);
  229. } else {
  230. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  231. if(!err){
  232. rationItemModel.update({rationRepId: rationLibId}, {$pull: {rationTemplateList: {rationID: {$in: rIds}}}}, function (theErr) {
  233. if (!theErr) {
  234. callback(false, "Remove successfully", docs);
  235. } else {
  236. callback(true, "Fail to remove", false);
  237. }
  238. });
  239. } else {
  240. callback(true, "Fail to remove", false);
  241. }
  242. })
  243. }
  244. })
  245. } else {
  246. callback(false, "No records were deleted!", null);
  247. }
  248. };
  249. rationItemDAO.prototype.getRationItemsByCode = function(repId, code,callback){
  250. rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$or": [{"isDeleted": null}, {"isDeleted": false}]},function(err,data){
  251. if(err) callback(true, "Fail to get items", "")
  252. else callback(false,"Get items successfully", data);
  253. })
  254. };
  255. rationItemDAO.prototype.findRation = function (repId, keyword, callback) {
  256. var filter = {
  257. 'rationRepId': repId,
  258. '$and': [{
  259. '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
  260. }, {
  261. '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
  262. }]
  263. };
  264. rationItemModel.find(filter, function (err, data) {
  265. if (err) {
  266. callback(true, 'Fail to find ration', null);
  267. } else {
  268. callback(false, '', data);
  269. }
  270. })
  271. }
  272. rationItemDAO.prototype.getRationItem = async function (repId, code) {
  273. let ration = await rationItemModel.findOne({rationRepId: repId, code: code});
  274. return ration;
  275. };
  276. rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  277. if (items && items.length > 0) {
  278. counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
  279. var maxId = result.sequence_value;
  280. var arr = [];
  281. for (var i = 0; i < items.length; i++) {
  282. var obj = new rationItemModel(items[i]);
  283. obj.ID = (maxId - (items.length - 1) + i);
  284. obj.sectionId = sectionId;
  285. obj.rationRepId = rationLibId;
  286. arr.push(obj);
  287. }
  288. rationItemModel.collection.insert(arr, null, function(err, docs){
  289. if (err) {
  290. callback(true, "Fail to save", false);
  291. } else {
  292. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  293. if(err){
  294. callback(true, "Fail to sava operator", false);
  295. }
  296. else{
  297. callback(false, "Save successfully", docs);
  298. }
  299. })
  300. }
  301. })
  302. });
  303. } else {
  304. callback(true, "Source error!", false);
  305. }
  306. };
  307. rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  308. console.log('enter============');
  309. var functions = [];
  310. for (var i=0; i < items.length; i++) {
  311. functions.push((function(doc) {
  312. return function(cb) {
  313. var filter = {};
  314. if (doc.ID) {
  315. filter.ID = doc.ID;
  316. } else {
  317. filter.sectionId = sectionId;
  318. if (rationLibId) filter.rationRepId = rationLibId;
  319. filter.code = doc.code;
  320. }
  321. rationItemModel.update(filter, doc, cb);
  322. };
  323. })(items[i]));
  324. }
  325. functions.push((function () {
  326. return function (cb) {
  327. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  328. if(err){
  329. cb(err);
  330. }
  331. else{
  332. cb(null);
  333. }
  334. });
  335. }
  336. })());
  337. async.parallel(functions, function(err, results) {
  338. callback(err, results);
  339. });
  340. };
  341. //ration round func
  342. function round(v,e){
  343. var t=1;
  344. for(;e>0;t*=10,e--);
  345. for(;e<0;t/=10,e++);
  346. return Math.round(v*t)/t;
  347. }
  348. rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, callback) {
  349. async.each(basePrcArr, function (basePrcObj, finalCb) {
  350. let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
  351. async.waterfall([
  352. function (cb) {
  353. if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
  354. rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
  355. if(err){
  356. cb(err);
  357. }
  358. else{
  359. //删除
  360. rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  361. if(err){
  362. cb(err);
  363. }
  364. else{
  365. //补充定额
  366. compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
  367. if(err){
  368. cb(err);
  369. }
  370. else {
  371. compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  372. if(err){
  373. cb(err);
  374. }
  375. else {
  376. for(let i = 0, len = compleRst.length; i < len; i++){
  377. compleRst[i]._doc.type = 'complementary';
  378. }
  379. cb(null, result.concat(compleRst));
  380. }
  381. });
  382. }
  383. });
  384. }
  385. });
  386. }
  387. });
  388. }
  389. else{
  390. rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
  391. if(err){
  392. cb(err);
  393. }
  394. else{
  395. compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
  396. if(err){
  397. cb(err);
  398. }
  399. else {
  400. for(let i = 0, len = compleRst.length; i < len; i++){
  401. compleRst[i]._doc.type = 'complementary';
  402. }
  403. cb(null, result.concat(compleRst));
  404. }
  405. });
  406. }
  407. });
  408. }
  409. },
  410. function (result, cb) {
  411. let compleRTasks = [], stdRTasks = [];
  412. //重算时需要用到的所有工料机,一次性取
  413. let compleGljIds = [], stdGljIds = [];
  414. for(let ration of result){
  415. for(let glj of ration.rationGljList){
  416. if(glj.type !== undefined && glj.type === 'complementary'){
  417. compleGljIds.push(glj.gljId);
  418. }
  419. else {
  420. stdGljIds.push(glj.gljId);
  421. }
  422. }
  423. }
  424. gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
  425. if(err){
  426. cb(err);
  427. }
  428. else {
  429. let gljIndex = {};
  430. for(let glj of allGljs){
  431. gljIndex[glj.ID] = glj;
  432. }
  433. async.each(result, function (rationItem, ecb) {
  434. let rationGljList = rationItem.rationGljList;
  435. let gljArr = [];
  436. for(let i=0; i<rationGljList.length; i++){
  437. let theGlj = gljIndex[rationGljList[i].gljId];
  438. if(theGlj !== undefined && theGlj){
  439. if(theGlj.ID === adjGljId){
  440. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, consumeAmt: rationGljList[i].consumeAmt});
  441. } else {
  442. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  443. let priceKeys = Object.keys(theGlj.priceProperty);
  444. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.priceProperty[priceKeys[0]]), consumeAmt: rationGljList[i].consumeAmt});
  445. } else {
  446. gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), consumeAmt: rationGljList[i].consumeAmt});
  447. }
  448. }
  449. }
  450. }
  451. //recalculate the price of ration
  452. let basePrice = 0;
  453. gljArr.forEach(function (gljItem) {
  454. basePrice += gljItem.basePrice * gljItem.consumeAmt;
  455. });
  456. basePrice = scMathUtil.roundTo(basePrice, 0);
  457. let task = {
  458. updateOne: {
  459. filter: {
  460. ID: rationItem.ID
  461. },
  462. update: {
  463. basePrice: 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.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  599. //自动匹配定额
  600. let matachCodes = [],
  601. matchRations = [];
  602. //要保存的数据
  603. let saveData = [];
  604. for (let data of templateData) {
  605. if (data.code) {
  606. matachCodes.push(data.code);
  607. }
  608. }
  609. matachCodes = Array.from(new Set(matachCodes));
  610. if (matachCodes.length > 0) {
  611. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  612. }
  613. let validData = [];
  614. //设置展示数据
  615. for (let data of templateData) {
  616. let match = false;
  617. for (let ration of matchRations) {
  618. if (data.code && data.code === ration.code) {
  619. match = true;
  620. data.name = ration.name;
  621. data.rationID = ration.ID;
  622. break;
  623. }
  624. }
  625. if (!match) {
  626. data.code = '';
  627. data.name = '';
  628. }
  629. if (data.type || data.code || data.name || data.billsLocation) {
  630. validData.push(data);
  631. }
  632. }
  633. for (let data of validData) {
  634. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  635. }
  636. //更新
  637. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  638. return validData;
  639. };
  640. //计算导入数据的价格
  641. rationItemDAO.prototype.calcForRation = function (stdGljList, ration) {
  642. let rationGljList = ration.rationGljList;
  643. let basePrice = 0;
  644. for(let rationGlj of rationGljList) {
  645. let glj = stdGljList[rationGlj.gljId];
  646. if (glj) {
  647. basePrice += glj.basePrice * rationGlj.consumeAmt;
  648. }
  649. }
  650. ration.basePrice = scMathUtil.roundTo(basePrice, 0).toString();
  651. };
  652. /**
  653. * 根据条件获取定额数据
  654. *
  655. * @param {Object} condition
  656. * @param {Object} fields
  657. * @param {String} indexBy
  658. * @return {Promise|Array}
  659. */
  660. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  661. let result = [];
  662. if (Object.keys(condition).length <= 0) {
  663. return result;
  664. }
  665. result = await rationItemModel.find(condition, fields).sort({code: 1});
  666. if (indexBy !== null && result.length > 0) {
  667. let tmpResult = {};
  668. for(let tmp of result) {
  669. tmpResult[tmp[indexBy]] = tmp;
  670. }
  671. result = tmpResult;
  672. }
  673. return result;
  674. };
  675. /**
  676. * 从excel中批量新增数据
  677. *
  678. * @param {Number} rationRepId
  679. * @param {Array} data
  680. * @return {bool}
  681. */
  682. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  683. if (data.length <= 0) {
  684. return false;
  685. }
  686. // 获取定额库相关数据
  687. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  688. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  689. return false;
  690. }
  691. // 获取标准工料机库数据
  692. const stdBillsLibListsModel = new STDGLJListModel();
  693. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  694. // 整理标准工料机库数据
  695. let stdGLJList = {};
  696. let stdGLJListByID = {};
  697. for (const tmp of stdGLJData) {
  698. stdGLJList[tmp.code.toString()] = tmp.ID;
  699. stdGLJListByID[tmp.ID] = tmp;
  700. }
  701. let lastData = {};
  702. const rationData = [];
  703. // 编码列表,用于查找库中是否有对应数据
  704. let rationCodeList = [];
  705. let gljCodeList = [];
  706. // 插入失败的工料机列表(用于提示)
  707. this.failGLJList = [];
  708. for (const tmp of data) {
  709. if (tmp.length <= 0) {
  710. continue;
  711. }
  712. console.log(typeof tmp[0], tmp[0]);
  713. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  714. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  715. // 如果不存在对应的工料机库数据则跳过
  716. if (stdGLJList[tmp[1]] === undefined) {
  717. const failString = '定额' + lastData.code + '下的' + tmp[1];
  718. this.failGLJList.push(failString);
  719. continue;
  720. }
  721. const tmpRationGlj = {
  722. gljId: stdGLJList[tmp[1]],
  723. consumeAmt: tmp[4],
  724. proportion: 0,
  725. };
  726. lastData.rationGljList.push(tmpRationGlj);
  727. if (gljCodeList.indexOf(tmp[1]) < 0) {
  728. gljCodeList.push(tmp[1]);
  729. }
  730. continue;
  731. }
  732. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  733. rationData.push(lastData);
  734. }
  735. // 组装数据
  736. lastData = {
  737. code: tmp[1],
  738. name: tmp[2],
  739. unit: tmp[3],
  740. caption: tmp[2],
  741. rationRepId: rationRepId,
  742. sectionId: 0,
  743. labourPrice: '0',
  744. materialPrice: '0',
  745. machinePrice: '0',
  746. basePrice: '0',
  747. rationGljList: []
  748. };
  749. // 防止重复加入
  750. if (rationCodeList.indexOf(tmp[1]) < 0) {
  751. rationCodeList.push(tmp[1]);
  752. }
  753. }
  754. // 最后一个入数组
  755. rationData.push(lastData);
  756. // 查找数据库中是否已存在待插入数据
  757. const condition = {
  758. rationRepId: rationRepId,
  759. code: { $in: rationCodeList }
  760. };
  761. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  762. // 过滤插入数据
  763. let insertData = [];
  764. //已存在定额,则更新价格及rationGLjList字段
  765. let updateData = [];
  766. for (const ration of rationData) {
  767. if (existCodeList[ration.code] !== undefined) {
  768. updateData.push(ration);
  769. continue;
  770. }
  771. insertData.push(ration);
  772. }
  773. //更新定额
  774. let updateBulk = [];
  775. for(let ration of updateData){
  776. this.calcForRation(stdGLJListByID, ration);
  777. updateBulk.push({
  778. updateOne: {
  779. filter: {rationRepId: rationRepId, code: ration.code},
  780. update: {$set: {rationGljList: ration.rationGljList, basePrice: ration.basePrice}}
  781. }
  782. });
  783. }
  784. //更新数据库
  785. if(updateBulk.length > 0){
  786. await rationItemModel.bulkWrite(updateBulk);
  787. }
  788. // 如果都已经存在,直接返回
  789. if (insertData.length <= 0) {
  790. return true;
  791. }
  792. //计算价格
  793. for(let ration of insertData){
  794. this.calcForRation(stdGLJListByID, ration);
  795. }
  796. // 组织id
  797. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  798. let maxId = counterInfo.sequence_value;
  799. maxId = parseInt(maxId);
  800. let count = 0;
  801. for (const index in insertData) {
  802. insertData[index].ID = maxId - (insertData.length - 1) + count;
  803. count++;
  804. }
  805. // 插入数据库
  806. const result = await rationItemModel.create(insertData);
  807. return result.length > 0;
  808. };
  809. /**
  810. * 导出到excel的数据
  811. *
  812. * @param {Number} rationRepId
  813. * @return {Array}
  814. */
  815. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  816. const condition = {
  817. rationRepId: rationRepId
  818. };
  819. // @todo 限制导出的数量以防内存溢出
  820. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice', 'jobContent', 'annotation']);
  821. // 整理数据
  822. let rationData = [];
  823. for (const tmp of rationDataList) {
  824. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  825. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  826. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice, tmp.jobContent, tmp.annotation];
  827. rationData.push(ration);
  828. }
  829. //根据编号排序,优先级:number-number-..., number, Anumber....
  830. /*let regConnector = /-/g,
  831. regLetter = /[a-z,A-Z]/g,
  832. regNum = /\d+/g;
  833. rationData.sort(function (a, b) {
  834. let aCode = a[3],
  835. bCode = b[3],
  836. rst = 0;
  837. function compareConnector(arrA, arrB) {
  838. let lessArr = arrA.length <= arrB ? arrA : arrB;
  839. for (let i = 0; i < lessArr.length; i++) {
  840. let result = compareUnit(arrA[i], arrB[i]);
  841. if (result !== 0) {
  842. return result;
  843. } else {
  844. }
  845. }
  846. function compareUnit(uA, uB) {
  847. let uAV = parseFloat(uA),
  848. uBV = parseFloat(uB);
  849. if (uAV > uBV) {
  850. return 1;
  851. } else if (uAV < uBV) {
  852. return -1;
  853. }
  854. return 0;
  855. }
  856. }
  857. if (regConnector.test(a) && !regConnector.test(b)) {
  858. rst = -1;
  859. } else if (!regConnector.test(a) && regConnector.test(b)) {
  860. rst = 1;
  861. } else if (regConnector.test(a) && regConnector.test(b)) {
  862. }
  863. });
  864. rationData.sort(function (a, b) {
  865. let aCode = a[3],
  866. bCode = b[3],
  867. rst = 0,
  868. splitA = aCode.split('-'),
  869. splitB = bCode.split('-');
  870. if(splitA[0] > splitB[0]){
  871. rst = 1;
  872. }
  873. else if(splitA[0] < splitB[0]){
  874. rst = -1;
  875. }
  876. else {
  877. if(splitA[1] && splitB[1]){
  878. let floatA = parseFloat(splitA[1]),
  879. floatB = parseFloat(splitB[1]);
  880. if(floatA > floatB){
  881. rst = 1;
  882. }
  883. else if(floatA < floatB){
  884. rst = -1;
  885. }
  886. }
  887. }
  888. return rst;
  889. });*/
  890. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价', '工作内容', '附注']];
  891. excelData.push.apply(excelData, rationData);
  892. return excelData;
  893. };
  894. /**
  895. * 批量更改章节id
  896. *
  897. * @param {Object} data
  898. * @return {bool}
  899. */
  900. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  901. if (data.length <= 0) {
  902. return false;
  903. }
  904. // 批量执行update
  905. let rationTasks = [],
  906. sectionIDs = [];
  907. for (const tmp of data) {
  908. let rationId = parseInt(tmp[2]);
  909. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  910. let sectionId = parseInt(tmp[0]);
  911. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  912. if (sectionId <= 0 || rationId <= 0) {
  913. continue;
  914. }
  915. sectionIDs.push(sectionId);
  916. // 取费专业
  917. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  918. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  919. let name = tmp[4];
  920. name = name ? name : '';
  921. let caption = tmp[5];
  922. caption = caption ? caption : '';
  923. let jobContent = tmp[7] ? tmp[7] : '';
  924. let annotation = tmp[8] ? tmp[8] : '';
  925. rationTasks.push({updateOne: {
  926. filter: {ID: rationId},
  927. update: {$set: {
  928. sectionId,
  929. feeType,
  930. name,
  931. caption,
  932. jobContent,
  933. annotation
  934. }}}});
  935. }
  936. if(rationTasks.length <= 0){
  937. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  938. }
  939. // 更新定额数据
  940. await rationItemModel.bulkWrite(rationTasks);
  941. // 更新章节树工作内容、附注节点选项(全设置为ALL)
  942. sectionIDs = Array.from(new Set(sectionIDs));
  943. if (sectionIDs.length) {
  944. await stdRationSectionModel.updateMany(
  945. {ID: {$in: sectionIDs}},
  946. {$set: {
  947. jobContentSituation: 'ALL',
  948. annotationSituation: 'ALL'
  949. }}
  950. )
  951. }
  952. };
  953. module.exports = new rationItemDAO();