ration_glj_facade.js 39 KB

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