ration_glj_facade.js 40 KB

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