material.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. 'use strict';
  2. /**
  3. * 期计量 数据模型
  4. *
  5. * @author Mai
  6. * @date 2018/8/13
  7. * @version
  8. */
  9. const auditConst = require('../const/audit').material;
  10. const projectLogConst = require('../const/project_log');
  11. module.exports = app => {
  12. class Material extends app.BaseService {
  13. /**
  14. * 构造函数
  15. *
  16. * @param {Object} ctx - egg全局变量
  17. * @return {void}
  18. */
  19. constructor(ctx) {
  20. super(ctx);
  21. this.tableName = 'material';
  22. }
  23. /**
  24. * 获取 最新一期 材料调差期计量
  25. * @param tenderId
  26. * @param includeUnCheck
  27. * @return {Promise<*>}
  28. */
  29. async getLastestMaterial(tenderId, includeUnCheck = false) {
  30. this.initSqlBuilder();
  31. this.sqlBuilder.setAndWhere('tid', {
  32. value: tenderId,
  33. operate: '=',
  34. });
  35. if (!includeUnCheck) {
  36. this.sqlBuilder.setAndWhere('status', {
  37. value: auditConst.status.uncheck,
  38. operate: '!=',
  39. });
  40. }
  41. this.sqlBuilder.orderBy = [['order', 'desc']];
  42. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  43. const material = await this.db.queryOne(sql, sqlParam);
  44. return material;
  45. }
  46. /**
  47. * 获取 最新一期 审批完成的 材料调差期计量
  48. * @param tenderId
  49. * @return {Promise<*>}
  50. */
  51. async getLastestCompleteMaterial(tenderId) {
  52. this.initSqlBuilder();
  53. this.sqlBuilder.setAndWhere('tid', {
  54. value: tenderId,
  55. operate: '=',
  56. });
  57. this.sqlBuilder.setAndWhere('status', {
  58. value: auditConst.status.checked,
  59. operate: '=',
  60. });
  61. this.sqlBuilder.orderBy = [['order', 'desc']];
  62. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  63. const material = await this.db.queryOne(sql, sqlParam);
  64. return material;
  65. }
  66. async checkMaterial(tid, order) {
  67. if (this.ctx.material) return;
  68. const materials = await this.getSelectMaterial(tid, order);
  69. this.ctx.material = materials[0]
  70. }
  71. /**
  72. * 获取标段下的全部计量期,按倒序
  73. * @param tenderId
  74. * @return {Promise<void>}
  75. */
  76. async getSelectMaterial(tenderId, order) {
  77. const materials = await this.db.select(this.tableName, {
  78. where: { tid: tenderId, order },
  79. });
  80. if (materials.length > 0 && materials[0].status !== auditConst.status.checked) {
  81. const material = materials[0];
  82. const curAuditor = await this.ctx.service.materialAudit.getCurAuditor(material.id, material.times);
  83. const isActive = curAuditor ? curAuditor.id === this.ctx.session.sessionUser.accountId : material.user_id === this.ctx.session.sessionUser.accountId;
  84. if (isActive) {
  85. material.curTimes = material.times;
  86. material.curOrder = curAuditor ? curAuditor.order : 0;
  87. }
  88. }
  89. return materials;
  90. }
  91. async getValidMaterials(tenderId) {
  92. const materials = await this.db.select(this.tableName, {
  93. where: { tid: tenderId },
  94. orders: [['order', 'desc']],
  95. });
  96. if (materials.length !== 0) {
  97. const lastMaterial = materials[materials.length - 1];
  98. if (lastMaterial.status === auditConst.status.uncheck && lastMaterial.user_id !== this.ctx.session.sessionUser.accountId && !this.ctx.tender.isTourist) {
  99. materials.splice(materials.length - 1, 1);
  100. }
  101. }
  102. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  103. if (materials.length > 0 && materials[0].status !== auditConst.status.checked) {
  104. const material = materials[0];
  105. const curAuditor = await this.ctx.service.materialAudit.getCurAuditor(material.id, material.times);
  106. const isActive = curAuditor ? curAuditor.id === this.ctx.session.sessionUser.accountId : material.user_id === this.ctx.session.sessionUser.accountId;
  107. if (isActive) {
  108. material.curTimes = material.times;
  109. material.curOrder = curAuditor ? curAuditor.order : 0;
  110. }
  111. }
  112. return materials;
  113. }
  114. /**
  115. * 添加材料调差期
  116. * @param tenderId - 标段id
  117. * @param data - post的数据
  118. * @return {Promise<void>}
  119. */
  120. async addMaterial(tenderId, data) {
  121. const materials = await this.getAllDataByCondition({
  122. where: { tid: tenderId },
  123. order: ['order'],
  124. });
  125. const preMaterial = materials[materials.length - 1];
  126. if (materials.length > 0 && materials[materials.length - 1].status !== auditConst.status.checked) {
  127. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  128. }
  129. const order = materials.length + 1;
  130. const newMaterial = {
  131. tid: tenderId,
  132. order,
  133. in_time: new Date(),
  134. times: 1,
  135. status: auditConst.status.uncheck,
  136. user_id: this.ctx.session.sessionUser.accountId,
  137. stage_id: data.stage_id.join(','),
  138. s_order: data.s_order,
  139. material_tax: this.ctx.session.sessionProject.page_show.openMaterialTax,
  140. };
  141. const transaction = await this.db.beginTransaction();
  142. try {
  143. if (preMaterial) {
  144. newMaterial.rate = preMaterial.rate;
  145. newMaterial.pre_tp = this.ctx.helper.add(preMaterial.m_tp, preMaterial.pre_tp);
  146. newMaterial.ex_pre_tp = this.ctx.helper.add(preMaterial.ex_tp, preMaterial.ex_pre_tp);
  147. newMaterial.m_tax_pre_tp = preMaterial.material_tax ? this.ctx.helper.add(preMaterial.m_tax_tp, preMaterial.m_tax_pre_tp) : preMaterial.m_tax_pre_tp;
  148. }
  149. // 新增期记录
  150. const result = await transaction.insert(this.tableName, newMaterial);
  151. if (result.affectedRows === 1) {
  152. newMaterial.id = result.insertId;
  153. } else {
  154. throw '新增期数据失败';
  155. }
  156. // 存在上一期时,复制上一期审批流程、不参与调差的清单、上期清单并算本期有效价差,本期应耗数量,并算本期总金额
  157. if (preMaterial) {
  158. const auditResult = await this.ctx.service.materialAudit.copyPreMaterialAuditors(transaction, preMaterial, newMaterial);
  159. if (!auditResult) {
  160. throw '复制上一期审批流程失败';
  161. }
  162. // 复制不参与调差清单
  163. const preNotJoinList = await this.ctx.service.materialListNotjoin.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  164. await this.ctx.service.materialListNotjoin.copyNewStageNotJoinList(transaction, preNotJoinList, newMaterial.id);
  165. // 复制调差清单工料关联表
  166. await this.ctx.service.materialList.copyPreMaterialList(transaction, preMaterial, newMaterial);
  167. // 修改本期应耗数量值和有效价差,需要剔除不参与调差的清单数据,并返回总金额
  168. const [m_tp, m_tax_tp] = await this.ctx.service.materialBills.updateNewMaterial(transaction, this.ctx.tender.id, newMaterial.id, this.ctx, newMaterial.stage_id);
  169. // 修改现行价格指数,并返回调差基数json
  170. const ex_calc = await this.ctx.service.materialExponent.updateNewMaterial(transaction, newMaterial.id, this.ctx, newMaterial.stage_id, preMaterial.ex_calc);
  171. // 计算得出本期总金额
  172. const updateMaterialData = {
  173. id: newMaterial.id,
  174. m_tp,
  175. m_tax_tp,
  176. ex_calc: JSON.stringify(ex_calc),
  177. };
  178. await transaction.update(this.tableName, updateMaterialData);
  179. }
  180. await transaction.commit();
  181. return newMaterial;
  182. } catch (err) {
  183. await transaction.rollback();
  184. throw err;
  185. }
  186. }
  187. /**
  188. * 删除材料调差期
  189. *
  190. * @param {Number} id - 期Id
  191. * @return {Promise<void>}
  192. */
  193. async deleteMaterial(id) {
  194. const transaction = await this.db.beginTransaction();
  195. try {
  196. // 删除文件
  197. const attList = await this.ctx.service.materialFile.getAllMaterialFiles(this.ctx.tender.id, id);
  198. await this.ctx.helper.delFiles(attList);
  199. await transaction.delete(this.ctx.service.materialAudit.tableName, { mid: id });
  200. await transaction.delete(this.ctx.service.materialBills.tableName, { mid: id });
  201. await transaction.delete(this.ctx.service.materialList.tableName, { mid: id });
  202. await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { mid: id });
  203. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { mid: id });
  204. await transaction.delete(this.ctx.service.materialFile.tableName, { mid: id });
  205. await transaction.delete(this.ctx.service.materialExponent.tableName, { mid: id });
  206. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, { mid: id });
  207. // 如果存在上一期,把上一期的quantity,expr,msg_tp,msg_times,msg_spread,m_up_risk,m_down_risk,m_spread,m_tp,pre_tp,orgin,is_summary添加到bill中
  208. const materialInfo = await this.getDataById(id);
  209. if (materialInfo.order > 1) {
  210. const sql = 'UPDATE ' + this.ctx.service.materialBills.tableName + ' as mb, ' +
  211. this.ctx.service.materialBillsHistory.tableName + ' as mbh ' +
  212. 'SET mb.`quantity` = mbh.`quantity`, mb.`expr` = mbh.`expr`, ' +
  213. 'mb.`msg_tp` = mbh.`msg_tp`, mb.`msg_times` = mbh.`msg_times`, ' +
  214. 'mb.`msg_spread` = mbh.`msg_spread`, mb.`m_up_risk` = mbh.`m_up_risk`, ' +
  215. 'mb.`m_down_risk` = mbh.`m_down_risk`, mb.`m_spread` = mbh.`m_spread`, ' +
  216. 'mb.`m_tp` = mbh.`m_tp`, mb.`pre_tp` = mbh.`pre_tp`, ' +
  217. 'mb.`m_tax_tp` = mbh.`m_tax_tp`, mb.`tax_pre_tp` = mbh.`tax_pre_tp`, ' +
  218. 'mb.`origin` = mbh.`origin`, mb.`is_summary` = mbh.`is_summary`, mb.`m_tax` = mbh.`m_tax` ' +
  219. 'WHERE mbh.`tid` = ? AND mbh.`order` = ? AND mbh.`mb_id` = mb.`id`';
  220. const sqlParam = [this.ctx.tender.id, materialInfo.order - 1];
  221. await transaction.query(sql, sqlParam);
  222. const sql2 = 'UPDATE ' + this.ctx.service.materialExponent.tableName + ' as me, ' +
  223. this.ctx.service.materialExponentHistory.tableName + ' as meh ' +
  224. 'SET me.`weight_num` = meh.`weight_num`, me.`basic_price` = meh.`basic_price`, ' +
  225. 'me.`basic_times` = meh.`basic_times`, me.`m_price` = meh.`m_price`, ' +
  226. 'me.`calc_num` = meh.`calc_num`, me.`is_summary` = meh.`is_summary` ' +
  227. 'WHERE meh.`tid` = ? AND meh.`order` = ? AND meh.`me_id` = me.`id`';
  228. const sqlParam2 = [this.ctx.tender.id, materialInfo.order - 1];
  229. await transaction.query(sql2, sqlParam2);
  230. }
  231. await transaction.delete(this.tableName, { id });
  232. // 记录删除日志
  233. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.material, projectLogConst.status.delete, '第' + materialInfo.order + '期');
  234. await transaction.commit();
  235. return true;
  236. } catch (err) {
  237. await transaction.rollback();
  238. throw err;
  239. }
  240. }
  241. /**
  242. * 获取包含当前期之前的调差期id
  243. *
  244. * @param {Number} id - 期Id
  245. * @return {Promise<void>}
  246. */
  247. async getPreMidList(tid, order) {
  248. const midList = await this.getAllDataByCondition({
  249. where: { tid },
  250. columns: ['id'],
  251. limit: order,
  252. offset: 0,
  253. });
  254. const list = [];
  255. for (const ml of midList) {
  256. list.push(ml.id);
  257. }
  258. return list;
  259. }
  260. /**
  261. * 修改增税税率
  262. * @param {int} rate 税率
  263. * @return {Promise<*>}
  264. */
  265. async changeRate(rate) {
  266. const updateData = {
  267. id: this.ctx.material.id,
  268. rate,
  269. };
  270. return await this.db.update(this.tableName, updateData);
  271. }
  272. /**
  273. * 修改调差基数
  274. * @param {int} rate 税率
  275. * @return {Promise<*>}
  276. */
  277. async changeExCalc(ex_calc) {
  278. const transaction = await this.db.beginTransaction();
  279. try {
  280. const updateData = {
  281. id: this.ctx.material.id,
  282. ex_calc: JSON.stringify(ex_calc),
  283. };
  284. await transaction.update(this.tableName, updateData);
  285. const [ex_tp, ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction, ex_calc);
  286. await transaction.commit();
  287. return [ex_tp, ex_expr];
  288. } catch (err) {
  289. await transaction.rollback();
  290. throw err;
  291. }
  292. }
  293. /**
  294. * 取当前期截止上期含建筑税金额
  295. * @param {int} tid 标段id
  296. * @param {int} order 调差期数
  297. * @return {Promise<*>}
  298. */
  299. async getPreTpHs(tid, order) {
  300. const sql = 'SELECT SUM(ROUND(`m_tp`*(1+ `rate`/100),2)) AS `pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  301. const sqlParam = [this.tableName, tid, 0, order];
  302. const result = await this.db.queryOne(sql, sqlParam);
  303. return result.pre_tp_hs;
  304. }
  305. /**
  306. * 取当前期截止上期含材料税金额
  307. * @param {int} tid 标段id
  308. * @param {int} order 调差期数
  309. * @return {Promise<*>}
  310. */
  311. async getTaxPreTpHs(tid, order) {
  312. const sql = 'SELECT SUM(`m_tax_tp`) AS `tax_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  313. const sqlParam = [this.tableName, tid, 1, order];
  314. const result = await this.db.queryOne(sql, sqlParam);
  315. return result.tax_pre_tp_hs;
  316. }
  317. /**
  318. * 取当前期截止上期含建筑税指数金额
  319. * @param {int} tid 标段id
  320. * @param {int} order 调差期数
  321. * @return {Promise<*>}
  322. */
  323. async getExPreTpHs(tid, order) {
  324. const sql = 'SELECT SUM(ROUND(`ex_tp`*(1+ `rate`/100),2)) AS `ex_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `order` < ?';
  325. const sqlParam = [this.tableName, tid, order];
  326. const result = await this.db.queryOne(sql, sqlParam);
  327. return result.ex_pre_tp_hs;
  328. }
  329. async updateMaterialTax(id, mtax) {
  330. const updateData = {
  331. id,
  332. material_tax: mtax,
  333. };
  334. return await this.db.update(this.tableName, updateData);
  335. }
  336. async getMaterialTaxTp(id) {
  337. const info = await this.getDataById(id);
  338. return info.m_tax_tp;
  339. }
  340. async getSumMaterial(tid) {
  341. const sql = 'Select sum(IFNULL(m_tp, 0) + IFNULL(ex_tp, 0)) as tp From ' + this.tableName + ' where tid = ?';
  342. const result = await this.db.queryOne(sql, [tid]);
  343. return result ? result.tp : 0;
  344. }
  345. async getOldMaterialTax(tid, order) {
  346. const sql = 'SELECT COUNT(id) as count FROM ?? WHERE `tid` = ? AND `order` <= ? AND `material_tax` = 1';
  347. const sqlParam = [this.tableName, tid, order];
  348. const result = await this.db.queryOne(sql, sqlParam);
  349. return result && result.count !== 0;
  350. }
  351. }
  352. return Material;
  353. };