ration_item.js 52 KB

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