index.js 15 KB

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