index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import BaseController from "../../common/base/base_controller";
  2. import CompilationModel from '../../users/models/compilation_model';
  3. import { checkCompilationPermission } from '../../common/base/base_util';
  4. const multiparty = require('multiparty');
  5. const excel = require('node-xlsx');
  6. const fs = require('fs');
  7. const facade = require('../facade/index');
  8. const config = require("../../../config/config.js");
  9. class PriceInfoController extends BaseController {
  10. async main(req, res) {
  11. const compilationModel = new CompilationModel();
  12. const compilationList = await compilationModel.getPermissionCompilationList(req, { _id: 1, name: 1 });
  13. compilationList.unshift({ _id: 'all', name: '所有' });
  14. const activeCompilation = compilationList.find(compilation => compilation._id.toString() === req.query.filter);
  15. if (activeCompilation) {
  16. activeCompilation.active = 'active';
  17. } else {
  18. compilationList[0].active = 'active'
  19. }
  20. const filter = req.query.filter ? { compilationID: req.query.filter } : {};
  21. let libs = await facade.getLibs(filter);
  22. const compilationPermission = req.session.managerData.compilationPermission || [];
  23. libs = libs.filter(lib => compilationPermission.includes(lib.compilationID));
  24. libs.forEach(lib => {
  25. compilationList.forEach(compilation => {
  26. if (compilation._id.toString() === lib.compilationID) {
  27. lib.compilationName = compilation.name;
  28. }
  29. });
  30. });
  31. const listItem = `
  32. <li class="nav-item">
  33. <a class="nav-link" href="javascript:void(0);" aria-haspopup="true" aria-expanded="false" data-toggle="modal" data-target="#export-zj">导出材料信息价</a>
  34. </li>
  35. `
  36. const renderData = {
  37. title: '材料信息价库',
  38. userAccount: req.session.managerData.username,
  39. userID: req.session.managerData.userID,
  40. libs: libs,
  41. compilationList: compilationList,
  42. listItem,
  43. layout: 'maintain/common/html/layout'
  44. };
  45. res.render("maintain/price_info_lib/html/main.html", renderData);
  46. }
  47. async editView(req, res) {
  48. const { libID } = req.query;
  49. const libs = await facade.getLibs({ ID: libID });
  50. if (!libs.length) {
  51. return res.send(404);
  52. }
  53. checkCompilationPermission(req, res, libs[0].compilationID, '/priceInfo/main');
  54. const areaList = await facade.getAreas(libs[0].compilationID);
  55. const renderData = {
  56. compilationID: libs[0].compilationID,
  57. libName: libs[0].name,
  58. period: libs[0].period,
  59. areaList: JSON.stringify(areaList),
  60. userAccount: req.session.managerData.username,
  61. userID: req.session.managerData.userID,
  62. LicenseKey: config.getLicenseKey(process.env.NODE_ENV),
  63. };
  64. res.render("maintain/price_info_lib/html/edit.html", renderData);
  65. }
  66. async getAllLibs(req, res) {
  67. try {
  68. const data = await facade.getAllLibs();
  69. res.json({ error: 0, message: 'getAreas success', data });
  70. } catch (err) {
  71. console.log(err);
  72. res.json({ error: 1, message: err.toString() });
  73. }
  74. }
  75. async addLib(req, res) {
  76. try {
  77. const { name, period, compilationID } = req.body;
  78. await facade.createLib(name, period, compilationID)
  79. } catch (err) {
  80. console.log(err);
  81. }
  82. res.redirect(req.headers.referer);
  83. }
  84. async renameLib(req, res) {
  85. try {
  86. const { libID, name } = JSON.parse(req.body.data);
  87. await facade.updateLib({ ID: libID }, { name });
  88. res.json({ error: 0, message: 'rename success' });
  89. } catch (err) {
  90. console.log(err);
  91. res.json({ error: 1, message: err.toString() });
  92. }
  93. }
  94. async deleteLib(req, res) {
  95. try {
  96. const { libID } = JSON.parse(req.body.data);
  97. await facade.deleteLib(libID);
  98. res.json({ error: 0, message: 'delete success' });
  99. } catch (err) {
  100. console.log(err);
  101. res.json({ error: 1, message: err.toString() });
  102. }
  103. }
  104. async processChecking(req, res) {
  105. try {
  106. const { key } = JSON.parse(req.body.data);
  107. const data = await facade.processChecking(key);
  108. res.json({ error: 0, message: 'processChecking', data });
  109. } catch (err) {
  110. res.json({ error: 1, message: err.toString() });
  111. }
  112. }
  113. // 爬取数据
  114. async crawlData(req, res) {
  115. try {
  116. const { from, to, compilationID } = JSON.parse(req.body.data);
  117. //res.setTimeout(1000 * 60 * 60 * 2); // 不设置的话,处理时间过长,会触发默认的响应超时,报错(前端报错,后台还继续在处理)
  118. await facade.crawlDataByCompilation(compilationID, from, to);
  119. res.json({ error: 0, message: 'crawl processing' });
  120. } catch (err) {
  121. console.log(err);
  122. res.json({ error: 1, message: err.toString() });
  123. }
  124. }
  125. async importExcel(req, res) {
  126. let responseData = {
  127. err: 0,
  128. msg: ''
  129. };
  130. res.setTimeout(1000 * 60 * 10);
  131. const allowHeader = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  132. const uploadOption = {
  133. uploadDir: './public'
  134. };
  135. const form = new multiparty.Form(uploadOption);
  136. let uploadFullName;
  137. form.parse(req, async function (err, fields, files) {
  138. try {
  139. const libID = fields.libID !== undefined && fields.libID.length > 0 ?
  140. fields.libID[0] : null;
  141. const importType = fields.importType !== undefined && fields.importType.length > 0 ?
  142. fields.importType[0] : null;
  143. if (!libID || !importType) {
  144. throw '参数错误。';
  145. }
  146. const file = files.file !== undefined ? files.file[0] : null;
  147. if (err || file === null) {
  148. throw '上传失败。';
  149. }
  150. // 判断类型
  151. if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
  152. throw '不支持该类型';
  153. }
  154. // 重命名文件名
  155. uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
  156. fs.renameSync(file.path, uploadFullName);
  157. const sheet = excel.parse(uploadFullName, { raw: false });
  158. if (sheet[0] === undefined || sheet[0].data === undefined || sheet[0].data.length <= 0) {
  159. throw 'excel没有对应数据。';
  160. }
  161. // 提取excel数据并入库
  162. importType === 'originalData' ? await facade.importExcelData(libID, sheet[0].data) : await facade.importKeyData(libID, sheet[0].data, sheet[1].data);
  163. // 删除文件
  164. if (uploadFullName && fs.existsSync(uploadFullName)) {
  165. fs.unlink(uploadFullName);
  166. }
  167. res.json(responseData);
  168. }
  169. catch (error) {
  170. console.log(error);
  171. if (uploadFullName && fs.existsSync(uploadFullName)) {
  172. fs.unlink(uploadFullName);
  173. }
  174. responseData.err = 1;
  175. responseData.msg = error.toString();
  176. res.json(responseData);
  177. }
  178. });
  179. }
  180. async editArea(req, res) {
  181. try {
  182. const { updateData } = JSON.parse(req.body.data);
  183. await facade.updateAres(updateData);
  184. res.json({ error: 0, message: 'update areas success' });
  185. } catch (err) {
  186. console.log(err);
  187. res.json({ error: 1, message: err.toString() });
  188. }
  189. }
  190. async insertArea(req, res) {
  191. try {
  192. const { insertData } = JSON.parse(req.body.data);
  193. await facade.insertAreas(insertData);
  194. res.json({ error: 0, message: 'update areas success' });
  195. } catch (err) {
  196. console.log(err);
  197. res.json({ error: 1, message: err.toString() });
  198. }
  199. }
  200. async deleteArea(req, res) {
  201. try {
  202. const { deleteData } = JSON.parse(req.body.data);
  203. await facade.deleteAreas(deleteData);
  204. res.json({ error: 0, message: 'update areas success' });
  205. } catch (err) {
  206. console.log(err);
  207. res.json({ error: 1, message: err.toString() });
  208. }
  209. }
  210. async getClassData(req, res) {
  211. try {
  212. const { libID, areaID } = JSON.parse(req.body.data);
  213. const data = await facade.getClassData(libID, areaID);
  214. res.json({ error: 0, message: 'getCLass success', data });
  215. } catch (err) {
  216. console.log(err);
  217. res.json({ error: 1, message: err.toString() });
  218. }
  219. }
  220. async calcPriceIndex(req, res) {
  221. try {
  222. const { period, libID, compilationID } = JSON.parse(req.body.data);
  223. const areaID = '971fb9a0-0f93-11eb-b53c-45271c1df90f';//写死珠海地区
  224. const data = await facade.calcPriceIndex(libID, period, areaID, compilationID);
  225. res.json({ error: 0, message: 'getCLass success', data });
  226. } catch (err) {
  227. console.log(err);
  228. res.json({ error: 1, message: err.toString() });
  229. }
  230. }
  231. async getPriceData(req, res) {
  232. try {
  233. const { classIDList } = JSON.parse(req.body.data);
  234. const data = await facade.getPriceData(classIDList);
  235. res.json({ error: 0, message: 'getPriceData success', data });
  236. } catch (err) {
  237. console.log(err);
  238. res.json({ error: 1, message: err.toString() });
  239. }
  240. }
  241. async getPriceEmptyData(req, res) {
  242. try {
  243. const { libID, compilationID, areaID } = JSON.parse(req.body.data);
  244. const data = await facade.getPriceEmptyData(compilationID, libID, areaID);
  245. res.json({ error: 0, message: 'getPriceEmptyData success', data });
  246. } catch (err) {
  247. console.log(err);
  248. res.json({ error: 1, message: err.toString() });
  249. }
  250. }
  251. async getRecommendPriceSummaryData(req, res) {
  252. try {
  253. const { keyword } = JSON.parse(req.body.data);
  254. const data = await facade.getRecommendPriceSummaryData(keyword);
  255. res.json({ error: 0, message: 'getRecommendPriceSummaryData success', data });
  256. } catch (err) {
  257. console.log(err);
  258. res.json({ error: 1, message: err.toString() });
  259. }
  260. }
  261. async editPriceData(req, res) {
  262. try {
  263. const { postData } = JSON.parse(req.body.data);
  264. await facade.editPriceData(postData);
  265. res.json({ error: 0, message: 'editPrice success' });
  266. } catch (err) {
  267. console.log(err);
  268. res.json({ error: 1, message: err.toString() });
  269. }
  270. }
  271. async editClassData(req, res) {
  272. try {
  273. const { updateData } = JSON.parse(req.body.data);
  274. await facade.editClassData(updateData);
  275. res.json({ error: 0, message: 'editClass success' });
  276. } catch (err) {
  277. console.log(err);
  278. res.json({ error: 1, message: err.toString() });
  279. }
  280. }
  281. async batchUpdate(req, res) {
  282. try {
  283. const { priceItem, prop, val } = JSON.parse(req.body.data);
  284. await facade.batchUpdate(priceItem, prop, val);
  285. res.json({ error: 0, message: 'batchUpdate success' });
  286. } catch (err) {
  287. console.log(err);
  288. res.json({ error: 1, message: err.toString() });
  289. }
  290. }
  291. // 匹配总表
  292. async matchSummary(req, res) {
  293. try {
  294. const { compilationID, libID, areaID } = JSON.parse(req.body.data);
  295. await facade.matchSummary(compilationID, libID, areaID);
  296. res.json({ error: 0, message: 'matchSummary success' });
  297. } catch (err) {
  298. console.log(err);
  299. res.json({ error: 1, message: err.toString() });
  300. }
  301. }
  302. async exportInfoPriceByLib(request, response) {
  303. const libID = request.query.libID;
  304. try {
  305. const { jsonStr, period, name } = await facade.exportInfoPriceByLib(libID);
  306. const filePath = './public/exportInfoPriceByLib.json';
  307. fs.writeFileSync(filePath, jsonStr, 'utf8');
  308. const stats = fs.statSync(filePath);
  309. // 下载相关header
  310. console.log('name', name);
  311. response.set({
  312. 'Content-Type': 'application/octet-stream',
  313. 'Content-Disposition': `attachment; filename=${encodeURI(name)}.json`,
  314. 'Content-Length': stats.size
  315. });
  316. fs.createReadStream(filePath).pipe(response);
  317. fs.unlink(filePath);
  318. } catch (error) {
  319. response.end(error);
  320. }
  321. }
  322. async exportInfoPriceByCompilation(request, response) {
  323. const compilationID = request.query.compilationID;
  324. try {
  325. const compilationModel = new CompilationModel();
  326. const compilation = await compilationModel.getCompilationById(compilationID);
  327. if (!compilation) {
  328. throw new Error('不存在此编办!');
  329. }
  330. const { jsonStr } = await facade.exportInfoPriceByCompilation(compilationID);
  331. const filePath = './public/exportInfoPriceByCompilation.json';
  332. fs.writeFileSync(filePath, jsonStr, 'utf8');
  333. const stats = fs.statSync(filePath);
  334. const fileName = `${compilation.name}信息价`;
  335. // 下载相关header
  336. response.set({
  337. 'Content-Type': 'application/octet-stream',
  338. 'Content-Disposition': `attachment; filename=${encodeURI(fileName)}.json`,
  339. 'Content-Length': stats.size
  340. });
  341. fs.createReadStream(filePath).pipe(response);
  342. fs.unlink(filePath);
  343. } catch (error) {
  344. response.end(error);
  345. }
  346. }
  347. /**
  348. * 导出浙江省材料价格信息excel
  349. * @param {Object} request
  350. * @param {Object} response
  351. * @return {void}
  352. */
  353. async exportZheJiangExcel(request, response) {
  354. try {
  355. const { from, to } = request.query;
  356. const excelData = await facade.getZheJiangSheetData(from, to);
  357. const sheetOptions = { '!cols': [{ wch: 15 }, { wch: 10 }, { wch: 10 }, { wch: 10 }, { wch: 15 }, { wch: 10 }] };
  358. const buffer = excel.build([{ name: "sheet", data: excelData }], sheetOptions);
  359. const filePath = './public/price.xlsx';
  360. fs.writeFileSync(filePath, buffer, 'binary');
  361. const stats = fs.statSync(filePath);
  362. const filename = '浙江信息价.xlsx';
  363. const encoded = encodeURIComponent(filename);
  364. response.set({
  365. 'Content-Type': 'application/octet-stream',
  366. 'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
  367. 'Content-Length': stats.size
  368. });
  369. fs.createReadStream(filePath).pipe(response);
  370. fs.unlink(filePath);
  371. } catch (error) {
  372. response.end(error);
  373. }
  374. }
  375. }
  376. module.exports = {
  377. priceInfoController: new PriceInfoController()
  378. };