ration_item.js 44 KB

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