ration_glj_facade.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. /**
  2. * Created by chen on 2017/6/29.
  3. */
  4. module.exports = { //先 exports再require 防止循环引用
  5. save: save,
  6. getData: getData,
  7. deleteByRation: deleteByRation,
  8. getQuantityByProjectGLJ: getQuantityByProjectGLJ,
  9. getLibInfo: getLibInfo,
  10. getLibOptions,
  11. getLibOptionsForCompilation,
  12. getGLJData: getGLJData,
  13. getGLJDataByCodes: getGLJDataByCodes,
  14. addGLJ: addGLJ,
  15. deleteRationGLJ: deleteRationGLJ,
  16. deleteGLJ: deleteGLJ,
  17. insertAddTypeGLJ: insertAddTypeGLJ,
  18. replaceGLJ: replaceGLJ,
  19. replaceGLJByData: replaceGLJByData,
  20. mReplaceGLJ: mReplaceGLJ,
  21. updateRationGLJByEdit: updateRationGLJByEdit,
  22. getGLJClass: getGLJClass,
  23. insertGLJAsRation: insertGLJAsRation,
  24. getRationTypeGLJQuantity: getRationTypeGLJQuantity,
  25. getInfoFromProjectGLJ: getInfoFromProjectGLJ,
  26. createNewRecord: createNewRecord,
  27. getGLJSearchInfo: getGLJSearchInfo,
  28. updateRationGLJFromDoc: updateRationGLJFromDoc,
  29. getGLJLibByEngineerID: getGLJLibByEngineerID,
  30. prepareExtData: prepareExtData,
  31. setPropertyFromStd: setPropertyFromStd,
  32. updateProportion: updateProportion
  33. };
  34. let mongoose = require('mongoose');
  35. const uuidV1 = require('uuid/v1');
  36. let consts = require('../../main/models/project_consts')
  37. let commonConsts = consts.commonConst;
  38. let _ = require("lodash");
  39. let ration_glj = mongoose.model('ration_glj');
  40. const GLJListModel = require('../../glj/models/glj_list_model');
  41. let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
  42. let async_n = require("async");
  43. let ration = mongoose.model('ration');
  44. let ration_coe_facade = require('./ration_coe_facade');
  45. let ration_coe = mongoose.model('ration_coe');
  46. let std_ration_lib_ration_items = mongoose.model('std_ration_lib_ration_items');
  47. let glj_calculate_facade = require('./glj_calculate_facade');
  48. let glj_type_util = require('../../../public/cache/std_glj_type_util');
  49. let quantity_detail_facade = require('../../main/facade/quantity_detail_facade');
  50. let ration_installation_facade = require('../../main/facade/ration_installation_facade');
  51. let logger = require("../../../logs/log_helper").logger;
  52. const stdgljutil = require("../../../public/cache/std_glj_type_util");
  53. const EngineeringLibModel = require("../../users/models/engineering_lib_model");
  54. const GljDao = require("../../complementary_glj_lib/models/gljModel");
  55. const gljType = require("../../common/const/glj_type_const.js");
  56. const complementaryGljModel = mongoose.model('complementary_glj_lib');
  57. const stdGljModel = mongoose.model('std_glj_lib_gljList');
  58. const gljClassModel = mongoose.model('std_glj_lib_gljClass');
  59. const projectDao = require('../../pm/models/project_model').project;
  60. const pmFacade = require('../../pm/facade/pm_facade');
  61. const commonFacade = require('../../main/facade/common_facade');
  62. const compleClassModel = mongoose.model('complementary_glj_section');
  63. const stdRationLibModel = mongoose.model('std_ration_lib_map');
  64. const compilationModel = mongoose.model('compilation');
  65. const engineeringModel = mongoose.model('engineering_lib');
  66. let gljUtil = require('../../../public/gljUtil');
  67. let operationMap = {
  68. 'ut_create': create_ration_glj,
  69. 'ut_update': update_ration_glj,
  70. 'ut_delete': delete_ration_glj
  71. };
  72. let updateFunctionMap = {
  73. 'normalUpdate': normalUpdate
  74. };
  75. /**
  76. * 根据项目工料机ID和项目ID取消耗量
  77. *
  78. * @param {object} condition
  79. * @return Array
  80. */
  81. async function getQuantityByProjectGLJ(condition) {
  82. let query = {
  83. 'projectID': condition.projectID,
  84. };
  85. if (condition.projectGLJIDList) {
  86. query['projectGLJID'] = {
  87. $in: condition.projectGLJIDList
  88. };
  89. }
  90. let startTime = +new Date();
  91. let results = await ration_glj.find(query, ['projectGLJID', 'quantity', 'rationID'], {
  92. sort: {
  93. projectGLJID: 1
  94. }
  95. });
  96. let rationList = _.uniq(_.map(results, 'rationID'));
  97. let getQuantity = +new Date();
  98. console.log("取工料机消耗量时间-----" + (getQuantity - startTime));
  99. let rationQuery = {
  100. 'projectID': condition.projectID,
  101. 'ID': {
  102. $in: rationList
  103. },
  104. 'deleteInfo': null
  105. };
  106. /* $and: [
  107. {'projectID': condition.projectID},
  108. {'ID': {$in: rationList}},
  109. {'deleteInfo': null}
  110. ]*/
  111. let rations = await ration.find(rationQuery, ['ID', 'quantity']);
  112. let rationsTime = +new Date();
  113. console.log("取定额消耗量时间-----" + (rationsTime - getQuantity));
  114. return combineQuantity(results, rations);
  115. }
  116. function combineQuantity(results, rations) {
  117. let resultList = [];
  118. let rationMap = _.indexBy(rations, 'ID');
  119. for (let r of results) {
  120. let tmp = {
  121. projectGLJID: r.projectGLJID,
  122. quantity: Number(r.quantity)
  123. }
  124. let ration = rationMap[r.rationID]; //_.find(rations, {ID: r.rationID})
  125. if (ration) {
  126. tmp.rationID = ration.ID;
  127. tmp.rationQuantity = ration.quantity ? Number(ration.quantity) : undefined;
  128. }
  129. resultList.push(tmp);
  130. }
  131. return resultList;
  132. return resultList;
  133. }
  134. function get_lib_glj_info(ration_glj) {
  135. return function (result, cb) {
  136. std_glj_lib_gljList_model.findOne({
  137. 'ID': ration_glj.GLJID
  138. }, (err, glj) => {
  139. if (err) {
  140. cb(err, '')
  141. } else if (glj) {
  142. ration_glj.name = glj.name;
  143. ration_glj.code = glj.code;
  144. ration_glj.original_code = glj.code;
  145. ration_glj.unit = glj.unit;
  146. ration_glj.specs = glj.specs;
  147. ration_glj.basePrice = glj.basePrice;
  148. ration_glj.marketPrice = glj.basePrice;
  149. ration_glj.shortName = glj.shortName;
  150. ration_glj.type = glj.gljType;
  151. ration_glj.repositoryId = glj.repositoryId;
  152. ration_glj.adjCoe = glj.adjCoe;
  153. getInfoFromProjectGLJ(ration_glj).then(function (info) {
  154. if (info && info.length > 0) {
  155. let tem = {};
  156. tem.newRecode = createNewRecord(info[0]);
  157. tem.showData = info[0];
  158. result.datas.push(tem);
  159. cb(null, result);
  160. } else {
  161. cb(new Error('get project glj error'), null);
  162. }
  163. });
  164. } else {
  165. cb(null, result);
  166. }
  167. })
  168. }
  169. }
  170. function createNewRecord(ration_glj) {
  171. let newRecoed = {};
  172. newRecoed.ID = ration_glj.ID;
  173. newRecoed.projectID = ration_glj.projectID;
  174. newRecoed.GLJID = ration_glj.GLJID;
  175. newRecoed.rationID = ration_glj.rationID;
  176. newRecoed.rationItemQuantity = ration_glj.rationItemQuantity;
  177. newRecoed.customQuantity = ration_glj.customQuantity;
  178. newRecoed.quantity = ration_glj.quantity;
  179. newRecoed.rationProportion = ration_glj.rationProportion;
  180. newRecoed.adjustProportion = ration_glj.adjustProportion;
  181. newRecoed.name = ration_glj.name;
  182. newRecoed.code = ration_glj.code;
  183. newRecoed.original_code = ration_glj.original_code;
  184. newRecoed.unit = ration_glj.unit;
  185. newRecoed.specs = ration_glj.specs;
  186. newRecoed.from = ration_glj.from ? ration_glj.from : 'std';
  187. newRecoed.createType = ration_glj.createType ? ration_glj.createType : 'normal';
  188. newRecoed.shortName = ration_glj.shortName;
  189. newRecoed.billsItemID = ration_glj.billsItemID;
  190. newRecoed.type = ration_glj.type;
  191. newRecoed.model = ration_glj.model;
  192. newRecoed.repositoryId = ration_glj.repositoryId;
  193. newRecoed.projectGLJID = ration_glj.projectGLJID;
  194. newRecoed.adjCoe = ration_glj.adjCoe;
  195. return newRecoed
  196. }
  197. async function getInfoFromProjectGLJ(ration_glj, unitPriceFileId, ext) {
  198. let data = getGLJSearchInfo(ration_glj);
  199. try {
  200. let projectGljModel = new GLJListModel();
  201. let result = await projectGljModel.addList(data, unitPriceFileId, ext);
  202. let typeString = result.type + "";
  203. ration_glj.marketPrice = result.unit_price.market_price;
  204. ration_glj.adjustPrice = result.unit_price.base_price;
  205. ration_glj.basePrice = result.unit_price.base_price;
  206. ration_glj.projectGLJID = result.id;
  207. if (typeString.startsWith("2") || typeString == '4' || typeString == '5') { //只有材料类型才显示是否暂估
  208. ration_glj.isEstimate = result.is_evaluate;
  209. }
  210. if (result.hasOwnProperty('subList') && result.subList.length > 0) {
  211. ration_glj.subList = getMixRatioShowDatas(result.subList);
  212. }
  213. return [ration_glj, result];
  214. } catch (err) {
  215. logger.err(err);
  216. return null;
  217. }
  218. }
  219. function getMixRatioShowDatas(subList) {
  220. var temRationGLJs = [];
  221. for (let pg of subList) {
  222. var tem = {
  223. projectGLJID: pg.id,
  224. code: pg.code,
  225. name: pg.name,
  226. specs: pg.specs,
  227. unit: pg.unit,
  228. shortName: pg.unit_price.short_name,
  229. rationItemQuantity: pg.ratio_data.consumption,
  230. basePrice: pg.unit_price.base_price,
  231. marketPrice: pg.unit_price.market_price,
  232. adjustPrice: pg.adjust_price,
  233. isEstimate: pg.is_evaluate,
  234. isMixRatio: true,
  235. isAdd: pg.unit_price.is_add,
  236. GLJID: pg.glj_id
  237. }
  238. temRationGLJs.push(tem);
  239. }
  240. temRationGLJs = _.sortBy(temRationGLJs, 'code');
  241. return temRationGLJs;
  242. }
  243. function create_ration_glj(user_id, datas) {
  244. return function (callback) {
  245. let ration_glj_list = datas.ration_glj_list;
  246. var tasks = [];
  247. tasks.push(startingTask("get glj info"))
  248. for (let i = 0; i < ration_glj_list.length; i++) {
  249. ration_glj_list[i].ID = uuidV1();
  250. tasks.push(get_lib_glj_info(ration_glj_list[i]))
  251. }
  252. async_n.waterfall(tasks, (err, results) => {
  253. if (err) {
  254. callback(err, results)
  255. } else {
  256. let newRecords = [];
  257. let showDatas = [];
  258. for (let r of results.datas) {
  259. if (r) {
  260. newRecords.push(r.newRecode);
  261. showDatas.push(r.showData);
  262. }
  263. }
  264. if (newRecords.length > 0) {
  265. ration_glj.insertMany(newRecords, (err, doc) => {
  266. if (err) {
  267. callback(err, null);
  268. } else {
  269. let returndata = {
  270. updateTpye: commonConsts.UT_CREATE,
  271. moduleName: 'ration_glj',
  272. data: {
  273. newRecords: newRecords,
  274. showDatas: showDatas
  275. }
  276. }
  277. callback(null, returndata)
  278. }
  279. });
  280. } else {
  281. logger.info("can't find gljs")
  282. callback(null, null)
  283. }
  284. }
  285. })
  286. }
  287. }
  288. function update_ration_glj(user_id, datas) {
  289. if (datas.updateFunction) {
  290. return updateFunctionMap[datas.updateFunction](user_id, datas);
  291. } else {
  292. return normalUpdate(user_id, datas);
  293. }
  294. }
  295. function normalUpdate(user_id, datas) {
  296. return function (callback) {
  297. ration_glj.update(datas.query, datas.doc, (err, result) => {
  298. if (err) {
  299. callback(err, '');
  300. } else {
  301. let returndata = {
  302. moduleName: 'ration_glj',
  303. data: {
  304. updateTpye: commonConsts.UT_UPDATE,
  305. query: datas.query,
  306. doc: datas.doc
  307. }
  308. }
  309. callback(null, returndata)
  310. }
  311. })
  312. }
  313. }
  314. async function doCustomQuantityUpdate(datas) {
  315. let result = await ration_glj.findOneAndUpdate(datas.query, datas.doc);
  316. let cal_result = await glj_calculate_facade.calculateQuantity({
  317. projectID: datas.query.projectID,
  318. rationID: datas.query.rationID
  319. });
  320. cal_result.glj_result.forEach(function (item) {
  321. if (!item.doc.hasOwnProperty('customQuantity')) {
  322. item.doc.customQuantity = null;
  323. }
  324. });
  325. return cal_result;
  326. }
  327. function delete_ration_glj(user_id, datas) {
  328. return function (callback) {
  329. deleteByID(datas, callback);
  330. //callback(new Error("删除子数据失败!"),null)
  331. //这个方法已经不用,先注释,稳定后再删除
  332. /* if (datas.deleteType == "RATION") {
  333. deleteByRation(datas, callback);
  334. } else if (datas.deleteType == "BILL") {
  335. deleteByBill(user_id, datas, callback);
  336. } else {
  337. deleteByID(datas, callback);
  338. }*/
  339. }
  340. }
  341. function deleteByRation(datas, callback) {
  342. let data = datas.updateData;
  343. let tasks = [];
  344. tasks.push(deleteGLJList(data));
  345. tasks.push(ration_coe_facade.delete_ration_coe(data));
  346. tasks.push(quantity_detail_facade.deleteByRation(data));
  347. tasks.push(ration_installation_facade.deleteByRation(data));
  348. async_n.parallel(tasks, function (err, result) {
  349. commonCallback(callback, result, err)
  350. })
  351. }
  352. function deleteGLJList(data) {
  353. return function (callback) {
  354. ration_glj.deleteMany({
  355. projectID: data.projectID,
  356. rationID: data.ID
  357. }, (err, result) => {
  358. commonCallback(callback, result, err)
  359. });
  360. }
  361. }
  362. function deleteByBill(user_id, datas, callback) {
  363. let tasks = [];
  364. tasks.push(startingTask("deleteByBill"));
  365. tasks.push(getRationsByBill(datas));
  366. tasks.push(deleteRationsbyBill(user_id, datas));
  367. tasks.push(deleteByMultiRations(datas));
  368. async_n.waterfall(tasks, function (err, results) {
  369. if (err) {
  370. callback(err, '');
  371. } else {
  372. callback(null, results);
  373. }
  374. })
  375. }
  376. function deleteByID(datas, callback) {
  377. deleteAndUpdateState(datas).then(function (result) {
  378. if (result.err) {
  379. callback(result.err, '');
  380. } else {
  381. let returndata = {
  382. moduleName: 'ration_glj',
  383. data: {
  384. updateTpye: commonConsts.UT_DELETE,
  385. query: datas.query,
  386. adjustState: result.adjustState
  387. }
  388. }
  389. callback(null, returndata)
  390. }
  391. })
  392. }
  393. async function deleteGLJ(IDs) {
  394. await ration_glj.deleteMany({
  395. 'ID': {
  396. $in: IDs
  397. }
  398. });
  399. }
  400. async function deleteAndUpdateState(datas) {
  401. let result = {
  402. err: null
  403. }
  404. try {
  405. await ration_glj.deleteOne(datas.query);
  406. let stateResult = await glj_calculate_facade.calculateQuantity({
  407. projectID: datas.query.projectID,
  408. rationID: datas.doc.rationID
  409. });
  410. result.adjustState = stateResult.adjustState;
  411. } catch (err) {
  412. result.err = err;
  413. }
  414. return result;
  415. }
  416. function startingTask(processName) {
  417. return function (asyncCallBack) {
  418. var result = {
  419. processName: processName,
  420. datas: []
  421. };
  422. asyncCallBack(null, result);
  423. };
  424. }
  425. function getRationsByBill(datas) {
  426. return function (results, callback) {
  427. ration.find({
  428. projectID: datas.updateData.projectID,
  429. billsItemID: datas.updateData.ID
  430. }, function (err, rations) {
  431. if (err) {
  432. callback(err, '')
  433. } else {
  434. results.rations = rations;
  435. callback(null, results)
  436. }
  437. })
  438. }
  439. }
  440. function deleteRationsbyBill(user_id, datas) {
  441. return function (results, callback) {
  442. let deleteInfo = {
  443. deleteInfo: {
  444. deleted: true,
  445. deleteDateTime: new Date(),
  446. deleteBy: user_id
  447. }
  448. };
  449. ration.update({
  450. projectID: datas.updateData.projectID,
  451. billsItemID: datas.updateData.ID
  452. }, deleteInfo, {
  453. multi: true
  454. }, (err, deleteresults) => {
  455. if (err) {
  456. callback(err, '');
  457. } else {
  458. callback(null, results);
  459. }
  460. });
  461. }
  462. }
  463. function deleteByMultiRations(datas) {
  464. return function (results, deleteCallBack) {
  465. var delete_tasks = [];
  466. var deleteOne = function (ration) {
  467. return function (callback) {
  468. ration_glj.deleteMany({
  469. projectID: ration.projectID,
  470. rationID: ration.ID
  471. }, function (err, result) {
  472. commonCallback(callback, result, err)
  473. });
  474. }
  475. }
  476. let rations = results.rations;
  477. for (let i = 0; i < rations.length; i++) {
  478. delete_tasks.push(deleteOne(rations[i]._doc));
  479. delete_tasks.push(ration_coe_facade.delete_ration_coe(rations[i]._doc));
  480. delete_tasks.push(quantity_detail_facade.deleteByRation(rations[i]._doc));
  481. delete_tasks.push(ration_installation_facade.deleteByRation(rations[i]._doc));
  482. }
  483. delete_tasks.push(quantity_detail_facade.deleteByBill(datas.updateData));
  484. async_n.parallel(delete_tasks, (err, results) => {
  485. if (err) {
  486. deleteCallBack(err, '')
  487. } else {
  488. deleteCallBack(null, results)
  489. }
  490. })
  491. }
  492. }
  493. /*
  494. function deleteByRation(doc) {
  495. return function (callback){
  496. ration_glj.deleteMany({projectID: doc.updateData.projectID, rationID: doc.updateData.ID},callback);
  497. }
  498. }
  499. */
  500. function save(user_id, datas, callback) {
  501. let operations = [];
  502. if (_.isArray(datas)) {
  503. for (let i = 0; i < datas.length; i++) {
  504. operations.push(operationMap[datas[i].updateType](user_id, datas[i]));
  505. }
  506. } else {
  507. operations.push(operationMap[datas.updateType](user_id, datas));
  508. }
  509. async_n.parallel(operations, function (err, results) {
  510. if (err) {
  511. callback(err, '');
  512. } else {
  513. if (results.length == 1) {
  514. callback(null, results[0])
  515. } else {
  516. callback(null, results)
  517. }
  518. }
  519. })
  520. }
  521. async function getLibInfo(req) {
  522. let gljLibId = null,
  523. engineerID, sessionCompilation = req.session.sessionCompilation;
  524. engineerID = req.params.engineerID;
  525. if (engineerID) {
  526. gljLibId = await getGLJLibByEngineerID(engineerID);
  527. } else {
  528. throw new Error("工程专业ID为空!");
  529. }
  530. let data = {
  531. userID: req.session.sessionUser.id,
  532. gljLibId: gljLibId,
  533. compilationId: sessionCompilation._id
  534. };
  535. return data;
  536. }
  537. async function getGLJLibByEngineerID(engineerID) {
  538. let engineeringLibModel = new EngineeringLibModel();
  539. let engineeringInfo = await engineeringLibModel.findDataByCondition({
  540. '_id': engineerID
  541. });
  542. let gljLibId = engineeringInfo.glj_lib.length > 0 && typeof engineeringInfo.glj_lib !== 'undefined' ? engineeringInfo.glj_lib[0].id : null;
  543. return gljLibId
  544. }
  545. // 获取人材机选择页面,可选的定额库-人材机库映射选项
  546. async function getLibOptions(engineerID) {
  547. // 找到工程专业绑定的定额库,再获取这些定额库引用的人材机库
  548. const engineeringLibModel = new EngineeringLibModel();
  549. const engineeringInfo = await engineeringLibModel.findDataByCondition({
  550. _id: engineerID
  551. });
  552. const rationLibs = engineeringInfo.ration_lib;
  553. const rationLibIDs = rationLibs.map(lib => lib.id);
  554. const rationLibData = await stdRationLibModel.find({
  555. ID: {
  556. $in: rationLibIDs
  557. }
  558. }, 'ID gljLib').lean();
  559. const rst = [];
  560. rationLibs.forEach(lib => {
  561. rationLibData.forEach(stdLib => {
  562. if (+lib.id === +stdLib.ID) {
  563. lib.gljLibId = stdLib.gljLib;
  564. rst.push(lib);
  565. }
  566. });
  567. });
  568. return rst;
  569. }
  570. // 获取人材机选择库页面,可选的定额库为费用定额下,所有工程专业的定额库(需要去重)
  571. async function getLibOptionsForCompilation(compilationId) {
  572. const compilation = await compilationModel.findOne({
  573. _id: mongoose.Types.ObjectId(compilationId)
  574. }, 'ration_valuation bill_valuation');
  575. const valuationIDs = [];
  576. if (compilation.ration_valuation[0] && compilation.ration_valuation[0].enable) {
  577. valuationIDs.push(compilation.ration_valuation[0].id);
  578. }
  579. if (compilation.bill_valuation[0] && compilation.bill_valuation[0].enable) {
  580. valuationIDs.push(compilation.bill_valuation[0].id);
  581. }
  582. const engineeringLibs = await engineeringModel.find({
  583. valuationID: {
  584. $in: valuationIDs
  585. },
  586. visible: true
  587. }, 'ration_lib');
  588. const rationLibs = [];
  589. const rationLibIDs = [];
  590. let hasDefalut = false;
  591. engineeringLibs.forEach(lib => {
  592. lib.ration_lib.forEach(rLib => {
  593. if (!rationLibIDs.includes(rLib.id)) {
  594. rationLibIDs.push(rLib.id);
  595. rationLibs.push({
  596. isDefault: hasDefalut ? false : rLib.isDefault,
  597. name: rLib.name,
  598. id: rLib.id
  599. });
  600. if (rLib.isDefault) {
  601. hasDefalut = true;
  602. }
  603. }
  604. });
  605. });
  606. const stdRationLibs = await stdRationLibModel.find({
  607. ID: {
  608. $in: rationLibIDs
  609. }
  610. }, 'ID gljLib').lean();
  611. rationLibs.forEach(lib => {
  612. stdRationLibs.forEach(stdLib => {
  613. if (+lib.id === +stdLib.ID) {
  614. lib.gljLibId = stdLib.gljLib;
  615. }
  616. });
  617. });
  618. return rationLibs;
  619. }
  620. function getGLJData(info, callback) {
  621. let gljDao = new GljDao();
  622. let datas = {};
  623. let gljDistTypeCache = stdgljutil.getStdGljTypeCacheObj().toArray();
  624. datas.distTypeTree = gljDistTypeCache;
  625. async_n.parallel([
  626. async function (cb) {
  627. try {
  628. datas.treeData = await gljDao.getMixedTree(info.gljLibId, info.userID, info.compilationId);
  629. cb(null);
  630. } catch (err) {
  631. cb(err);
  632. }
  633. },
  634. function (cb) {
  635. gljDao.getGljItems(info.gljLibId, info.userID, info.compilationId, {
  636. _id: 0
  637. }, function (err, data) {
  638. if (err) {
  639. cb(err);
  640. } else {
  641. datas.stdGLJ = data.stdGljs;
  642. datas.complementaryGLJs = data.complementaryGljs;
  643. cb(null);
  644. }
  645. });
  646. }
  647. ], function (err) {
  648. if (err) {
  649. callback(true, null);
  650. } else {
  651. callback(false, datas);
  652. }
  653. })
  654. }
  655. function getGLJSearchInfo(ration_glj) {
  656. let data = {
  657. glj_id: ration_glj.GLJID,
  658. project_id: ration_glj.projectID,
  659. code: ration_glj.code,
  660. original_code: ration_glj.original_code,
  661. name: ration_glj.name,
  662. //shortName: ration_glj.shortName,
  663. specs: ration_glj.specs ? ration_glj.specs : '',
  664. unit: ration_glj.unit ? ration_glj.unit : '',
  665. type: ration_glj.subType ? ration_glj.subType : ration_glj.type, //如果有subType,则是通过插入定额级的工料机进来的
  666. model: ration_glj.model,
  667. type_of_work: ration_glj.subType ? ration_glj.subType : ration_glj.type,
  668. base_price: ration_glj.basePrice,
  669. market_price: ration_glj.marketPrice,
  670. repositoryId: ration_glj.repositoryId,
  671. adjCoe: ration_glj.adjCoe,
  672. materialType: ration_glj.materialType,
  673. is_main_material: ration_glj.is_main_material ? ration_glj.is_main_material : 1,
  674. materialCoe: ration_glj.materialCoe,
  675. grossWeightCoe: ration_glj.grossWeightCoe,
  676. purchaseStorageRate: ration_glj.purchaseStorageRate,
  677. offSiteTransportLossRate: ration_glj.offSiteTransportLossRate,
  678. handlingLossRate: ration_glj.handlingLossRate,
  679. is_adjust_price: 0,
  680. is_evaluate: 0,
  681. is_eval_material: 0,
  682. from: ration_glj.from ? ration_glj.from : 'std' //std:标准工料机库, cpt:补充工料机库
  683. };
  684. let glj_type_object = glj_type_util.getStdGljTypeCacheObj();
  685. let type = glj_type_object.getItemById(data.type);
  686. data.shortName = type.shortName;
  687. if (data.from == 'cpt') { //从补充工料机来的数据即为新增数据
  688. data.is_add = 1;
  689. }
  690. return data;
  691. }
  692. async function prepareExtData(projectID, compilation) {
  693. let ext, unitFileId;
  694. let property = await projectDao.getProjectProperty(projectID);
  695. ext = pmFacade.getExtendData(property, compilation);
  696. unitFileId = property.unitPriceFile !== undefined ? property.unitPriceFile.id : 0;
  697. return [unitFileId, ext];
  698. }
  699. function setPropertyFromStd(newGLJ, std_glj) {
  700. newGLJ.GLJID = std_glj.ID;
  701. newGLJ.name = std_glj.name;
  702. newGLJ.code = std_glj.code;
  703. newGLJ.original_code = std_glj.code;
  704. newGLJ.unit = std_glj.unit;
  705. newGLJ.specs = std_glj.specs;
  706. newGLJ.model = std_glj.model;
  707. newGLJ.basePrice = std_glj.basePrice;
  708. newGLJ.marketPrice = std_glj.basePrice;
  709. newGLJ.shortName = std_glj.shortName;
  710. newGLJ.type = std_glj.gljType;
  711. newGLJ.repositoryId = std_glj.repositoryId;
  712. newGLJ.adjCoe = std_glj.adjCoe;
  713. newGLJ.materialType = std_glj.materialType;
  714. newGLJ.materialCoe = std_glj.materialCoe;
  715. newGLJ.grossWeightCoe = std_glj.grossWeightCoe;
  716. newGLJ.purchaseStorageRate = std_glj.purchaseStorageRate;
  717. newGLJ.offSiteTransportLossRate = std_glj.offSiteTransportLossRate;
  718. newGLJ.handlingLossRate = std_glj.handlingLossRate;
  719. newGLJ.createType = 'normal';
  720. }
  721. async function addGLJ(rgList, compilation) {
  722. if (rgList.length <= 0) return {};
  723. let [newRecodes, projectGLJList] = await insertAddTypeGLJ(rgList, compilation);
  724. let stateResult = await glj_calculate_facade.calculateQuantity({
  725. projectID: rgList[0].projectID,
  726. rationID: rgList[0].rationID
  727. });
  728. let result = {
  729. newRecodes: newRecodes,
  730. projectGLJList: projectGLJList,
  731. showData: rgList,
  732. adjustState: stateResult.adjustState
  733. };
  734. return result;
  735. }
  736. async function insertAddTypeGLJ(rgList, compilation, needInsert = true) {
  737. let newRecodes = [],
  738. GLJMap = null;
  739. let projectGLJList = [];
  740. let [unitFileId, ext] = await prepareExtData(rgList[0].projectID, compilation);
  741. for (let g of rgList) {
  742. let projectGljModel = new GLJListModel();
  743. let result = await projectGljModel.addList(getGLJSearchInfo(g), unitFileId, ext);
  744. let typeString = result.type + '';
  745. g.marketPrice = result.unit_price.market_price;
  746. g.adjustPrice = result.unit_price.base_price;
  747. g.basePrice = result.unit_price.base_price;
  748. g.isAdd = result.unit_price.is_add;
  749. g.projectGLJID = result.id;
  750. if (typeString.startsWith("2") || typeString == '4' || typeString == '5') { //只有材料类型才显示是否暂估
  751. g.isEstimate = result.is_evaluate;
  752. }
  753. g.ID = uuidV1();
  754. if (result.subList && result.subList.length > 0) {
  755. g.subList = getMixRatioShowDatas(result.subList);
  756. //对于混凝土,砂浆,配合比,组成物还要插入定额工料机
  757. if (gljUtil.isConcreteType(g.type)) {
  758. if (GLJMap == null) {
  759. let oldGLJList = await ration_glj.find({
  760. 'rationID': g.rationID
  761. });
  762. GLJMap = _.indexBy(oldGLJList, "projectGLJID");
  763. }
  764. addMixRatioToRationGLJ(g, result.subList, newRecodes, GLJMap);
  765. }
  766. }
  767. newRecodes.push(createNewRecord(g));
  768. projectGLJList.push(result);
  769. }
  770. //分摊那里调用时不用真的插入
  771. if (needInsert == true) await ration_glj.insertMany(newRecodes);
  772. return [newRecodes, projectGLJList];
  773. }
  774. async function deleteRationGLJ(data) {
  775. let deleteIDs = [data.ID];
  776. if (gljUtil.isConcreteType(data.type)) { //如果是混凝土、砂浆、配合比,还要删除没有被引用的组成物工料机
  777. let projectGljModel = new GLJListModel();
  778. let rationGLJList = await ration_glj.find({
  779. 'rationID': data.rationID
  780. });
  781. let unitFileId = await commonFacade.getUnitPriceFileId(data.projectID);
  782. let projectGLJMap = {},
  783. referenceMap = {};
  784. let deleteMix = [];
  785. for (let r of rationGLJList) {
  786. projectGLJMap[r.projectGLJID] = r;
  787. if (gljUtil.isConcreteType(r.type)) {
  788. if (r.ID == data.ID) { //是要删除的工料机
  789. deleteMix = await projectGljModel.getCompositionGLJByData(r, unitFileId);
  790. } else {
  791. let comList = await projectGljModel.getCompositionGLJByData(r, unitFileId);
  792. for (let c of comList) {
  793. referenceMap[c.id] = c;
  794. }
  795. }
  796. }
  797. }
  798. for (let d of deleteMix) {
  799. //删除不属于其它的组成物并且定额消耗为0
  800. if (referenceMap[d.id]) continue;
  801. if (projectGLJMap[d.id] && (projectGLJMap[d.id].rationItemQuantity == '0' || projectGLJMap[d.id].rationItemQuantity == 0)) {
  802. deleteIDs.push(projectGLJMap[d.id].ID);
  803. }
  804. }
  805. await ration_glj.deleteMany({
  806. 'ID': {
  807. "$in": deleteIDs
  808. }
  809. });
  810. } else {
  811. await ration_glj.deleteOne({
  812. ID: data.ID
  813. });
  814. }
  815. let calcResult = await glj_calculate_facade.calculateQuantity({
  816. projectID: data.projectID,
  817. rationID: data.rationID
  818. });
  819. calcResult.deleteList = deleteIDs;
  820. return calcResult;
  821. }
  822. function addMixRatioToRationGLJ(g, subList, newRecodes, GLJMap) {
  823. let newMap = {};
  824. for (let mr of subList) {
  825. //先查找该定额下是否已经有了工料机了,有就不用再插入了
  826. newMap[mr.id] = mr; //新增的定额工料机映射表
  827. if (GLJMap[mr.id] || _.find(newRecodes, {
  828. 'projectGLJID': mr.id
  829. })) continue;
  830. //没有的情况下,生成一条定额工料机计录
  831. let newMr = {
  832. projectID: g.projectID,
  833. GLJID: mr.glj_id,
  834. rationID: g.rationID,
  835. rationItemQuantity: 0,
  836. quantity: 0,
  837. name: mr.name,
  838. code: mr.code,
  839. original_code: mr.original_code,
  840. unit: mr.unit,
  841. specs: mr.specs,
  842. from: mr.from,
  843. createType: 'add',
  844. shortName: mr.unit_price.short_name,
  845. billsItemID: g.billsItemID,
  846. type: mr.type,
  847. model: mr.model,
  848. repositoryId: g.repositoryId,
  849. projectGLJID: mr.id,
  850. adjCoe: mr.adjCoe
  851. };
  852. newMr.ID = uuidV1();
  853. newRecodes.push(newMr);
  854. }
  855. return newMap;
  856. }
  857. async function replaceGLJByData(data, compilation, needUpdate = true, rationGLJList) {
  858. let projectGljModel = new GLJListModel(),
  859. newRecodes = [],
  860. deleteList = [];
  861. let [unitFileId, ext] = await prepareExtData(data.projectID, compilation);
  862. let result = await projectGljModel.addList(getGLJSearchInfo(data), unitFileId, ext);
  863. data.projectGLJID = result.id;
  864. if (data.toCommercial == true) { //从混凝土改成商品混凝土,
  865. let [contype, newR] = await concreteTypeToCommercial(data, needUpdate);
  866. newRecodes.push(newR);
  867. data = contype;
  868. } else {
  869. let [newList, tdelList] = await replaceMixRatio(data, result, unitFileId, needUpdate, rationGLJList);
  870. newRecodes = newList;
  871. deleteList = tdelList;
  872. if (needUpdate == true) await ration_glj.findOneAndUpdate({
  873. ID: data.ID,
  874. projectID: data.projectID
  875. }, data); //更新定额工料机
  876. }
  877. return {
  878. data: data,
  879. newRecodes: newRecodes,
  880. deleteList: deleteList,
  881. projectGLJ: result
  882. };
  883. }
  884. async function concreteTypeToCommercial(data, needUpdate) {
  885. //旧的自定义消耗量改为0
  886. let contype = null;
  887. if (needUpdate == true) {
  888. contype = await ration_glj.findOneAndUpdate({
  889. ID: data.originalID
  890. }, {
  891. customQuantity: '0'
  892. });
  893. } else {
  894. contype = {
  895. customQuantity: '0'
  896. }
  897. }
  898. //因为商品混凝土是没有组成物的,所以不用考虑组成物的情况
  899. let new_glj = createComercialConcreteData(data);
  900. if (needUpdate == true) await ration_glj.create(new_glj);
  901. return [contype, new_glj];
  902. }
  903. function createComercialConcreteData(data) {
  904. data.ID = uuidV1();
  905. return createNewRecord(data);
  906. }
  907. async function replaceMixRatio(g, result, unitFileId, needUpdate, trationGLJList) {
  908. let newRecodes = [],
  909. deleteList = [];
  910. if (gljUtil.isConcreteType(g.type) || gljUtil.isCommercialConcreteType(g.type)) { //混凝土大类,商品混凝土属于相同大类,替换前和替换后只判断一个就好了
  911. let IDMap = {},
  912. projectGLJMap = {},
  913. referenceMap = {},
  914. concreteList = [],
  915. newMap = {};
  916. let projectGljModel = new GLJListModel();
  917. let rationGLJList = trationGLJList ? trationGLJList : await ration_glj.find({
  918. 'rationID': g.rationID
  919. });
  920. for (let r of rationGLJList) {
  921. IDMap[r.ID] = r;
  922. projectGLJMap[r.projectGLJID] = r;
  923. if (gljUtil.isConcreteType(r.type) && r.ID != g.ID) concreteList.push(r) //除了本身,记录一下其它混凝土类型
  924. }
  925. if (result.subList && result.subList.length > 0) {
  926. newMap = addMixRatioToRationGLJ(g, result.subList, newRecodes, projectGLJMap); //先生成要添加的工料机
  927. }
  928. let oldMixList = await projectGljModel.getCompositionGLJByData(IDMap[g.ID], unitFileId);
  929. for (let c of concreteList) { //找出要删除的子定额工料机(没人引用,并且定额消耗量为0)
  930. let temList = await projectGljModel.getCompositionGLJByData(c, unitFileId);
  931. for (let t of temList) {
  932. referenceMap[t.id] = t;
  933. }
  934. }
  935. for (let o of oldMixList) {
  936. if (newMap[o.id] || referenceMap[o.id]) continue; //如果两个地方有一个存在,那么就不用删除
  937. //没有被其它地方引用并且定额消耗量为0,就删除对应的定额工料机
  938. if (projectGLJMap[o.id] && (projectGLJMap[o.id].rationItemQuantity == '0' || projectGLJMap[o.id].rationItemQuantity == 0)) deleteList.push(projectGLJMap[o.id].ID)
  939. }
  940. }
  941. if (deleteList.length > 0 && needUpdate == true) await ration_glj.deleteMany({
  942. 'ID': {
  943. "$in": deleteList
  944. }
  945. }); //删除定额工料机
  946. if (newRecodes.length > 0 && needUpdate == true) await ration_glj.insertMany(newRecodes);
  947. return [newRecodes, deleteList]
  948. }
  949. async function replaceGLJ(data, compilation) {
  950. let rdata = {};
  951. let r_result = await replaceGLJByData(data, compilation);
  952. data = r_result.data;
  953. let stateResult = await glj_calculate_facade.calculateQuantity({
  954. projectID: data.projectID,
  955. rationID: data.rationID
  956. }, null, true);
  957. rdata.data = data;
  958. rdata.projectGLJ = r_result.projectGLJ;
  959. rdata.adjustState = stateResult.adjustState;
  960. rdata.name = stateResult.rationName;
  961. rdata.newRecodes = r_result.newRecodes;
  962. rdata.deleteList = r_result.deleteList;
  963. rdata.glj_result = stateResult.glj_result;
  964. return rdata;
  965. }
  966. async function replaceMixRatioForMReplace(tasks, result, unitFileId) {
  967. let allNewRecodes = [],
  968. allDeleteList = [];
  969. for (let t of tasks) { //要新增一条商品混凝土
  970. if (t.insertOne) {
  971. t.insertOne.document.projectGLJID = result.id;
  972. t.insertOne.document = createComercialConcreteData(t.insertOne.document);
  973. allNewRecodes.push(t.insertOne.document);
  974. } else if (t.updateOne && t.updateOne.update.isConcrete == true) { //过滤掉只更新自定义消耗量的task
  975. let tem = _.cloneDeep(t.updateOne.update);
  976. tem.ID = t.updateOne.filter.ID;
  977. tem.rationID = t.updateOne.filter.rationID;
  978. delete t.updateOne.filter.rationID;
  979. delete t.updateOne.update.isConcrete;
  980. let [newRecodes, deleteList] = await replaceMixRatio(tem, result, unitFileId);
  981. allNewRecodes = allNewRecodes.concat(newRecodes);
  982. allDeleteList = allDeleteList.concat(deleteList);
  983. }
  984. }
  985. return {
  986. newRecodes: allNewRecodes,
  987. deleteList: allDeleteList
  988. }
  989. }
  990. async function mReplaceGLJ(data, compilation) {
  991. let mresult = {},
  992. mixResult = null,
  993. noNeedCal = true;
  994. let projectGljModel = new GLJListModel();
  995. let [unitFileId, ext] = await prepareExtData(data.doc.projectID, compilation);
  996. //
  997. let result = await projectGljModel.addList(getGLJSearchInfo(data.doc), unitFileId, ext);
  998. let typeString = result.type + '';
  999. let newDoc = {};
  1000. newDoc.projectGLJID = result.id;
  1001. let rationList = []; //await ration_glj.distinct('rationID', data.query);
  1002. for (let t of data.tasks) {
  1003. if (t.updateOne) {
  1004. rationList.push(t.updateOne.filter.rationID);
  1005. if (t.updateOne.update.code) t.updateOne.update.projectGLJID = result.id; //如果是不是只修改自定义消耗的task,更新项目工料机ID
  1006. }
  1007. }
  1008. if (gljUtil.isConcreteType(result.unit_price.type) || gljUtil.isCommercialConcreteType(result.unit_price.type)) {
  1009. mixResult = await replaceMixRatioForMReplace(data.tasks, result, unitFileId);
  1010. noNeedCal = null;
  1011. }
  1012. await ration_glj.bulkWrite(data.tasks);
  1013. let [stateList, glj_result] = await changAdjustState(data, rationList, noNeedCal);
  1014. data.doc = newDoc;
  1015. mresult.data = data;
  1016. mresult.stateList = stateList;
  1017. mresult.newRecodes = mixResult ? mixResult.newRecodes : [];
  1018. mresult.deleteList = mixResult ? mixResult.deleteList : [];
  1019. mresult.glj_result = glj_result;
  1020. mresult.projectGLJ = result;
  1021. return mresult
  1022. }
  1023. async function updateRationGLJByEdit(data) {
  1024. var doc = data.doc;
  1025. var result;
  1026. if (doc.hasOwnProperty('customQuantity')) {
  1027. result = await doCustomQuantityUpdate(data)
  1028. } else {
  1029. result = await doRationGLJUpdate(data);
  1030. }
  1031. return result;
  1032. }
  1033. async function updateRationGLJFromDoc(rg, doc, priceInfo) {
  1034. let gljListModel = new GLJListModel();
  1035. let projectGLJ = getGLJSearchInfo(rg);
  1036. for (let key in doc) {
  1037. projectGLJ[key] = doc[key]
  1038. }
  1039. projectGLJ.base_price = priceInfo.base_price;
  1040. projectGLJ.market_price = priceInfo.market_price;
  1041. let projcetGLJ_n = await gljListModel.modifyGLJ(projectGLJ, rg);
  1042. doc.code = projcetGLJ_n.code;
  1043. doc.projectGLJID = projcetGLJ_n.id;
  1044. if (projcetGLJ_n.unit_price.is_add == 1) {
  1045. doc.createType = 'replace';
  1046. doc.rcode = projcetGLJ_n.original_code;
  1047. } else {
  1048. doc.createType = 'normal';
  1049. doc.rcode = '';
  1050. }
  1051. await ration_glj.findOneAndUpdate({
  1052. ID: rg.ID
  1053. }, doc);
  1054. return [projcetGLJ_n, doc]
  1055. }
  1056. async function doRationGLJUpdate(data) {
  1057. let resutl = {};
  1058. let priceInfo = data.priceInfo;
  1059. let rg = await ration_glj.findOne(data.query);
  1060. let [projcetGLJ_n, doc] = await updateRationGLJFromDoc(rg, data.doc, priceInfo);
  1061. //取价格
  1062. let gljListModel = new GLJListModel();
  1063. gljListModel.getGLJPrice(projcetGLJ_n);
  1064. doc.basePrice = projcetGLJ_n.unit_price.base_price;
  1065. doc.marketPrice = projcetGLJ_n.unit_price.market_price;
  1066. doc.adjustPrice = projcetGLJ_n.adjust_price;
  1067. doc.isAdd = projcetGLJ_n.unit_price.is_add;
  1068. resutl.doc = doc;
  1069. let stateResult = await glj_calculate_facade.calculateQuantity({
  1070. projectID: data.query.projectID,
  1071. rationID: data.query.rationID
  1072. }, null, true);
  1073. resutl.adjustState = stateResult.adjustState;
  1074. resutl.name = stateResult.rationName;
  1075. return resutl;
  1076. }
  1077. async function updateProportion(proportionList, projectID, rationID) {
  1078. const bulks = proportionList.map(item => {
  1079. return {
  1080. updateOne: {
  1081. filter: {
  1082. ID: item.ID
  1083. },
  1084. update: {
  1085. $set: {
  1086. adjustProportion: item.adjustProportion
  1087. }
  1088. }
  1089. }
  1090. }
  1091. });
  1092. if (bulks.length) {
  1093. await ration_glj.bulkWrite(bulks);
  1094. }
  1095. const calcRst = await glj_calculate_facade.calculateQuantity({
  1096. projectID,
  1097. rationID
  1098. }, null, true);
  1099. const rationGLJ = {
  1100. quantityRefresh: true,
  1101. glj_result: calcRst.glj_result
  1102. };
  1103. const ration = {
  1104. ID: calcRst.rationID,
  1105. adjustState: calcRst.adjustState,
  1106. name: calcRst.rationName
  1107. };
  1108. return {
  1109. ration_glj: rationGLJ,
  1110. ration,
  1111. add: [],
  1112. delete: [],
  1113. replace: []
  1114. };
  1115. }
  1116. async function getGLJClass(info, data) {
  1117. let result = {
  1118. exist: false
  1119. }
  1120. //检查补充工料机中是否已经存在一样的记录了
  1121. let condition = {
  1122. userId: info.userID,
  1123. compilationId: info.compilationId,
  1124. code: data.code,
  1125. name: data.name,
  1126. unit: data.unit,
  1127. gljType: data.type,
  1128. basePrice: data.basePrice
  1129. }
  1130. if (data.specs != null && data.specs != undefined && data.specs != '') {
  1131. condition['specs'] = data.specs;
  1132. }
  1133. let glj = await complementaryGljModel.find(condition);
  1134. if (glj.length > 0) { //如果已存在就直接返回,不用再新增了
  1135. result.exist = true;
  1136. return result
  1137. }
  1138. //查找工料机类型树
  1139. let items = await compleClassModel.find({
  1140. userId: info.userID,
  1141. compilationId: info.compilationId
  1142. });
  1143. result.items = items;
  1144. return result;
  1145. }
  1146. async function insertGLJAsRation(data, compilation) {
  1147. let gljList = data.gljList;
  1148. if (data.hasOwnProperty("selectedSerialNo")) { //如果需要,更新序列号。
  1149. let query = {
  1150. projectID: data.projectID,
  1151. billsItemID: data.billsItemID,
  1152. serialNo: {
  1153. $gt: data.selectedSerialNo
  1154. }
  1155. }
  1156. await ration.update(query, {
  1157. $inc: {
  1158. serialNo: gljList.length
  1159. }
  1160. }, {
  1161. multi: true
  1162. });
  1163. }
  1164. let [unitFileId, ext] = await prepareExtData(data.projectID, compilation);
  1165. for (let glj of gljList) {
  1166. let p_glj = getGLJSearchInfo(glj);
  1167. let projectGljModel = new GLJListModel();
  1168. let result = await projectGljModel.addList(p_glj, unitFileId, ext); //逐条添加到项目工料机
  1169. let typeString = result.type + '';
  1170. glj.marketPrice = result.unit_price.market_price;
  1171. glj.adjustPrice = result.unit_price.base_price;
  1172. glj.basePrice = result.unit_price.base_price;
  1173. glj.isAdd = result.unit_price.is_add;
  1174. glj.projectGLJID = result.id;
  1175. if (typeString.startsWith("2") || typeString == '4' || typeString == '5') { //只有材料类型才显示是否暂估
  1176. glj.isEstimate = result.is_evaluate;
  1177. }
  1178. }
  1179. await ration.insertMany(gljList);
  1180. return gljList;
  1181. }
  1182. async function getRationTypeGLJQuantity(projectID) {
  1183. let rations = await ration.find({
  1184. 'projectID': projectID,
  1185. 'type': 3,
  1186. 'deleteInfo': null
  1187. }, ['ID', 'projectGLJID', 'quantity']);
  1188. return rations;
  1189. }
  1190. async function changAdjustState(data, rationList, noNeedCal) {
  1191. let stateList = [],
  1192. glj_result = [];
  1193. for (let r of rationList) {
  1194. let stateResult = await glj_calculate_facade.calculateQuantity({
  1195. projectID: data.query.projectID,
  1196. rationID: r
  1197. }, noNeedCal, true);
  1198. if (stateResult) {
  1199. stateList.push({
  1200. rationID: r,
  1201. adjustState: stateResult.adjustState,
  1202. name: stateResult.rationName
  1203. });
  1204. glj_result = glj_result.concat(stateResult.glj_result)
  1205. }
  1206. }
  1207. return [stateList, glj_result];
  1208. }
  1209. async function getGLJDataByCodes(data, compilation) {
  1210. let gljLibId = await getGLJLibByEngineerID(data.engineerID);
  1211. let gljDatas = [];
  1212. if (gljLibId) {
  1213. let stdList = await std_glj_lib_gljList_model.find({
  1214. 'repositoryId': gljLibId,
  1215. code: {
  1216. '$in': data.codes
  1217. }
  1218. });
  1219. if (stdList.length > 0) {
  1220. let property = await projectDao.getProjectProperty(data.projectID);
  1221. let ext = pmFacade.getExtendData(property, compilation); //多单价处理
  1222. for (let s of stdList) {
  1223. let tem = JSON.parse(JSON.stringify(s));
  1224. if (ext && ext.priceField && tem && tem.priceProperty) {
  1225. tem.basePrice = tem.priceProperty[ext.priceField];
  1226. }
  1227. gljDatas.push(tem);
  1228. }
  1229. }
  1230. }
  1231. return gljDatas
  1232. }
  1233. async function testError() {
  1234. throw new Error('test Error');
  1235. }
  1236. function getData(projectID, callback, isReport) {
  1237. function findRation(rations, ID) {
  1238. let ration = rations.find(function getElement(element) {
  1239. return element.ID == ID;
  1240. });
  1241. return ration && ration._doc;
  1242. };
  1243. ration_glj.find({
  1244. 'projectID': projectID
  1245. }, (err, datas) => {
  1246. if (err) {
  1247. callback(1, '', null);
  1248. } else {
  1249. if (isReport) { // 调价中间件机制
  1250. ration.find({
  1251. 'projectID': projectID
  1252. }, ['ID', 'code', 'name', 'quantityCoe', 'quantity', 'rationQuantityCoe'],
  1253. function cbData(err, rations) {
  1254. if (!err) {
  1255. for (let i = 0; i < datas.length; i++) {
  1256. let glj = datas[i]._doc;
  1257. let ration = findRation(rations, glj.rationID);
  1258. let coe = 1;
  1259. if (ration && ration.quantityCoe) {
  1260. if ([gljType.LABOUR].includes(glj.type)) {
  1261. if (ration.quantityCoe._doc.labour)
  1262. coe = ration.quantityCoe._doc.labour;
  1263. } else if (
  1264. [gljType.GENERAL_MATERIAL,
  1265. gljType.CONCRETE,
  1266. gljType.MORTAR,
  1267. gljType.MIX_RATIO,
  1268. gljType.COMMERCIAL_CONCRETE,
  1269. gljType.COMMERCIAL_MORTAR,
  1270. gljType.OTHER_MATERIAL
  1271. ].includes(glj.type)) {
  1272. if (ration.quantityCoe._doc.material)
  1273. coe = ration.quantityCoe._doc.material;
  1274. } else if ([gljType.GENERAL_MACHINE,
  1275. gljType.MACHINE_COMPOSITION,
  1276. gljType.MACHINE_LABOUR
  1277. ].includes(glj.type)) {
  1278. if (ration.quantityCoe._doc.machine)
  1279. coe = ration.quantityCoe._doc.machine;
  1280. } else if ([gljType.MAIN_MATERIAL].includes(glj.type)) {
  1281. if (ration.quantityCoe._doc.main)
  1282. coe = ration.quantityCoe._doc.main;
  1283. } else if ([gljType.EQUIPMENT].includes(glj.type)) {
  1284. if (ration.quantityCoe._doc.equipment)
  1285. coe = ration.quantityCoe._doc.equipment;
  1286. };
  1287. };
  1288. if ((!coe) || (coe == '0')) coe = 1;
  1289. glj.quantity = glj.quantity * coe;
  1290. }
  1291. }
  1292. });
  1293. };
  1294. callback(0, consts.projectConst.RATION_GLJ, datas);
  1295. }
  1296. })
  1297. }
  1298. function commonCallback(callback, result, err) {
  1299. if (err) {
  1300. callback(err, '');
  1301. } else {
  1302. callback(null, result);
  1303. }
  1304. }