ration_repository_controller.js 13 KB

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