ration_glj_facade.js 43 KB

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