ration_item.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. /**
  2. * Created by Tony on 2017/4/28.
  3. */
  4. const mongoose = require('mongoose');
  5. let async = require("async");
  6. let moment = require('moment');
  7. let counter = require('../../../public/counter/counter');
  8. let gljDao = require('./glj_repository');
  9. let rationRepositoryDao = require('./repository_map');
  10. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  11. const rationItemModel = mongoose.model('std_ration_lib_ration_items');
  12. const stdRationLibModel = mongoose.model('std_ration_lib_map');
  13. const stdRationSectionModel = mongoose.model('std_ration_lib_ration_chapter_trees');
  14. const compleRationModel = mongoose.model('complementary_ration_items');
  15. import STDGLJListModel from '../../std_glj_lib/models/gljModel';
  16. import InstallationDao from '../models/installation';
  17. const installationDao = new InstallationDao();
  18. import GljDao from "../../std_glj_lib/models/gljModel";
  19. const stdGljDao = new GljDao();
  20. import stdgljutil from "../../../public/cache/std_glj_type_util";
  21. var rationItemDAO = function(){};
  22. // 由于导入excel时,excel数据存在负的工程量,所以导入后一些定额人材机的消耗量可能为负,需要处理
  23. rationItemDAO.prototype.handleMinusQuantity = async function() {
  24. const updateTask = [];
  25. const repIDs = new Set();
  26. const rations = await rationItemModel.find({'rationGljList.consumeAmt': {$lt: 0}}).lean();
  27. for (const ration of rations) {
  28. repIDs.add(ration.rationRepId);
  29. const rationGLJList = [];
  30. for (const rGLJ of ration.rationGljList) {
  31. rationGLJList.push({
  32. gljId: rGLJ.gljId,
  33. consumeAmt: Math.abs(rGLJ.consumeAmt),
  34. proportion: rGLJ.proportion
  35. });
  36. }
  37. updateTask.push({
  38. updateOne: {
  39. filter: { ID: ration.ID },
  40. update: { $set: { rationGljList: rationGLJList } }
  41. }
  42. });
  43. }
  44. if (updateTask.length) {
  45. await rationItemModel.bulkWrite(updateTask);
  46. }
  47. console.log(`repIDs`);
  48. console.log(repIDs);
  49. };
  50. rationItemDAO.prototype.prepareInitData = async function (rationRepId) {
  51. // 定额库
  52. const libTask = stdRationLibModel.findOne({ID: rationRepId}, '-_id ID dispName gljLib');
  53. // 定额编码
  54. const codesTask = rationItemModel.find({rationRepId}, '-_id code', {lean: true});
  55. // 定额章节树
  56. const sectionTreeTask = stdRationSectionModel.find({rationRepId}, '-_id', {lean: true});
  57. // 安装增加费
  58. const installationTask = installationDao.getInstallation(rationRepId);
  59. const [libInfo, codesArr, sectionTree, installationList] = await Promise.all([libTask, codesTask, sectionTreeTask, installationTask]);
  60. const rationsCodes = codesArr.reduce((acc, cur) => {
  61. acc.push(cur.code);
  62. return acc;
  63. }, []);
  64. // 人材机分类树
  65. const gljLibId = libInfo.gljLib;
  66. const gljTreeTask = stdGljDao.getGljTreeSync(gljLibId);
  67. const gljTask = stdGljDao.getGljItemsSync(gljLibId);
  68. const [gljTree, gljList] = await Promise.all([gljTreeTask, gljTask]);
  69. const gljDistTypeList = stdgljutil.getStdGljTypeCacheObj().toArray();
  70. return {
  71. libInfo,
  72. rationsCodes,
  73. sectionTree,
  74. installationList,
  75. gljTree,
  76. gljList,
  77. gljDistTypeList
  78. };
  79. };
  80. rationItemDAO.prototype.getRationItemsByLib = async function (rationRepId, showHint = null, returnFields = '') {
  81. let rationLib = await stdRationLibModel.findOne({ID: rationRepId, deleted: false});
  82. if(!rationLib){
  83. return [];
  84. }
  85. let startDate = new Date();
  86. let rations = await rationItemModel.find({rationRepId: rationRepId}, returnFields);
  87. console.log(`Date: ${new Date() - startDate}====================================`);
  88. if(!showHint){
  89. return rations;
  90. }
  91. else {
  92. const stdBillsLibListsModel = new STDGLJListModel();
  93. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib, '-_id ID code name unit gljType');
  94. let gljMapping = {};
  95. for(let glj of stdGLJData){
  96. gljMapping[glj.ID] = glj;
  97. }
  98. //设置悬浮
  99. for(let ration of rations){
  100. let hintsArr = [];
  101. //对人材机进行排序
  102. ration.rationGljList.sort(function (a, b) {
  103. let gljA = gljMapping[a.gljId],
  104. gljB = gljMapping[b.gljId];
  105. if(gljA && gljB){
  106. let aV = gljA.gljType + gljA.code,
  107. bV = gljB.gljType + gljB.code;
  108. if(aV > bV) {
  109. return 1;
  110. } else if(aV < bV) {
  111. return -1;
  112. }
  113. }
  114. return 0;
  115. });
  116. for(let rationGlj of ration.rationGljList){
  117. let subGlj = gljMapping[rationGlj.gljId];
  118. if(subGlj){
  119. hintsArr.push(` ${subGlj.code} ${subGlj.name}${subGlj.specs ? '&nbsp;&nbsp;&nbsp;' + subGlj.specs : ''}&nbsp;&nbsp&nbsp;${subGlj.unit}&nbsp;&nbsp;&nbsp;${rationGlj.consumeAmt}`);
  120. }
  121. }
  122. hintsArr.push(`基价 元 ${ration.basePrice}`);
  123. if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
  124. hintsArr.push(`工作内容:`);
  125. hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
  126. }
  127. if(ration.annotation && ration.annotation.toString().trim() !== ''){
  128. hintsArr.push(`附注:`);
  129. hintsArr = hintsArr.concat(ration.annotation.split('\n'));
  130. }
  131. ration._doc.hint = hintsArr.join('<br>');
  132. }
  133. return rations;
  134. }
  135. };
  136. rationItemDAO.prototype.sortToNumber = function (datas) {
  137. for(let i = 0, len = datas.length; i < len; i++){
  138. let data = datas[i]._doc;
  139. if(_exist(data, 'labourPrice')){
  140. data['labourPrice'] = parseFloat(data['labourPrice']);
  141. }
  142. if(_exist(data, 'materialPrice')){
  143. data['materialPrice'] = parseFloat(data['materialPrice']);
  144. }
  145. if(_exist(data, 'machinePrice')){
  146. data['machinePrice'] = parseFloat(data['machinePrice']);
  147. }
  148. if(_exist(data, 'basePrice')){
  149. data['basePrice'] = parseFloat(data['basePrice']);
  150. }
  151. if(_exist(data, 'rationGljList')){
  152. for(let j = 0, jLen = data['rationGljList'].length; j < jLen; j++){
  153. let raGljObj = data['rationGljList'][j]._doc;
  154. if(_exist(raGljObj, 'consumeAmt')){
  155. raGljObj['consumeAmt'] = parseFloat(raGljObj['consumeAmt']);
  156. }
  157. }
  158. }
  159. }
  160. function _exist(data, attr){
  161. return data && data[attr] !== undefined && data[attr];
  162. }
  163. };
  164. rationItemDAO.prototype.getRationItemsBySection = async function(rationRepId, sectionId,callback){
  165. let me = this;
  166. try {
  167. let rations = await rationItemModel.find({rationRepId: rationRepId, sectionId: sectionId});
  168. me.sortToNumber(rations);
  169. let matchRationIDs = [],
  170. matchRations = [];
  171. for (let ration of rations) {
  172. if (ration.rationTemplateList) {
  173. for (let rt of ration.rationTemplateList) {
  174. if (rt.rationID) {
  175. matchRationIDs.push(rt.rationID);
  176. }
  177. }
  178. }
  179. }
  180. if (matchRationIDs.length > 0) {
  181. matchRations = await rationItemModel.find({ID: {$in: matchRationIDs}}, '-_id ID code name');
  182. }
  183. for (let mr of matchRations) {
  184. for (let ration of rations) {
  185. if (ration.rationTemplateList) {
  186. for (let rt of ration.rationTemplateList) {
  187. if (rt.rationID && rt.rationID === mr.ID) {
  188. rt.code = mr.code ? mr.code : '';
  189. rt.name = mr.name ? mr.name : '';
  190. }
  191. }
  192. }
  193. }
  194. }
  195. callback(false,"Get items successfully", rations);
  196. } catch (err) {
  197. console.log(err);
  198. callback(true, "Fail to get items", "");
  199. }
  200. /* rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
  201. if(err) callback(true, "Fail to get items", "");
  202. else {
  203. me.sortToNumber(data);
  204. callback(false,"Get items successfully", data);
  205. }
  206. })*/
  207. };
  208. rationItemDAO.prototype.mixUpdateRationItems = function(rationLibId, lastOpr, sectionId, updateItems, addItems, rIds, callback){
  209. var me = this;
  210. if (updateItems.length == 0 && rIds.length == 0) {
  211. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  212. } else {
  213. me.removeRationItems(rationLibId, lastOpr, rIds, function(err, message, docs) {
  214. if (err) {
  215. callback(true, "Fail to remove", false);
  216. } else {
  217. me.updateRationItems(rationLibId, lastOpr, sectionId, updateItems, function(err, results){
  218. if (err) {
  219. console.log(err);
  220. callback(true, "Fail to save", false);
  221. } else {
  222. if (addItems && addItems.length > 0) {
  223. me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
  224. } else {
  225. callback(false, "Save successfully", results);
  226. }
  227. }
  228. });
  229. }
  230. })
  231. }
  232. };
  233. rationItemDAO.prototype.removeRationItems = function(rationLibId, lastOpr, rIds,callback){
  234. if (rIds.length > 0) {
  235. rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
  236. if (err) {
  237. callback(true, "Fail to remove", false);
  238. } else {
  239. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  240. if(!err){
  241. rationItemModel.update({rationRepId: rationLibId}, {$pull: {rationTemplateList: {rationID: {$in: rIds}}}}, function (theErr) {
  242. if (!theErr) {
  243. callback(false, "Remove successfully", docs);
  244. } else {
  245. callback(true, "Fail to remove", false);
  246. }
  247. });
  248. } else {
  249. callback(true, "Fail to remove", false);
  250. }
  251. })
  252. }
  253. })
  254. } else {
  255. callback(false, "No records were deleted!", null);
  256. }
  257. };
  258. rationItemDAO.prototype.getRationItemsByCode = function(repId, code,callback){
  259. rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$or": [{"isDeleted": null}, {"isDeleted": false}]},function(err,data){
  260. if(err) callback(true, "Fail to get items", "")
  261. else callback(false,"Get items successfully", data);
  262. })
  263. };
  264. rationItemDAO.prototype.findRation = function (repId, keyword, callback) {
  265. var filter = {
  266. 'rationRepId': repId,
  267. '$and': [{
  268. '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
  269. }, {
  270. '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
  271. }]
  272. };
  273. rationItemModel.find(filter, function (err, data) {
  274. if (err) {
  275. callback(true, 'Fail to find ration', null);
  276. } else {
  277. callback(false, '', data);
  278. }
  279. })
  280. }
  281. rationItemDAO.prototype.getRationItem = async function (repId, code) {
  282. let ration = await rationItemModel.findOne({rationRepId: repId, code: code});
  283. return ration;
  284. };
  285. rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  286. if (items && items.length > 0) {
  287. counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
  288. var maxId = result.sequence_value;
  289. var arr = [];
  290. for (var i = 0; i < items.length; i++) {
  291. var obj = new rationItemModel(items[i]);
  292. obj.ID = (maxId - (items.length - 1) + i);
  293. obj.sectionId = sectionId;
  294. obj.rationRepId = rationLibId;
  295. arr.push(obj);
  296. }
  297. rationItemModel.collection.insert(arr, null, function(err, docs){
  298. if (err) {
  299. callback(true, "Fail to save", false);
  300. } else {
  301. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  302. if(err){
  303. callback(true, "Fail to sava operator", false);
  304. }
  305. else{
  306. callback(false, "Save successfully", docs);
  307. }
  308. })
  309. }
  310. })
  311. });
  312. } else {
  313. callback(true, "Source error!", false);
  314. }
  315. };
  316. rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
  317. console.log('enter============');
  318. var functions = [];
  319. for (var i=0; i < items.length; i++) {
  320. functions.push((function(doc) {
  321. return function(cb) {
  322. var filter = {};
  323. if (doc.ID) {
  324. filter.ID = doc.ID;
  325. } else {
  326. filter.sectionId = sectionId;
  327. if (rationLibId) filter.rationRepId = rationLibId;
  328. filter.code = doc.code;
  329. }
  330. rationItemModel.update(filter, doc, cb);
  331. };
  332. })(items[i]));
  333. }
  334. functions.push((function () {
  335. return function (cb) {
  336. rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  337. if(err){
  338. cb(err);
  339. }
  340. else{
  341. cb(null);
  342. }
  343. });
  344. }
  345. })());
  346. async.parallel(functions, function(err, results) {
  347. callback(err, results);
  348. });
  349. };
  350. //ration round func
  351. function round(v,e){
  352. var t=1;
  353. for(;e>0;t*=10,e--);
  354. for(;e<0;t/=10,e++);
  355. return Math.round(v*t)/t;
  356. }
  357. function calcRation(gljArr) {
  358. let labourPrc = [],
  359. materialPrc = [],
  360. machinePrc = [],
  361. managePrc = [],
  362. profitPrc = [],
  363. riskPrc = [],
  364. singlePrc,
  365. updatePrc = {labourPrice: 0, materialPrice: 0, machinePrice: 0, managePrice: 0, profitPrice: 0, riskPrice: 0, basePrice: 0};
  366. gljArr.forEach(function (gljItem) {
  367. if(gljItem.gljParentType !== -1){
  368. singlePrc = scMathUtil.roundTo(gljItem.basePrice * gljItem.consumeAmt, -3);
  369. if(gljItem.gljParentType === 1){
  370. labourPrc.push(singlePrc);
  371. }
  372. else if(gljItem.gljParentType ===2){
  373. materialPrc.push(singlePrc);
  374. }
  375. else if(gljItem.gljParentType === 3){
  376. machinePrc.push(singlePrc);
  377. }
  378. else if(gljItem.gljParentType === 6){
  379. managePrc.push(singlePrc);
  380. }
  381. else if(gljItem.gljParentType === 7){
  382. profitPrc.push(singlePrc);
  383. }
  384. else if(gljItem.gljParentType === 8){
  385. riskPrc.push(singlePrc);
  386. }
  387. }
  388. });
  389. if(labourPrc.length > 0){
  390. let sumLaP = 0;
  391. for(let i=0; i<labourPrc.length; i++){
  392. sumLaP = scMathUtil.roundTo(sumLaP + labourPrc[i], -6);
  393. }
  394. updatePrc.labourPrice = scMathUtil.roundTo(sumLaP, -2);
  395. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.labourPrice, -2);
  396. }
  397. if(materialPrc.length > 0){
  398. let sumMtP = 0;
  399. for(let i= 0; i<materialPrc.length; i++){
  400. sumMtP = scMathUtil.roundTo(sumMtP + materialPrc[i], -6);
  401. }
  402. updatePrc.materialPrice = scMathUtil.roundTo(sumMtP, -2);
  403. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.materialPrice, -2);
  404. }
  405. if(machinePrc.length > 0){
  406. let sumMaP = 0;
  407. for(let i =0; i< machinePrc.length; i++){
  408. sumMaP = scMathUtil.roundTo(sumMaP + machinePrc[i], -6);
  409. }
  410. updatePrc.machinePrice = scMathUtil.roundTo(sumMaP, -2);
  411. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.machinePrice, -2);
  412. }
  413. if(managePrc.length > 0){
  414. let sumMgP = 0;
  415. for(let i =0; i< managePrc.length; i++){
  416. sumMgP = scMathUtil.roundTo(sumMgP + managePrc[i], -6);
  417. }
  418. updatePrc.managePrice = scMathUtil.roundTo(sumMgP, -2);
  419. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.managePrice, -2);
  420. }
  421. if(profitPrc.length > 0){
  422. let sumPfP = 0;
  423. for(let i =0; i< profitPrc.length; i++){
  424. sumPfP = scMathUtil.roundTo(sumPfP + profitPrc[i], -6);
  425. }
  426. updatePrc.profitPrice = scMathUtil.roundTo(sumPfP, -2);
  427. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.profitPrice, -2);
  428. }
  429. if(riskPrc.length > 0){
  430. let sumRkP = 0;
  431. for(let i =0; i< riskPrc.length; i++){
  432. sumRkP = scMathUtil.roundTo(sumRkP + riskPrc[i], -6);
  433. }
  434. updatePrc.riskPrice = scMathUtil.roundTo(sumRkP, -2);
  435. updatePrc.basePrice = scMathUtil.roundTo(updatePrc.basePrice + updatePrc.riskPrice, -2);
  436. }
  437. return updatePrc;
  438. }
  439. rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, overWriteUrl, callback) {
  440. async.each(basePrcArr, function (basePrcObj, finalCb) {
  441. let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
  442. async.waterfall([
  443. function (cb) {
  444. if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
  445. rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
  446. if(err){
  447. cb(err);
  448. }
  449. else{
  450. //删除
  451. rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  452. if(err){
  453. cb(err);
  454. }
  455. else{
  456. //补充定额
  457. compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
  458. if(err){
  459. cb(err);
  460. }
  461. else {
  462. compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
  463. if(err){
  464. cb(err);
  465. }
  466. else {
  467. for(let i = 0, len = compleRst.length; i < len; i++){
  468. compleRst[i]._doc.type = 'complementary';
  469. }
  470. cb(null, result.concat(compleRst));
  471. }
  472. });
  473. }
  474. });
  475. }
  476. });
  477. }
  478. });
  479. }
  480. else{
  481. rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
  482. if(err){
  483. cb(err);
  484. }
  485. else{
  486. compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
  487. if(err){
  488. cb(err);
  489. }
  490. else {
  491. for(let i = 0, len = compleRst.length; i < len; i++){
  492. compleRst[i]._doc.type = 'complementary';
  493. }
  494. cb(null, result.concat(compleRst));
  495. }
  496. });
  497. }
  498. });
  499. }
  500. },
  501. function (result, cb) {
  502. let compleRTasks = [], stdRTasks = [];
  503. //重算时需要用到的所有工料机,一次性取
  504. let compleGljIds = [], stdGljIds = [];
  505. for(let ration of result){
  506. for(let glj of ration.rationGljList){
  507. if(glj.type !== undefined && glj.type === 'complementary'){
  508. compleGljIds.push(glj.gljId);
  509. }
  510. else {
  511. stdGljIds.push(glj.gljId);
  512. }
  513. }
  514. }
  515. gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
  516. if(err){
  517. cb(err);
  518. }
  519. else {
  520. let gljIndex = {};
  521. for(let glj of allGljs){
  522. gljIndex[glj.ID] = glj;
  523. }
  524. async.each(result, function (rationItem, ecb) {
  525. let rationGljList = rationItem.rationGljList;
  526. let gljArr = [];
  527. for(let i=0; i<rationGljList.length; i++){
  528. let theGlj = gljIndex[rationGljList[i].gljId];
  529. if(theGlj !== undefined && theGlj){
  530. let gljParentType = -1;
  531. if(theGlj.ID === adjGljId){
  532. theGlj.gljType = adjGljType;
  533. }
  534. if(theGlj.gljType <= 3){
  535. gljParentType = theGlj.gljType;
  536. } else if(theGlj.gljType > 200 && theGlj.gljType < 300){
  537. gljParentType = 2;
  538. } else if(theGlj.gljType > 300 && theGlj.gljType < 400){
  539. gljParentType = 3;
  540. } else if(theGlj.gljType === 6){ //管理费
  541. gljParentType = 6;
  542. } else if(theGlj.gljType === 7){ //利润
  543. gljParentType = 7;
  544. } else if(theGlj.gljType === 8){ //风险费
  545. gljParentType = 8;
  546. }
  547. if(theGlj)
  548. if(theGlj.ID === adjGljId){
  549. gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, gljParentType: gljParentType, unit: theGlj.unit});
  550. } else {
  551. if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
  552. gljArr.push({
  553. gljId: theGlj.ID,
  554. basePrice: parseFloat(theGlj.priceProperty.price1),
  555. gljParentType: gljParentType,
  556. unit: theGlj.unit});
  557. } else {
  558. gljArr.push({
  559. gljId: theGlj.ID,
  560. basePrice: parseFloat(theGlj.basePrice),
  561. gljParentType: gljParentType,
  562. unit: theGlj.unit});
  563. }
  564. }
  565. }
  566. }
  567. gljArr.forEach(function (gljItem) {
  568. rationGljList.forEach(function (rationGlj) {
  569. if(gljItem.gljId === rationGlj.gljId){
  570. gljItem.consumeAmt = parseFloat(rationGlj.consumeAmt);
  571. }
  572. })
  573. });
  574. let updatePrc = null;
  575. let overWriteCalc = false; //需要重写算法
  576. if (overWriteUrl) {
  577. let overWriteExports = require(overWriteUrl);
  578. if (typeof overWriteExports.calcRation !== 'undefined') {
  579. overWriteCalc = true;
  580. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  581. }
  582. }
  583. if (!overWriteCalc) {
  584. updatePrc = calcRation(gljArr);
  585. }
  586. let task = {
  587. updateOne: {
  588. filter: {
  589. ID: rationItem.ID
  590. },
  591. update: {
  592. labourPrice: updatePrc.labourPrice.toString(),
  593. materialPrice: updatePrc.materialPrice.toString(),
  594. machinePrice: updatePrc.machinePrice.toString(),
  595. basePrice: updatePrc.basePrice.toString()
  596. }
  597. }
  598. };
  599. //updateDataBase
  600. if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
  601. compleRTasks.push(task);
  602. ecb(null);
  603. }
  604. else {
  605. stdRTasks.push(task);
  606. ecb(null);
  607. }
  608. }, async function(err){
  609. if(err){
  610. cb(err);
  611. }
  612. else {
  613. //do sth
  614. try{
  615. if(compleRTasks.length > 0){
  616. await compleRationModel.bulkWrite(compleRTasks);
  617. }
  618. if(stdRTasks.length > 0){
  619. await rationItemModel.bulkWrite(stdRTasks);
  620. }
  621. }
  622. catch(e){
  623. cb(err);
  624. }
  625. cb(null);
  626. }
  627. });
  628. }
  629. });
  630. },
  631. ], function (err) {
  632. if(err){
  633. finalCb(err);
  634. }
  635. else{
  636. finalCb(null);
  637. }
  638. });
  639. }, function (err) {
  640. if(err){
  641. callback(err, 'Error');
  642. }
  643. else{
  644. callback(null, '');
  645. }
  646. });
  647. };
  648. rationItemDAO.prototype.getRationGljIds = function (data, callback) {
  649. let repId = data.repId;
  650. rationItemModel.find({rationRepId: repId}, function (err, result) {
  651. if(err){
  652. callback(err, 'Error', null);
  653. }
  654. else{
  655. let rstIds = [], newRst = [];
  656. result.forEach(function (data) {
  657. if(data.rationGljList.length >0){
  658. data.rationGljList.forEach(function (gljObj) {
  659. rstIds.push(gljObj.gljId);
  660. })
  661. }
  662. });
  663. for(let i= 0; i< rstIds.length; i++){
  664. if(newRst.indexOf(rstIds[i]) === -1){
  665. newRst.push(rstIds[i]);
  666. }
  667. }
  668. callback(null, '', newRst);
  669. }
  670. });
  671. };
  672. rationItemDAO.prototype.getRationsCodes = function (data, callback) {
  673. let repId = data.repId;
  674. rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
  675. if(err){
  676. callback(err, 'Error', null);
  677. }
  678. else{
  679. let rstCodes = [];
  680. result.forEach(function (rationItem) {
  681. rstCodes.push(rationItem.code);
  682. });
  683. callback(null, 'get all rationCodes success', rstCodes);
  684. }
  685. })
  686. };
  687. rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
  688. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  689. async.each(updateArr, function (obj, cb) {
  690. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
  691. if(err){
  692. cb(err);
  693. }
  694. else{
  695. cb(null);
  696. }
  697. })
  698. }, function (err) {
  699. if(err){
  700. callback(err);
  701. }
  702. else{
  703. callback(null);
  704. }
  705. });
  706. });
  707. }
  708. rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
  709. rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
  710. async.each(updateArr, function (obj, cb) {
  711. rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
  712. if(err){
  713. cb(err);
  714. }
  715. else{
  716. cb(null);
  717. }
  718. })
  719. }, function (err) {
  720. if(err){
  721. callback(err);
  722. }
  723. else{
  724. callback(null);
  725. }
  726. });
  727. });
  728. };
  729. //更新定额下模板关联
  730. rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
  731. //自动匹配定额
  732. let matachCodes = [],
  733. matchRations = [];
  734. //要保存的数据
  735. let saveData = [];
  736. for (let data of templateData) {
  737. if (data.code) {
  738. matachCodes.push(data.code);
  739. }
  740. }
  741. matachCodes = Array.from(new Set(matachCodes));
  742. if (matachCodes.length > 0) {
  743. matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
  744. }
  745. let validData = [];
  746. //设置展示数据
  747. for (let data of templateData) {
  748. let match = false;
  749. for (let ration of matchRations) {
  750. if (data.code && data.code === ration.code) {
  751. match = true;
  752. data.name = ration.name;
  753. data.rationID = ration.ID;
  754. break;
  755. }
  756. }
  757. if (!match) {
  758. data.code = '';
  759. data.name = '';
  760. }
  761. if (data.type || data.code || data.name || data.billsLocation) {
  762. validData.push(data);
  763. }
  764. }
  765. for (let data of validData) {
  766. saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
  767. }
  768. //更新
  769. await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
  770. return validData;
  771. };
  772. // 根据章节列表批量更新定额
  773. rationItemDAO.prototype.updateRationBySection = async function (rationRepId, sectionList, updateData) {
  774. await rationItemModel.updateMany({rationRepId, sectionId: {$in: sectionList}}, updateData);
  775. }
  776. //计算导入数据的价格
  777. rationItemDAO.prototype.calcForRation = function (stdGljList, ration, overWriteUrl) {
  778. let rationGljList = ration.rationGljList,
  779. gljArr = [];
  780. for(let rationGlj of rationGljList) {
  781. let glj = stdGljList[rationGlj.gljId];
  782. let gljPType = parseInt(glj.gljType.toString().match(/\d+?/)[0]);
  783. let newGlj = {
  784. gljId: glj.ID,
  785. consumeAmt: rationGlj.consumeAmt,
  786. gljParentType: gljPType,
  787. unit: glj.unit
  788. };
  789. newGlj.basePrice = glj.priceProperty && Object.keys(glj.priceProperty).length > 0
  790. ? parseFloat(glj.priceProperty.price1)
  791. : parseFloat(glj.basePrice);
  792. gljArr.push(newGlj);
  793. }
  794. let updatePrc = null;
  795. let overWriteCalc = false; //需要重写算法
  796. if (overWriteUrl) {
  797. let overWriteExports = require(overWriteUrl);
  798. if (typeof overWriteExports.calcRation !== 'undefined') {
  799. overWriteCalc = true;
  800. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  801. }
  802. }
  803. if (!overWriteCalc) {
  804. updatePrc = calcRation(gljArr);
  805. }
  806. ration.labourPrice = updatePrc.labourPrice.toString();
  807. ration.materialPrice = updatePrc.materialPrice.toString();
  808. ration.machinePrice = updatePrc.machinePrice.toString();
  809. ration.basePrice = updatePrc.basePrice.toString();
  810. };
  811. /**
  812. * 根据条件获取定额数据
  813. *
  814. * @param {Object} condition
  815. * @param {Object} fields
  816. * @param {String} indexBy
  817. * @return {Promise|Array}
  818. */
  819. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  820. let result = [];
  821. if (Object.keys(condition).length <= 0) {
  822. return result;
  823. }
  824. result = await rationItemModel.find(condition, fields).sort({code: 1});
  825. if (indexBy !== null && result.length > 0) {
  826. let tmpResult = {};
  827. for(let tmp of result) {
  828. tmpResult[tmp[indexBy]] = tmp;
  829. }
  830. result = tmpResult;
  831. }
  832. return result;
  833. };
  834. /**
  835. * 从excel中批量新增数据
  836. *
  837. * @param {Number} rationRepId
  838. * @param {Array} data
  839. * @return {bool}
  840. */
  841. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  842. if (data.length <= 0) {
  843. return false;
  844. }
  845. // 获取定额库相关数据
  846. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  847. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  848. return false;
  849. }
  850. // 获取标准工料机库数据
  851. const stdBillsLibListsModel = new STDGLJListModel();
  852. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  853. // 整理标准工料机库数据
  854. let stdGLJList = {};
  855. let stdGLJListByID = {};
  856. for (const tmp of stdGLJData) {
  857. stdGLJList[tmp.code.toString()] = tmp.ID;
  858. stdGLJListByID[tmp.ID] = tmp;
  859. }
  860. let lastData = {};
  861. // 定额xx下提示的次数
  862. let lastFailCount = 0;
  863. const rationData = [];
  864. // 编码列表,用于查找库中是否有对应数据
  865. let rationCodeList = [];
  866. let gljCodeList = [];
  867. // 插入失败的工料机列表(用于提示)
  868. let failGLJList = [];
  869. for (const tmp of data) {
  870. if (tmp.length <= 0) {
  871. continue;
  872. }
  873. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  874. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  875. // 如果不存在对应的工料机库数据则跳过
  876. if (stdGLJList[tmp[1]] === undefined) {
  877. if (lastFailCount === 0) {
  878. failGLJList.push('定额' + lastData.code + '下的');
  879. lastFailCount++;
  880. }
  881. //const failString = '定额' + lastData.code + '下的' + tmp[1];
  882. failGLJList.push(tmp[1]);
  883. continue;
  884. }
  885. const tmpRationGlj = {
  886. gljId: stdGLJList[tmp[1]],
  887. consumeAmt: Math.abs(tmp[4]),
  888. proportion: 0,
  889. };
  890. lastData.rationGljList.push(tmpRationGlj);
  891. if (gljCodeList.indexOf(tmp[1]) < 0) {
  892. gljCodeList.push(tmp[1]);
  893. }
  894. continue;
  895. }
  896. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  897. rationData.push(lastData);
  898. }
  899. lastFailCount = 0;
  900. // 组装数据
  901. lastData = {
  902. code: tmp[1],
  903. name: tmp[2],
  904. unit: tmp[3],
  905. caption: tmp[2],
  906. rationRepId: rationRepId,
  907. sectionId: 0,
  908. labourPrice: '0',
  909. materialPrice: '0',
  910. machinePrice: '0',
  911. basePrice: '0',
  912. rationGljList: []
  913. };
  914. // 防止重复加入
  915. if (rationCodeList.indexOf(tmp[1]) < 0) {
  916. rationCodeList.push(tmp[1]);
  917. }
  918. }
  919. // 最后一个入数组
  920. rationData.push(lastData);
  921. // 查找数据库中是否已存在待插入数据
  922. const condition = {
  923. rationRepId: rationRepId,
  924. code: { $in: rationCodeList }
  925. };
  926. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  927. // 过滤插入数据
  928. let insertData = [];
  929. //已存在定额,则更新价格及rationGLjList字段
  930. let updateData = [];
  931. for (const ration of rationData) {
  932. if (existCodeList[ration.code] !== undefined) {
  933. updateData.push(ration);
  934. continue;
  935. }
  936. insertData.push(ration);
  937. }
  938. //更新定额
  939. let updateBulk = [];
  940. for(let ration of updateData){
  941. this.calcForRation(stdGLJListByID, ration);
  942. updateBulk.push({
  943. updateOne: {
  944. filter: {rationRepId: rationRepId, code: ration.code},
  945. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  946. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  947. }
  948. });
  949. }
  950. //更新数据库
  951. if(updateBulk.length > 0){
  952. await rationItemModel.bulkWrite(updateBulk);
  953. }
  954. // 如果都已经存在,直接返回
  955. if (insertData.length <= 0) {
  956. return failGLJList;
  957. }
  958. //计算价格
  959. for(let ration of insertData){
  960. this.calcForRation(stdGLJListByID, ration);
  961. }
  962. // 组织id
  963. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  964. let maxId = counterInfo.sequence_value;
  965. maxId = parseInt(maxId);
  966. let count = 0;
  967. for (const index in insertData) {
  968. insertData[index].ID = maxId - (insertData.length - 1) + count;
  969. count++;
  970. }
  971. // 插入数据库
  972. await rationItemModel.create(insertData);
  973. return failGLJList;
  974. };
  975. /**
  976. * 导出到excel的数据
  977. *
  978. * @param {Number} rationRepId
  979. * @return {Array}
  980. */
  981. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  982. const condition = {
  983. rationRepId: rationRepId
  984. };
  985. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice', 'jobContent', 'annotation']);
  986. // 整理数据
  987. let rationData = [];
  988. for (const tmp of rationDataList) {
  989. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  990. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  991. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice, tmp.jobContent, tmp.annotation];
  992. rationData.push(ration);
  993. }
  994. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价', '工作内容', '附注']];
  995. excelData.push.apply(excelData, rationData);
  996. return excelData;
  997. //根据编号排序,优先级:number-number-..., number, Anumber....
  998. /*let regConnector = /-/g,
  999. regLetter = /[a-z,A-Z]/g,
  1000. regNum = /\d+/g;
  1001. rationData.sort(function (a, b) {
  1002. let aCode = a[3],
  1003. bCode = b[3],
  1004. rst = 0;
  1005. function compareConnector(arrA, arrB) {
  1006. let lessArr = arrA.length <= arrB ? arrA : arrB;
  1007. for (let i = 0; i < lessArr.length; i++) {
  1008. let result = compareUnit(arrA[i], arrB[i]);
  1009. if (result !== 0) {
  1010. return result;
  1011. } else {
  1012. }
  1013. }
  1014. function compareUnit(uA, uB) {
  1015. let uAV = parseFloat(uA),
  1016. uBV = parseFloat(uB);
  1017. if (uAV > uBV) {
  1018. return 1;
  1019. } else if (uAV < uBV) {
  1020. return -1;
  1021. }
  1022. return 0;
  1023. }
  1024. }
  1025. if (regConnector.test(a) && !regConnector.test(b)) {
  1026. rst = -1;
  1027. } else if (!regConnector.test(a) && regConnector.test(b)) {
  1028. rst = 1;
  1029. } else if (regConnector.test(a) && regConnector.test(b)) {
  1030. }
  1031. });
  1032. rationData.sort(function (a, b) {
  1033. let aCode = a[3],
  1034. bCode = b[3],
  1035. rst = 0,
  1036. splitA = aCode.split('-'),
  1037. splitB = bCode.split('-');
  1038. if(splitA[0] > splitB[0]){
  1039. rst = 1;
  1040. }
  1041. else if(splitA[0] < splitB[0]){
  1042. rst = -1;
  1043. }
  1044. else {
  1045. if(splitA[1] && splitB[1]){
  1046. let floatA = parseFloat(splitA[1]),
  1047. floatB = parseFloat(splitB[1]);
  1048. if(floatA > floatB){
  1049. rst = 1;
  1050. }
  1051. else if(floatA < floatB){
  1052. rst = -1;
  1053. }
  1054. }
  1055. }
  1056. return rst;
  1057. });*/
  1058. /*const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  1059. excelData.push.apply(excelData, rationData);
  1060. return excelData;*/
  1061. };
  1062. /**
  1063. * 批量更改章节id
  1064. *
  1065. * @param {Object} data
  1066. * @return {bool}
  1067. */
  1068. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  1069. if (data.length <= 0) {
  1070. return false;
  1071. }
  1072. // 批量执行update
  1073. let bulkOprs = [],
  1074. sectionIDs = [];
  1075. for (const tmp of data) {
  1076. let rationId = parseInt(tmp[2]);
  1077. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  1078. let sectionId = parseInt(tmp[0]);
  1079. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  1080. if (sectionId <= 0 || rationId <= 0) {
  1081. continue;
  1082. }
  1083. sectionIDs.push(sectionId);
  1084. // 取费专业
  1085. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  1086. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  1087. let name = tmp[4];
  1088. name = name ? name : '';
  1089. let caption = tmp[5];
  1090. caption = caption ? caption : '';
  1091. let jobContent = tmp[7] ? tmp[7] : '';
  1092. let annotation = tmp[8] ? tmp[8] : '';
  1093. bulkOprs.push({updateOne: {
  1094. filter: {ID: rationId},
  1095. update: {$set: {
  1096. sectionId,
  1097. feeType,
  1098. name,
  1099. caption,
  1100. jobContent,
  1101. annotation
  1102. }}}
  1103. });
  1104. }
  1105. if(bulkOprs.length <= 0){
  1106. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1107. }
  1108. await rationItemModel.bulkWrite(bulkOprs);
  1109. // 更新章节树工作内容、附注节点选项(全设置为ALL)
  1110. sectionIDs = Array.from(new Set(sectionIDs));
  1111. if (sectionIDs.length) {
  1112. await stdRationSectionModel.updateMany(
  1113. {ID: {$in: sectionIDs}},
  1114. {$set: {
  1115. jobContentSituation: 'ALL',
  1116. annotationSituation: 'ALL'
  1117. }}
  1118. )
  1119. }
  1120. };
  1121. module.exports = new rationItemDAO();