ration_glj_facade.js 43 KB

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