ration_item.js 40 KB

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