ration_repository_controller.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /**
  2. * Created by Tony on 2017/4/20.
  3. */
  4. const mongoose = require('mongoose');
  5. var rationRepository = require("../models/repository_map");
  6. import baseController from "../../common/base/base_controller";
  7. import CompilationModel from "../../users/models/compilation_model";
  8. const gljMapModel = mongoose.model('std_glj_lib_map');
  9. import async from "async";
  10. var callback = function(req, res, err, message, data){
  11. res.json({error: err, message: message, data: data});
  12. };
  13. // 上传控件
  14. const multiparty = require("multiparty");
  15. const fs = require("fs");
  16. // excel解析
  17. const excel = require("node-xlsx");
  18. const rationItem = require("../models/ration_item");
  19. const rationLibModel = mongoose.model('std_ration_lib_map');
  20. const rationItemModel = mongoose.model('std_ration_lib_ration_items');
  21. import STDGLJListModel from '../../std_glj_lib/models/gljModel';
  22. class RationRepositoryController extends baseController {
  23. // 定额页面初始化数据
  24. async prepareInitData(req, res) {
  25. try {
  26. const data = JSON.parse(req.body.data);
  27. const rst = await rationItem.prepareInitData(data.rationRepId);
  28. // console.log(rst);
  29. // fs.writeFile(`D:/GitHome/YangHuOperation/tmp/testDataResult_${(new Date()).getTime()}.js`, JSON.stringify(rst.sectionTree), { 'flag': 'a' }, function(err){ // 这个只是导出SectionTree
  30. // fs.writeFile(`D:/GitHome/YangHuOperation/tmp/testDataResult_${(new Date()).getTime()}.js`, JSON.stringify(rst), { 'flag': 'a' }, function(err){ // 这个导出全部
  31. // if(err) throw err;
  32. // });
  33. res.json({error: 0, message: 'success', data: rst});
  34. } catch (err) {
  35. console.log(err);
  36. res.json({error: 1, message: 'fail', data: null});
  37. }
  38. }
  39. async getRationLibsByCompilation(req, res){
  40. try{
  41. let data = JSON.parse(req.body.data);
  42. let rationLibs = await rationRepository.getRationLibsByCompilation(data.compilationId);
  43. callback(req, res, 0, '', rationLibs);
  44. }
  45. catch(err){
  46. callback(req, res, 1, err, null);
  47. }
  48. }
  49. async getCompilationList(req, res) {
  50. try {
  51. let compilationModel = new CompilationModel(), rst = [];
  52. let compilationList = await compilationModel.getCompilationList();
  53. if (compilationList.length <= 0) {
  54. throw '没有数据';
  55. }
  56. else {
  57. compilationList.forEach(function (compilation) {
  58. rst.push({_id: compilation._id, name: compilation.name});
  59. });
  60. //获得相关编办下的工料机库
  61. let parallelFucs = [];
  62. for (let i = 0; i < rst.length; i++) {
  63. parallelFucs.push((function (obj) {
  64. return function (cb) {
  65. gljMapModel.find({compilationId: obj._id, deleted: false}, function (err, result) {
  66. if (err) {
  67. cb(err);
  68. }
  69. else {
  70. cb(null, result);
  71. }
  72. })
  73. }
  74. })(rst[i]));
  75. }
  76. async.parallel(parallelFucs, function (err, result) {
  77. if (err) {
  78. callback(req, res, err, '没有数据', null);
  79. }
  80. else {
  81. let gljLibsRst = [];
  82. for (let i = 0; i < result.length; i++) {
  83. for (let j = 0; j < result[i].length; j++) {
  84. gljLibsRst.push(result[i][j]);
  85. }
  86. }
  87. callback(req, res, false, '', {compilation: rst, gljLibs: gljLibsRst});
  88. }
  89. })
  90. }
  91. }
  92. catch (err) {
  93. callback(req, res, err, '没有数据', null);
  94. }
  95. }
  96. addRationRepository(req, res) {
  97. var rationObj = JSON.parse(req.body.rationRepObj);
  98. rationRepository.addRationRepository(rationObj, function (err, data) {
  99. if (data) {
  100. callback(req, res, err, "has data", data);
  101. } else {
  102. callback(req, res, err, "no data", null);
  103. }
  104. })
  105. }
  106. getRationLib(req, res){
  107. let data = JSON.parse(req.body.data);
  108. let libId = data.libId;
  109. rationRepository.getRationLib(libId, function(err, data){
  110. if (data) {
  111. callback(req, res, err, "has data", data);
  112. } else {
  113. callback(req, res, err, "no data", null);
  114. }
  115. });
  116. }
  117. getDisPlayRationLibs(req, res) {
  118. rationRepository.getDisplayRationLibs(function (err, data) {
  119. if (data) {
  120. callback(req, res, err, "has data", data);
  121. } else {
  122. callback(req, res, err, "no data", null);
  123. }
  124. });
  125. }
  126. getRealLibName(req, res) {
  127. var libName = req.body.rationName;
  128. rationRepository.getRealLibName(libName, function (err, data) {
  129. if (data) {
  130. callback(req, res, err, "has data", data);
  131. } else {
  132. callback(req, res, err, "no data", null);
  133. }
  134. })
  135. }
  136. getLibIDByName(req, res) {
  137. rationRepository.getLibIDByName(req.body.libName, function (err, data) {
  138. if (data) {
  139. callback(req, res, err, "has ID", data);
  140. } else {
  141. callback(req, res, err, "no ID", null);
  142. }
  143. })
  144. }
  145. deleteRationLib(req, res) {
  146. let oprtor = req.body.oprtor,
  147. libId = req.body.libId;
  148. rationRepository.deleteRationLib(oprtor, libId, function (err, message) {
  149. callback(req, res, err, message, null);
  150. });
  151. }
  152. updateRationRepositoryName(req, res) {
  153. let oprtor = req.body.oprtor,
  154. renameObj = JSON.parse(req.body.renameObj);
  155. rationRepository.updateName(oprtor, renameObj, function (err, message) {
  156. callback(req, res, err, message, null);
  157. })
  158. }
  159. /**
  160. * 上传定额库原始数据
  161. *
  162. * @param {Object} request
  163. * @param {Object} response
  164. * @return {void}
  165. */
  166. async uploadSourceData(request, response) {
  167. let responseData = {
  168. err: 0,
  169. msg: ''
  170. };
  171. const allowHeader = [
  172. 'application/vnd.ms-excel',
  173. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  174. 'application/octet-stream'
  175. ];
  176. const uploadOption = {
  177. uploadDir: './public'
  178. };
  179. const form = new multiparty.Form(uploadOption);
  180. let uploadFullName
  181. form.parse(request, async function(err, fields, files) {
  182. try{
  183. const rationRepId = fields.rationRepId !== undefined && fields.rationRepId.length > 0 ?
  184. fields.rationRepId[0] : 0;
  185. const type = fields.type !== undefined && fields.type.length > 0 ?
  186. fields.type[0] : '';
  187. if (rationRepId <= 0 || type === '') {
  188. throw '参数错误';
  189. }
  190. const file = files.file !== undefined ? files.file[0] : null;
  191. if (err || file === null) {
  192. throw '上传失败';
  193. }
  194. // 判断类型
  195. if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
  196. throw '不支持该类型';
  197. }
  198. // 重命名文件名
  199. uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
  200. fs.renameSync(file.path, uploadFullName);
  201. const sheet = excel.parse(uploadFullName);
  202. if (sheet[0] === undefined || sheet[0].data === undefined) {
  203. throw 'excel没有对应数据';
  204. }
  205. const result = type === 'source_file' ?
  206. // 导入原始数据
  207. await rationItem.batchAddFromExcel(rationRepId, sheet[0].data) :
  208. // 导入内部数据
  209. await rationItem.batchUpdateSectionIdFromExcel(sheet[0].data);
  210. if (rationItem.failGLJList && rationItem.failGLJList.length > 0) {
  211. responseData.msg = rationItem.failGLJList.join("\r\n");
  212. rationItem.failGLJList = [];
  213. }
  214. // 删除文件
  215. if(uploadFullName && fs.existsSync(uploadFullName)){
  216. fs.unlink(uploadFullName);
  217. }
  218. response.json(responseData);
  219. }
  220. catch (error){
  221. console.log(error);
  222. if(uploadFullName && fs.existsSync(uploadFullName)){
  223. fs.unlink(uploadFullName);
  224. }
  225. responseData.err = 1;
  226. responseData.msg = error;
  227. response.json(responseData);
  228. }
  229. });
  230. return;
  231. }
  232. /**
  233. * 导出内部数据
  234. *
  235. * @param {Object} request
  236. * @param {Object} response
  237. * @return {void}
  238. */
  239. async exportRationData(request, response) {
  240. let rationRepId = request.query.rationRepId;
  241. rationRepId = parseInt(rationRepId);
  242. try {
  243. if (isNaN(rationRepId) || rationRepId <= 0) {
  244. throw '参数错误';
  245. }
  246. const excelData = await rationItem.exportExcelData(rationRepId);
  247. const buffer = excel.build([{name: "sheet", data: excelData}]);
  248. const filePath = './public/export.xlsx';
  249. fs.writeFileSync(filePath, buffer, 'binary');
  250. const stats = fs.statSync(filePath);
  251. // 下载相关header
  252. response.set({
  253. 'Content-Type': 'application/octet-stream',
  254. 'Content-Disposition': 'attachment; filename=ration.xlsx',
  255. 'Content-Length': stats.size
  256. });
  257. fs.createReadStream(filePath).pipe(response);
  258. fs.unlink(filePath);
  259. } catch (error) {
  260. response.end(error);
  261. }
  262. }
  263. //一键重新计算所有定额数据
  264. async reCalcAll(req, res){
  265. try{
  266. let data = JSON.parse(req.body.data);
  267. let rationRepId = data.rationRepId;
  268. let rationLib = await rationLibModel.findOne({ID: rationRepId, $or: [{deleted: null},{deleted: false}]});
  269. if(!rationLib){
  270. throw '不存在此定额库';
  271. }
  272. let task = [];
  273. // 获取标准工料机库数据
  274. const stdBillsLibListsModel = new STDGLJListModel();
  275. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib);
  276. // 整理标准工料机库数据
  277. let stdGLJList = {};
  278. let stdGLJListByID = {};
  279. for (const tmp of stdGLJData) {
  280. if (tmp.priceProperty && tmp.priceProperty.price1) {
  281. tmp.basePrice = tmp.priceProperty.price1;
  282. }
  283. stdGLJList[tmp.code.toString()] = tmp.ID;
  284. stdGLJListByID[tmp.ID] = tmp;
  285. }
  286. //获取所有的定额
  287. let allRations = await rationItemModel.find({rationRepId: rationRepId, $or: [{isDeleted: false}, {isDeleted: null}]});
  288. for(let ration of allRations){
  289. rationItem.calcForRation(stdGLJListByID, ration);
  290. task.push({
  291. updateOne: {
  292. filter: {ID: ration.ID},
  293. update: {$set: {basePrice: ration.basePrice}}
  294. }
  295. });
  296. }
  297. if(task.length > 0){
  298. await rationItemModel.bulkWrite(task);
  299. }
  300. res.json({error: 0, message: 'success', data: null});
  301. }
  302. catch (err){
  303. res.json({error: 1, message: err, data: null});
  304. }
  305. }
  306. }
  307. export default RationRepositoryController;
  308. /*
  309. module.exports = {
  310. addRationRepository:function(req,res){
  311. var rationObj = JSON.parse(req.body.rationRepObj);
  312. rationRepository.addRationRepository(rationObj,function(err,data){
  313. if (data) {
  314. callback(req, res, err, "has data", data);
  315. } else {
  316. callback(req, res, err, "no data", null);
  317. }
  318. })
  319. },
  320. getDisPlayRationLibs: function(req, res){
  321. rationRepository.getDisplayRationLibs(function(err, data){
  322. if (data) {
  323. callback(req, res, err, "has data",data);
  324. } else {
  325. callback(req, res, err, "no data", null);
  326. }
  327. });
  328. },
  329. getRealLibName:function(req,res){
  330. var libName = req.body.rationName;
  331. rationRepository.getRealLibName(libName,function(err,data){
  332. if (data) {
  333. callback(req, res, err, "has data", data);
  334. } else {
  335. callback(req, res, err, "no data", null);
  336. }
  337. })
  338. },
  339. getLibIDByName:function(req,res){
  340. rationRepository.getLibIDByName(req.body.libName, function(err,data){
  341. if (data) {
  342. callback(req, res, err, "has ID", data);
  343. } else {
  344. callback(req, res, err, "no ID", null);
  345. }
  346. })
  347. },
  348. deleteRationLib:function(req,res){
  349. var rationName = req.body.rationName;
  350. rationRepository.deleteRationLib(rationName,function(err,data){
  351. if (data) {
  352. callback(req, res, err, "has data", data);
  353. } else {
  354. callback(req, res, err, "no data", null);
  355. }
  356. })
  357. },
  358. updateRationRepositoryName: function(req, res) {
  359. var orgName = req.body.rationName;
  360. var newName = req.body.newName;
  361. rationRepository.updateName(orgName, newName, function(err, data){
  362. if (data) {
  363. callback(req, res, err, "has data", data);
  364. } else {
  365. callback(req, res, err, "no data", null);
  366. }
  367. });
  368. }
  369. }*/