gljModel.js 31 KB

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