ration_glj_facade.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. /**
  2. * Created by chen on 2017/6/29.
  3. */
  4. module.exports = {
  5. save: save,
  6. getData: getData,
  7. deleteByRation: deleteByRation,
  8. getQuantityByProjectGLJ: getQuantityByProjectGLJ,
  9. getLibInfo: getLibInfo,
  10. getLibOptions,
  11. getLibOptionsForCompilation,
  12. getGLJLib,
  13. getGLJData: getGLJData,
  14. getGLJDataPaging: getGLJDataPaging,
  15. getGLJDataByCodes:getGLJDataByCodes,
  16. addGLJ: addGLJ,
  17. deleteGLJ:deleteGLJ,
  18. insertAddTypeGLJ:insertAddTypeGLJ,
  19. replaceGLJ: replaceGLJ,
  20. replaceGLJByData:replaceGLJByData,
  21. mReplaceGLJ: mReplaceGLJ,
  22. updateRationGLJByEdit: updateRationGLJByEdit,
  23. getGLJClass: getGLJClass,
  24. insertGLJAsRation: insertGLJAsRation,
  25. getRationTypeGLJQuantity:getRationTypeGLJQuantity,
  26. getInfoFromProjectGLJ:getInfoFromProjectGLJ,
  27. createNewRecord:createNewRecord,
  28. getGLJSearchInfo:getGLJSearchInfo,
  29. updateRationGLJFromDoc:updateRationGLJFromDoc,
  30. getGLJLibByEngineerID:getGLJLibByEngineerID,
  31. prepareExtData:prepareExtData
  32. }
  33. let mongoose = require('mongoose');
  34. const uuidV1 = require('uuid/v1');
  35. let consts = require('../../main/models/project_consts')
  36. let commonConsts = consts.commonConst;
  37. let _ = require("lodash");
  38. let ration_glj = mongoose.model('ration_glj');
  39. const GLJListModel = require('../../glj/models/glj_list_model');
  40. let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
  41. let async_n = require("async");
  42. let ration = mongoose.model('ration');
  43. let ration_coe_facade = require('./ration_coe_facade');
  44. let ration_coe = mongoose.model('ration_coe');
  45. let std_ration_lib_ration_items = mongoose.model('std_ration_lib_ration_items');
  46. let glj_calculate_facade = require('./glj_calculate_facade');
  47. let glj_type_util = require('../../../public/cache/std_glj_type_util');
  48. let quantity_detail_facade = require('../../main/facade/quantity_detail_facade');
  49. let ration_installation_facade = require('../../main/facade/ration_installation_facade');
  50. let logger = require("../../../logs/log_helper").logger;
  51. const stdgljutil = require("../../../public/cache/std_glj_type_util");
  52. const EngineeringLibModel = require("../../users/models/engineering_lib_model");
  53. const GljDao = require("../../complementary_glj_lib/models/gljModel");
  54. const gljType = require("../../common/const/glj_type_const.js");
  55. const complementaryGljModel = mongoose.model('complementary_glj_lib');
  56. const stdGljModel = mongoose.model('std_glj_lib_gljList');
  57. const gljClassModel = mongoose.model('std_glj_lib_gljClass');
  58. const stdGLJLibModel = mongoose.model('std_glj_lib_map');
  59. const projectDao = require('../../pm/models/project_model').project;
  60. const compleClassModel = mongoose.model('complementary_glj_section');
  61. const stdRationLibModel = mongoose.model('std_ration_lib_map');
  62. const compilationModel = mongoose.model('compilation');
  63. const engineeringModel = mongoose.model('engineering_lib');
  64. let operationMap = {
  65. 'ut_create': create_ration_glj,
  66. 'ut_update': update_ration_glj,
  67. 'ut_delete': delete_ration_glj
  68. };
  69. let updateFunctionMap = {
  70. 'normalUpdate': normalUpdate
  71. };
  72. /**
  73. * 根据项目工料机ID和项目ID取消耗量
  74. *
  75. * @param {object} condition
  76. * @return Array
  77. */
  78. async function getQuantityByProjectGLJ(condition) {
  79. let query = {
  80. 'projectID': condition.projectID,
  81. };
  82. if(condition.projectGLJIDList){
  83. query['projectGLJID'] = {$in: condition.projectGLJIDList};
  84. }
  85. let startTime = +new Date();
  86. let results = await ration_glj.find(query, ['projectGLJID', 'quantity', 'rationID'], {sort: {projectGLJID: 1}});
  87. let rationList = _.uniq(_.map(results, 'rationID'));
  88. let getQuantity = +new Date();
  89. console.log("取工料机消耗量时间-----"+(getQuantity - startTime));
  90. let rationQuery = {
  91. 'projectID': condition.projectID,
  92. 'ID': {$in: rationList},
  93. 'deleteInfo': null
  94. };
  95. /* $and: [
  96. {'projectID': condition.projectID},
  97. {'ID': {$in: rationList}},
  98. {'deleteInfo': null}
  99. ]*/
  100. let rations = await ration.find(rationQuery, ['ID', 'quantity']);
  101. let rationsTime = +new Date();
  102. console.log("取定额消耗量时间-----"+(rationsTime - getQuantity));
  103. return combineQuantity(results, rations);
  104. }
  105. function combineQuantity(results, rations) {
  106. let resultList = [];
  107. let rationMap = _.indexBy(rations,'ID');
  108. for(let r of results){
  109. let tmp = {
  110. projectGLJID: r.projectGLJID,
  111. quantity: Number(r.quantity)
  112. }
  113. let ration = rationMap[r.rationID];//_.find(rations, {ID: r.rationID})
  114. if (ration) {
  115. tmp.rationID = ration.ID;
  116. tmp.rationQuantity = ration.quantity ? Number(ration.quantity) : undefined;
  117. }
  118. resultList.push(tmp);
  119. }
  120. return resultList;
  121. return resultList;
  122. }
  123. function get_lib_glj_info(ration_glj) {
  124. return function (result, cb) {
  125. std_glj_lib_gljList_model.findOne({'ID': ration_glj.GLJID}, (err, glj) => {
  126. if (err) {
  127. cb(err, '')
  128. } else if (glj) {
  129. ration_glj.name = glj.name;
  130. ration_glj.code = glj.code;
  131. ration_glj.original_code = glj.code;
  132. ration_glj.unit = glj.unit;
  133. ration_glj.specs = glj.specs;
  134. ration_glj.basePrice = glj.basePrice;
  135. ration_glj.marketPrice = glj.basePrice;
  136. ration_glj.taxRate = glj.taxRate;
  137. ration_glj.shortName = glj.shortName;
  138. ration_glj.type = glj.gljType;
  139. ration_glj.repositoryId = glj.repositoryId;
  140. ration_glj.adjCoe = glj.adjCoe;
  141. getInfoFromProjectGLJ(ration_glj).then(function (info) {
  142. if (info &&info.length>0) {
  143. let tem = {};
  144. tem.newRecode = createNewRecord(info[0]);
  145. tem.showData = info[0];
  146. result.datas.push(tem);
  147. cb(null, result);
  148. } else {
  149. cb(new Error('get project glj error'), null);
  150. }
  151. });
  152. } else {
  153. cb(null, result);
  154. }
  155. })
  156. }
  157. }
  158. function createNewRecord(ration_glj) {
  159. let newRecoed = {};
  160. newRecoed.ID = ration_glj.ID;
  161. newRecoed.projectID = ration_glj.projectID;
  162. newRecoed.GLJID = ration_glj.GLJID;
  163. newRecoed.rationID = ration_glj.rationID;
  164. newRecoed.rationItemQuantity = ration_glj.rationItemQuantity;
  165. newRecoed.quantity = ration_glj.quantity;
  166. newRecoed.name = ration_glj.name;
  167. newRecoed.code = ration_glj.code;
  168. newRecoed.original_code = ration_glj.original_code;
  169. newRecoed.unit = ration_glj.unit;
  170. newRecoed.specs = ration_glj.specs;
  171. newRecoed.from = ration_glj.from ? ration_glj.from : 'std';
  172. newRecoed.createType = ration_glj.createType ? ration_glj.createType : 'normal';
  173. newRecoed.shortName = ration_glj.shortName;
  174. newRecoed.billsItemID = ration_glj.billsItemID;
  175. newRecoed.type = ration_glj.type;
  176. newRecoed.model = ration_glj.model;
  177. newRecoed.repositoryId = ration_glj.repositoryId;
  178. newRecoed.projectGLJID = ration_glj.projectGLJID;
  179. newRecoed.adjCoe = ration_glj.adjCoe;
  180. if (ration_glj.fromUser) {
  181. newRecoed.fromUser = ration_glj.fromUser;
  182. }
  183. return newRecoed
  184. }
  185. async function getInfoFromProjectGLJ(ration_glj,unitPriceFileId,ext) {
  186. let data = getGLJSearchInfo(ration_glj);
  187. try {
  188. let projectGljModel = new GLJListModel();
  189. let result = await projectGljModel.addList(data,unitPriceFileId,ext);
  190. let typeString = result.type+"";
  191. ration_glj.marketPrice = result.unit_price.market_price;
  192. ration_glj.adjustPrice = result.unit_price.base_price;
  193. ration_glj.basePrice = result.unit_price.base_price;
  194. ration_glj.projectGLJID = result.id;
  195. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  196. ration_glj.isEstimate = result.is_evaluate;
  197. }
  198. if (result.hasOwnProperty('subList') && result.subList.length > 0) {
  199. ration_glj.subList = getMixRatioShowDatas(result.subList);
  200. }
  201. return [ration_glj,result];
  202. } catch (err) {
  203. logger.err(err);
  204. return null;
  205. }
  206. }
  207. function getMixRatioShowDatas(subList) {
  208. var temRationGLJs = [];
  209. for (let pg of subList) {
  210. var tem = {
  211. projectGLJID: pg.id,
  212. code: pg.code,
  213. name: pg.name,
  214. specs: pg.specs,
  215. unit: pg.unit,
  216. shortName: pg.unit_price.short_name,
  217. rationItemQuantity: pg.ratio_data.consumption,
  218. basePrice: pg.unit_price.base_price,
  219. marketPrice: pg.unit_price.market_price,
  220. adjustPrice: pg.adjust_price,
  221. isEstimate: pg.is_evaluate,
  222. isMixRatio: true,
  223. isAdd: pg.unit_price.is_add,
  224. GLJID: pg.glj_id
  225. }
  226. temRationGLJs.push(tem);
  227. }
  228. temRationGLJs = _.sortBy(temRationGLJs, 'code');
  229. return temRationGLJs;
  230. }
  231. function create_ration_glj(user_id, datas) {
  232. return function (callback) {
  233. let ration_glj_list = datas.ration_glj_list;
  234. var tasks = [];
  235. tasks.push(startingTask("get glj info"))
  236. for (let i = 0; i < ration_glj_list.length; i++) {
  237. ration_glj_list[i].ID = uuidV1();
  238. tasks.push(get_lib_glj_info(ration_glj_list[i]))
  239. }
  240. async_n.waterfall(tasks, (err, results) => {
  241. if (err) {
  242. callback(err, results)
  243. } else {
  244. let newRecords = [];
  245. let showDatas = [];
  246. for (let r of results.datas) {
  247. if (r) {
  248. newRecords.push(r.newRecode);
  249. showDatas.push(r.showData);
  250. }
  251. }
  252. if (newRecords.length > 0) {
  253. ration_glj.insertMany(newRecords, (err, doc) => {
  254. if (err) {
  255. callback(err, null);
  256. } else {
  257. let returndata = {
  258. updateTpye: commonConsts.UT_CREATE,
  259. moduleName: 'ration_glj',
  260. data: {
  261. newRecords: newRecords,
  262. showDatas: showDatas
  263. }
  264. }
  265. callback(null, returndata)
  266. }
  267. });
  268. } else {
  269. logger.info("can't find gljs")
  270. callback(null, null)
  271. }
  272. }
  273. })
  274. }
  275. }
  276. function update_ration_glj(user_id, datas) {
  277. if (datas.updateFunction) {
  278. return updateFunctionMap[datas.updateFunction](user_id, datas);
  279. } else {
  280. return normalUpdate(user_id, datas);
  281. }
  282. }
  283. function normalUpdate(user_id, datas) {
  284. return function (callback) {
  285. ration_glj.update(datas.query, datas.doc, (err, result) => {
  286. if (err) {
  287. callback(err, '');
  288. } else {
  289. let returndata = {
  290. moduleName: 'ration_glj',
  291. data: {
  292. updateTpye: commonConsts.UT_UPDATE,
  293. query: datas.query,
  294. doc: datas.doc
  295. }
  296. }
  297. callback(null, returndata)
  298. }
  299. })
  300. }
  301. }
  302. async function doCustomQuantityUpdate(datas) {
  303. let result = await ration_glj.findOneAndUpdate(datas.query, datas.doc);
  304. let cal_result = await glj_calculate_facade.calculateQuantity({
  305. projectID: datas.query.projectID,
  306. rationID: datas.query.rationID
  307. });
  308. cal_result.glj_result.forEach(function (item) {
  309. if (!item.doc.hasOwnProperty('customQuantity')) {
  310. item.doc.customQuantity = null;
  311. }
  312. });
  313. return cal_result;
  314. }
  315. function delete_ration_glj(user_id, datas) {
  316. return function (callback) {
  317. deleteByID(datas, callback);
  318. //callback(new Error("删除子数据失败!"),null)
  319. //这个方法已经不用,先注释,稳定后再删除
  320. /* if (datas.deleteType == "RATION") {
  321. deleteByRation(datas, callback);
  322. } else if (datas.deleteType == "BILL") {
  323. deleteByBill(user_id, datas, callback);
  324. } else {
  325. deleteByID(datas, callback);
  326. }*/
  327. }
  328. }
  329. function deleteByRation(datas, callback) {
  330. let data = datas.updateData;
  331. let tasks = [];
  332. tasks.push(deleteGLJList(data));
  333. tasks.push(ration_coe_facade.delete_ration_coe(data));
  334. tasks.push(quantity_detail_facade.deleteByRation(data));
  335. tasks.push(ration_installation_facade.deleteByRation(data));
  336. async_n.parallel(tasks, function (err, result) {
  337. commonCallback(callback, result, err)
  338. })
  339. }
  340. function deleteGLJList(data) {
  341. return function (callback) {
  342. ration_glj.deleteMany({projectID: data.projectID, rationID: data.ID}, (err, result) => {
  343. commonCallback(callback, result, err)
  344. });
  345. }
  346. }
  347. function deleteByBill(user_id, datas, callback) {
  348. let tasks = [];
  349. tasks.push(startingTask("deleteByBill"));
  350. tasks.push(getRationsByBill(datas));
  351. tasks.push(deleteRationsbyBill(user_id, datas));
  352. tasks.push(deleteByMultiRations(datas));
  353. async_n.waterfall(tasks, function (err, results) {
  354. if (err) {
  355. callback(err, '');
  356. } else {
  357. callback(null, results);
  358. }
  359. })
  360. }
  361. function deleteByID(datas, callback) {
  362. deleteAndUpdateState(datas).then(function (result) {
  363. if (result.err) {
  364. callback(result.err, '');
  365. } else {
  366. let returndata = {
  367. moduleName: 'ration_glj',
  368. data: {
  369. updateTpye: commonConsts.UT_DELETE,
  370. query: datas.query,
  371. adjustState: result.adjustState
  372. }
  373. }
  374. callback(null, returndata)
  375. }
  376. })
  377. }
  378. async function deleteGLJ(IDs) {
  379. await ration_glj.deleteMany({'ID': {$in: IDs}});
  380. }
  381. async function deleteAndUpdateState(datas) {
  382. let result = {
  383. err: null
  384. }
  385. try {
  386. await ration_glj.deleteOne(datas.query);
  387. let stateResult = await glj_calculate_facade.calculateQuantity({
  388. projectID: datas.query.projectID,
  389. rationID: datas.doc.rationID
  390. });
  391. result.adjustState = stateResult.adjustState;
  392. } catch (err) {
  393. result.err = err;
  394. }
  395. return result;
  396. }
  397. function startingTask(processName) {
  398. return function (asyncCallBack) {
  399. var result = {
  400. processName: processName,
  401. datas: []
  402. };
  403. asyncCallBack(null, result);
  404. };
  405. }
  406. function getRationsByBill(datas) {
  407. return function (results, callback) {
  408. ration.find({
  409. projectID: datas.updateData.projectID,
  410. billsItemID: datas.updateData.ID
  411. }, function (err, rations) {
  412. if (err) {
  413. callback(err, '')
  414. } else {
  415. results.rations = rations;
  416. callback(null, results)
  417. }
  418. })
  419. }
  420. }
  421. function deleteRationsbyBill(user_id, datas) {
  422. return function (results, callback) {
  423. let deleteInfo = {
  424. deleteInfo: {deleted: true, deleteDateTime: new Date(), deleteBy: user_id}
  425. };
  426. ration.update({
  427. projectID: datas.updateData.projectID,
  428. billsItemID: datas.updateData.ID
  429. }, deleteInfo, {multi: true}, (err, deleteresults) => {
  430. if (err) {
  431. callback(err, '');
  432. } else {
  433. callback(null, results);
  434. }
  435. });
  436. }
  437. }
  438. function deleteByMultiRations(datas) {
  439. return function (results, deleteCallBack) {
  440. var delete_tasks = [];
  441. var deleteOne = function (ration) {
  442. return function (callback) {
  443. ration_glj.deleteMany({projectID: ration.projectID, rationID: ration.ID}, function (err, result) {
  444. commonCallback(callback, result, err)
  445. });
  446. }
  447. }
  448. let rations = results.rations;
  449. for (let i = 0; i < rations.length; i++) {
  450. delete_tasks.push(deleteOne(rations[i]._doc));
  451. delete_tasks.push(ration_coe_facade.delete_ration_coe(rations[i]._doc));
  452. delete_tasks.push(quantity_detail_facade.deleteByRation(rations[i]._doc));
  453. delete_tasks.push(ration_installation_facade.deleteByRation(rations[i]._doc));
  454. }
  455. delete_tasks.push(quantity_detail_facade.deleteByBill(datas.updateData));
  456. async_n.parallel(delete_tasks, (err, results) => {
  457. if (err) {
  458. deleteCallBack(err, '')
  459. } else {
  460. deleteCallBack(null, results)
  461. }
  462. })
  463. }
  464. }
  465. /*
  466. function deleteByRation(doc) {
  467. return function (callback){
  468. ration_glj.deleteMany({projectID: doc.updateData.projectID, rationID: doc.updateData.ID},callback);
  469. }
  470. }
  471. */
  472. function save(user_id, datas, callback) {
  473. let operations = [];
  474. if (_.isArray(datas)) {
  475. for (let i = 0; i < datas.length; i++) {
  476. operations.push(operationMap[datas[i].updateType](user_id, datas[i]));
  477. }
  478. } else {
  479. operations.push(operationMap[datas.updateType](user_id, datas));
  480. }
  481. async_n.parallel(operations, function (err, results) {
  482. if (err) {
  483. callback(err, '');
  484. } else {
  485. if (results.length == 1) {
  486. callback(null, results[0])
  487. } else {
  488. callback(null, results)
  489. }
  490. }
  491. })
  492. }
  493. async function getLibInfo(req) {
  494. let gljLibId = null, engineerID, sessionCompilation = req.session.sessionCompilation;
  495. engineerID = req.params.engineerID;
  496. if(engineerID){
  497. gljLibId = await getGLJLibByEngineerID(engineerID);
  498. }else {
  499. throw new Error("工程专业ID为空!");
  500. }
  501. let data = {
  502. userID: req.session.sessionUser.id,
  503. gljLibId: gljLibId,
  504. compilationId: sessionCompilation._id
  505. };
  506. return data;
  507. }
  508. async function getGLJLib(query) {
  509. return stdGLJLibModel.findOne(query);
  510. }
  511. async function getGLJLibByEngineerID (engineerID) {
  512. let engineeringLibModel = new EngineeringLibModel() ;
  513. let engineeringInfo = await engineeringLibModel.findDataByCondition({'_id': engineerID});
  514. let gljLibId = engineeringInfo.glj_lib.length > 0 && typeof engineeringInfo.glj_lib !== 'undefined' ? engineeringInfo.glj_lib[0].id : null;
  515. return gljLibId
  516. }
  517. // 获取人材机选择页面,可选的定额库-人材机库映射选项
  518. async function getLibOptions(engineerID) {
  519. // 找到工程专业绑定的定额库,再获取这些定额库引用的人材机库
  520. const engineeringLibModel = new EngineeringLibModel();
  521. const engineeringInfo = await engineeringLibModel.findDataByCondition({ _id: engineerID });
  522. const rationLibs = engineeringInfo.ration_lib;
  523. const rationLibIDs = rationLibs.map(lib => lib.id);
  524. const rationLibData = await stdRationLibModel.find({ ID: { $in: rationLibIDs } }, 'ID gljLib').lean();
  525. const rst = [];
  526. rationLibs.forEach(lib => {
  527. rationLibData.forEach(stdLib => {
  528. if (+lib.id === +stdLib.ID) {
  529. lib.gljLibId = stdLib.gljLib;
  530. rst.push(lib);
  531. }
  532. });
  533. });
  534. return rst;
  535. }
  536. // 获取人材机选择库页面,可选的定额库为费用定额下,所有工程专业的定额库(需要去重)
  537. async function getLibOptionsForCompilation(compilationId) {
  538. const compilation = await compilationModel.findOne({ _id: mongoose.Types.ObjectId(compilationId) }, 'ration_valuation bill_valuation');
  539. const valuationIDs = [];
  540. if (compilation.ration_valuation[0] && compilation.ration_valuation[0].enable) {
  541. valuationIDs.push(compilation.ration_valuation[0].id);
  542. }
  543. if (compilation.bill_valuation[0] && compilation.bill_valuation[0].enable) {
  544. valuationIDs.push(compilation.bill_valuation[0].id);
  545. }
  546. const engineeringLibs = await engineeringModel.find({ valuationID: { $in: valuationIDs }, visible: true }, 'ration_lib');
  547. const rationLibs = [];
  548. const rationLibIDs = [];
  549. let hasDefalut = false;
  550. engineeringLibs.forEach(lib => {
  551. lib.ration_lib.forEach(rLib => {
  552. if (!rationLibIDs.includes(rLib.id)) {
  553. rationLibIDs.push(rLib.id);
  554. rationLibs.push({
  555. isDefault: hasDefalut ? false: rLib.isDefault,
  556. name: rLib.name,
  557. id: rLib.id
  558. });
  559. if (rLib.isDefault) {
  560. hasDefalut = true;
  561. }
  562. }
  563. });
  564. });
  565. const stdRationLibs = await stdRationLibModel.find({ ID: { $in: rationLibIDs } }, 'ID gljLib').lean();
  566. rationLibs.forEach(lib => {
  567. stdRationLibs.forEach(stdLib => {
  568. if (+lib.id === +stdLib.ID) {
  569. lib.gljLibId = stdLib.gljLib;
  570. }
  571. });
  572. });
  573. return rationLibs;
  574. }
  575. async function getGLJDataPaging(info, condition) {
  576. let gljDao = new GljDao();
  577. let rst = {};
  578. // 初始化,需要生成分类树和类型数据
  579. if (condition.init) {
  580. rst.treeData = await gljDao.getMixedTree(info.gljLibId, info.userID, info.compilationId);
  581. rst.distTypeTree = stdgljutil.getStdGljTypeCacheObj().toArray();
  582. }
  583. let gljData = await gljDao.getGLJPaging({...info, ...condition});
  584. Object.assign(rst, gljData);
  585. return rst;
  586. }
  587. function getGLJData(info, callback) {
  588. let gljDao = new GljDao();
  589. let datas = {};
  590. let gljDistTypeCache = stdgljutil.getStdGljTypeCacheObj().toArray();
  591. datas.distTypeTree = gljDistTypeCache;
  592. async_n.parallel([
  593. async function (cb) {
  594. try {
  595. datas.treeData = await gljDao.getMixedTree(info.gljLibId, info.userID, info.compilationId);
  596. cb(null);
  597. } catch (err) {
  598. cb(err);
  599. }
  600. },
  601. function (cb) {
  602. if (info.skipGLJ) {
  603. datas.stdGLJ = [];
  604. datas.complementaryGLJs = [];
  605. cb(null);
  606. return;
  607. }
  608. gljDao.getGljItems(info.gljLibId, info.userID, info.compilationId, {_id: 0}, function (err, data) {
  609. if (err) {
  610. cb(err);
  611. } else {
  612. datas.stdGLJ = data.stdGljs;
  613. datas.complementaryGLJs = data.complementaryGljs;
  614. cb(null);
  615. }
  616. });
  617. }
  618. ], function (err) {
  619. if (err) {
  620. callback(true, null);
  621. }
  622. else {
  623. callback(false, datas);
  624. }
  625. })
  626. }
  627. function getGLJSearchInfo(ration_glj) {
  628. let data = {
  629. glj_id: ration_glj.GLJID,
  630. project_id: ration_glj.projectID,
  631. code: ration_glj.code,
  632. original_code: ration_glj.original_code,
  633. name: ration_glj.name,
  634. //shortName: ration_glj.shortName,
  635. specs: ration_glj.specs,
  636. unit: ration_glj.unit,
  637. type: ration_glj.subType ? ration_glj.subType : ration_glj.type,//如果有subType,则是通过插入定额级的工料机进来的
  638. model: ration_glj.model,
  639. type_of_work: ration_glj.subType ? ration_glj.subType : ration_glj.type,
  640. base_price: ration_glj.basePrice,
  641. market_price: ration_glj.marketPrice,
  642. taxRate:ration_glj.taxRate,//税率
  643. repositoryId: ration_glj.repositoryId,
  644. adjCoe: ration_glj.adjCoe,
  645. materialType:ration_glj.materialType,
  646. materialCoe:ration_glj.materialCoe,
  647. materialIndexType:ration_glj.materialIndexType,
  648. materialIndexUnit:ration_glj.materialIndexUnit,
  649. is_evaluate:ration_glj.isEstimate?ration_glj.isEstimate:0,
  650. is_eval_material:0,
  651. no_tax_eqp:0,
  652. is_adjust_price:0,
  653. is_main_material:0,
  654. is_contractor_material:0,
  655. supply_quantity:0,
  656. supply:0,
  657. materialIndexCoe:ration_glj.materialIndexCoe,
  658. from: ration_glj.from ? ration_glj.from : 'std',//std:标准工料机库, cpt:补充工料机库
  659. fromUser: ration_glj.fromUser,
  660. };
  661. let glj_type_object = glj_type_util.getStdGljTypeCacheObj();
  662. let type = glj_type_object.getItemById(data.type);
  663. data.shortName = type.shortName;
  664. if (data.from == 'cpt') {//从补充工料机来的数据即为新增数据
  665. data.is_add = 1;
  666. }
  667. return data;
  668. }
  669. async function prepareExtData(projectID,compilation) {
  670. let ext , unitFileId ;
  671. let property = await projectDao.getProjectProperty(projectID);
  672. ext = projectDao.getExtendData(property,compilation);
  673. unitFileId = property.unitPriceFile !== undefined ? property.unitPriceFile.id : 0;
  674. return [unitFileId,ext];
  675. }
  676. async function addGLJ(rgList,compilation) {
  677. if (rgList.length <= 0) return {};
  678. let [newRecodes,projectGLJList] = await insertAddTypeGLJ(rgList,compilation);
  679. let stateResult = await glj_calculate_facade.calculateQuantity({
  680. projectID: rgList[0].projectID,
  681. rationID: rgList[0].rationID
  682. });
  683. let result = {
  684. newRecodes: newRecodes,
  685. projectGLJList:projectGLJList,
  686. showData: rgList,
  687. adjustState: stateResult.adjustState
  688. };
  689. return result;
  690. }
  691. async function insertAddTypeGLJ(rgList,compilation) {
  692. let newRecodes = [];
  693. let projectGLJList = [];
  694. let [unitFileId,ext] = await prepareExtData(rgList[0].projectID,compilation);
  695. for (let g of rgList) {
  696. let projectGljModel = new GLJListModel();
  697. let result = await projectGljModel.addList(getGLJSearchInfo(g),unitFileId,ext);
  698. let typeString = result.type+'';
  699. g.marketPrice = result.unit_price.market_price;
  700. g.adjustPrice = result.unit_price.base_price;
  701. g.basePrice = result.unit_price.base_price;
  702. g.isAdd = result.unit_price.is_add;
  703. g.projectGLJID = result.id;
  704. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  705. g.isEstimate = result.is_evaluate;
  706. }
  707. g.ID = uuidV1();
  708. if (result.hasOwnProperty('subList') && result.subList.length > 0) {
  709. g.subList = getMixRatioShowDatas(result.subList);
  710. }
  711. newRecodes.push(createNewRecord(g));
  712. projectGLJList.push(result);
  713. }
  714. await ration_glj.insertMany(newRecodes);
  715. return [newRecodes,projectGLJList];
  716. }
  717. async function replaceGLJByData(data,compilation) {
  718. let projectGljModel = new GLJListModel();
  719. let [unitFileId,ext] = await prepareExtData(data.projectID,compilation);
  720. let result = await projectGljModel.addList(getGLJSearchInfo(data),unitFileId,ext);
  721. let typeString = result.type+'';
  722. data.projectGLJID = result.id;
  723. let updateResult = await ration_glj.findOneAndUpdate({ID: data.ID, projectID: data.projectID}, data);//更新定额工料机
  724. //组装回传数据
  725. data.marketPrice = result.unit_price.market_price;
  726. data.adjustPrice = result.unit_price.base_price;
  727. data.basePrice = result.unit_price.base_price;
  728. data.isAdd = result.unit_price.is_add;
  729. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  730. data.isEstimate = result.is_evaluate;
  731. }
  732. /* if (result.hasOwnProperty('subList') && result.subList.length > 0) {
  733. data.subList = getMixRatioShowDatas(result.subList);
  734. } */
  735. return [data,result];
  736. }
  737. async function replaceGLJ(data,compilation) {
  738. let rdata = {};
  739. let [tdata,projectGLJ] = await replaceGLJByData(data,compilation);
  740. let stateResult = await glj_calculate_facade.calculateQuantity({
  741. projectID: tdata.projectID,
  742. rationID: tdata.rationID
  743. }, true,true);
  744. rdata.data = tdata;
  745. rdata.adjustState = stateResult.adjustState;
  746. rdata.name = stateResult.rationName;
  747. rdata.projectGLJ = projectGLJ;
  748. return rdata;
  749. }
  750. async function mReplaceGLJ(data,compilation) {
  751. let mresult = {};
  752. let projectGljModel = new GLJListModel();
  753. let [unitFileId,ext] = await prepareExtData(data.doc.projectID,compilation);
  754. //
  755. let result = await projectGljModel.addList(getGLJSearchInfo(data.doc),unitFileId,ext);
  756. let typeString = result.type+'';
  757. let newDoc = {};
  758. newDoc.projectGLJID = result.id;
  759. let rationList = await ration_glj.distinct('rationID', data.query);
  760. for(let t of data.tasks){
  761. t.updateOne.update.projectGLJID = result.id;//更新项目工料机ID
  762. }
  763. await ration_glj.bulkWrite(data.tasks);
  764. //let updateResult = await ration_glj.update(data.query, data.doc, {multi: true});
  765. newDoc.marketPrice = result.unit_price.market_price;
  766. newDoc.adjustPrice = result.unit_price.base_price;
  767. newDoc.basePrice = result.unit_price.base_price;
  768. newDoc.isAdd = result.unit_price.is_add;
  769. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  770. newDoc.isEstimate = result.is_evaluate;
  771. }
  772. if (result.hasOwnProperty('subList') && result.subList.length > 0) {
  773. newDoc.subList = getMixRatioShowDatas(result.subList);
  774. }
  775. let stateList = await changAdjustState(data, rationList);
  776. data.doc = newDoc;
  777. mresult.data = data;
  778. mresult.stateList = stateList;
  779. mresult.projectGLJ = result;
  780. return mresult
  781. }
  782. async function updateRationGLJByEdit(data) {
  783. var doc = data.doc;
  784. var result;
  785. if (doc.hasOwnProperty('customQuantity')) {
  786. result = await doCustomQuantityUpdate(data)
  787. } else {
  788. result = await doRationGLJUpdate(data);
  789. }
  790. return result;
  791. }
  792. async function updateRationGLJFromDoc(rg,doc,priceInfo) {
  793. let gljListModel = new GLJListModel();
  794. let projectGLJ = getGLJSearchInfo(rg);
  795. for (let key in doc) {
  796. projectGLJ[key] = doc[key]
  797. }
  798. projectGLJ.base_price = priceInfo.base_price;
  799. projectGLJ.market_price = priceInfo.market_price;
  800. projectGLJ.taxRate = priceInfo.taxRate;
  801. let projcetGLJ_n = await gljListModel.modifyGLJ(projectGLJ, rg);
  802. doc.code = projcetGLJ_n.code;
  803. doc.projectGLJID = projcetGLJ_n.id;
  804. if(rg.createType == 'replace'&& rg.rcode == projcetGLJ_n.code){//如果原数据已经是替换过的,这次替换又恢复成原数据,则把类型改回来
  805. doc.createType = 'normal';
  806. }
  807. if (rg.createType===undefined || rg.createType == 'normal'){// createTypel 默认是normal 只有是定额下带的工料机才需把类型改成替换,其它的保持不变
  808. if(rg.code != projcetGLJ_n.code){
  809. doc.createType = 'replace';
  810. doc.rcode = rg.code;
  811. }
  812. }
  813. await ration_glj.findOneAndUpdate({ID:rg.ID}, doc);
  814. return [projcetGLJ_n,doc]
  815. }
  816. async function doRationGLJUpdate(data) {
  817. let resutl = {};
  818. let priceInfo = data.priceInfo;
  819. let rg = await ration_glj.findOne(data.query);
  820. let [projcetGLJ_n,doc] = await updateRationGLJFromDoc(rg,data.doc,priceInfo);
  821. //取价格
  822. let gljListModel = new GLJListModel();
  823. gljListModel.getGLJPrice(projcetGLJ_n);
  824. doc.basePrice = projcetGLJ_n.unit_price.base_price;
  825. doc.marketPrice = projcetGLJ_n.unit_price.market_price;
  826. doc.adjustPrice = projcetGLJ_n.adjust_price;
  827. doc.taxRate = projcetGLJ_n.unit_price.taxRate;
  828. doc.isAdd = projcetGLJ_n.unit_price.is_add;
  829. resutl.doc = doc;
  830. let stateResult = await glj_calculate_facade.calculateQuantity({
  831. projectID: data.query.projectID,
  832. rationID: data.query.rationID
  833. },null,true);
  834. resutl.adjustState = stateResult.adjustState;
  835. resutl.name = stateResult.rationName;
  836. return resutl;
  837. }
  838. async function getGLJClass(info, data) {
  839. let result = {
  840. exist: false
  841. }
  842. //检查补充工料机中是否已经存在一样的记录了
  843. let condition = {
  844. userId: info.userID,
  845. compilationId: info.compilationId,
  846. code: data.code,
  847. name: data.name,
  848. unit: data.unit,
  849. gljType: data.type,
  850. basePrice: data.basePrice
  851. }
  852. if (data.specs != null && data.specs != undefined && data.specs != '') {
  853. condition['specs'] = data.specs;
  854. }
  855. let glj = await complementaryGljModel.find(condition);
  856. if (glj.length > 0) { //如果已存在就直接返回,不用再新增了
  857. result.exist = true;
  858. return result
  859. }
  860. //查找工料机类型树
  861. let items = await compleClassModel.find({
  862. userId: info.userID,
  863. compilationId: info.compilationId
  864. });
  865. result.items = items;
  866. return result;
  867. }
  868. async function insertGLJAsRation(data,compilation) {
  869. let gljList = data.gljList;
  870. if (data.hasOwnProperty("selectedSerialNo")) { //如果需要,更新序列号。
  871. let query = {
  872. projectID: data.projectID,
  873. billsItemID: data.billsItemID,
  874. serialNo: {$gt: data.selectedSerialNo}
  875. }
  876. await ration.update(query, {$inc: {serialNo: gljList.length}}, {multi: true});
  877. }
  878. let [unitFileId,ext] = await prepareExtData(data.projectID,compilation);
  879. for (let glj of gljList) {
  880. let p_glj = getGLJSearchInfo(glj);
  881. let projectGljModel = new GLJListModel();
  882. let result = await projectGljModel.addList(p_glj,unitFileId,ext);//逐条添加到项目工料机
  883. let typeString = result.type+'';
  884. glj.marketPrice = result.unit_price.market_price;
  885. glj.adjustPrice = result.unit_price.base_price;
  886. glj.basePrice = result.unit_price.base_price;
  887. glj.isAdd = result.unit_price.is_add;
  888. glj.projectGLJID = result.id;
  889. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  890. glj.isEstimate = result.is_evaluate;
  891. }
  892. }
  893. await ration.insertMany(gljList);
  894. return gljList;
  895. }
  896. async function getRationTypeGLJQuantity(projectID) {
  897. let rations = await ration.find({'projectID': projectID,'type':3,'deleteInfo': null}, ['ID', 'projectGLJID','quantity']);
  898. return rations;
  899. }
  900. async function changAdjustState(data, rationList) {
  901. let stateList = [];
  902. for (let r of rationList) {
  903. let stateResult = await glj_calculate_facade.calculateQuantity({
  904. projectID: data.query.projectID,
  905. rationID: r
  906. }, true,true);
  907. if(stateResult){
  908. stateList.push({rationID: r, adjustState: stateResult.adjustState,name:stateResult.rationName});
  909. }
  910. }
  911. return stateList;
  912. }
  913. async function getGLJDataByCodes(data,compilation) {
  914. let gljLibId = await getGLJLibByEngineerID(data.engineerID);
  915. let gljDatas = [];
  916. if(gljLibId){
  917. let stdList = await std_glj_lib_gljList_model.find({'repositoryId':gljLibId,code:{'$in':data.codes}});
  918. if(stdList.length > 0){
  919. let property = await projectDao.getProjectProperty(data.projectID);
  920. let ext = projectDao.getExtendData(property,compilation);//多单价处理
  921. for(let s of stdList){
  922. let tem = JSON.parse(JSON.stringify(s));
  923. if(ext && ext.priceField && tem && tem.priceProperty && tem.priceProperty[ext.priceField] !== null && tem.priceProperty[ext.priceField] !== undefined){
  924. tem.basePrice = tem.priceProperty[ext.priceField];
  925. }
  926. gljDatas.push(tem);
  927. }
  928. }
  929. }
  930. return gljDatas
  931. }
  932. async function testError() {
  933. throw new Error('test Error');
  934. }
  935. function getData(projectID, callback, isReport) {
  936. function findRation(rations, ID) {
  937. let ration = rations.find(function getElement(element) {
  938. return element.ID == ID;
  939. });
  940. return ration && ration._doc;
  941. };
  942. ration_glj.find({'projectID': projectID}, (err, datas) => {
  943. if (err) {
  944. callback(1, '', null);
  945. } else {
  946. if (isReport) { // 调价中间件机制
  947. ration.find({'projectID': projectID}, ['ID', 'code', 'name', 'quantityCoe', 'quantity', 'rationQuantityCoe'],
  948. function cbData(err, rations) {
  949. if (!err) {
  950. for (let i = 0; i < datas.length; i++) {
  951. let glj = datas[i]._doc;
  952. let ration = findRation(rations, glj.rationID);
  953. let coe = 1;
  954. if (ration && ration.quantityCoe){
  955. if ([gljType.LABOUR].includes(glj.type)){
  956. if (ration.quantityCoe._doc.labour)
  957. coe = ration.quantityCoe._doc.labour;
  958. }
  959. else if (
  960. [gljType.GENERAL_MATERIAL,
  961. gljType.CONCRETE,
  962. gljType.MORTAR,
  963. gljType.MIX_RATIO,
  964. gljType.COMMERCIAL_CONCRETE,
  965. gljType.COMMERCIAL_MORTAR,
  966. gljType.OTHER_MATERIAL].includes(glj.type)){
  967. if (ration.quantityCoe._doc.material)
  968. coe = ration.quantityCoe._doc.material;
  969. }
  970. else if ([gljType.GENERAL_MACHINE,
  971. gljType.MACHINE_COMPOSITION,
  972. gljType.MACHINE_LABOUR].includes(glj.type)){
  973. if (ration.quantityCoe._doc.machine)
  974. coe = ration.quantityCoe._doc.machine;
  975. }
  976. else if ([gljType.MAIN_MATERIAL].includes(glj.type)){
  977. if (ration.quantityCoe._doc.main)
  978. coe = ration.quantityCoe._doc.main;
  979. }
  980. else if ([gljType.EQUIPMENT].includes(glj.type)){
  981. if (ration.quantityCoe._doc.equipment)
  982. coe = ration.quantityCoe._doc.equipment;
  983. };
  984. };
  985. if ((!coe) || (coe == '0')) coe = 1;
  986. glj.quantity = glj.quantity * coe;
  987. }
  988. }
  989. });
  990. };
  991. callback(0, consts.projectConst.RATION_GLJ, datas);
  992. }
  993. })
  994. }
  995. function commonCallback(callback, result, err) {
  996. if (err) {
  997. callback(err, '');
  998. } else {
  999. callback(null, result);
  1000. }
  1001. }