ration_glj_facade.js 43 KB

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