deal_bills_controller.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/5/7
  7. * @version
  8. */
  9. const fs = require('fs');
  10. const path = require('path');
  11. const excel = require('node-xlsx');
  12. const xlsx = require('js-xlsx');
  13. const loadExcelType = {
  14. display: 1,
  15. actual: 2,
  16. };
  17. const loadType = loadExcelType.display;
  18. const auditConst = require('../const/audit').ledger;
  19. const permissionConst = require('../const/account_permission');
  20. module.exports = app => {
  21. class DealBillsController extends app.BaseController {
  22. /**
  23. * 获取标段的签约清单数据
  24. * @param ctx
  25. * @return {Promise<void>}
  26. */
  27. async getData(ctx) {
  28. const responseData = {
  29. err: 0,
  30. msg: '',
  31. data: [],
  32. };
  33. try {
  34. responseData.data = await ctx.service.dealBills.getAllDataByCondition({
  35. where: { tender_id: ctx.tender.id },
  36. orders: [['order', 'asc']],
  37. });
  38. } catch (error) {
  39. this.log(error);
  40. responseData.err = 1;
  41. responseData.msg = error.toString();
  42. }
  43. ctx.body = responseData;
  44. }
  45. async checkPermisision(ctx) {
  46. if (!ctx.tender.data) throw '标段数据错误';
  47. const tender = ctx.tender.data;
  48. const isUser = tender.user_id === this.ctx.session.sessionUser.accountId;
  49. const auditors = await this.service.ledgerAudit.getAuditors(tender.id, tender.ledger_times);
  50. const auditorsId = this.ctx.helper._.map(auditors, 'audit_id');
  51. const isAuditor = auditorsId.indexOf(this.ctx.session.sessionUser.accountId) >= 0;
  52. const upPermision = this.ctx.session.sessionUser.permission
  53. ? this.ctx.session.sessionUser.permission.tender.indexOf('3') >= 0
  54. : false;
  55. if (!(((tender.ledger_status === auditConst.status.uncheck || tender.ledger_status === auditConst.status.checkNo) && isUser) ||
  56. (tender.ledger_status === auditConst.status.checking && isAuditor) ||
  57. (tender.ledger_status === auditConst.status.checked && isAuditor && upPermision))) {
  58. throw '您无权进行该操作';
  59. }
  60. }
  61. /**
  62. * 导入Excel数据
  63. * @param ctx
  64. * @return {Promise<void>}
  65. */
  66. async loadExcel(ctx) {
  67. try {
  68. await this.checkPermisision(ctx);
  69. const file = ctx.request.files[0];
  70. const create_time = Date.parse(new Date()) / 1000;
  71. const fileInfo = path.parse(file.filename);
  72. const fileName = this.app.config.filePath + '/cache/deal_bills/uploads/' + 'deal_bills' + create_time + fileInfo.ext;
  73. // 保存文件
  74. try {
  75. await ctx.helper.copyFileSync(file.filepath, fileName);
  76. } finally {
  77. await fs.unlinkSync(file.filepath);
  78. }
  79. if (loadType === loadExcelType.display) {
  80. const wb = xlsx.readFile(fileName);
  81. const name = wb.SheetNames[0];
  82. const sheetData = {
  83. rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
  84. merge: wb.Sheets[name]["!merges"],
  85. };
  86. const result = await ctx.service.dealBills.importDataJsXlsx(sheetData, ctx.tender.id);
  87. if (!result) {
  88. throw '导入数据失败';
  89. }
  90. } else {
  91. // 读取文件
  92. const sheet = excel.parse(fileName);
  93. if (!sheet || sheet.length === 0 || sheet[0] === undefined || sheet[0].data === undefined) {
  94. throw 'excel没有对应数据';
  95. }
  96. const result = await ctx.service.dealBills.importData(sheet[0], ctx.tender.id);
  97. if (!result) {
  98. throw '导入数据失败';
  99. }
  100. }
  101. const dealBills = await this.ctx.service.dealBills.getAllDataByCondition({
  102. where: { tender_id: ctx.tender.id },
  103. orders: [['order', 'asc']],
  104. });
  105. ctx.body = {err: 0, msg: '', data: dealBills};
  106. } catch (err) {
  107. this.log(err);
  108. this.ajaxErrorBody(err, '导入数据失败');
  109. }
  110. }
  111. /**
  112. * 下载模板文件
  113. * @param ctx
  114. * @return {Promise<void>}
  115. */
  116. async download(ctx) {
  117. const file = ctx.params.file;
  118. if (file) {
  119. try {
  120. let fileName;
  121. if (file === '签约清单导入格式.xls') {
  122. fileName = this.app.baseDir + '/app/public/deal_bills/签约清单导入格式.xls';
  123. ctx.body = await fs.readFileSync(fileName);
  124. } else if (file === '签约清单.xlsx') {
  125. const create_time = Date.parse(new Date()) / 1000;
  126. fileName = this.app.baseDir + '/app/public/deal_bills/downloads/' + ctx.tender.id + '-' + create_time + '.xlsx';
  127. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/deal_bills/downloads');
  128. // todo 导出签约清单Excel
  129. const setting = {
  130. header: ['清单编号', '名称', '单位', '数量', '单价', '金额'],
  131. width: [80, 150, 60, 80, 80, 80],
  132. hAlign: ['left', 'left', 'center', 'right', 'right', 'right'],
  133. };
  134. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  135. const data = [];
  136. for (const db of dealBills) {
  137. data.push([db.code, db.name, db.unit, db.quantity, db.unit_price, db.total_price]);
  138. }
  139. const arraySheetData = this.ctx.helper.simpleXlsxSheetData(setting, data);
  140. xlsx.writeFile({
  141. SheetNames: ['Sheet1'],
  142. Sheets: {
  143. 'Sheet1': arraySheetData,
  144. },
  145. }, fileName);
  146. ctx.body = await fs.readFileSync(fileName);
  147. // 输出文件后删除
  148. fs.unlinkSync(fileName);
  149. }
  150. } catch (err) {
  151. this.log(err);
  152. }
  153. }
  154. }
  155. async _base(ctx, type, data) {
  156. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  157. if (type !== 'add') {
  158. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  159. }
  160. switch (type) {
  161. case 'add':
  162. return await ctx.service.dealBills.addNodeBatch(ctx.tender.id, data.id, {}, data.count);
  163. case 'delete':
  164. return await ctx.service.dealBills.delete(ctx.tender.id, data.id, data.count);
  165. }
  166. }
  167. /**
  168. * 更新清单相关 (Ajax)
  169. * @param ctx
  170. * @return {Promise<void>}
  171. */
  172. async update(ctx) {
  173. try {
  174. await this.checkPermisision(ctx);
  175. const data = JSON.parse(ctx.request.body.data);
  176. const result = await ctx.service.dealBills.updateDatas(data);
  177. ctx.body = { err: 0, msg: '', data: result };
  178. } catch (err) {
  179. this.log(err);
  180. ctx.body = this.ajaxErrorBody(err);
  181. }
  182. }
  183. }
  184. return DealBillsController;
  185. };