ration_item.js 45 KB

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