ration_item.js 43 KB

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