gljModel.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 projectGLJModel = mongoose.model('glj_list');
  9. const projectModel = mongoose.model('projects');
  10. const userModel = mongoose.model('users');
  11. const gljClassTemplateModel = mongoose.model('std_glj_lib_gljClassTemplate');
  12. const compilationModel = mongoose.model('compilation');
  13. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  14. const rationMapModel = mongoose.model('std_ration_lib_map');
  15. const rationModel = mongoose.model('std_ration_lib_ration_items');
  16. const complementaryRationModel = mongoose.model('complementary_ration_items');
  17. import {OprDao} from "./gljMapModel";
  18. import moment from "moment";
  19. import counter from "../../../public/counter/counter";
  20. import async from "async";
  21. let _ = require("lodash");
  22. class GljDao extends OprDao{
  23. async copyLib(sourceLibID, targetLibID) {
  24. const task = [
  25. this.copyClassData(sourceLibID, targetLibID),
  26. this.copyGLJData(sourceLibID, targetLibID)
  27. ];
  28. await Promise.all(task);
  29. }
  30. async copyClassData(sourceLibID, targetLibID) {
  31. const sourceClassData = await gljClassModel.find({ repositoryId: sourceLibID }, '-_id').lean();
  32. const insertData = sourceClassData.map(item => ({
  33. ... item,
  34. repositoryId: targetLibID
  35. }));
  36. if (insertData.length) {
  37. await gljClassModel.insertMany(insertData);
  38. }
  39. }
  40. async copyGLJData(sourceLibID, targetLibID) {
  41. const sourceGLJData = await gljModel.find({ repositoryId: sourceLibID }, '-_id').lean();
  42. const IDMapping = {};
  43. const countData = await counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, sourceGLJData.length);
  44. const countIdx = countData.sequence_value - (sourceGLJData.length - 1);
  45. sourceGLJData.forEach((glj, index) => {
  46. IDMapping[glj.ID] = countIdx + index;
  47. });
  48. const insertData = sourceGLJData.map(glj => {
  49. const newComponent = (glj.component || []).map(c => ({
  50. ID: IDMapping[c.ID],
  51. consumeAmt: c.consumeAmt
  52. }));
  53. return {
  54. ...glj,
  55. repositoryId: targetLibID,
  56. ID: IDMapping[glj.ID],
  57. component: newComponent
  58. };
  59. });
  60. if (insertData.length) {
  61. await gljModel.insertMany(insertData);
  62. }
  63. }
  64. async getReference(repositoryId, gljId) {
  65. const gljLib = await gljMapModel.findOne({ID: repositoryId});
  66. const rationLibIds = gljLib.rationLibs.map(lib => lib.ID);
  67. const rationLibs = await rationMapModel.find({ID: {$in: rationLibIds}}, '-_id ID dispName');
  68. const rationLibNameMapping = {};
  69. rationLibs.forEach(item => {
  70. rationLibNameMapping[item.ID] = item.dispName;
  71. });
  72. const stdRations = await rationModel.find({rationRepId: {$in: rationLibIds}, 'rationGljList.gljId': gljId}, '-_id code rationRepId');
  73. const rst = {};
  74. const unknownLib = '未知定额库';
  75. const complementaryLib = '补充定额库';
  76. stdRations.forEach(ration => {
  77. const libName = rationLibNameMapping[ration.rationRepId] || unknownLib;
  78. if (!rst[libName]) {
  79. rst[libName] = [];
  80. }
  81. rst[libName].push(ration);
  82. });
  83. const complementaryRations = await complementaryRationModel.find({'rationGljList.gljId': gljId}, '-_id code');
  84. if (complementaryRations.length) {
  85. rst[complementaryLib] = [];
  86. }
  87. complementaryRations.forEach(ration => rst[complementaryLib].push({code: ration.code}));
  88. return rst;
  89. }
  90. async getUsedInfo(repositoryId, gljId) {
  91. let userMap = {};
  92. let userIDList = [];
  93. let projectList = await projectGLJModel.find({"glj_id":gljId},'-_id project_id').lean();
  94. if(projectList.length > 0){
  95. let projectUserList = await projectModel.find({'ID':{$in:_.map(projectList,"project_id")}},'-_id ID userID').lean();
  96. for(let p of projectUserList){
  97. if(!userMap[p.userID]){
  98. userMap[p.userID] = true;
  99. userIDList.push(p.userID);
  100. }
  101. }
  102. let userList = await userModel.find({'_id':{$in:userIDList}},'_id username mobile').lean();
  103. for(let u of userList){
  104. userMap[u._id.toString()] = u;
  105. }
  106. for(let p of projectUserList){
  107. p.username = userMap[p.userID].username;
  108. p.mobile = userMap[p.userID].mobile;
  109. }
  110. return projectUserList
  111. }
  112. return [];
  113. }
  114. async getGljTreeSync(gljLibId) {
  115. return await gljClassModel.find({repositoryId: gljLibId});
  116. }
  117. getGljTypes (gljLibId, callback){
  118. gljClassModel.find({"repositoryId": gljLibId, "$or": [{"isDeleted": null}, {"isDeleted": false}, {deleted: false} ]},
  119. '-_id', {lean: true}, function(err,data){
  120. if(err) callback("获取工料机类型错误!",false)
  121. else {
  122. callback(0, data);
  123. }
  124. })
  125. }
  126. _exist(data, attr){
  127. return data && data[attr] !== 'undefined' && data[attr];
  128. }
  129. sortToNumber(datas){
  130. for(let i = 0, len = datas.length; i < len; i++){
  131. let data = datas[i]._doc;
  132. if(this._exist(data, 'basePrice')){
  133. data['basePrice'] = parseFloat(data['basePrice']);
  134. }
  135. if(this._exist(data, 'component')){
  136. for(let j = 0, jLen = data['component'].length; j < jLen; j++){
  137. let comGljObj = data['component'][j]._doc;
  138. if(this._exist(comGljObj, 'consumeAmt')){
  139. comGljObj['consumeAmt'] = parseFloat(comGljObj['consumeAmt']);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. async getGljItemsSync(gljLibId) {
  146. return await gljModel.find({repositoryId: gljLibId}, '-_id', {lean: true});
  147. }
  148. async getGljItemsByRep(repositoryId,callback = null){
  149. /* let me = this;
  150. if (callback === null) {
  151. return gljModel.find({"repositoryId": repositoryId});
  152. } else {
  153. gljModel.find({"repositoryId": repositoryId},function(err,data){
  154. if(err) callback(true, "")
  155. else {
  156. me.sortToNumber(data);
  157. callback(false,data);
  158. }
  159. })
  160. }*/
  161. let me = this;
  162. let rst = [];
  163. //批量获取异步
  164. let functions = [];
  165. let count = await gljModel.find({repositoryId: repositoryId, $or: [{deleted: null}, {deleted: false}]}).count();
  166. let findCount = Math.ceil(count/500);
  167. for(let i = 0, len = findCount; i < len; i++){
  168. functions.push((function(flag) {
  169. return function (cb) {
  170. gljModel.find({repositoryId: repositoryId, deleted: null}, '-_id', {lean: true}, cb).skip(flag).sort({ID: 1}).limit(500);
  171. }
  172. })(i*500));
  173. }
  174. async.parallel(functions, function (err, results) {
  175. if(err){
  176. callback(err, null);
  177. }
  178. else{
  179. for(let stdGljs of results){
  180. rst = rst.concat(stdGljs);
  181. }
  182. me.sortToNumber(rst);
  183. callback(0, rst);
  184. }
  185. });
  186. }
  187. getGljItemByType (repositoryId, type, callback){
  188. let me = this;
  189. gljModel.find({"repositoryId": repositoryId, "gljType": type},function(err,data){
  190. if(err) callback(true, "");
  191. else {
  192. me.sortToNumber(data);
  193. callback(false, data);
  194. }
  195. })
  196. };
  197. getGljItem (repositoryId, code, callback){
  198. let me = this;
  199. gljModel.find({"repositoryId": repositoryId, "code": code},function(err,data){
  200. if(err) callback(true, "")
  201. else {
  202. me.sortToNumber(data);
  203. callback(false, data);
  204. }
  205. })
  206. };
  207. getGljItems (gljIds, callback){
  208. let me = this;
  209. gljModel.find({"ID": {"$in": gljIds}},function(err,data){
  210. if(err) callback(true, "")
  211. else {
  212. me.sortToNumber(data);
  213. callback(false, data);
  214. }
  215. })
  216. };
  217. getGljItemsByCode (repositoryId, codes, callback){
  218. let me = this;
  219. gljModel.find({"repositoryId": repositoryId,"code": {"$in": codes}},function(err,data){
  220. if(err) callback(true, "");
  221. else {
  222. me.sortToNumber(data);
  223. callback(false, data);
  224. }
  225. })
  226. };
  227. updateComponent(libId, oprtor, updateArr, callback){
  228. let parallelFucs = [];
  229. for(let i = 0; i < updateArr.length; i++){
  230. parallelFucs.push((function(obj){
  231. return function (cb) {
  232. if(typeof obj.component === 'undefined'){
  233. obj.component = [];
  234. }
  235. gljModel.update({repositoryId: libId, ID: obj.ID}, obj, function (err, result) {
  236. if(err){
  237. cb(err);
  238. }
  239. else{
  240. cb(null, obj);
  241. }
  242. })
  243. }
  244. })(updateArr[i]));
  245. }
  246. parallelFucs.push((function () {
  247. return function (cb) {
  248. GljDao.updateOprArr({ID: libId}, oprtor, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  249. if(err){
  250. cb(err);
  251. }
  252. else{
  253. cb(null);
  254. }
  255. })
  256. }
  257. })());
  258. async.parallel(parallelFucs, function (err, result) {
  259. if(err){
  260. callback(err, '更新组成物错误!', null);
  261. }
  262. else{
  263. callback(null, '成功!', result);
  264. }
  265. });
  266. }
  267. mixUpdateGljItems (repId, lastOpr, updateItems, addItems, rIds, callback) {
  268. if (updateItems.length == 0 && rIds.length == 0) {
  269. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  270. }
  271. else if(rIds.length > 0 && updateItems.length > 0){
  272. async.parallel([
  273. function (cb) {
  274. GljDao.removeGljItems(repId, lastOpr, rIds, cb);
  275. },
  276. function (cb) {
  277. GljDao.updateGljItems(repId, lastOpr, updateItems, cb);
  278. }
  279. ], function (err) {
  280. if(err){
  281. callback(true, "Fail to update and delete", false)
  282. }
  283. else{
  284. callback(false, "Save successfully", false);
  285. }
  286. })
  287. }
  288. else if (rIds.length > 0 && updateItems.length === 0) {
  289. GljDao.removeGljItems(repId, lastOpr, rIds, callback);
  290. }
  291. else if(updateItems.length > 0 || addItems.length > 0){
  292. GljDao.updateGljItems(repId, lastOpr, updateItems, function(err, results){
  293. if (err) {
  294. callback(true, "Fail to update", false);
  295. } else {
  296. if (addItems && addItems.length > 0) {
  297. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  298. } else {
  299. callback(false, "Save successfully", results);
  300. }
  301. }
  302. });
  303. }
  304. }
  305. /*mixUpdateGljItems (repId, lastOpr, updateItems, addItems, rIds, callback) {
  306. if (updateItems.length == 0 && rIds.length == 0) {
  307. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  308. } else if (rIds.length > 0) {
  309. GljDao.removeGljItems(repId, lastOpr, rIds, function(err, message, docs) {
  310. });
  311. }else{
  312. GljDao.updateGljItems(repId, lastOpr, updateItems, function(err, results){
  313. if (err) {
  314. callback(true, "Fail to update", false);
  315. } else {
  316. if (addItems && addItems.length > 0) {
  317. GljDao.addGljItems(repId, lastOpr, addItems, callback);
  318. } else {
  319. callback(false, "Save successfully", results);
  320. }
  321. }
  322. });
  323. }
  324. };*/
  325. static removeGljItems (repId, lastOpr, rIds, callback) {
  326. if (rIds && rIds.length > 0) {
  327. gljModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
  328. if (err) {
  329. callback(true, "Fail to remove", false);
  330. } else {
  331. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  332. if(err){
  333. callback(true, "Fail to update operator", false);
  334. }
  335. else{
  336. callback(false, "Remove successfully", docs);
  337. }
  338. });
  339. }
  340. })
  341. } else {
  342. callback(false, "No records were deleted!", null);
  343. }
  344. }
  345. static addGljItems (repId, lastOpr, items, callback) {
  346. if (items && items.length > 0) {
  347. const codes = [];
  348. items.forEach(item => codes.push(item.code));
  349. gljModel.find({repositoryId: repId, code: {$in: codes}}, '-_id code', {lean: true}, (err, codeData) => {
  350. if (err) {
  351. callback(true, '判断编码唯一性失败', false);
  352. return;
  353. }
  354. const insertData = [];
  355. const failCode = [];
  356. items.forEach(item => {
  357. const matchData = codeData.find(codeItem => codeItem.code === item.code);
  358. if (!matchData) {
  359. insertData.push(item);
  360. } else {
  361. failCode.push(item.code);
  362. }
  363. });
  364. if (!insertData.length) {
  365. callback(false, 'empty data', {insertData, failCode});
  366. return;
  367. }
  368. counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, items.length, (counterErr, counterData) => {
  369. if (counterErr) {
  370. callback(true, '获取人材机ID失败', false);
  371. return;
  372. }
  373. const maxId = counterData.sequence_value;
  374. for (let i = 0; i < insertData.length; i++) {
  375. insertData[i].ID = (maxId - (insertData.length - 1) + i);
  376. insertData[i].repositoryId = repId;
  377. }
  378. const task = [];
  379. insertData.forEach(item => {
  380. task.push({
  381. insertOne: {document: item}
  382. });
  383. });
  384. gljModel.bulkWrite(task, (insertErr, rst) => {
  385. if (insertErr) {
  386. callback(true, '新增数据失败', false);
  387. return;
  388. }
  389. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  390. if(err){
  391. callback(true, "Fail to update Operator", false);
  392. } else{
  393. callback(false, "Add successfully", {insertData, failCode});
  394. }
  395. });
  396. });
  397. });
  398. });
  399. } else {
  400. callback(true, "No source", false);
  401. }
  402. }
  403. static updateGljItems(repId, lastOpr, items, callback) {
  404. var functions = [];
  405. for (var i=0; i < items.length; i++) {
  406. functions.push((function(doc) {
  407. return function(cb) {
  408. var filter = {};
  409. if (doc.ID) {
  410. filter.ID = doc.ID;
  411. } else {
  412. filter.repositoryId = repId;
  413. filter.code = doc.code;
  414. }
  415. gljModel.update(filter, doc, cb);
  416. };
  417. })(items[i]));
  418. }
  419. functions.push((function () {
  420. return function (cb) {
  421. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  422. if(err){
  423. cb(err);
  424. }
  425. else{
  426. cb(null);
  427. }
  428. })
  429. }
  430. })());
  431. async.parallel(functions, function(err, results) {
  432. callback(err, results);
  433. });
  434. }
  435. getRationGljIds(rationLibs, callback){
  436. }
  437. updateNodes (updateData, lastOpr, callback) {
  438. let functions = [];
  439. for (let i = 0, len = updateData.length; i < len; i++) {
  440. functions.push((function(doc) {
  441. return function(cb) {
  442. if(doc.updateType === 'update' && !doc.updateData.deleted){
  443. gljClassModel.update({repositoryId: doc.updateData.repositoryId, ID: doc.updateData.ID}, doc.updateData, function (err) {
  444. if(err){
  445. cb(err);
  446. }
  447. else {
  448. cb(null);
  449. }
  450. });
  451. }
  452. else if(doc.updateType === 'update' && doc.updateData.deleted){
  453. gljClassModel.remove({repositoryId: doc.updateData.repositoryId, ID: doc.updateData.ID}, function (err) {
  454. if(err){
  455. cb(err);
  456. }
  457. else {
  458. gljModel.remove({repositoryId: doc.updateData.repositoryId, gljClass: doc.updateData.ID}, function (err) {
  459. if(err){
  460. cb(err);
  461. }
  462. else{
  463. cb(null);
  464. }
  465. });
  466. }
  467. });
  468. }
  469. else if(doc.updateType === 'new'){
  470. gljClassModel.create(doc.updateData, function (err) {
  471. if(err){
  472. cb(err);
  473. }
  474. else {
  475. cb(null);
  476. }
  477. });
  478. }
  479. };
  480. })(updateData[i]));
  481. }
  482. if(updateData.length > 0){
  483. functions.push((function () {
  484. return function (cb) {
  485. GljDao.updateOprArr({ID: updateData[0].updateData.rationRepId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  486. if(err){
  487. cb(err);
  488. }
  489. else{
  490. cb(null);
  491. }
  492. })
  493. }
  494. })());
  495. }
  496. async.parallel(functions, function(err, results) {
  497. if(!err){
  498. err = 0;
  499. }
  500. callback(err, results);
  501. });
  502. }
  503. /* updateNodes (repId, lastOpr, nodes, callback) {
  504. var functions = [];
  505. for (var i=0; i < nodes.length; i++) {
  506. functions.push((function(doc) {
  507. return function(cb) {
  508. gljClassModel.update({ID: doc.ID}, doc, cb);
  509. };
  510. })(nodes[i]));
  511. }
  512. functions.push((function () {
  513. return function (cb) {
  514. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  515. if(err){
  516. cb(err);
  517. }
  518. else{
  519. cb(null);
  520. }
  521. })
  522. }
  523. })());
  524. async.parallel(functions, function(err, results) {
  525. callback(err, results);
  526. });
  527. }*/
  528. removeNodes (repId, lastOpr, nodeIds, preNodeId, preNodeNextId, callback){
  529. var functions = [];
  530. if (preNodeId != -1) {
  531. functions.push((function(nodeId, nextId) {
  532. return function(cb) {
  533. gljClassModel.update({ID: nodeId}, {"NextSiblingID": nextId}, cb);
  534. };
  535. })(preNodeId, preNodeNextId));
  536. }
  537. for (var i=0; i < nodeIds.length; i++) {
  538. functions.push((function(nodeId) {
  539. return function(cb) {
  540. gljClassModel.update({ID: nodeId}, {"isDeleted": true}, cb);
  541. };
  542. })(nodeIds[i]));
  543. }
  544. functions.push((function () {
  545. return function (cb) {
  546. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  547. if(err){
  548. cb(err);
  549. }
  550. else{
  551. cb(null);
  552. }
  553. })
  554. }
  555. })());
  556. async.parallel(functions, function(err, results) {
  557. callback(err, results);
  558. });
  559. }
  560. createNewNode(repId, lastOpr, lastNodeId, nodeData, callback) {
  561. return counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, 1, function(err, result){
  562. nodeData.repositoryId = repId;
  563. nodeData.ID = result.sequence_value;
  564. var node = new gljModel(nodeData);
  565. async.parallel([
  566. function (cb) {
  567. node.save(function (err, result) {
  568. if (err) {
  569. cb("章节树ID错误!", false);
  570. } else {
  571. if (lastNodeId > 0) {
  572. gljClassModel.update({ID: lastNodeId}, {"NextSiblingID": nodeData.ID}, function(err, rst){
  573. if (err) {
  574. cb("章节树ID错误!", false);
  575. } else {
  576. cb(false, result);
  577. }
  578. });
  579. } else cb(false, result);
  580. }
  581. });
  582. },
  583. function (cb) {
  584. GljDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  585. if(err){
  586. cb(err);
  587. }
  588. else{
  589. cb(null);
  590. }
  591. })
  592. }
  593. ], function (err, result) {
  594. if(err){
  595. callback(true, "章节树错误!", false);
  596. }
  597. else{
  598. callback(false, '', result[0]);
  599. }
  600. })
  601. });
  602. }
  603. getGljItemsOccupied(repId, occupation, callback){
  604. gljModel.find({repositoryId: repId}, occupation, function (err, result) {
  605. if(err) callback(true, 'fail', null);
  606. else callback(false, 'sc', result);
  607. });
  608. }
  609. async getGljItemsByRepId(repositoryId, returnFields = ''){
  610. return gljModel.find({"repositoryId": repositoryId}, returnFields);
  611. }
  612. async batchUpdateGljPrice(gljLibId, sheetData){
  613. let gljLib = await gljMapModel.findOne({ID: gljLibId});
  614. if(!gljLib){
  615. throw '不存在此人材机库';
  616. }
  617. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(gljLib.compilationId)});
  618. if(!compilation){
  619. throw '不存在此费用定额';
  620. }
  621. let priceProperties = compilation.priceProperties ? compilation.priceProperties : [];
  622. //根据第一行数据,获取列下标与字段名映射
  623. let colMapping = {};
  624. for(let col = 0; col < sheetData[0].length; col++){
  625. let cData = sheetData[0][col];
  626. if(cData === '编码'){
  627. colMapping['code'] = col;
  628. }
  629. else {
  630. if(priceProperties.length === 0){
  631. if(cData === '定额价'){
  632. colMapping['basePrice'] = col;
  633. break;
  634. }
  635. }
  636. else {
  637. for(let priceProp of priceProperties){
  638. if(priceProp.price.dataName === cData){
  639. colMapping[priceProp.price.dataCode] = col;
  640. break;
  641. }
  642. }
  643. }
  644. }
  645. }
  646. let colMappingKeys = Object.keys(colMapping);
  647. if(colMappingKeys.length < 2){
  648. throw 'excel数据不正确'
  649. }
  650. let updateBulk = [];
  651. //避免重复
  652. let updateCodes = [];
  653. //库中存在的人材机
  654. let dateA = Date.now();
  655. let existGljs = await gljModel.find({repositoryId: gljLibId}, '-_id code ID');
  656. let existMapping = {};
  657. for (let glj of existGljs) {
  658. existMapping[glj.code] = glj;
  659. }
  660. for(let row = 0; row < sheetData.length; row++){
  661. if(row === 0){
  662. continue;
  663. }
  664. let gljCode = sheetData[row][colMapping.code],
  665. existGlj = existMapping[gljCode];
  666. //更新多单价、不覆盖priceProperty字段,覆盖priceProperty下的子字段'priceProperty.x'
  667. if(gljCode && gljCode !== '' && !updateCodes.includes(gljCode) && existGlj){
  668. if(priceProperties.length > 0){
  669. for(let priceProp of priceProperties){
  670. let dataCode = priceProp.price.dataCode;
  671. let priceCellData = sheetData[row][colMapping[dataCode]];
  672. //Excel中没有这个单价则跳过
  673. if (!colMapping[dataCode]) {
  674. continue;
  675. }
  676. let updateSet = {};
  677. updateSet['priceProperty.' + dataCode] = priceCellData && !isNaN(priceCellData) ?
  678. scMathUtil.roundTo(parseFloat(priceCellData), -2) : 0;
  679. updateBulk.push({
  680. updateOne: {filter: {ID: existGlj.ID}, update: {$set: updateSet}}
  681. });
  682. }
  683. updateCodes.push(gljCode);
  684. }
  685. else {
  686. if(colMapping.basePrice){
  687. let priceCellData = sheetData[row][colMapping.basePrice];
  688. let basePrice = priceCellData && !isNaN(priceCellData) ?
  689. scMathUtil.roundTo(priceCellData, -2) : 0;
  690. updateCodes.push(gljCode);
  691. updateBulk.push({
  692. updateOne: {filter: {ID: existGlj.ID}, update: {$set: {basePrice: basePrice}}}
  693. });
  694. }
  695. }
  696. }
  697. }
  698. if(updateBulk.length > 0){
  699. while (updateBulk.length > 0) {
  700. let sliceBulk = updateBulk.splice(0, 1000);
  701. await gljModel.bulkWrite(sliceBulk);
  702. }
  703. }
  704. }
  705. async importComponents(gljLibId, sheetData) {
  706. const gljLib = await gljMapModel.findOne({ID: gljLibId});
  707. if (!gljLib) {
  708. throw '不存在此人材机库';
  709. }
  710. const compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(gljLib.compilationId)});
  711. if (!compilation) {
  712. throw '不存在此费用定额';
  713. }
  714. // 将所有人材机进行编码映射
  715. const allGLJs = await gljModel.find({repositoryId: gljLibId}, {ID: true, code: true}).lean();
  716. const codeMapping = {};
  717. allGLJs.forEach(glj => codeMapping[glj.code] = glj);
  718. // excel表格列号与字段的映射
  719. const colMapping = {
  720. // 材料编码
  721. code: 0,
  722. // 组成物编码
  723. componentCode: 1,
  724. // 组成物消耗量
  725. consumeAmt: 2
  726. };
  727. // 跳过列头
  728. for (let row = 1; row < sheetData.length; row++) {
  729. const rowData = sheetData[row];
  730. const code = rowData[colMapping.code];
  731. const componentCode = rowData[colMapping.componentCode];
  732. const consumeAmt = +rowData[colMapping.consumeAmt];
  733. const glj = codeMapping[code];
  734. const component = codeMapping[componentCode];
  735. if (!glj || !component) {
  736. continue;
  737. }
  738. if (!glj.component) {
  739. glj.component = [];
  740. }
  741. glj.component.push({
  742. ID: component.ID,
  743. consumeAmt: consumeAmt
  744. });
  745. }
  746. // 更新数据
  747. const tasks = [];
  748. allGLJs.filter(glj => glj.component && glj.component.length).forEach(glj => {
  749. tasks.push({
  750. updateOne: {
  751. filter: {
  752. ID: glj.ID
  753. },
  754. update: {$set: {component: glj.component}}
  755. }
  756. });
  757. });
  758. if (tasks.length) {
  759. await gljModel.bulkWrite(tasks);
  760. }
  761. }
  762. }
  763. export default GljDao;