ration_repository_controller.js 13 KB

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