ration_item.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  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).lean();
  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.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.getRationByID = async function (ID) {
  490. let ration = await rationItemModel.findOne({ ID: +ID }).lean();
  491. return ration;
  492. };
  493. rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  494. if (items && items.length > 0) {
  495. counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
  496. var maxId = result.sequence_value;
  497. var arr = [];
  498. for (var i = 0; i < items.length; i++) {
  499. var obj = new rationItemModel(items[i]);
  500. obj.ID = (maxId - (items.length - 1) + i);
  501. obj.sectionId = sectionId;
  502. obj.rationRepId = rationLibId;
  503. arr.push(obj);
  504. }
  505. rationItemModel.collection.insert(arr, null, function(err, docs){
  506. if (err) {
  507. callback(true, "Fail to save", false);
  508. } else {
  509. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  510. if(err){
  511. callback(true, "Fail to sava operator", false);
  512. }
  513. else{
  514. callback(false, "Save successfully", docs);
  515. }
  516. })
  517. }
  518. })
  519. });
  520. } else {
  521. callback(true, "Source error!", false);
  522. }
  523. };
  524. rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  525. console.log('enter============');
  526. var functions = [];
  527. for (var i=0; i < items.length; i++) {
  528. functions.push((function(doc) {
  529. return function(cb) {
  530. var filter = {};
  531. if (doc.ID) {
  532. filter.ID = doc.ID;
  533. } else {
  534. filter.sectionId = sectionId;
  535. if (rationLibId) filter.rationRepId = rationLibId;
  536. filter.code = doc.code;
  537. }
  538. rationItemModel.update(filter, doc, cb);
  539. };
  540. })(items[i]));
  541. }
  542. functions.push((function () {
  543. return function (cb) {
  544. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  545. if(err){
  546. cb(err);
  547. }
  548. else{
  549. cb(null);
  550. }
  551. });
  552. }
  553. })());
  554. async.parallel(functions, function(err, results) {
  555. callback(err, results);
  556. });
  557. };
  558. //ration round func
  559. function round(v,e){
  560. var t=1;
  561. for(;e>0;t*=10,e--);
  562. for(;e<0;t/=10,e++);
  563. return Math.round(v*t)/t;
  564. }
  565. function calcRation(gljArr) {
  566. let labourPrc = [],
  567. materialPrc = [],
  568. machinePrc = [],
  569. managePrc = [],
  570. profitPrc = [],
  571. riskPrc = [],
  572. singlePrc,
  573. updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, managePrice: 0, profitPrice: 0, riskPrice: 0, basePrice: 0};
  574. gljArr.forEach(function (gljItem) {
  575. if(gljItem.gljParentType !== -1){
  576. singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3);
  577. if(gljItem.gljParentType === 1){
  578. labourPrc.push(singlePrc);
  579. }
  580. else if(gljItem.gljParentType ===2){
  581. materialPrc.push(singlePrc);
  582. }
  583. else if(gljItem.gljParentType === 3){
  584. machinePrc.push(singlePrc);
  585. }
  586. else if(gljItem.gljParentType === 6){
  587. managePrc.push(singlePrc);
  588. }
  589. else if(gljItem.gljParentType === 7){
  590. profitPrc.push(singlePrc);
  591. }
  592. else if(gljItem.gljParentType === 8){
  593. riskPrc.push(singlePrc);
  594. }
  595. }
  596. });
  597. if(labourPrc.length > 0){
  598. let sumLaP = 0;
  599. for(let i=0; i<labourPrc.length; i++){
  600. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], -6);
  601. }
  602. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  603. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.labourPrice, -2);
  604. }
  605. if(materialPrc.length > 0){
  606. let sumMtP = 0;
  607. for(let i= 0; i<materialPrc.length; i++){
  608. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], -6);
  609. }
  610. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  611. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.materialPrice, -2);
  612. }
  613. if(machinePrc.length > 0){
  614. let sumMaP = 0;
  615. for(let i =0; i< machinePrc.length; i++){
  616. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], -6);
  617. }
  618. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  619. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.machinePrice, -2);
  620. }
  621. if(managePrc.length > 0){
  622. let sumMgP = 0;
  623. for(let i =0; i< managePrc.length; i++){
  624. sumMgP = scMathUtil.roundTo(sumMgP + managePrc[i], -6);
  625. }
  626. updatePrc.managePrice = scMathUtil.roundTo(sumMgP, -2);
  627. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.managePrice, -2);
  628. }
  629. if(profitPrc.length > 0){
  630. let sumPfP = 0;
  631. for(let i =0; i< profitPrc.length; i++){
  632. sumPfP = scMathUtil.roundTo(sumPfP + profitPrc[i], -6);
  633. }
  634. updatePrc.profitPrice = scMathUtil.roundTo(sumPfP, -2);
  635. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.profitPrice, -2);
  636. }
  637. if(riskPrc.length > 0){
  638. let sumRkP = 0;
  639. for(let i =0; i< riskPrc.length; i++){
  640. sumRkP = scMathUtil.roundTo(sumRkP + riskPrc[i], -6);
  641. }
  642. updatePrc.riskPrice = scMathUtil.roundTo(sumRkP, -2);
  643. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.riskPrice, -2);
  644. }
  645. return updatePrc;
  646. }
  647. rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, overWriteUrl, callback) {
  648. async.each(basePrcArr, function (basePrcObj, finalCb) {
  649. let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
  650. async.waterfall([
  651. function (cb) {
  652. if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
  653. rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
  654. if(err){
  655. cb(err);
  656. }
  657. else{
  658. //删除
  659. rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  660. if(err){
  661. cb(err);
  662. }
  663. else{
  664. //补充定额
  665. compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
  666. if(err){
  667. cb(err);
  668. }
  669. else {
  670. compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  671. if(err){
  672. cb(err);
  673. }
  674. else {
  675. for(let i = 0, len = compleRst.length; i < len; i++){
  676. compleRst[i]._doc.type = 'complementary';
  677. }
  678. cb(null, result.concat(compleRst));
  679. }
  680. });
  681. }
  682. });
  683. }
  684. });
  685. }
  686. });
  687. }
  688. else{
  689. rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
  690. if(err){
  691. cb(err);
  692. }
  693. else{
  694. compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
  695. if(err){
  696. cb(err);
  697. }
  698. else {
  699. for(let i = 0, len = compleRst.length; i < len; i++){
  700. compleRst[i]._doc.type = 'complementary';
  701. }
  702. cb(null, result.concat(compleRst));
  703. }
  704. });
  705. }
  706. });
  707. }
  708. },
  709. function (result, cb) {
  710. let compleRTasks = [], stdRTasks = [];
  711. //重算时需要用到的所有工料机,一次性取
  712. let compleGljIds = [], stdGljIds = [];
  713. for(let ration of result){
  714. for(let glj of ration.rationGljList){
  715. if(glj.type !== undefined && glj.type === 'complementary'){
  716. compleGljIds.push(glj.gljId);
  717. }
  718. else {
  719. stdGljIds.push(glj.gljId);
  720. }
  721. }
  722. }
  723. gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
  724. if(err){
  725. cb(err);
  726. }
  727. else {
  728. let gljIndex = {};
  729. for(let glj of allGljs){
  730. gljIndex[glj.ID] = glj;
  731. }
  732. async.each(result, function (rationItem, ecb) {
  733. let rationGljList = rationItem.rationGljList;
  734. let gljArr = [];
  735. for(let i=0; i<rationGljList.length; i++){
  736. let theGlj = gljIndex[rationGljList[i].gljId];
  737. if(theGlj !== undefined && theGlj){
  738. let gljParentType = -1;
  739. if(theGlj.ID === adjGljId){
  740. theGlj.gljType = adjGljType;
  741. }
  742. if(theGlj.gljType <= 3){
  743. gljParentType = theGlj.gljType;
  744. } else if(theGlj.gljType > 200 && theGlj.gljType < 300){
  745. gljParentType = 2;
  746. } else if(theGlj.gljType > 300 && theGlj.gljType < 400){
  747. gljParentType = 3;
  748. } else if(theGlj.gljType === 6){ //管理费
  749. gljParentType = 6;
  750. } else if(theGlj.gljType === 7){ //利润
  751. gljParentType = 7;
  752. } else if(theGlj.gljType === 8){ //风险费
  753. gljParentType = 8;
  754. }
  755. if(theGlj)
  756. if(theGlj.ID === adjGljId){
  757. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, gljParentType: gljParentType, unit: theGlj.unit});
  758. } else {
  759. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  760. gljArr.push({
  761. gljId: theGlj.ID,
  762. basePrice: parseFloat(theGlj.priceProperty.price1),
  763. gljParentType: gljParentType,
  764. unit: theGlj.unit});
  765. } else {
  766. gljArr.push({
  767. gljId: theGlj.ID,
  768. basePrice: parseFloat(theGlj.basePrice),
  769. gljParentType: gljParentType,
  770. unit: theGlj.unit});
  771. }
  772. }
  773. }
  774. }
  775. gljArr.forEach(function (gljItem) {
  776. rationGljList.forEach(function (rationGlj) {
  777. if(gljItem.gljId === rationGlj.gljId){
  778. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  779. }
  780. })
  781. });
  782. let updatePrc = null;
  783. let overWriteCalc = false; //需要重写算法
  784. if (overWriteUrl) {
  785. let overWriteExports = require(overWriteUrl);
  786. if (typeof overWriteExports.calcRation !== 'undefined') {
  787. overWriteCalc = true;
  788. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  789. }
  790. }
  791. if (!overWriteCalc) {
  792. updatePrc = calcRation(gljArr);
  793. }
  794. let task = {
  795. updateOne: {
  796. filter: {
  797. ID: rationItem.ID
  798. },
  799. update: {
  800. labourPrice: updatePrc.labourPrice.toString(),
  801. materialPrice: updatePrc.materialPrice.toString(),
  802. machinePrice: updatePrc.machinePrice.toString(),
  803. basePrice: updatePrc.basePrice.toString()
  804. }
  805. }
  806. };
  807. //updateDataBase
  808. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  809. compleRTasks.push(task);
  810. ecb(null);
  811. }
  812. else {
  813. stdRTasks.push(task);
  814. ecb(null);
  815. }
  816. }, async function(err){
  817. if(err){
  818. cb(err);
  819. }
  820. else {
  821. //do sth
  822. try{
  823. if(compleRTasks.length > 0){
  824. await compleRationModel.bulkWrite(compleRTasks);
  825. }
  826. if(stdRTasks.length > 0){
  827. await rationItemModel.bulkWrite(stdRTasks);
  828. }
  829. }
  830. catch(e){
  831. cb(err);
  832. }
  833. cb(null);
  834. }
  835. });
  836. }
  837. });
  838. },
  839. ], function (err) {
  840. if(err){
  841. finalCb(err);
  842. }
  843. else{
  844. finalCb(null);
  845. }
  846. });
  847. }, function (err) {
  848. if(err){
  849. callback(err, 'Error');
  850. }
  851. else{
  852. callback(null, '');
  853. }
  854. });
  855. };
  856. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  857. let repId = data.repId;
  858. rationItemModel.find({rationRepId: repId}, function (err, result) {
  859. if(err){
  860. callback(err, 'Error', null);
  861. }
  862. else{
  863. let rstIds = [], newRst = [];
  864. result.forEach(function (data) {
  865. if(data.rationGljList.length >0){
  866. data.rationGljList.forEach(function (gljObj) {
  867. rstIds.push(gljObj.gljId);
  868. })
  869. }
  870. });
  871. for(let i= 0; i< rstIds.length; i++){
  872. if(newRst.indexOf(rstIds[i]) === -1){
  873. newRst.push(rstIds[i]);
  874. }
  875. }
  876. callback(null, '', newRst);
  877. }
  878. });
  879. };
  880. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  881. let repId = data.repId;
  882. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  883. if(err){
  884. callback(err, 'Error', null);
  885. }
  886. else{
  887. let rstCodes = [];
  888. result.forEach(function (rationItem) {
  889. rstCodes.push(rationItem.code);
  890. });
  891. callback(null, 'get all rationCodes success', rstCodes);
  892. }
  893. })
  894. };
  895. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  896. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  897. async.each(updateArr, function (obj, cb) {
  898. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  899. if(err){
  900. cb(err);
  901. }
  902. else{
  903. cb(null);
  904. }
  905. })
  906. }, function (err) {
  907. if(err){
  908. callback(err);
  909. }
  910. else{
  911. callback(null);
  912. }
  913. });
  914. });
  915. }
  916. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  917. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  918. async.each(updateArr, function (obj, cb) {
  919. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  920. if(err){
  921. cb(err);
  922. }
  923. else{
  924. cb(null);
  925. }
  926. })
  927. }, function (err) {
  928. if(err){
  929. callback(err);
  930. }
  931. else{
  932. callback(null);
  933. }
  934. });
  935. });
  936. };
  937. //更新定额下模板关联
  938. rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  939. //自动匹配定额
  940. let matachCodes = [],
  941. matchRations = [];
  942. //要保存的数据
  943. let saveData = [];
  944. for (let data of templateData) {
  945. if (data.code) {
  946. matachCodes.push(data.code);
  947. }
  948. }
  949. matachCodes = Array.from(new Set(matachCodes));
  950. if (matachCodes.length > 0) {
  951. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  952. }
  953. let validData = [];
  954. //设置展示数据
  955. for (let data of templateData) {
  956. let match = false;
  957. for (let ration of matchRations) {
  958. if (data.code && data.code === ration.code) {
  959. match = true;
  960. data.name = ration.name;
  961. data.rationID = ration.ID;
  962. break;
  963. }
  964. }
  965. if (!match) {
  966. data.code = '';
  967. data.name = '';
  968. }
  969. if (data.type || data.code || data.name || data.billsLocation) {
  970. validData.push(data);
  971. }
  972. }
  973. for (let data of validData) {
  974. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  975. }
  976. //更新
  977. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  978. return validData;
  979. };
  980. // 根据章节列表批量更新定额
  981. rationItemDAO.prototype.updateRationBySection = async function (rationRepId, sectionList, updateData) {
  982. await rationItemModel.updateMany({rationRepId, sectionId: {$in: sectionList}}, updateData);
  983. }
  984. //计算导入数据的价格
  985. rationItemDAO.prototype.calcForRation = function (stdGljList, ration, overWriteUrl) {
  986. let rationGljList = ration.rationGljList,
  987. gljArr = [];
  988. for(let rationGlj of rationGljList) {
  989. let glj = stdGljList[rationGlj.gljId];
  990. let gljPType = parseInt(glj.gljType.toString().match(/\d+?/)[0]);
  991. let newGlj = {
  992. gljId: glj.ID,
  993. consumeAmt: rationGlj.consumeAmt,
  994. gljParentType: gljPType,
  995. unit: glj.unit
  996. };
  997. newGlj.basePrice = glj.priceProperty && Object.keys(glj.priceProperty).length > 0
  998. ? parseFloat(glj.priceProperty.price1)
  999. : parseFloat(glj.basePrice);
  1000. gljArr.push(newGlj);
  1001. }
  1002. let updatePrc = null;
  1003. let overWriteCalc = false; //需要重写算法
  1004. if (overWriteUrl) {
  1005. let overWriteExports = require(overWriteUrl);
  1006. if (typeof overWriteExports.calcRation !== 'undefined') {
  1007. overWriteCalc = true;
  1008. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  1009. }
  1010. }
  1011. if (!overWriteCalc) {
  1012. updatePrc = calcRation(gljArr);
  1013. }
  1014. ration.labourPrice = updatePrc.labourPrice.toString();
  1015. ration.materialPrice = updatePrc.materialPrice.toString();
  1016. ration.machinePrice = updatePrc.machinePrice.toString();
  1017. ration.basePrice = updatePrc.basePrice.toString();
  1018. };
  1019. /**
  1020. * 根据条件获取定额数据
  1021. *
  1022. * @param {Object} condition
  1023. * @param {Object} fields
  1024. * @param {String} indexBy
  1025. * @return {Promise|Array}
  1026. */
  1027. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  1028. let result = [];
  1029. if (Object.keys(condition).length <= 0) {
  1030. return result;
  1031. }
  1032. result = await rationItemModel.find(condition, fields).sort({code: 1});
  1033. if (indexBy !== null && result.length > 0) {
  1034. let tmpResult = {};
  1035. for(let tmp of result) {
  1036. tmpResult[tmp[indexBy]] = tmp;
  1037. }
  1038. result = tmpResult;
  1039. }
  1040. return result;
  1041. };
  1042. /**
  1043. * 从excel中批量新增数据
  1044. *
  1045. * @param {Number} rationRepId
  1046. * @param {Array} data
  1047. * @return {bool}
  1048. */
  1049. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  1050. if (data.length <= 0) {
  1051. return false;
  1052. }
  1053. // 获取定额库相关数据
  1054. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  1055. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  1056. return false;
  1057. }
  1058. // 获取标准工料机库数据
  1059. const stdBillsLibListsModel = new STDGLJListModel();
  1060. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  1061. // 整理标准工料机库数据
  1062. let stdGLJList = {};
  1063. let stdGLJListByID = {};
  1064. for (const tmp of stdGLJData) {
  1065. stdGLJList[tmp.code.toString()] = tmp.ID;
  1066. stdGLJListByID[tmp.ID] = tmp;
  1067. }
  1068. let lastData = {};
  1069. // 定额xx下提示的次数
  1070. let lastFailCount = 0;
  1071. const rationData = [];
  1072. // 编码列表,用于查找库中是否有对应数据
  1073. let rationCodeList = [];
  1074. let gljCodeList = [];
  1075. // 插入失败的工料机列表(用于提示)
  1076. let failGLJList = [];
  1077. for (const tmp of data) {
  1078. if (tmp.length <= 0) {
  1079. continue;
  1080. }
  1081. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  1082. if (!tmp[0] && Object.keys(lastData).length > 0) {
  1083. // 如果不存在对应的工料机库数据则跳过
  1084. if (!stdGLJList[tmp[1]]) {
  1085. if (lastFailCount === 0) {
  1086. failGLJList.push('定额' + lastData.code + '下的');
  1087. lastFailCount++;
  1088. }
  1089. //const failString = '定额' + lastData.code + '下的' + tmp[1];
  1090. failGLJList.push(tmp[1]);
  1091. continue;
  1092. }
  1093. const tmpRationGlj = {
  1094. gljId: stdGLJList[tmp[1]],
  1095. consumeAmt: Math.abs(tmp[4]),
  1096. proportion: 0,
  1097. };
  1098. lastData.rationGljList.push(tmpRationGlj);
  1099. if (gljCodeList.indexOf(tmp[1]) < 0) {
  1100. gljCodeList.push(tmp[1]);
  1101. }
  1102. continue;
  1103. }
  1104. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  1105. rationData.push(lastData);
  1106. }
  1107. lastFailCount = 0;
  1108. // 组装数据
  1109. lastData = {
  1110. code: tmp[1],
  1111. name: tmp[2],
  1112. unit: tmp[3],
  1113. caption: tmp[2],
  1114. rationRepId: rationRepId,
  1115. sectionId: 0,
  1116. labourPrice: '0',
  1117. materialPrice: '0',
  1118. machinePrice: '0',
  1119. basePrice: '0',
  1120. rationGljList: []
  1121. };
  1122. // 防止重复加入
  1123. if (rationCodeList.indexOf(tmp[1]) < 0) {
  1124. rationCodeList.push(tmp[1]);
  1125. }
  1126. }
  1127. // 最后一个入数组
  1128. rationData.push(lastData);
  1129. // 查找数据库中是否已存在待插入数据
  1130. const condition = {
  1131. rationRepId: rationRepId,
  1132. code: { $in: rationCodeList }
  1133. };
  1134. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  1135. // 过滤插入数据
  1136. let insertData = [];
  1137. //已存在定额,则更新价格及rationGLjList字段
  1138. let updateData = [];
  1139. for (const ration of rationData) {
  1140. if (existCodeList[ration.code] !== undefined) {
  1141. updateData.push(ration);
  1142. continue;
  1143. }
  1144. insertData.push(ration);
  1145. }
  1146. //更新定额
  1147. let updateBulk = [];
  1148. for(let ration of updateData){
  1149. this.calcForRation(stdGLJListByID, ration);
  1150. updateBulk.push({
  1151. updateOne: {
  1152. filter: {rationRepId: rationRepId, code: ration.code},
  1153. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  1154. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  1155. }
  1156. });
  1157. }
  1158. //更新数据库
  1159. if(updateBulk.length > 0){
  1160. await rationItemModel.bulkWrite(updateBulk);
  1161. }
  1162. // 如果都已经存在,直接返回
  1163. if (insertData.length <= 0) {
  1164. return failGLJList;
  1165. }
  1166. //计算价格
  1167. for(let ration of insertData){
  1168. this.calcForRation(stdGLJListByID, ration);
  1169. }
  1170. // 组织id
  1171. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  1172. let maxId = counterInfo.sequence_value;
  1173. maxId = parseInt(maxId);
  1174. let count = 0;
  1175. for (const index in insertData) {
  1176. insertData[index].ID = maxId - (insertData.length - 1) + count;
  1177. count++;
  1178. }
  1179. // 插入数据库
  1180. await rationItemModel.create(insertData);
  1181. return failGLJList;
  1182. };
  1183. /**
  1184. * 导出到excel的数据
  1185. *
  1186. * @param {Number} rationRepId
  1187. * @return {Array}
  1188. */
  1189. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  1190. const condition = {
  1191. rationRepId: rationRepId
  1192. };
  1193. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice', 'jobContent', 'annotation']);
  1194. // 整理数据
  1195. let rationData = [];
  1196. for (const tmp of rationDataList) {
  1197. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  1198. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  1199. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice, tmp.jobContent, tmp.annotation];
  1200. rationData.push(ration);
  1201. }
  1202. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价', '工作内容', '附注']];
  1203. excelData.push.apply(excelData, rationData);
  1204. return excelData;
  1205. //根据编号排序,优先级:number-number-..., number, Anumber....
  1206. /*let regConnector = /-/g,
  1207. regLetter = /[a-z,A-Z]/g,
  1208. regNum = /\d+/g;
  1209. rationData.sort(function (a, b) {
  1210. let aCode = a[3],
  1211. bCode = b[3],
  1212. rst = 0;
  1213. function compareConnector(arrA, arrB) {
  1214. let lessArr = arrA.length <= arrB ? arrA : arrB;
  1215. for (let i = 0; i < lessArr.length; i++) {
  1216. let result = compareUnit(arrA[i], arrB[i]);
  1217. if (result !== 0) {
  1218. return result;
  1219. } else {
  1220. }
  1221. }
  1222. function compareUnit(uA, uB) {
  1223. let uAV = parseFloat(uA),
  1224. uBV = parseFloat(uB);
  1225. if (uAV > uBV) {
  1226. return 1;
  1227. } else if (uAV < uBV) {
  1228. return -1;
  1229. }
  1230. return 0;
  1231. }
  1232. }
  1233. if (regConnector.test(a) && !regConnector.test(b)) {
  1234. rst = -1;
  1235. } else if (!regConnector.test(a) && regConnector.test(b)) {
  1236. rst = 1;
  1237. } else if (regConnector.test(a) && regConnector.test(b)) {
  1238. }
  1239. });
  1240. rationData.sort(function (a, b) {
  1241. let aCode = a[3],
  1242. bCode = b[3],
  1243. rst = 0,
  1244. splitA = aCode.split('-'),
  1245. splitB = bCode.split('-');
  1246. if(splitA[0] > splitB[0]){
  1247. rst = 1;
  1248. }
  1249. else if(splitA[0] < splitB[0]){
  1250. rst = -1;
  1251. }
  1252. else {
  1253. if(splitA[1] && splitB[1]){
  1254. let floatA = parseFloat(splitA[1]),
  1255. floatB = parseFloat(splitB[1]);
  1256. if(floatA > floatB){
  1257. rst = 1;
  1258. }
  1259. else if(floatA < floatB){
  1260. rst = -1;
  1261. }
  1262. }
  1263. }
  1264. return rst;
  1265. });*/
  1266. /*const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  1267. excelData.push.apply(excelData, rationData);
  1268. return excelData;*/
  1269. };
  1270. /**
  1271. * 批量更改章节id
  1272. *
  1273. * @param {Object} data
  1274. * @return {bool}
  1275. */
  1276. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  1277. if (data.length <= 0) {
  1278. return false;
  1279. }
  1280. // 批量执行update
  1281. let bulkOprs = [],
  1282. sectionIDs = [];
  1283. for (const tmp of data) {
  1284. let rationId = parseInt(tmp[2]);
  1285. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  1286. let sectionId = parseInt(tmp[0]);
  1287. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  1288. if (sectionId <= 0 || rationId <= 0) {
  1289. continue;
  1290. }
  1291. sectionIDs.push(sectionId);
  1292. // 取费专业
  1293. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  1294. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  1295. let name = tmp[4];
  1296. name = name ? name : '';
  1297. let caption = tmp[5];
  1298. caption = caption ? caption : '';
  1299. let jobContent = tmp[7] ? tmp[7] : '';
  1300. let annotation = tmp[8] ? tmp[8] : '';
  1301. bulkOprs.push({updateOne: {
  1302. filter: {ID: rationId},
  1303. update: {$set: {
  1304. sectionId,
  1305. feeType,
  1306. name,
  1307. caption,
  1308. jobContent,
  1309. annotation
  1310. }}}
  1311. });
  1312. }
  1313. if(bulkOprs.length <= 0){
  1314. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1315. }
  1316. await rationItemModel.bulkWrite(bulkOprs);
  1317. // 更新章节树工作内容、附注节点选项(全设置为ALL)
  1318. sectionIDs = Array.from(new Set(sectionIDs));
  1319. if (sectionIDs.length) {
  1320. await stdRationSectionModel.updateMany(
  1321. {ID: {$in: sectionIDs}},
  1322. {$set: {
  1323. jobContentSituation: 'ALL',
  1324. annotationSituation: 'ALL'
  1325. }}
  1326. )
  1327. }
  1328. };
  1329. module.exports = new rationItemDAO();