ration_repository_controller.js 12 KB

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