ration_repository_controller.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. // 判断类型
  190. if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
  191. throw '不支持该类型';
  192. }
  193. // 重命名文件名
  194. uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
  195. fs.renameSync(file.path, uploadFullName);
  196. const sheet = excel.parse(uploadFullName);
  197. if (sheet[0] === undefined || sheet[0].data === undefined) {
  198. throw 'excel没有对应数据';
  199. }
  200. let failGLJList;
  201. switch (type) {
  202. // 导入原始数据
  203. case 'source_file':
  204. failGLJList = await rationItem.batchAddFromExcel(rationRepId, sheet[0].data);
  205. break;
  206. // 导入内部数据
  207. case 'import_data':
  208. failGLJList = await rationItem.batchUpdateSectionIdFromExcel(sheet[0].data);
  209. break;
  210. // 导入章节数据(一列文本,生成兄弟节点树)
  211. case 'section_file':
  212. await rationSectionTree.importSection(rationRepId, sheet[0].data);
  213. break;
  214. }
  215. if (Array.isArray(failGLJList) && failGLJList.length > 0) {
  216. responseData.msg = failGLJList.join("<br/>");
  217. }
  218. // 删除文件
  219. if(uploadFullName && fs.existsSync(uploadFullName)){
  220. fs.unlink(uploadFullName);
  221. }
  222. response.json(responseData);
  223. }
  224. catch (error){
  225. console.log(error);
  226. if(uploadFullName && fs.existsSync(uploadFullName)){
  227. fs.unlink(uploadFullName);
  228. }
  229. responseData.err = 1;
  230. responseData.msg = error;
  231. response.json(responseData);
  232. }
  233. });
  234. return;
  235. }
  236. /**
  237. * 导出内部数据
  238. *
  239. * @param {Object} request
  240. * @param {Object} response
  241. * @return {void}
  242. */
  243. async exportRationData(request, response) {
  244. let rationRepId = request.query.rationRepId;
  245. rationRepId = parseInt(rationRepId);
  246. try {
  247. if (isNaN(rationRepId) || rationRepId <= 0) {
  248. throw '参数错误';
  249. }
  250. const excelData = await rationItem.exportExcelData(rationRepId);
  251. const buffer = excel.build([{name: "sheet", data: excelData}]);
  252. const filePath = './public/export.xlsx';
  253. fs.writeFileSync(filePath, buffer, 'binary');
  254. const stats = fs.statSync(filePath);
  255. // 下载相关header
  256. response.set({
  257. 'Content-Type': 'application/octet-stream',
  258. 'Content-Disposition': 'attachment; filename=ration.xlsx',
  259. 'Content-Length': stats.size
  260. });
  261. fs.createReadStream(filePath).pipe(response);
  262. fs.unlink(filePath);
  263. } catch (error) {
  264. response.end(error);
  265. }
  266. }
  267. //一键重新计算所有定额数据
  268. async reCalcAll(req, res){
  269. try{
  270. let data = JSON.parse(req.body.data);
  271. let rationRepId = data.rationRepId;
  272. let rationLib = await rationLibModel.findOne({ID: rationRepId, $or: [{deleted: null},{deleted: false}]});
  273. if(!rationLib){
  274. throw '不存在此定额库';
  275. }
  276. let task = [];
  277. // 获取标准工料机库数据
  278. const stdBillsLibListsModel = new STDGLJListModel();
  279. const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib);
  280. // 整理标准工料机库数据
  281. let stdGLJList = {};
  282. let stdGLJListByID = {};
  283. for (const tmp of stdGLJData) {
  284. if (tmp.priceProperty && Object.keys(tmp.priceProperty).length) {
  285. tmp.basePrice = tmp.priceProperty.price1;
  286. }
  287. stdGLJList[tmp.code.toString()] = tmp.ID;
  288. stdGLJListByID[tmp.ID] = tmp;
  289. }
  290. //获取所有的定额
  291. let allRations = await rationItemModel.find({rationRepId: rationRepId, $or: [{isDeleted: false}, {isDeleted: null}]});
  292. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(rationLib.compilationId)});
  293. let tempUrl = compilation.overWriteUrl ? req.app.locals.rootDir + compilation.overWriteUrl : req.app.locals.rootDir;
  294. let absoluteUrl = fs.existsSync(tempUrl) && fs.statSync(tempUrl).isFile()? tempUrl : null;
  295. for(let ration of allRations){
  296. rationItem.calcForRation(stdGLJListByID, ration, absoluteUrl);
  297. task.push({
  298. updateOne: {
  299. filter: {ID: ration.ID},
  300. update: {$set: {labourPrice: ration.labourPrice, materialPrice: ration.materialPrice, machinePrice: ration.machinePrice, basePrice: ration.basePrice}}
  301. }
  302. });
  303. }
  304. if(task.length > 0){
  305. await rationItemModel.bulkWrite(task);
  306. }
  307. res.json({error: 0, message: 'success', data: null});
  308. }
  309. catch (err){
  310. res.json({error: 1, message: err, data: null});
  311. }
  312. }
  313. }
  314. export default RationRepositoryController;