index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 deleteOrphanPriceItems(req, res) {
  105. try {
  106. const { libID } = JSON.parse(req.body.data);
  107. if (typeof libID !== 'string' || !libID.trim()) {
  108. return res.json({ error: 1, message: '无效的信息价库 ID' });
  109. }
  110. const [lib] = await facade.getLibs({ ID: libID });
  111. const compilationPermission = req.session.managerData.compilationPermission || [];
  112. if (!lib || !compilationPermission.includes(lib.compilationID)) {
  113. return res.json({ error: 1, message: '信息价库不存在或无权操作' });
  114. }
  115. const deletedCount = await facade.deleteOrphanPriceItems(libID);
  116. return res.json({ error: 0, data: { deletedCount } });
  117. } catch (err) {
  118. console.log(err);
  119. return res.json({ error: 1, message: '清理无分类材料失败' });
  120. }
  121. }
  122. async processChecking(req, res) {
  123. try {
  124. const { key } = JSON.parse(req.body.data);
  125. const data = await facade.processChecking(key);
  126. res.json({ error: 0, message: 'processChecking', data });
  127. } catch (err) {
  128. res.json({ error: 1, message: err.toString() });
  129. }
  130. }
  131. // 爬取数据
  132. async crawlData(req, res) {
  133. try {
  134. const { from, to, compilationID } = JSON.parse(req.body.data);
  135. //res.setTimeout(1000 * 60 * 60 * 2); // 不设置的话,处理时间过长,会触发默认的响应超时,报错(前端报错,后台还继续在处理)
  136. await facade.crawlDataByCompilation(compilationID, from, to);
  137. res.json({ error: 0, message: 'crawl processing' });
  138. } catch (err) {
  139. console.log(err);
  140. res.json({ error: 1, message: err.toString() });
  141. }
  142. }
  143. async importExcel(req, res) {
  144. let responseData = {
  145. err: 0,
  146. msg: ''
  147. };
  148. res.setTimeout(1000 * 60 * 10);
  149. const allowHeader = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  150. const uploadOption = {
  151. uploadDir: './public'
  152. };
  153. const form = new multiparty.Form(uploadOption);
  154. let uploadFullName;
  155. form.parse(req, async function (err, fields, files) {
  156. try {
  157. const libID = fields.libID !== undefined && fields.libID.length > 0 ?
  158. fields.libID[0] : null;
  159. const importType = fields.importType !== undefined && fields.importType.length > 0 ?
  160. fields.importType[0] : null;
  161. if (!libID || !importType) {
  162. throw '参数错误。';
  163. }
  164. const file = files.file !== undefined ? files.file[0] : null;
  165. if (err || file === null) {
  166. throw '上传失败。';
  167. }
  168. // 判断类型
  169. if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
  170. throw '不支持该类型';
  171. }
  172. // 重命名文件名
  173. uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
  174. fs.renameSync(file.path, uploadFullName);
  175. const sheet = excel.parse(uploadFullName, { raw: false });
  176. if (sheet[0] === undefined || sheet[0].data === undefined || sheet[0].data.length <= 0) {
  177. throw 'excel没有对应数据。';
  178. }
  179. // 提取excel数据并入库
  180. importType === 'originalData' ? await facade.importExcelData(libID, sheet[0].data) : await facade.importKeyData(libID, sheet[0].data, sheet[1].data);
  181. // 删除文件
  182. if (uploadFullName && fs.existsSync(uploadFullName)) {
  183. fs.unlink(uploadFullName);
  184. }
  185. res.json(responseData);
  186. }
  187. catch (error) {
  188. console.log(error);
  189. if (uploadFullName && fs.existsSync(uploadFullName)) {
  190. fs.unlink(uploadFullName);
  191. }
  192. responseData.err = 1;
  193. responseData.msg = error.toString();
  194. res.json(responseData);
  195. }
  196. });
  197. }
  198. async editArea(req, res) {
  199. try {
  200. const { updateData } = JSON.parse(req.body.data);
  201. await facade.updateAres(updateData);
  202. res.json({ error: 0, message: 'update areas success' });
  203. } catch (err) {
  204. console.log(err);
  205. res.json({ error: 1, message: err.toString() });
  206. }
  207. }
  208. async insertArea(req, res) {
  209. try {
  210. const { insertData } = JSON.parse(req.body.data);
  211. await facade.insertAreas(insertData);
  212. res.json({ error: 0, message: 'update areas success' });
  213. } catch (err) {
  214. console.log(err);
  215. res.json({ error: 1, message: err.toString() });
  216. }
  217. }
  218. async deleteArea(req, res) {
  219. try {
  220. const { deleteData } = JSON.parse(req.body.data);
  221. await facade.deleteAreas(deleteData);
  222. res.json({ error: 0, message: 'update areas success' });
  223. } catch (err) {
  224. console.log(err);
  225. res.json({ error: 1, message: err.toString() });
  226. }
  227. }
  228. async getClassData(req, res) {
  229. try {
  230. const { libID, areaID } = JSON.parse(req.body.data);
  231. const data = await facade.getClassData(libID, areaID);
  232. res.json({ error: 0, message: 'getCLass success', data });
  233. } catch (err) {
  234. console.log(err);
  235. res.json({ error: 1, message: err.toString() });
  236. }
  237. }
  238. async calcPriceIndex(req, res) {
  239. try {
  240. const { period, libID, compilationID } = JSON.parse(req.body.data);
  241. const areaID = '971fb9a0-0f93-11eb-b53c-45271c1df90f';//写死珠海地区
  242. const data = await facade.calcPriceIndex(libID, period, areaID, compilationID);
  243. res.json({ error: 0, message: 'getCLass success', data });
  244. } catch (err) {
  245. console.log(err);
  246. res.json({ error: 1, message: err.toString() });
  247. }
  248. }
  249. async getPriceData(req, res) {
  250. try {
  251. const { classIDList } = JSON.parse(req.body.data);
  252. const data = await facade.getPriceData(classIDList);
  253. res.json({ error: 0, message: 'getPriceData success', data });
  254. } catch (err) {
  255. console.log(err);
  256. res.json({ error: 1, message: err.toString() });
  257. }
  258. }
  259. async getPriceEmptyData(req, res) {
  260. try {
  261. const { libID, compilationID, areaID, matchAll } = JSON.parse(req.body.data);
  262. const data = await facade.getPriceEmptyData(compilationID, libID, areaID, matchAll);
  263. res.json({ error: 0, message: 'getPriceEmptyData success', data });
  264. } catch (err) {
  265. console.log(err);
  266. res.json({ error: 1, message: err.toString() });
  267. }
  268. }
  269. async getRecommendPriceSummaryData(req, res) {
  270. try {
  271. const { keyword } = JSON.parse(req.body.data);
  272. const data = await facade.getRecommendPriceSummaryData(keyword);
  273. res.json({ error: 0, message: 'getRecommendPriceSummaryData success', data });
  274. } catch (err) {
  275. console.log(err);
  276. res.json({ error: 1, message: err.toString() });
  277. }
  278. }
  279. async editPriceData(req, res) {
  280. try {
  281. const { postData } = JSON.parse(req.body.data);
  282. await facade.editPriceData(postData);
  283. res.json({ error: 0, message: 'editPrice success' });
  284. } catch (err) {
  285. console.log(err);
  286. res.json({ error: 1, message: err.toString() });
  287. }
  288. }
  289. async editClassData(req, res) {
  290. try {
  291. const { updateData } = JSON.parse(req.body.data);
  292. await facade.editClassData(updateData);
  293. res.json({ error: 0, message: 'editClass success' });
  294. } catch (err) {
  295. console.log(err);
  296. res.json({ error: 1, message: err.toString() });
  297. }
  298. }
  299. async batchUpdate(req, res) {
  300. try {
  301. const { priceItem, prop, val } = JSON.parse(req.body.data);
  302. await facade.batchUpdate(priceItem, prop, val);
  303. res.json({ error: 0, message: 'batchUpdate success' });
  304. } catch (err) {
  305. console.log(err);
  306. res.json({ error: 1, message: err.toString() });
  307. }
  308. }
  309. // 匹配总表
  310. async matchSummary(req, res) {
  311. try {
  312. const { compilationID, libID, areaID, matchAll } = JSON.parse(req.body.data);
  313. await facade.matchSummary(compilationID, libID, areaID, matchAll);
  314. res.json({ error: 0, message: 'matchSummary success' });
  315. } catch (err) {
  316. console.log(err);
  317. res.json({ error: 1, message: err.toString() });
  318. }
  319. }
  320. async exportInfoPriceByLib(request, response) {
  321. const libID = request.query.libID;
  322. try {
  323. const { jsonStr, period, name } = await facade.exportInfoPriceByLib(libID);
  324. const filePath = './public/exportInfoPriceByLib.json';
  325. fs.writeFileSync(filePath, jsonStr, 'utf8');
  326. const stats = fs.statSync(filePath);
  327. // 下载相关header
  328. console.log('name', name);
  329. response.set({
  330. 'Content-Type': 'application/octet-stream',
  331. 'Content-Disposition': `attachment; filename=${encodeURI(name)}.json`,
  332. 'Content-Length': stats.size
  333. });
  334. fs.createReadStream(filePath).pipe(response);
  335. fs.unlink(filePath);
  336. } catch (error) {
  337. response.end(error);
  338. }
  339. }
  340. async exportInfoPriceByCompilation(request, response) {
  341. const compilationID = request.query.compilationID;
  342. try {
  343. const compilationModel = new CompilationModel();
  344. const compilation = await compilationModel.getCompilationById(compilationID);
  345. if (!compilation) {
  346. throw new Error('不存在此编办!');
  347. }
  348. const { jsonStr } = await facade.exportInfoPriceByCompilation(compilationID);
  349. const filePath = './public/exportInfoPriceByCompilation.json';
  350. fs.writeFileSync(filePath, jsonStr, 'utf8');
  351. const stats = fs.statSync(filePath);
  352. const fileName = `${compilation.name}信息价`;
  353. // 下载相关header
  354. response.set({
  355. 'Content-Type': 'application/octet-stream',
  356. 'Content-Disposition': `attachment; filename=${encodeURI(fileName)}.json`,
  357. 'Content-Length': stats.size
  358. });
  359. fs.createReadStream(filePath).pipe(response);
  360. fs.unlink(filePath);
  361. } catch (error) {
  362. response.end(error);
  363. }
  364. }
  365. /**
  366. * 导出浙江省材料价格信息excel
  367. * @param {Object} request
  368. * @param {Object} response
  369. * @return {void}
  370. */
  371. async exportZheJiangExcel(request, response) {
  372. try {
  373. const { from, to } = request.query;
  374. const excelData = await facade.getZheJiangSheetData(from, to);
  375. const sheetOptions = { '!cols': [{ wch: 15 }, { wch: 10 }, { wch: 10 }, { wch: 10 }, { wch: 15 }, { wch: 10 }] };
  376. const buffer = excel.build([{ name: "sheet", data: excelData }], sheetOptions);
  377. const filePath = './public/price.xlsx';
  378. fs.writeFileSync(filePath, buffer, 'binary');
  379. const stats = fs.statSync(filePath);
  380. const filename = '浙江信息价.xlsx';
  381. const encoded = encodeURIComponent(filename);
  382. response.set({
  383. 'Content-Type': 'application/octet-stream',
  384. 'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
  385. 'Content-Length': stats.size
  386. });
  387. fs.createReadStream(filePath).pipe(response);
  388. fs.unlink(filePath);
  389. } catch (error) {
  390. response.end(error);
  391. }
  392. }
  393. }
  394. module.exports = {
  395. priceInfoController: new PriceInfoController()
  396. };