gljModel.js 31 KB

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