ration_repository_controller.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 failGLJList = type === 'source_file' ?
  189. await rationItem.batchAddFromExcel(rationRepId, sheet[0].data) :
  190. await rationItem.batchUpdateSectionIdFromExcel(sheet[0].data);
  191. if (Array.isArray(failGLJList) && failGLJList.length > 0) {
  192. responseData.msg = failGLJList.join("<br/>");
  193. }
  194. // 删除文件
  195. if(uploadFullName && fs.existsSync(uploadFullName)){
  196. fs.unlink(uploadFullName);
  197. }
  198. response.json(responseData);
  199. }
  200. catch (error){
  201. console.log(error);
  202. if(uploadFullName && fs.existsSync(uploadFullName)){
  203. fs.unlink(uploadFullName);
  204. }
  205. responseData.err = 1;
  206. responseData.msg = error;
  207. response.json(responseData);
  208. }
  209. });
  210. return;
  211. }
  212. /**
  213. * 导出内部数据
  214. *
  215. * @param {Object} request
  216. * @param {Object} response
  217. * @return {void}
  218. */
  219. async exportRationData(request, response) {
  220. let rationRepId = request.query.rationRepId;
  221. rationRepId = parseInt(rationRepId);
  222. try {
  223. if (isNaN(rationRepId) || rationRepId <= 0) {
  224. throw '参数错误';
  225. }
  226. const excelData = await rationItem.exportExcelData(rationRepId);
  227. const buffer = excel.build([{name: "sheet", data: excelData}]);
  228. const filePath = './public/export.xlsx';
  229. fs.writeFileSync(filePath, buffer, 'binary');
  230. const stats = fs.statSync(filePath);
  231. // 下载相关header
  232. response.set({
  233. 'Content-Type': 'application/octet-stream',
  234. 'Content-Disposition': 'attachment; filename=ration.xlsx',
  235. 'Content-Length': stats.size
  236. });
  237. fs.createReadStream(filePath).pipe(response);
  238. fs.unlink(filePath);
  239. } catch (error) {
  240. response.end(error);
  241. }
  242. }
  243. //一键重新计算所有定额数据
  244. async reCalcAll(req, res){
  245. try{
  246. let data = JSON.parse(req.body.data);
  247. let rationRepId = data.rationRepId;
  248. let rationLib = await rationLibModel.findOne({ID: rationRepId, $or: [{deleted: null},{deleted: false}]});
  249. if(!rationLib){
  250. throw '不存在此定额库';
  251. }
  252. let task = [];
  253. // 获取标准工料机库数据
  254. const stdBillsLibListsModel = new STDGLJListModel();
  255. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib);
  256. // 整理标准工料机库数据
  257. let stdGLJList = {};
  258. let stdGLJListByID = {};
  259. for (const tmp of stdGLJData) {
  260. if (tmp.priceProperty && Object.keys(tmp.priceProperty).length) {
  261. tmp.basePrice = tmp.priceProperty.price1;
  262. }
  263. stdGLJList[tmp.code.toString()] = tmp.ID;
  264. stdGLJListByID[tmp.ID] = tmp;
  265. }
  266. //获取所有的定额
  267. let allRations = await rationItemModel.find({rationRepId: rationRepId, $or: [{isDeleted: false}, {isDeleted: null}]});
  268. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(rationLib.compilationId)});
  269. let tempUrl = compilation.overWriteUrl ? req.app.locals.rootDir + compilation.overWriteUrl : req.app.locals.rootDir;
  270. let absoluteUrl = fs.existsSync(tempUrl) && fs.statSync(tempUrl).isFile()? tempUrl : null;
  271. for(let ration of allRations){
  272. rationItem.calcForRation(stdGLJListByID, ration, absoluteUrl);
  273. task.push({
  274. updateOne: {
  275. filter: {ID: ration.ID},
  276. update: {$set: {labourPrice: ration.labourPrice, materialPrice: ration.materialPrice, machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  277. }
  278. });
  279. }
  280. if(task.length > 0){
  281. await rationItemModel.bulkWrite(task);
  282. }
  283. res.json({error: 0, message: 'success', data: null});
  284. }
  285. catch (err){
  286. res.json({error: 1, message: err, data: null});
  287. }
  288. }
  289. }
  290. export default RationRepositoryController;
  291. /*
  292. module.exports = {
  293. addRationRepository:function(req,res){
  294. var rationObj = JSON.parse(req.body.rationRepObj);
  295. rationRepository.addRationRepository(rationObj,function(err,data){
  296. if (data) {
  297. callback(req, res, err, "has data", data);
  298. } else {
  299. callback(req, res, err, "no data", null);
  300. }
  301. })
  302. },
  303. getDisPlayRationLibs: function(req, res){
  304. rationRepository.getDisplayRationLibs(function(err, data){
  305. if (data) {
  306. callback(req, res, err, "has data",data);
  307. } else {
  308. callback(req, res, err, "no data", null);
  309. }
  310. });
  311. },
  312. getRealLibName:function(req,res){
  313. var libName = req.body.rationName;
  314. rationRepository.getRealLibName(libName,function(err,data){
  315. if (data) {
  316. callback(req, res, err, "has data", data);
  317. } else {
  318. callback(req, res, err, "no data", null);
  319. }
  320. })
  321. },
  322. getLibIDByName:function(req,res){
  323. rationRepository.getLibIDByName(req.body.libName, function(err,data){
  324. if (data) {
  325. callback(req, res, err, "has ID", data);
  326. } else {
  327. callback(req, res, err, "no ID", null);
  328. }
  329. })
  330. },
  331. deleteRationLib:function(req,res){
  332. var rationName = req.body.rationName;
  333. rationRepository.deleteRationLib(rationName,function(err,data){
  334. if (data) {
  335. callback(req, res, err, "has data", data);
  336. } else {
  337. callback(req, res, err, "no data", null);
  338. }
  339. })
  340. },
  341. updateRationRepositoryName: function(req, res) {
  342. var orgName = req.body.rationName;
  343. var newName = req.body.newName;
  344. rationRepository.updateName(orgName, newName, function(err, data){
  345. if (data) {
  346. callback(req, res, err, "has data", data);
  347. } else {
  348. callback(req, res, err, "no data", null);
  349. }
  350. });
  351. }
  352. }*/