ration_item.js 41 KB

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