ration_item.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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.updateRationBySection = async function (rationRepId, sectionList, updateData) {
  745. await rationItemModel.updateMany({rationRepId, sectionId: {$in: sectionList}}, updateData);
  746. }
  747. //计算导入数据的价格
  748. rationItemDAO.prototype.calcForRation = function (stdGljList, ration, overWriteUrl) {
  749. let rationGljList = ration.rationGljList,
  750. gljArr = [];
  751. for(let rationGlj of rationGljList) {
  752. let glj = stdGljList[rationGlj.gljId];
  753. let gljPType = parseInt(glj.gljType.toString().match(/\d+?/)[0]);
  754. let newGlj = {
  755. gljId: glj.ID,
  756. consumeAmt: rationGlj.consumeAmt,
  757. gljParentType: gljPType,
  758. unit: glj.unit
  759. };
  760. newGlj.basePrice = glj.priceProperty && Object.keys(glj.priceProperty).length > 0
  761. ? parseFloat(glj.priceProperty.price1)
  762. : parseFloat(glj.basePrice);
  763. gljArr.push(newGlj);
  764. }
  765. let updatePrc = null;
  766. let overWriteCalc = false; //需要重写算法
  767. if (overWriteUrl) {
  768. let overWriteExports = require(overWriteUrl);
  769. if (typeof overWriteExports.calcRation !== 'undefined') {
  770. overWriteCalc = true;
  771. updatePrc = overWriteExports.calcRation(gljArr, scMathUtil);
  772. }
  773. }
  774. if (!overWriteCalc) {
  775. updatePrc = calcRation(gljArr);
  776. }
  777. ration.labourPrice = updatePrc.labourPrice.toString();
  778. ration.materialPrice = updatePrc.materialPrice.toString();
  779. ration.machinePrice = updatePrc.machinePrice.toString();
  780. ration.basePrice = updatePrc.basePrice.toString();
  781. };
  782. /**
  783. * 根据条件获取定额数据
  784. *
  785. * @param {Object} condition
  786. * @param {Object} fields
  787. * @param {String} indexBy
  788. * @return {Promise|Array}
  789. */
  790. rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
  791. let result = [];
  792. if (Object.keys(condition).length <= 0) {
  793. return result;
  794. }
  795. result = await rationItemModel.find(condition, fields).sort({code: 1});
  796. if (indexBy !== null && result.length > 0) {
  797. let tmpResult = {};
  798. for(let tmp of result) {
  799. tmpResult[tmp[indexBy]] = tmp;
  800. }
  801. result = tmpResult;
  802. }
  803. return result;
  804. };
  805. /**
  806. * 从excel中批量新增数据
  807. *
  808. * @param {Number} rationRepId
  809. * @param {Array} data
  810. * @return {bool}
  811. */
  812. rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
  813. if (data.length <= 0) {
  814. return false;
  815. }
  816. // 获取定额库相关数据
  817. const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
  818. if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
  819. return false;
  820. }
  821. // 获取标准工料机库数据
  822. const stdBillsLibListsModel = new STDGLJListModel();
  823. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
  824. // 整理标准工料机库数据
  825. let stdGLJList = {};
  826. let stdGLJListByID = {};
  827. for (const tmp of stdGLJData) {
  828. stdGLJList[tmp.code.toString()] = tmp.ID;
  829. stdGLJListByID[tmp.ID] = tmp;
  830. }
  831. let lastData = {};
  832. // 定额xx下提示的次数
  833. let lastFailCount = 0;
  834. const rationData = [];
  835. // 编码列表,用于查找库中是否有对应数据
  836. let rationCodeList = [];
  837. let gljCodeList = [];
  838. // 插入失败的工料机列表(用于提示)
  839. let failGLJList = [];
  840. for (const tmp of data) {
  841. if (tmp.length <= 0) {
  842. continue;
  843. }
  844. // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
  845. if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
  846. // 如果不存在对应的工料机库数据则跳过
  847. if (stdGLJList[tmp[1]] === undefined) {
  848. if (lastFailCount === 0) {
  849. failGLJList.push('定额' + lastData.code + '下的');
  850. lastFailCount++;
  851. }
  852. //const failString = '定额' + lastData.code + '下的' + tmp[1];
  853. failGLJList.push(tmp[1]);
  854. continue;
  855. }
  856. const tmpRationGlj = {
  857. gljId: stdGLJList[tmp[1]],
  858. consumeAmt: tmp[4],
  859. proportion: 0,
  860. };
  861. lastData.rationGljList.push(tmpRationGlj);
  862. if (gljCodeList.indexOf(tmp[1]) < 0) {
  863. gljCodeList.push(tmp[1]);
  864. }
  865. continue;
  866. }
  867. if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
  868. rationData.push(lastData);
  869. }
  870. lastFailCount = 0;
  871. // 组装数据
  872. lastData = {
  873. code: tmp[1],
  874. name: tmp[2],
  875. unit: tmp[3],
  876. caption: tmp[2],
  877. rationRepId: rationRepId,
  878. sectionId: 0,
  879. labourPrice: '0',
  880. materialPrice: '0',
  881. machinePrice: '0',
  882. basePrice: '0',
  883. rationGljList: []
  884. };
  885. // 防止重复加入
  886. if (rationCodeList.indexOf(tmp[1]) < 0) {
  887. rationCodeList.push(tmp[1]);
  888. }
  889. }
  890. // 最后一个入数组
  891. rationData.push(lastData);
  892. // 查找数据库中是否已存在待插入数据
  893. const condition = {
  894. rationRepId: rationRepId,
  895. code: { $in: rationCodeList }
  896. };
  897. const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
  898. // 过滤插入数据
  899. let insertData = [];
  900. //已存在定额,则更新价格及rationGLjList字段
  901. let updateData = [];
  902. for (const ration of rationData) {
  903. if (existCodeList[ration.code] !== undefined) {
  904. updateData.push(ration);
  905. continue;
  906. }
  907. insertData.push(ration);
  908. }
  909. //更新定额
  910. let updateBulk = [];
  911. for(let ration of updateData){
  912. this.calcForRation(stdGLJListByID, ration);
  913. updateBulk.push({
  914. updateOne: {
  915. filter: {rationRepId: rationRepId, code: ration.code},
  916. update: {$set: {rationGljList: ration.rationGljList, labourPrice: ration.labourPrice, materialPrice: ration.materialPrice,
  917. machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  918. }
  919. });
  920. }
  921. //更新数据库
  922. if(updateBulk.length > 0){
  923. await rationItemModel.bulkWrite(updateBulk);
  924. }
  925. // 如果都已经存在,直接返回
  926. if (insertData.length <= 0) {
  927. return failGLJList;
  928. }
  929. //计算价格
  930. for(let ration of insertData){
  931. this.calcForRation(stdGLJListByID, ration);
  932. }
  933. // 组织id
  934. const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
  935. let maxId = counterInfo.sequence_value;
  936. maxId = parseInt(maxId);
  937. let count = 0;
  938. for (const index in insertData) {
  939. insertData[index].ID = maxId - (insertData.length - 1) + count;
  940. count++;
  941. }
  942. // 插入数据库
  943. await rationItemModel.create(insertData);
  944. return failGLJList;
  945. };
  946. /**
  947. * 导出到excel的数据
  948. *
  949. * @param {Number} rationRepId
  950. * @return {Array}
  951. */
  952. rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
  953. const condition = {
  954. rationRepId: rationRepId
  955. };
  956. const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice', 'jobContent', 'annotation']);
  957. // 整理数据
  958. let rationData = [];
  959. for (const tmp of rationDataList) {
  960. const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
  961. const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
  962. const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice, tmp.jobContent, tmp.annotation];
  963. rationData.push(ration);
  964. }
  965. const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价', '工作内容', '附注']];
  966. excelData.push.apply(excelData, rationData);
  967. return excelData;
  968. //根据编号排序,优先级:number-number-..., number, Anumber....
  969. /*let regConnector = /-/g,
  970. regLetter = /[a-z,A-Z]/g,
  971. regNum = /\d+/g;
  972. rationData.sort(function (a, b) {
  973. let aCode = a[3],
  974. bCode = b[3],
  975. rst = 0;
  976. function compareConnector(arrA, arrB) {
  977. let lessArr = arrA.length <= arrB ? arrA : arrB;
  978. for (let i = 0; i < lessArr.length; i++) {
  979. let result = compareUnit(arrA[i], arrB[i]);
  980. if (result !== 0) {
  981. return result;
  982. } else {
  983. }
  984. }
  985. function compareUnit(uA, uB) {
  986. let uAV = parseFloat(uA),
  987. uBV = parseFloat(uB);
  988. if (uAV > uBV) {
  989. return 1;
  990. } else if (uAV < uBV) {
  991. return -1;
  992. }
  993. return 0;
  994. }
  995. }
  996. if (regConnector.test(a) && !regConnector.test(b)) {
  997. rst = -1;
  998. } else if (!regConnector.test(a) && regConnector.test(b)) {
  999. rst = 1;
  1000. } else if (regConnector.test(a) && regConnector.test(b)) {
  1001. }
  1002. });
  1003. rationData.sort(function (a, b) {
  1004. let aCode = a[3],
  1005. bCode = b[3],
  1006. rst = 0,
  1007. splitA = aCode.split('-'),
  1008. splitB = bCode.split('-');
  1009. if(splitA[0] > splitB[0]){
  1010. rst = 1;
  1011. }
  1012. else if(splitA[0] < splitB[0]){
  1013. rst = -1;
  1014. }
  1015. else {
  1016. if(splitA[1] && splitB[1]){
  1017. let floatA = parseFloat(splitA[1]),
  1018. floatB = parseFloat(splitB[1]);
  1019. if(floatA > floatB){
  1020. rst = 1;
  1021. }
  1022. else if(floatA < floatB){
  1023. rst = -1;
  1024. }
  1025. }
  1026. }
  1027. return rst;
  1028. });*/
  1029. /*const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
  1030. excelData.push.apply(excelData, rationData);
  1031. return excelData;*/
  1032. };
  1033. /**
  1034. * 批量更改章节id
  1035. *
  1036. * @param {Object} data
  1037. * @return {bool}
  1038. */
  1039. rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
  1040. if (data.length <= 0) {
  1041. return false;
  1042. }
  1043. // 批量执行update
  1044. let bulkOprs = [],
  1045. sectionIDs = [];
  1046. for (const tmp of data) {
  1047. let rationId = parseInt(tmp[2]);
  1048. rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
  1049. let sectionId = parseInt(tmp[0]);
  1050. sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
  1051. if (sectionId <= 0 || rationId <= 0) {
  1052. continue;
  1053. }
  1054. sectionIDs.push(sectionId);
  1055. // 取费专业
  1056. let feeType = tmp[1] ? parseInt(tmp[1]) : null;
  1057. feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
  1058. let name = tmp[4];
  1059. name = name ? name : '';
  1060. let caption = tmp[5];
  1061. caption = caption ? caption : '';
  1062. let jobContent = tmp[7] ? tmp[7] : '';
  1063. let annotation = tmp[8] ? tmp[8] : '';
  1064. bulkOprs.push({updateOne: {
  1065. filter: {ID: rationId},
  1066. update: {$set: {
  1067. sectionId,
  1068. feeType,
  1069. name,
  1070. caption,
  1071. jobContent,
  1072. annotation
  1073. }}}
  1074. });
  1075. }
  1076. if(bulkOprs.length <= 0){
  1077. throw '无有效数据(树ID、定额ID不为空、且为数值)';
  1078. }
  1079. await rationItemModel.bulkWrite(bulkOprs);
  1080. // 更新章节树工作内容、附注节点选项(全设置为ALL)
  1081. sectionIDs = Array.from(new Set(sectionIDs));
  1082. if (sectionIDs.length) {
  1083. await stdRationSectionModel.updateMany(
  1084. {ID: {$in: sectionIDs}},
  1085. {$set: {
  1086. jobContentSituation: 'ALL',
  1087. annotationSituation: 'ALL'
  1088. }}
  1089. )
  1090. }
  1091. };
  1092. module.exports = new rationItemDAO();