ration_item.js 38 KB

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