gljModel.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /**
  2. * Created by Zhong on 2017/8/11.
  3. */
  4. const mongoose = require('mongoose');
  5. const gljMapModel = mongoose.model('std_glj_lib_map');
  6. const gljModel = mongoose.model('std_glj_lib_gljList');
  7. const gljClassModel = mongoose.model('std_glj_lib_gljClass');
  8. const compilationModel = mongoose.model('compilation');
  9. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  10. const rationMapModel = mongoose.model('std_ration_lib_map');
  11. const rationModel = mongoose.model('std_ration_lib_ration_items');
  12. const complementaryRationModel = mongoose.model('complementary_ration_items');
  13. const { isDef, isEmptyVal } = require('../../../public/common_util');
  14. import {OprDao} from "./gljMapModel";
  15. import moment from "moment";
  16. import counter from "../../../public/counter/counter";
  17. import async from "async";
  18. class GljDao extends OprDao{
  19. // 自动计算组含有组成物的人材机的定额价
  20. async calcPriceForComposition(gljLibID) {
  21. const gljs = await gljModel.find({ repositoryId: gljLibID }, '-_id ID component basePrice').lean();
  22. const updateData = [];
  23. const toCalcGLJs = [];
  24. const gljIDMap = {};
  25. for (let i = 0; i < gljs.length; i++) {
  26. const glj = gljs[i];
  27. gljIDMap[glj.ID] = glj;
  28. if (glj.component && glj.component.length) {
  29. toCalcGLJs.push(glj);
  30. }
  31. }
  32. for (let i = 0; i < toCalcGLJs.length; i++) {
  33. const glj = toCalcGLJs[i];
  34. let sum = 0;
  35. for (let j = 0; j < glj.component.length; j++) {
  36. const c = glj.component[j];
  37. if (!gljIDMap[c.ID]) {
  38. continue;
  39. }
  40. sum += c.consumeAmt * gljIDMap[c.ID].basePrice;
  41. }
  42. sum = scMathUtil.roundTo(sum, -2);
  43. updateData.push({
  44. updateOne: {
  45. filter: { ID: glj.ID },
  46. update: { basePrice: sum }
  47. }
  48. });
  49. }
  50. if (updateData.length) {
  51. await gljModel.bulkWrite(updateData);
  52. }
  53. }
  54. async copyLib(sourceLibID, targetLibID) {
  55. const task = [
  56. this.copyClassData(sourceLibID, targetLibID),
  57. this.copyGLJData(sourceLibID, targetLibID)
  58. ];
  59. await Promise.all(task);
  60. }
  61. async copyClassData(sourceLibID, targetLibID) {
  62. const sourceClassData = await gljClassModel.find({ repositoryId: sourceLibID }, '-_id').lean();
  63. const insertData = sourceClassData.map(item => ({
  64. ... item,
  65. repositoryId: targetLibID
  66. }));
  67. if (insertData.length) {
  68. await gljClassModel.insertMany(insertData);
  69. }
  70. }
  71. async copyGLJData(sourceLibID, targetLibID) {
  72. const sourceGLJData = await gljModel.find({ repositoryId: sourceLibID }, '-_id').lean();
  73. const IDMapping = {};
  74. const countData = await counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, sourceGLJData.length);
  75. const countIdx = countData.sequence_value - (sourceGLJData.length - 1);
  76. sourceGLJData.forEach((glj, index) => {
  77. IDMapping[glj.ID] = countIdx + index;
  78. });
  79. const insertData = sourceGLJData.map(glj => {
  80. const newComponent = (glj.component || []).map(c => ({
  81. ID: IDMapping[c.ID],
  82. consumeAmt: c.consumeAmt
  83. }));
  84. return {
  85. ...glj,
  86. repositoryId: targetLibID,
  87. ID: IDMapping[glj.ID],
  88. component: newComponent
  89. };
  90. });
  91. if (insertData.length) {
  92. await gljModel.insertMany(insertData);
  93. }
  94. }
  95. async getReference(repositoryId, gljId) {
  96. const gljLib = await gljMapModel.findOne({ID: repositoryId});
  97. const rationLibIds = gljLib.rationLibs.map(lib => lib.ID);
  98. const rationLibs = await rationMapModel.find({ID: {$in: rationLibIds}}, '-_id ID dispName');
  99. const rationLibNameMapping = {};
  100. rationLibs.forEach(item => {
  101. rationLibNameMapping[item.ID] = item.dispName;
  102. });
  103. const stdRations = await rationModel.find({rationRepId: {$in: rationLibIds}, 'rationGljList.gljId': gljId}, '-_id code rationRepId');
  104. const rst = {};
  105. const unknownLib = '未知定额库';
  106. const complementaryLib = '补充定额库';
  107. stdRations.forEach(ration => {
  108. const libName = rationLibNameMapping[ration.rationRepId] || unknownLib;
  109. if (!rst[libName]) {
  110. rst[libName] = [];
  111. }
  112. rst[libName].push(ration);
  113. });
  114. const complementaryRations = await complementaryRationModel.find({'rationGljList.gljId': gljId}, '-_id code');
  115. if (complementaryRations.length) {
  116. rst[complementaryLib] = [];
  117. }
  118. complementaryRations.forEach(ration => rst[complementaryLib].push({code: ration.code}));
  119. return rst;
  120. }
  121. async getGljTreeSync(gljLibId) {
  122. return await gljClassModel.find({repositoryId: gljLibId});
  123. }
  124. getGljTypes (gljLibId, callback){
  125. gljClassModel.find({"repositoryId": gljLibId, "$or": [{"isDeleted": null}, {"isDeleted": false}, {deleted: false} ]},
  126. '-_id', {lean: true}, function(err,data){
  127. if(err) callback("获取工料机类型错误!",false)
  128. else {
  129. callback(0, data);
  130. }
  131. });
  132. }
  133. _exist(data, attr){
  134. return data && data[attr] !== 'undefined' && data[attr];
  135. }
  136. sortToNumber(datas){
  137. for(let i = 0, len = datas.length; i < len; i++){
  138. let data = datas[i];
  139. if(this._exist(data, 'basePrice')){
  140. data['basePrice'] = parseFloat(data['basePrice']);
  141. }
  142. if(this._exist(data, 'component')){
  143. for(let j = 0, jLen = data['component'].length; j < jLen; j++){
  144. let comGljObj = data['component'][j];
  145. if(this._exist(comGljObj, 'consumeAmt')){
  146. comGljObj['consumeAmt'] = parseFloat(comGljObj['consumeAmt']);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. async getGljItemsSync(gljLibId) {
  153. return await gljModel.find({repositoryId: gljLibId}, '-_id', {lean: true});
  154. }
  155. async getGljItemsByRep(repositoryId,callback = null){
  156. try {
  157. let rst = await gljModel.find({repositoryId: repositoryId}).lean();
  158. // test-- 删除重复编码数据
  159. /*const map = {};
  160. rst.forEach(glj => {
  161. if (glj.code === '016100400') {
  162. console.log(glj);
  163. }
  164. const obj = {code: glj.code, ID: glj.ID};
  165. if (!map[glj.code]) {
  166. map[glj.code] = [obj];
  167. } else {
  168. map[glj.code].push(obj);
  169. }
  170. });
  171. const IDs = [];
  172. for (let code in map) {
  173. if (map[code].length > 1) {
  174. map[code].sort((a, b) => a.ID - b.ID);
  175. console.log(map[code]);
  176. let hasUsed = false;
  177. const removeIDs = [];
  178. const tempIDs = [];
  179. for (let i = 0; i < map[code].length; i++) {
  180. const glj = map[code][i];
  181. if (i !== 0) {
  182. tempIDs.push(glj.ID);
  183. }
  184. const isUsed = await rationModel.findOne({'rationGljList.gljId': glj.ID});
  185. if (isUsed) {
  186. hasUsed = true;
  187. } else {
  188. removeIDs.push(glj.ID);
  189. }
  190. }
  191. if (hasUsed) {
  192. IDs.push(...removeIDs);
  193. } else {
  194. IDs.push(...tempIDs);
  195. }
  196. //console.log(map[code]);
  197. }
  198. }
  199. if (IDs.length) {
  200. await gljModel.deleteMany({ID: {$in: IDs}});
  201. }
  202. console.log(IDs);*/
  203. // test--
  204. this.sortToNumber(rst);
  205. callback(0, rst);
  206. } catch (err) {
  207. callback(1, null);
  208. }
  209. }
  210. getGljItemByType (repositoryId, type, callback){
  211. let me = this;
  212. gljModel.find({"repositoryId": repositoryId, "gljType": type}, '-_id', {lean: true}, function(err,data){
  213. if(err) callback(true, "");
  214. else {
  215. me.sortToNumber(data);
  216. callback(false, data);
  217. }
  218. })
  219. };
  220. getGljItem (repositoryId, code, callback){
  221. let me = this;
  222. gljModel.find({"repositoryId": repositoryId, "code": code}, '-_id', {lean: true}, function(err,data){
  223. if(err) callback(true, "")
  224. else {
  225. me.sortToNumber(data);
  226. callback(false, data);
  227. }
  228. })
  229. };
  230. getGljItems (gljIds, callback){
  231. let me = this;
  232. gljModel.find({"ID": {"$in": gljIds}}, '-_id', {lean: true}, function(err,data){
  233. if(err) callback(true, "")
  234. else {
  235. me.sortToNumber(data);
  236. callback(false, data);
  237. }
  238. })
  239. };
  240. getGljItemsByCode (repositoryId, codes, callback){
  241. let me = this;
  242. gljModel.find({"repositoryId": repositoryId,"code": {"$in": codes}}, '-_id', {lean: true}, function(err,data){
  243. if(err) callback(true, "");
  244. else {
  245. me.sortToNumber(data);
  246. callback(false, data);
  247. }
  248. })
  249. };
  250. updateComponent(libId, oprtor, updateArr, callback){
  251. let parallelFucs = [];
  252. for(let i = 0; i < updateArr.length; i++){
  253. parallelFucs.push((function(obj){
  254. return function (cb) {
  255. if(typeof obj.component === 'undefined'){
  256. obj.component = [];
  257. }
  258. gljModel.update({repositoryId: libId, ID: obj.ID}, obj, function (err, result) {
  259. if(err){
  260. cb(err);
  261. }
  262. else{
  263. cb(null, obj);
  264. }
  265. })
  266. }
  267. })(updateArr[i]));
  268. }
  269. parallelFucs.push((function () {
  270. return function (cb) {
  271. GljDao.updateOprArr({ID: libId}, oprtor, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  272. if(err){
  273. cb(err);
  274. }
  275. else{
  276. cb(null);
  277. }
  278. })
  279. }
  280. })());
  281. async.parallel(parallelFucs, function (err, result) {
  282. if(err){
  283. callback(err, '更新组成物错误!', null);
  284. }
  285. else{
  286. callback(null, '成功!', result);
  287. }
  288. });
  289. }
  290. mixUpdateGljItems (repId, lastOpr, updateItems, addItems, rIds, callback) {
  291. if (updateItems.length == 0 && rIds.length == 0) {
  292. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  293. }
  294. else if(rIds.length > 0 && updateItems.length > 0){
  295. async.parallel([
  296. function (cb) {
  297. GljDao.removeGljItems(repId, lastOpr, rIds, cb);
  298. },
  299. function (cb) {
  300. GljDao.updateGljItems(repId, lastOpr, updateItems, cb);
  301. }
  302. ], function (err) {
  303. if(err){
  304. callback(true, "Fail to update and delete", false)
  305. }
  306. else{
  307. callback(false, "Save successfully", false);
  308. }
  309. })
  310. }
  311. else if (rIds.length > 0 && updateItems.length === 0) {
  312. GljDao.removeGljItems(repId, lastOpr, rIds, callback);
  313. }
  314. else if(updateItems.length > 0 || addItems.length > 0){
  315. GljDao.updateGljItems(repId, lastOpr, updateItems, function(err, results){
  316. if (err) {
  317. callback(true, "Fail to update", false);
  318. } else {
  319. if (addItems && addItems.length > 0) {
  320. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  321. } else {
  322. callback(false, "Save successfully", results);
  323. }
  324. }
  325. });
  326. }
  327. }
  328. /*mixUpdateGljItems (repId, lastOpr, updateItems, addItems, rIds, callback) {
  329. if (updateItems.length == 0 && rIds.length == 0) {
  330. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  331. } else if (rIds.length > 0) {
  332. GljDao.removeGljItems(repId, lastOpr, rIds, function(err, message, docs) {
  333. });
  334. }else{
  335. GljDao.updateGljItems(repId, lastOpr, updateItems, function(err, results){
  336. if (err) {
  337. callback(true, "Fail to update", false);
  338. } else {
  339. if (addItems && addItems.length > 0) {
  340. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  341. } else {
  342. callback(false, "Save successfully", results);
  343. }
  344. }
  345. });
  346. }
  347. };*/
  348. static removeGljItems (repId, lastOpr, rIds, callback) {
  349. if (rIds && rIds.length > 0) {
  350. gljModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
  351. if (err) {
  352. callback(true, "Fail to remove", false);
  353. } else {
  354. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  355. if(err){
  356. callback(true, "Fail to update operator", false);
  357. }
  358. else{
  359. callback(false, "Remove successfully", docs);
  360. }
  361. });
  362. }
  363. })
  364. } else {
  365. callback(false, "No records were deleted!", null);
  366. }
  367. }
  368. static addGljItems (repId, lastOpr, items, callback) {
  369. if (items && items.length > 0) {
  370. const codes = [];
  371. items.forEach(item => codes.push(item.code));
  372. gljModel.find({repositoryId: repId, code: {$in: codes}}, '-_id code', {lean: true}, (err, codeData) => {
  373. if (err) {
  374. callback(true, '判断编码唯一性失败', false);
  375. return;
  376. }
  377. const insertData = [];
  378. const failCode = [];
  379. items.forEach(item => {
  380. const matchData = codeData.find(codeItem => codeItem.code === item.code);
  381. if (!matchData) {
  382. insertData.push(item);
  383. } else {
  384. failCode.push(item.code);
  385. }
  386. });
  387. if (!insertData.length) {
  388. callback(false, 'empty data', {insertData, failCode});
  389. return;
  390. }
  391. counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, items.length, (counterErr, counterData) => {
  392. if (counterErr) {
  393. callback(true, '获取人材机ID失败', false);
  394. return;
  395. }
  396. const maxId = counterData.sequence_value;
  397. for (let i = 0; i < insertData.length; i++) {
  398. insertData[i].ID = (maxId - (insertData.length - 1) + i);
  399. insertData[i].repositoryId = repId;
  400. }
  401. const task = [];
  402. insertData.forEach(item => {
  403. task.push({
  404. insertOne: {document: item}
  405. });
  406. });
  407. gljModel.bulkWrite(task, (insertErr, rst) => {
  408. if (insertErr) {
  409. callback(true, '新增数据失败', false);
  410. return;
  411. }
  412. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  413. if(err){
  414. callback(true, "Fail to update Operator", false);
  415. } else{
  416. callback(false, "Add successfully", {insertData, failCode});
  417. }
  418. });
  419. });
  420. });
  421. });
  422. /*counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, items.length, function(err, result){
  423. const maxId = result.sequence_value;
  424. const arr = [];
  425. for (let i = 0; i < items.length; i++) {
  426. const obj = new gljModel(items[i]);
  427. obj.ID = (maxId - (items.length - 1) + i);
  428. obj.repositoryId = repId;
  429. arr.push(obj);
  430. }
  431. gljModel.collection.insert(arr, null, function(err, docs){
  432. if (err) {
  433. callback(true, "Fail to add", false);
  434. } else {
  435. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  436. if(err){
  437. callback(true, "Fail to update Operator", false);
  438. }
  439. else{
  440. callback(false, "Add successfully", docs);
  441. }
  442. });
  443. }
  444. })
  445. });*/
  446. } else {
  447. callback(true, "No source", false);
  448. }
  449. }
  450. static updateGljItems(repId, lastOpr, items, callback) {
  451. var functions = [];
  452. for (var i=0; i < items.length; i++) {
  453. functions.push((function(doc) {
  454. return function(cb) {
  455. var filter = {};
  456. if (doc.ID) {
  457. filter.ID = doc.ID;
  458. } else {
  459. filter.repositoryId = repId;
  460. filter.code = doc.code;
  461. }
  462. gljModel.update(filter, doc, cb);
  463. };
  464. })(items[i]));
  465. }
  466. functions.push((function () {
  467. return function (cb) {
  468. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  469. if(err){
  470. cb(err);
  471. }
  472. else{
  473. cb(null);
  474. }
  475. })
  476. }
  477. })());
  478. async.parallel(functions, function(err, results) {
  479. callback(err, results);
  480. });
  481. }
  482. getRationGljIds(rationLibs, callback){
  483. }
  484. updateNodes (updateData, lastOpr, callback) {
  485. let functions = [];
  486. for (let i = 0, len = updateData.length; i < len; i++) {
  487. functions.push((function(doc) {
  488. return function(cb) {
  489. if(doc.updateType === 'update' && !doc.updateData.deleted){
  490. gljClassModel.update({repositoryId: doc.updateData.repositoryId, ID: doc.updateData.ID}, doc.updateData, function (err) {
  491. if(err){
  492. cb(err);
  493. }
  494. else {
  495. cb(null);
  496. }
  497. });
  498. }
  499. else if(doc.updateType === 'update' && doc.updateData.deleted){
  500. gljClassModel.remove({repositoryId: doc.updateData.repositoryId, ID: doc.updateData.ID}, function (err) {
  501. if(err){
  502. cb(err);
  503. }
  504. else {
  505. gljModel.remove({repositoryId: doc.updateData.repositoryId, gljClass: doc.updateData.ID}, function (err) {
  506. if(err){
  507. cb(err);
  508. }
  509. else{
  510. cb(null);
  511. }
  512. });
  513. }
  514. });
  515. }
  516. else if(doc.updateType === 'new'){
  517. gljClassModel.create(doc.updateData, function (err) {
  518. if(err){
  519. cb(err);
  520. }
  521. else {
  522. cb(null);
  523. }
  524. });
  525. }
  526. };
  527. })(updateData[i]));
  528. }
  529. if(updateData.length > 0){
  530. functions.push((function () {
  531. return function (cb) {
  532. GljDao.updateOprArr({ID: updateData[0].updateData.rationRepId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  533. if(err){
  534. cb(err);
  535. }
  536. else{
  537. cb(null);
  538. }
  539. })
  540. }
  541. })());
  542. }
  543. async.parallel(functions, function(err, results) {
  544. if(!err){
  545. err = 0;
  546. }
  547. callback(err, results);
  548. });
  549. }
  550. /* updateNodes (repId, lastOpr, nodes, callback) {
  551. var functions = [];
  552. for (var i=0; i < nodes.length; i++) {
  553. functions.push((function(doc) {
  554. return function(cb) {
  555. gljClassModel.update({ID: doc.ID}, doc, cb);
  556. };
  557. })(nodes[i]));
  558. }
  559. functions.push((function () {
  560. return function (cb) {
  561. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  562. if(err){
  563. cb(err);
  564. }
  565. else{
  566. cb(null);
  567. }
  568. })
  569. }
  570. })());
  571. async.parallel(functions, function(err, results) {
  572. callback(err, results);
  573. });
  574. }*/
  575. removeNodes (repId, lastOpr, nodeIds, preNodeId, preNodeNextId, callback){
  576. var functions = [];
  577. if (preNodeId != -1) {
  578. functions.push((function(nodeId, nextId) {
  579. return function(cb) {
  580. gljClassModel.update({ID: nodeId}, {"NextSiblingID": nextId}, cb);
  581. };
  582. })(preNodeId, preNodeNextId));
  583. }
  584. for (var i=0; i < nodeIds.length; i++) {
  585. functions.push((function(nodeId) {
  586. return function(cb) {
  587. gljClassModel.update({ID: nodeId}, {"isDeleted": true}, cb);
  588. };
  589. })(nodeIds[i]));
  590. }
  591. functions.push((function () {
  592. return function (cb) {
  593. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  594. if(err){
  595. cb(err);
  596. }
  597. else{
  598. cb(null);
  599. }
  600. })
  601. }
  602. })());
  603. async.parallel(functions, function(err, results) {
  604. callback(err, results);
  605. });
  606. }
  607. createNewNode(repId, lastOpr, lastNodeId, nodeData, callback) {
  608. return counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, 1, function(err, result){
  609. nodeData.repositoryId = repId;
  610. nodeData.ID = result.sequence_value;
  611. var node = new gljModel(nodeData);
  612. async.parallel([
  613. function (cb) {
  614. node.save(function (err, result) {
  615. if (err) {
  616. cb("章节树ID错误!", false);
  617. } else {
  618. if (lastNodeId > 0) {
  619. gljClassModel.update({ID: lastNodeId}, {"NextSiblingID": nodeData.ID}, function(err, rst){
  620. if (err) {
  621. cb("章节树ID错误!", false);
  622. } else {
  623. cb(false, result);
  624. }
  625. });
  626. } else cb(false, result);
  627. }
  628. });
  629. },
  630. function (cb) {
  631. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  632. if(err){
  633. cb(err);
  634. }
  635. else{
  636. cb(null);
  637. }
  638. })
  639. }
  640. ], function (err, result) {
  641. if(err){
  642. callback(true, "章节树错误!", false);
  643. }
  644. else{
  645. callback(false, '', result[0]);
  646. }
  647. })
  648. });
  649. }
  650. getGljItemsOccupied(repId, occupation, callback){
  651. gljModel.find({repositoryId: repId}, occupation, function (err, result) {
  652. if(err) callback(true, 'fail', null);
  653. else callback(false, 'sc', result);
  654. });
  655. }
  656. async getGljItemsByRepId(repositoryId, returnFields = ''){
  657. return gljModel.find({"repositoryId": repositoryId}, returnFields);
  658. }
  659. /* async batchUpdateGljPrice(gljLibId, sheetData){
  660. let gljLib = await gljMapModel.findOne({ID: gljLibId});
  661. if(!gljLib){
  662. throw '不存在此人材机库';
  663. }
  664. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(gljLib.compilationId)});
  665. if(!compilation){
  666. throw '不存在此费用定额';
  667. }
  668. let priceProperties = compilation.priceProperties ? compilation.priceProperties : [];
  669. //根据第一行数据,获取列下标与字段名映射
  670. let colMapping = {};
  671. for(let col = 0; col < sheetData[0].length; col++){
  672. let cData = sheetData[0][col];
  673. if (cData === '编码'){
  674. colMapping.code = col;
  675. } else if (cData === '税率') {
  676. colMapping.taxRate = col;
  677. } else {
  678. if(priceProperties.length === 0){
  679. if(cData === '定额价'){
  680. colMapping.basePrice = col;
  681. break;
  682. }
  683. } else {
  684. for(let priceProp of priceProperties){
  685. if(priceProp.price.dataName === cData){
  686. colMapping[priceProp.price.dataCode] = col;
  687. break;
  688. }
  689. }
  690. }
  691. }
  692. }
  693. let colMappingKeys = Object.keys(colMapping);
  694. if(colMappingKeys.length < 2){
  695. throw 'excel数据不正确'
  696. }
  697. let updateBulk = [];
  698. //避免重复
  699. let updateCodes = [];
  700. //库中存在的人材机
  701. let dateA = Date.now();
  702. let existGljs = await gljModel.find({repositoryId: gljLibId}, '-_id code ID');
  703. let existMapping = {};
  704. for (let glj of existGljs) {
  705. existMapping[glj.code] = glj;
  706. }
  707. for(let row = 0; row < sheetData.length; row++){
  708. if(row === 0){
  709. continue;
  710. }
  711. let gljCode = sheetData[row][colMapping.code],
  712. existGlj = existMapping[gljCode];
  713. //更新多单价、不覆盖priceProperty字段,覆盖priceProperty下的子字段'priceProperty.x'
  714. if(gljCode && gljCode !== '' && !updateCodes.includes(gljCode) && existGlj){
  715. const updateSet = {};
  716. // 税率
  717. const taxRateCol = colMapping.taxRate;
  718. if (isDef(taxRateCol) && !isEmptyVal(sheetData[row][taxRateCol])) {
  719. updateSet.taxRate = sheetData[row][taxRateCol];
  720. }
  721. // 价格
  722. if(priceProperties.length > 0){ // 多单价
  723. for(let priceProp of priceProperties){
  724. let dataCode = priceProp.price.dataCode;
  725. let priceCellData = sheetData[row][colMapping[dataCode]];
  726. //Excel中没有这个单价则跳过
  727. if (!colMapping[dataCode]) {
  728. continue;
  729. }
  730. let updateSet = {};
  731. updateSet['priceProperty.' + dataCode] = priceCellData && !isNaN(priceCellData) ?
  732. scMathUtil.roundTo(parseFloat(priceCellData), -2) : 0;
  733. updateBulk.push({
  734. updateOne: {filter: {ID: existGlj.ID}, update: {$set: updateSet}}
  735. });
  736. }
  737. updateCodes.push(gljCode);
  738. } else { // 单单价
  739. if(colMapping.basePrice){
  740. let priceCellData = sheetData[row][colMapping.basePrice];
  741. let basePrice = priceCellData && !isNaN(priceCellData) ?
  742. scMathUtil.roundTo(priceCellData, -2) : 0;
  743. updateCodes.push(gljCode);
  744. updateBulk.push({
  745. updateOne: {filter: {ID: existGlj.ID}, update: {$set: {basePrice: basePrice}}}
  746. });
  747. }
  748. }
  749. }
  750. }
  751. if(updateBulk.length > 0){
  752. while (updateBulk.length > 0) {
  753. let sliceBulk = updateBulk.splice(0, 1000);
  754. await gljModel.bulkWrite(sliceBulk);
  755. }
  756. }
  757. } */
  758. async batchUpdateGljPrice(gljLibId, sheetData){
  759. let gljLib = await gljMapModel.findOne({ID: gljLibId});
  760. if(!gljLib){
  761. throw '不存在此人材机库';
  762. }
  763. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(gljLib.compilationId)});
  764. if(!compilation){
  765. throw '不存在此费用定额';
  766. }
  767. let priceProperties = compilation.priceProperties ? compilation.priceProperties : [];
  768. //根据第一行数据,获取列下标与字段名映射
  769. let colMapping = {};
  770. for(let col = 0; col < sheetData[0].length; col++){
  771. let cData = sheetData[0][col];
  772. if (cData === '编码'){
  773. colMapping.code = col;
  774. } else if (cData === '税率') {
  775. colMapping.taxRate = col;
  776. } else {
  777. if(priceProperties.length === 0){
  778. if(cData === '定额价'){
  779. colMapping.basePrice = col;
  780. break;
  781. }
  782. } else {
  783. for(let priceProp of priceProperties){
  784. if(priceProp.price.dataName === cData){
  785. colMapping[priceProp.price.dataCode] = col;
  786. break;
  787. }
  788. }
  789. }
  790. }
  791. }
  792. let colMappingKeys = Object.keys(colMapping);
  793. if(colMappingKeys.length < 2){
  794. throw 'excel数据不正确'
  795. }
  796. let updateBulk = [];
  797. //避免重复
  798. let updateCodes = [];
  799. //库中存在的人材机
  800. let dateA = Date.now();
  801. let existGljs = await gljModel.find({repositoryId: gljLibId}, '-_id code ID');
  802. let existMapping = {};
  803. for (let glj of existGljs) {
  804. existMapping[glj.code] = glj;
  805. }
  806. for(let row = 0; row < sheetData.length; row++){
  807. if(row === 0){
  808. continue;
  809. }
  810. let gljCode = sheetData[row][colMapping.code],
  811. existGlj = existMapping[gljCode];
  812. //更新多单价、不覆盖priceProperty字段,覆盖priceProperty下的子字段'priceProperty.x'
  813. if(gljCode && gljCode !== '' && !updateCodes.includes(gljCode) && existGlj){
  814. const updateSet = {};
  815. // 税率
  816. const taxRateCol = colMapping.taxRate;
  817. if (isDef(taxRateCol) && !isEmptyVal(sheetData[row][taxRateCol])) {
  818. updateSet.taxRate = sheetData[row][taxRateCol];
  819. }
  820. // 价格
  821. if(priceProperties.length > 0){ // 多单价
  822. for(let priceProp of priceProperties){
  823. let dataCode = priceProp.price.dataCode;
  824. let priceCellData = sheetData[row][colMapping[dataCode]];
  825. //Excel中没有这个单价则跳过
  826. if (!colMapping[dataCode] || isEmptyVal(priceCellData)) {
  827. continue;
  828. }
  829. updateSet['priceProperty.' + dataCode] = priceCellData && !isNaN(priceCellData) ?
  830. scMathUtil.roundTo(parseFloat(priceCellData), -2) : 0;
  831. /* updateBulk.push({
  832. updateOne: {filter: {ID: existGlj.ID}, update: {$set: updateSet}}
  833. }); */
  834. }
  835. //updateCodes.push(gljCode);
  836. } else { // 单单价
  837. if(colMapping.basePrice && !isEmptyVal(sheetData[row][colMapping.basePrice])){
  838. let priceCellData = sheetData[row][colMapping.basePrice];
  839. let basePrice = priceCellData && !isNaN(priceCellData) ?
  840. scMathUtil.roundTo(priceCellData, -2) : 0;
  841. updateSet.basePrice = basePrice;
  842. /* updateCodes.push(gljCode);
  843. updateBulk.push({
  844. updateOne: {filter: {ID: existGlj.ID}, update: {$set: {basePrice: basePrice}}}
  845. }); */
  846. }
  847. }
  848. if (Object.keys(updateSet).length) {
  849. updateCodes.push(gljCode);
  850. updateBulk.push({
  851. updateOne: {filter: {ID: existGlj.ID}, update: {$set: updateSet}}
  852. });
  853. }
  854. }
  855. }
  856. if(updateBulk.length > 0){
  857. while (updateBulk.length > 0) {
  858. let sliceBulk = updateBulk.splice(0, 1000);
  859. await gljModel.bulkWrite(sliceBulk);
  860. }
  861. }
  862. }
  863. // 批量修改人材机类型
  864. async batchUpdateGLJType(gljLibId, sheetData) {
  865. // 将所有人材机进行编码映射
  866. const allGLJs = await gljModel.find({repositoryId: gljLibId}, {ID: true, code: true, gljType: true, shortName: true}).lean();
  867. const codeMapping = {};
  868. allGLJs.forEach(glj => codeMapping[glj.code] = glj);
  869. const updateTask = [];
  870. for (let row = 1; row < sheetData.length; row++) {
  871. const rowData = sheetData[row];
  872. const code = rowData[0];
  873. const gljType = rowData[1];
  874. const shortName = rowData[2];
  875. const glj = codeMapping[code];
  876. if (!glj) {
  877. continue;
  878. }
  879. updateTask.push({
  880. updateOne: {
  881. filter: { ID: glj.ID },
  882. update: { gljType, shortName }
  883. }
  884. });
  885. }
  886. if (updateTask.length) {
  887. gljModel.bulkWrite(updateTask);
  888. }
  889. }
  890. // 导入组成物(替换原本的数据)
  891. // excel第一行应为:人材机、组成物、消耗量(或者:消耗-一般、消耗-简易等)
  892. async importComponents(gljLibId, sheetData) {
  893. const gljLib = await gljMapModel.findOne({ID: gljLibId});
  894. if (!gljLib) {
  895. throw '不存在此人材机库';
  896. }
  897. const compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(gljLib.compilationId)});
  898. if (!compilation) {
  899. throw '不存在此费用定额';
  900. }
  901. const consumeAmtProperties = compilation.consumeAmtProperties || [];
  902. // 根据第一行数据,获取列号与字段映射
  903. const colMapping = {};
  904. const firstRow = sheetData[0];
  905. const multiConsumeAmt = [];
  906. firstRow.forEach((colData, col) => {
  907. if (colData === '人材机') {
  908. colMapping.code = col;
  909. } else if (colData === '组成物') {
  910. colMapping.componentCode = col;
  911. } else if (colData === '消耗量') {
  912. colMapping.consumeAmt = col;
  913. } else {
  914. // 多消耗量
  915. const consumeAmtItem = consumeAmtProperties.find(item => item.consumeAmt.dataName === colData);
  916. if (consumeAmtItem) {
  917. colMapping[consumeAmtItem.consumeAmt.dataCode] = col;
  918. multiConsumeAmt.push(consumeAmtItem.consumeAmt.dataCode);
  919. }
  920. }
  921. });
  922. if (Object.getOwnPropertyNames(colMapping).length < 3) {
  923. throw 'exel数据错误';
  924. }
  925. // 将所有人材机进行编码映射
  926. const allGLJs = await gljModel.find({repositoryId: gljLibId}, {ID: true, code: true}).lean();
  927. const codeMapping = {};
  928. allGLJs.forEach(glj => codeMapping[glj.code] = glj);
  929. const updateGLJs = [];
  930. //const forTest = [];
  931. // 跳过列头
  932. for (let row = 1; row < sheetData.length; row++) {
  933. const rowData = sheetData[row];
  934. const code = rowData[colMapping.code];
  935. const componentCode = rowData[colMapping.componentCode];
  936. //const consumeAmt = +rowData[colMapping.consumeAmt];
  937. const glj = codeMapping[code];
  938. const component = codeMapping[componentCode];
  939. if (!glj || !component) {
  940. continue;
  941. }
  942. if (!glj.component) {
  943. glj.component = [];
  944. }
  945. const componentIsExist = glj.component.some(item => item.ID === component.ID);
  946. if (componentIsExist) {
  947. //forTest.push(code);
  948. continue;
  949. }
  950. const componentGLJ = { ID: component.ID };
  951. if (multiConsumeAmt.length) { // 多消耗量
  952. const consumeAmtProperty = {};
  953. for (const dataCode of multiConsumeAmt) {
  954. consumeAmtProperty[dataCode] = +rowData[colMapping[dataCode]]
  955. }
  956. componentGLJ.consumeAmtProperty = consumeAmtProperty;
  957. } else { // 单消耗量
  958. componentGLJ.consumeAmt = +rowData[colMapping.consumeAmt]
  959. }
  960. glj.component.push(componentGLJ);
  961. if (updateGLJs.indexOf(glj) < 0) {
  962. updateGLJs.push(glj);
  963. }
  964. }
  965. // 更新数据
  966. const tasks = [];
  967. //console.log(`[new Set(forTest)]`);
  968. //console.log([new Set(forTest)]);
  969. updateGLJs.filter(glj => glj.component && glj.component.length).forEach(glj => {
  970. tasks.push({
  971. updateOne: {
  972. filter: {
  973. ID: glj.ID
  974. },
  975. update: {$set: {component: glj.component}}
  976. }
  977. });
  978. });
  979. if (tasks.length) {
  980. await gljModel.bulkWrite(tasks);
  981. }
  982. }
  983. }
  984. export default GljDao;