ration_repository_controller.js 14 KB

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