ration_repository_controller.js 13 KB

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