pay_controller.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. 'use strict';
  2. /**
  3. * 合同支付
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const audit = require('../const/audit');
  10. const shenpiConst = require('../const/shenpi');
  11. const sendToWormhole = require('stream-wormhole');
  12. const path = require('path');
  13. module.exports = app => {
  14. class PayController extends app.BaseController {
  15. /**
  16. * 构造函数
  17. *
  18. * @param {Object} ctx - egg全局变量
  19. * @return {void}
  20. */
  21. constructor(ctx) {
  22. super(ctx);
  23. }
  24. async index(ctx) {
  25. try {
  26. const phasePays = await this.ctx.service.phasePay.getAllPhasePay(ctx.tender.id, 'DESC');
  27. const relaStage = [];
  28. for (const p of phasePays) {
  29. if (p.audit_status !== audit.common.status.checked) await this.ctx.service.phasePay.loadUser(p);
  30. relaStage.push(...p.rela_stage);
  31. }
  32. const stages = await this.ctx.service.stage.getAllDataByCondition({ where: { tid: ctx.tender.id }, orders: [['order', 'AEC']] });
  33. const validStages = stages.filter(s => {
  34. return !relaStage.find(r => { return s.id === r.stage_id; });
  35. });
  36. this.ctx.service.phasePay.calculatePhasePay(phasePays);
  37. const renderData = {
  38. auditType: audit.auditType,
  39. phasePays,
  40. validStages,
  41. auditConst: audit.common,
  42. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.phasePay.list)
  43. };
  44. await this.layout('phase_pay/index.ejs', renderData, 'phase_pay/modal.ejs');
  45. } catch (err) {
  46. ctx.log(err);
  47. ctx.redirect(ctx.request.header.referer);
  48. }
  49. }
  50. async add(ctx) {
  51. try {
  52. if (ctx.session.sessionUser.accountId !== ctx.tender.data.user_id && ctx.tender.userAssistsId.indexOf(ctx.session.sessionUser.accountId) < 0) {
  53. throw '您无权创建计量期';
  54. }
  55. const date = ctx.request.body.date;
  56. if (!date) throw '请选择支付年月';
  57. const stage = ctx.request.body.stage;
  58. if (!stage) throw '请选择计量期';
  59. const memo = ctx.request.body.memo;
  60. const pays = await ctx.service.phasePay.getAllPhasePay(ctx.tender.id, 'DESC');
  61. const unCompleteCount = pays.filter(s => { return s.status !== audit.common.status.checked; }).length;
  62. if (unCompleteCount.length > 0) throw `最新一起未审批通过,请审批通过后再新增`;
  63. // 预留可以关联多期
  64. const stages = await ctx.service.stage.getAllDataByCondition({ where: { tid: ctx.tender.id, order: stage } });
  65. const newPhase = await ctx.service.phasePay.add(ctx.tender.id, stages, date, memo);
  66. if (!newPhase) throw '新增期失败';
  67. newPhase.curTimes = 1;
  68. newPhase.curSort = 0;
  69. await ctx.service.phasePayDetail.calculateSave(newPhase);
  70. ctx.redirect('/tender/' + ctx.tender.id + '/pay/' + newPhase.phase_order + '/detail');
  71. } catch (err) {
  72. ctx.log(err);
  73. ctx.postError(err, '新增期失败');
  74. ctx.redirect('/tender/' + ctx.tender.id + '/pay');
  75. }
  76. }
  77. async del(ctx) {
  78. try {
  79. if (!ctx.session.sessionUser.is_admin && ctx.request.body.confirm !== '确认删除本期') throw '请输入文本确认删除本期';
  80. const phase_id = ctx.request.body.phase_id;
  81. const phasePay = await ctx.service.phasePay.getDataById(phase_id);
  82. if (!phasePay) throw '删除的期不存在,请刷新页面';
  83. if (!ctx.session.sessionUser.is_admin && phasePay.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权删除本期';
  84. // 获取最新的期数
  85. const phasePayCount = await ctx.service.phasePay.count({ tid: ctx.tender.id });
  86. if (phasePay.phase_order !== phasePayCount) throw '非最新一期,不可删除';
  87. await ctx.service.phasePay.delete(phase_id);
  88. // todo 刷新金额概况缓存
  89. // await ctx.service.tenderCache.refreshPayCache(phasePay.tenderId);
  90. ctx.redirect('/tender/' + ctx.tender.id + '/pay');
  91. } catch (err) {
  92. ctx.log(err);
  93. ctx.redirect('/tender/' + ctx.tender.id + '/pay');
  94. }
  95. }
  96. async save(ctx) {
  97. try {
  98. const phase_id = ctx.request.body.phase_id;
  99. const data = {
  100. phase_date: ctx.request.body.date,
  101. memo: ctx.request.body.memo,
  102. };
  103. const phasePay = await ctx.service.phasePay.getPhasePay(phase_id);
  104. if (!phasePay) throw '删除的期不存在,请刷新页面';
  105. if (!ctx.session.sessionUser.is_admin && phasePay.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权修改该数据';
  106. await this.ctx.service.phasePay.save(phasePay, data);
  107. if (phasePay.audit_status === audit.common.status.uncheck && ctx.request.body.stage) {
  108. const stages = await ctx.service.stage.getAllDataByCondition({ where: { tid: ctx.tender.id, order: ctx.request.body.stage } });
  109. await this.ctx.service.phasePay.resetRelaStageId(phasePay, stages);
  110. }
  111. ctx.redirect('/tender/' + ctx.tender.id + '/pay');
  112. } catch (err) {
  113. ctx.log(err);
  114. ctx.redirect('/tender/' + ctx.tender.id + '/pay');
  115. }
  116. }
  117. /**
  118. * 期审批流程(POST)
  119. * @param ctx
  120. * @return {Promise<void>}
  121. */
  122. async loadAuditors(ctx) {
  123. try {
  124. const order = JSON.parse(ctx.request.body.data).order;
  125. const tenderId = ctx.params.id;
  126. const phasePay = await ctx.service.phasePay.getPhasePayByOrder(tenderId, order);
  127. await ctx.service.phasePay.loadUser(phasePay);
  128. await ctx.service.phasePay.loadAuditViewData(phasePay);
  129. ctx.body = { err: 0, msg: '', data: phasePay };
  130. } catch (error) {
  131. ctx.log(error);
  132. ctx.body = { err: 1, msg: error.toString(), data: null };
  133. }
  134. }
  135. async detail(ctx) {
  136. try {
  137. // await this.ctx.service.phasePayDetail.calculateSave(ctx.phasePay);
  138. await this.ctx.service.phasePay.loadAuditViewData(ctx.phasePay);
  139. const pays = await this.ctx.service.phasePayDetail.getDetailData(ctx.phasePay);
  140. const calcBase = this.ctx.service.phasePay.getPhasePayCalcBase(ctx.phasePay, ctx.tender.info);
  141. const projectFunInfo = await this.ctx.service.project.getFunRela(ctx.session.sessionProject.id);
  142. const lastStage = await this.ctx.service.stage.getLastestCompleteStage(ctx.tender.id);
  143. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  144. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  145. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  146. });
  147. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  148. const accountGroup = unitList.map(item => {
  149. const groupList = accountList.filter(item1 => item1.company === item.name);
  150. return { groupName: item.name, groupList };
  151. });
  152. // 是否已验证手机短信
  153. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  154. const renderData = {
  155. pays,
  156. calcBase,
  157. lockPayExpr: projectFunInfo.lockPayExpr,
  158. auditConst: audit.common,
  159. deadlineType: this.ctx.service.phasePayDetail.deadlineType,
  160. maxStageOrder: lastStage.order,
  161. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.phasePay.detail),
  162. accountList,
  163. accountGroup,
  164. shenpiConst,
  165. auditType: audit.auditType,
  166. authMobile: pa.auth_mobile,
  167. };
  168. await this.layout('phase_pay/detail.ejs', renderData, 'phase_pay/detail_modal.ejs');
  169. } catch (err) {
  170. ctx.log(err);
  171. ctx.postError(err, '读取合同支付数据错误');
  172. ctx.redirect('/tender/' + ctx.tender.id + '/pay');
  173. }
  174. }
  175. async detailLoad(ctx) {
  176. try {
  177. const data = JSON.parse(ctx.request.body.data);
  178. if (!data.filter) throw '参数错误';
  179. const filter = data.filter.split(',');
  180. const result = {};
  181. for (const f of filter) {
  182. switch(f) {
  183. case 'pay':
  184. result.pay = await this.ctx.service.phasePayDetail.getDetailData(ctx.phasePay);
  185. break;
  186. case 'base':
  187. result.base = this.ctx.service.phasePay.getPhasePayCalcBase(ctx.phasePay, ctx.tender.info);
  188. break;
  189. case 'add':
  190. result.add = ctx.phasePay.calc_base;
  191. break;
  192. case 'file':
  193. result.file = await this.ctx.service.phasePayFile.getData(ctx.phasePay.id, 'pay');
  194. }
  195. }
  196. ctx.body = { err: 0, msg: '', data: result };
  197. } catch (err) {
  198. ctx.log(err);
  199. ctx.ajaxErrorBody(err, '读取合同支付数据错误');
  200. }
  201. }
  202. async detailUpdate(ctx) {
  203. try {
  204. const data = JSON.parse(ctx.request.body.data);
  205. if (!data.postType || !data.postData) throw '数据错误';
  206. const responseData = { err: 0, msg: '', data: {} };
  207. switch (data.postType) {
  208. case 'add':
  209. responseData.data = await this.ctx.service.phasePayDetail.addDetailNode(ctx.phasePay, data.postData.id, data.postData.count || 1);
  210. break;
  211. case 'delete':
  212. await this.ctx.service.phasePayDetail.deleteDetailNode(ctx.phasePay, data.postData.id, data.postData.count || 1);
  213. await this.ctx.service.phasePayDetail.calculateSave(ctx.phasePay);
  214. responseData.data.reload = await this.ctx.service.phasePayDetail.getDetailData(ctx.phasePay);
  215. break;
  216. case 'up-move':
  217. responseData.data = await this.ctx.service.phasePayDetail.upMoveDetailNode(ctx.phasePay, data.postData.id, data.postData.count || 1);
  218. break;
  219. case 'down-move':
  220. responseData.data = await this.ctx.service.phasePayDetail.downMoveDetailNode(ctx.phasePay, data.postData.id, data.postData.count || 1);
  221. break;
  222. case 'update':
  223. const updateDetail = await this.ctx.service.phasePayDetail.updateDetail(ctx.phasePay, data.postData);
  224. if (this.ctx.service.phasePayDetail.checkCalc(data.postData)) {
  225. await this.ctx.service.phasePayDetail.calculateSave(ctx.phasePay);
  226. responseData.data.reload = await this.ctx.service.phasePayDetail.getDetailData(ctx.phasePay);
  227. } else {
  228. responseData.data.update = updateDetail;
  229. }
  230. break;
  231. case 'calc':
  232. await this.ctx.service.phasePayDetail.calculateSave(ctx.phasePay);
  233. responseData.data.reload = await this.ctx.service.phasePayDetail.getDetailData(ctx.phasePay);
  234. break;
  235. case 'refreshBase':
  236. await this.ctx.service.phasePay.refreshCalcBase(ctx.phasePay);
  237. responseData.data.reload = await this.ctx.service.phasePayDetail.getDetailData(ctx.phasePay);
  238. responseData.data.calcBase = this.ctx.service.phasePay.getPhasePayCalcBase(ctx.phasePay, ctx.tender.info);
  239. responseData.data.calcBase.forEach(x => { x.formatValue = ctx.tender.info.display.thousandth ? ctx.helper.formatNum(x.value, '#,##0.######') : x.value; });
  240. responseData.data.addBase = ctx.phasePay.calc_base;
  241. break;
  242. default:
  243. throw '未知操作';
  244. }
  245. ctx.body = responseData;
  246. } catch (err) {
  247. ctx.log(err);
  248. ctx.body = this.ajaxErrorBody(err, '数据错误');
  249. }
  250. }
  251. async uploadFile(ctx) {
  252. let stream;
  253. try {
  254. const parts = ctx.multipart({autoFields: true});
  255. let index = 0;
  256. const create_time = Date.parse(new Date()) / 1000;
  257. let stream = await parts();
  258. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  259. const rela_type = parts.fields.type;
  260. const rela_id = parts.field.rela_id;
  261. const uploadfiles = [];
  262. while (stream !== undefined) {
  263. if (!stream.filename) throw '未发现上传文件!';
  264. const fileInfo = path.parse(stream.filename);
  265. const filepath = `app/public/upload/${ctx.phasePay.tid}/phasePay/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  266. // 保存文件
  267. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  268. await sendToWormhole(stream);
  269. // 插入到stage_pay对应的附件列表中
  270. uploadfiles.push({
  271. rela_id,
  272. filename: fileInfo.name,
  273. fileext: fileInfo.ext,
  274. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  275. filepath,
  276. });
  277. ++index;
  278. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  279. stream = await parts();
  280. } else {
  281. stream = undefined;
  282. }
  283. }
  284. const result = await ctx.service.phasePayFile.addFiles(ctx.phasePay, 'pay', uploadfiles, user);
  285. ctx.body = {err: 0, msg: '', data: result};
  286. } catch (error) {
  287. ctx.log(error);
  288. // 失败需要消耗掉stream 以防卡死
  289. if (stream) await sendToWormhole(stream);
  290. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  291. }
  292. }
  293. async deleteFile(ctx) {
  294. try{
  295. const data = JSON.parse(ctx.request.body.data);
  296. if (!data) throw '缺少参数';
  297. const result = await ctx.service.phasePayFile.delFiles(data);
  298. ctx.body = { err: 0, msg: '', data: result };
  299. } catch(error) {
  300. ctx.log(error);
  301. ctx.ajaxErrorBody(error, '删除附件失败');
  302. }
  303. }
  304. /**
  305. * 添加审批人
  306. * @param ctx
  307. * @return {Promise<void>}
  308. */
  309. async addAudit(ctx) {
  310. try {
  311. const data = JSON.parse(ctx.request.body.data);
  312. const id = this.app._.toInteger(data.auditorId);
  313. if (isNaN(id) || id <= 0) throw '参数错误';
  314. // 检查权限等
  315. if (ctx.phasePay.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权添加审核人';
  316. if (ctx.phasePay.audit_status !== audit.common.status.uncheck && ctx.phasePay.audit_status !== audit.common.status.checkNo) {
  317. throw '当前不允许添加审核人';
  318. }
  319. // 检查审核人是否已存在
  320. const exist = await ctx.service.phasePayAudit.getDataByCondition({ phase_id: ctx.phasePay.id, audit_times: ctx.phasePay.audit_times, audit_id: id });
  321. if (exist) throw '该审核人已存在,请勿重复添加';
  322. const auditorInfo = await this.ctx.service.projectAccount.getDataById(id);
  323. if (!auditorInfo) throw '添加的审批人不存在';
  324. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.phasePay, sp_status: shenpiConst.sp_status.gdzs });
  325. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.phasePay === shenpiConst.sp_status.gdzs ? 1 : 0;
  326. const result = await ctx.service.phasePayAudit.addAuditor(ctx.phasePay.id, auditorInfo, ctx.phasePay.audit_times, is_gdzs);
  327. if (!result) throw '添加审核人失败';
  328. const auditors = await ctx.service.phasePayAudit.getAuditorGroup(ctx.phasePay.id, ctx.phasePay.audit_times);
  329. ctx.body = { err: 0, msg: '', data: auditors };
  330. } catch (err) {
  331. ctx.log(err);
  332. ctx.body = { err: 1, msg: err.toString(), data: null };
  333. }
  334. }
  335. /**
  336. * 移除审批人
  337. * @param ctx
  338. * @return {Promise<void>}
  339. */
  340. async deleteAudit(ctx) {
  341. try {
  342. const data = JSON.parse(ctx.request.body.data);
  343. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  344. if (isNaN(id) || id <= 0) throw '参数错误';
  345. const result = await ctx.service.phasePayAudit.deleteAuditor(ctx.phasePay.id, id, ctx.phasePay.audit_times);
  346. if (!result) throw '移除审核人失败';
  347. const auditors = await ctx.service.phasePayAudit.getAuditors(ctx.phasePay.id, ctx.phasePay.audit_times);
  348. ctx.body = { err: 0, msg: '', data: auditors };
  349. } catch (err) {
  350. ctx.log(err);
  351. ctx.body = { err: 1, msg: err.toString(), data: null };
  352. }
  353. }
  354. async auditStart(ctx) {
  355. try {
  356. if (ctx.phasePay.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权上报该期数据';
  357. if (ctx.phasePay.revising) throw '台账修订中,不可上报';
  358. if (ctx.phasePay.audit_status !== audit.common.status.uncheck && ctx.phasePay.audit_status !== audit.common.status.checkNo) throw '该期数据当前无法上报';
  359. await ctx.service.phasePayAudit.start(ctx.phasePay);
  360. ctx.redirect(ctx.request.header.referer);
  361. } catch (err) {
  362. ctx.log(err);
  363. ctx.postError(err, '上报失败');
  364. ctx.redirect(`/tender/${ctx.phasePay.tid}/pay/${ctx.phasePay.phase_order}/detail`);
  365. }
  366. }
  367. async auditCheck(ctx) {
  368. try {
  369. if (!ctx.phasePay || (ctx.phasePay.audit_status !== audit.common.status.checking && ctx.phasePay.audit_status !== audit.common.status.checkNoPre)) {
  370. throw '当前期数据有误';
  371. }
  372. if (ctx.phasePay.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) < 0) {
  373. throw '您无权进行该操作';
  374. }
  375. if (ctx.phasePay.revising) throw '台账修订中,不可审批';
  376. const checkType = parseInt(ctx.request.body.checkType);
  377. const opinion = ctx.request.body.opinion.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
  378. await ctx.service.phasePayAudit.check(ctx.phasePay, checkType, opinion);
  379. } catch (err) {
  380. ctx.log(err);
  381. ctx.postError(err, '审批失败');
  382. }
  383. ctx.redirect(ctx.request.header.referer);
  384. }
  385. async auditCheckAgain(ctx) {
  386. try {
  387. if (ctx.phasePay.isLatest) throw '非最新一期,不可重新审批';
  388. if (ctx.phasePay.audit_status !== audit.common.status.checked) throw '未审批完成,不可重新审批';
  389. if (ctx.phasePay.revising) throw '台账修订中,不可重审';
  390. if (ctx.session.sessionUser.loginStatus === 0) {
  391. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  392. if (!user.auth_mobile) throw '未绑定手机号';
  393. const code = ctx.request.body.code;
  394. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  395. const cacheCode = await app.redis.get(cacheKey);
  396. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  397. throw '验证码不正确!';
  398. }
  399. }
  400. const adminCheckAgain = ctx.request.body.confirm === '确认设置终审审批' && ctx.session.sessionUser.is_admin;
  401. if (ctx.phasePay.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) < 0 && !adminCheckAgain) throw '您无权重新审批';
  402. await ctx.service.phasePayAudit.checkAgain(ctx.phasePay, adminCheckAgain);
  403. } catch (err) {
  404. ctx.log(err);
  405. ctx.postError(err, '重新审批失败');
  406. }
  407. ctx.redirect(ctx.request.header.referer);
  408. }
  409. async auditCheckCancel(ctx) {
  410. try {
  411. if (ctx.phasePay.revising) throw '台账修订中,不可撤回';
  412. if (!ctx.phasePay.cancancel) throw '您无权进行该操作';
  413. await ctx.service.phasePayAudit.checkCancel(ctx.phasePay);
  414. } catch (err) {
  415. ctx.log(err);
  416. ctx.postError(err, '撤回失败');
  417. }
  418. ctx.redirect(ctx.request.header.referer);
  419. }
  420. }
  421. return PayController;
  422. };