gljModel.js 30 KB

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