ration_item.js 52 KB

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