material.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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 auditType = require('../const/audit').auditType;
  11. const projectLogConst = require('../const/project_log');
  12. const materialConst = require('../const/material');
  13. module.exports = app => {
  14. class Material extends app.BaseService {
  15. /**
  16. * 构造函数
  17. *
  18. * @param {Object} ctx - egg全局变量
  19. * @return {void}
  20. */
  21. constructor(ctx) {
  22. super(ctx);
  23. this.tableName = 'material';
  24. }
  25. async loadMaterialUser(material) {
  26. const status = auditConst.status;
  27. const accountId = this.ctx.session.sessionUser.accountId;
  28. material.user = await this.ctx.service.projectAccount.getAccountInfoById(material.user_id);
  29. material.auditors = await this.ctx.service.materialAudit.getAuditors(material.id, material.times); // 全部参与的审批人
  30. material.auditorIds = this._.map(material.auditors, 'aid');
  31. material.curAuditors = material.auditors.filter(x => { return x.status === status.checking; }); // 当前流程中审批中的审批人
  32. material.curAuditorIds = this._.map(material.curAuditors, 'aid');
  33. material.flowAuditors = material.curAuditors.length > 0 ? material.auditors.filter(x => { return x.order === material.curAuditors[0].order; }) : []; // 当前流程中参与的审批人(包含会签时,审批通过的人)
  34. material.flowAuditorIds = this._.map(material.flowAuditors, 'aid');
  35. material.nextAuditors = material.curAuditors.length > 0 ? material.auditors.filter(x => { return x.order === material.curAuditors[0].order + 1; }) : [];
  36. material.nextAuditorIds = this._.map(material.nextAuditors, 'aid');
  37. const newAuditors = material.auditors.filter(x => { return x.is_old === 0; });
  38. material.auditorGroups = this.ctx.helper.groupAuditors(newAuditors);
  39. material.userGroups = this.ctx.helper.groupAuditorsUniq(material.auditorGroups);
  40. material.userGroups.unshift([{
  41. aid: material.user.id, order: 0, times: material.times, audit_order: 0, audit_type: auditType.key.common,
  42. name: material.user.name, role: material.user.role, company: material.user.company,
  43. }]);
  44. material.finalAuditorIds = material.userGroups[material.userGroups.length - 1].map(x => { return x.aid; });
  45. }
  46. async loadMaterialAuditViewData(material) {
  47. const times = material.status === auditConst.status.checkNo ? material.times - 1 : material.times;
  48. if (!material.user) material.user = await this.ctx.service.projectAccount.getAccountInfoById(material.user_id);
  49. material.auditHistory = await this.ctx.service.materialAudit.getAuditorHistory(material.id, times);
  50. // 获取审批流程中左边列表
  51. if (material.status === auditConst.status.checkNo && material.user_id !== this.ctx.session.sessionUser.accountId) {
  52. const auditors = await this.ctx.service.materialAudit.getAuditors(material.id, times); // 全部参与的审批人
  53. const newAuditors = auditors.filter(x => { return x.is_old === 0; });
  54. const auditorGroups = this.ctx.helper.groupAuditors(newAuditors);
  55. material.auditors2 = this.ctx.helper.groupAuditorsUniq(auditorGroups);
  56. material.auditors2.unshift([{
  57. aid: material.user.id, order: 0, times: material.times - 1, audit_order: 0, audit_type: auditType.key.common,
  58. name: material.user.name, role: material.user.role, company: material.user.company,
  59. }]);
  60. } else {
  61. material.auditors2 = material.userGroups;
  62. }
  63. if (material.status === auditConst.status.uncheck || material.status === auditConst.status.checkNo) {
  64. material.auditorList = await this.ctx.service.materialAudit.getAuditors(material.id, material.times);
  65. }
  66. }
  67. async checkExponentUpdate(material) {
  68. if (!material.pre_exponent_node) return false; // 空则直接通过
  69. const need = material.pre_exponent_node.split(',');// 要求的节点数组
  70. const got = material.exponent_node ? material.exponent_node.split(',') : [];// 实际的节点数组
  71. // every 表示:need 中每个元素都必须包含在 got 中
  72. return !need.every(n => got.includes(n));
  73. }
  74. /**
  75. * 获取 最新一期 材料调差期计量
  76. * @param tenderId
  77. * @param includeUnCheck
  78. * @return {Promise<*>}
  79. */
  80. async getLastestMaterial(tenderId, includeUnCheck = false) {
  81. this.initSqlBuilder();
  82. this.sqlBuilder.setAndWhere('tid', {
  83. value: tenderId,
  84. operate: '=',
  85. });
  86. if (!includeUnCheck) {
  87. this.sqlBuilder.setAndWhere('status', {
  88. value: auditConst.status.uncheck,
  89. operate: '!=',
  90. });
  91. }
  92. this.sqlBuilder.orderBy = [['order', 'desc']];
  93. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  94. const material = await this.db.queryOne(sql, sqlParam);
  95. return material;
  96. }
  97. /**
  98. * 获取 最新一期 审批完成的 材料调差期计量
  99. * @param tenderId
  100. * @return {Promise<*>}
  101. */
  102. async getLastestCompleteMaterial(tenderId) {
  103. this.initSqlBuilder();
  104. this.sqlBuilder.setAndWhere('tid', {
  105. value: tenderId,
  106. operate: '=',
  107. });
  108. this.sqlBuilder.setAndWhere('status', {
  109. value: auditConst.status.checked,
  110. operate: '=',
  111. });
  112. this.sqlBuilder.orderBy = [['order', 'desc']];
  113. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  114. const material = await this.db.queryOne(sql, sqlParam);
  115. return material;
  116. }
  117. async checkMaterial(tid, order) {
  118. if (this.ctx.material) return;
  119. const materials = await this.getSelectMaterial(tid, order);
  120. this.ctx.material = materials[0];
  121. if (this.ctx.session.sessionUser.accountId === this.ctx.material.user_id) {
  122. this.ctx.material.curTimes = this.ctx.material.times;
  123. } else {
  124. this.ctx.material.curTimes = this.ctx.material.status === auditConst.status.checkNo ? this.ctx.material.times - 1 : this.ctx.material.times;
  125. }
  126. }
  127. /**
  128. * 获取标段下的全部计量期,按倒序
  129. * @param tenderId
  130. * @return {Promise<void>}
  131. */
  132. async getSelectMaterial(tenderId, order) {
  133. const materials = await this.db.select(this.tableName, {
  134. where: { tid: tenderId, order },
  135. });
  136. if (materials.length > 0 && materials[0].status !== auditConst.status.checked) {
  137. const material = materials[0];
  138. const curAuditor = await this.ctx.service.materialAudit.getCurAuditor(material.id, material.times);
  139. const isActive = curAuditor ? curAuditor.aid === this.ctx.session.sessionUser.accountId : material.user_id === this.ctx.session.sessionUser.accountId;
  140. if (isActive) {
  141. material.curTimes = material.times;
  142. material.curOrder = curAuditor ? curAuditor.order : 0;
  143. }
  144. }
  145. return materials;
  146. }
  147. async getValidMaterials(tenderId) {
  148. const materials = await this.db.select(this.tableName, {
  149. where: { tid: tenderId },
  150. orders: [['order', 'desc']],
  151. });
  152. if (materials.length !== 0) {
  153. const lastMaterial = materials[materials.length - 1];
  154. if (lastMaterial.status === auditConst.status.uncheck && lastMaterial.user_id !== this.ctx.session.sessionUser.accountId && !this.ctx.tender.isTourist && !this.ctx.session.sessionUser.is_admin) {
  155. materials.splice(materials.length - 1, 1);
  156. }
  157. }
  158. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  159. if (materials.length > 0 && materials[0].status !== auditConst.status.checked) {
  160. const material = materials[0];
  161. const curAuditors = await this.ctx.service.materialAudit.getCurAuditors(material.id, material.times);
  162. const isActive = curAuditors && curAuditors.length > 0 ? this._.findIndex(curAuditors, { aid: this.ctx.session.sessionUser.accountId }) !== -1 : material.user_id === this.ctx.session.sessionUser.accountId;
  163. if (isActive) {
  164. material.curTimes = material.times;
  165. material.curOrder = curAuditors && curAuditors.length > 0 ? curAuditors[0].order : 0;
  166. }
  167. }
  168. return materials;
  169. }
  170. /**
  171. * 添加材料调差期
  172. * @param tenderId - 标段id
  173. * @param data - post的数据
  174. * @return {Promise<void>}
  175. */
  176. async addMaterial(tenderId, data) {
  177. const materials = await this.getAllDataByCondition({
  178. where: { tid: tenderId },
  179. order: ['order'],
  180. });
  181. const preMaterial = materials[materials.length - 1];
  182. if (materials.length > 0 && materials[materials.length - 1].status !== auditConst.status.checked) {
  183. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  184. }
  185. const order = materials.length + 1;
  186. const newMaterial = {
  187. tid: tenderId,
  188. order,
  189. period: data.period,
  190. in_time: new Date(),
  191. times: 1,
  192. status: auditConst.status.uncheck,
  193. user_id: this.ctx.session.sessionUser.accountId,
  194. stage_id: data.stage_id.join(','),
  195. s_order: data.s_order,
  196. material_tax: this.ctx.subProject.page_show.openMaterialTax,
  197. decimal: preMaterial && preMaterial.decimal ? preMaterial.decimal : JSON.stringify(materialConst.decimal),
  198. exponent_decimal: preMaterial && preMaterial.exponent_decimal ? preMaterial.exponent_decimal : JSON.stringify(materialConst.exponent_decimal),
  199. is_new: 1,
  200. is_stage_self: data.is_stage_self,
  201. qty_source: data.qty_source,
  202. is_new_qty: 1,
  203. is_new_exponent: data.is_stage_self ? 0 : 1,
  204. rate: 9,
  205. calc_stage: data.stage_id.join(','),
  206. calc_tp: 1,
  207. };
  208. const transaction = await this.db.beginTransaction();
  209. try {
  210. if (preMaterial) {
  211. newMaterial.rate = preMaterial.rate;
  212. newMaterial.exponent_rate = preMaterial.exponent_rate;
  213. newMaterial.pre_tp = this.ctx.helper.add(preMaterial.m_tp, preMaterial.pre_tp);
  214. newMaterial.ex_pre_tp = this.ctx.helper.add(preMaterial.ex_tp, preMaterial.ex_pre_tp);
  215. newMaterial.ex_tax_pre_tp = this.ctx.helper.add(preMaterial.ex_tax_tp, preMaterial.ex_tax_pre_tp);
  216. 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;
  217. newMaterial.calc_stage = '';
  218. newMaterial.calc_tp = 0;
  219. newMaterial.is_new_exponent = 1;
  220. // newMaterial.exponent_node = preMaterial.exponent_node;
  221. newMaterial.pre_exponent_node = preMaterial.exponent_node;
  222. }
  223. // 新增期记录
  224. const result = await transaction.insert(this.tableName, newMaterial);
  225. if (result.affectedRows === 1) {
  226. newMaterial.id = result.insertId;
  227. } else {
  228. throw '新增期数据失败';
  229. }
  230. const insertMaterialStage = [];
  231. if (data.is_stage_self) {
  232. // 新建多期单独单价表,工料表
  233. for (const [i, d] of data.stage_id.entries()) {
  234. insertMaterialStage.push({
  235. tid: tenderId,
  236. mid: newMaterial.id,
  237. sid: d,
  238. order: data.s_order.split(',')[i],
  239. });
  240. }
  241. if (insertMaterialStage.length > 0) {
  242. const resultStage = await transaction.insert(this.ctx.service.materialStage.tableName, insertMaterialStage);
  243. // 获取刚批量添加的所有list
  244. for (let j = 0; j < insertMaterialStage.length; j++) {
  245. insertMaterialStage[j].id = resultStage.insertId + j;
  246. }
  247. }
  248. }
  249. // 存在上一期时,复制上一期审批流程、不参与调差的清单、上期清单并算本期有效价差,本期应耗数量,并算本期总金额
  250. if (preMaterial) {
  251. const auditResult = await this.ctx.service.materialAudit.copyPreMaterialAuditors(transaction, preMaterial, newMaterial);
  252. if (!auditResult) {
  253. throw '复制上一期审批流程失败';
  254. }
  255. // 复制不参与调差或不计算数量变更清单
  256. const preNotJoinList = await this.ctx.service.materialListNotjoin.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  257. await this.ctx.service.materialListNotjoin.copyNewStageNotJoinList(transaction, preNotJoinList, newMaterial.id);
  258. // 复制单独计量调差清单
  259. const preSelfList = await this.ctx.service.materialListSelf.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  260. await this.ctx.service.materialListSelf.copyNewStageSelfList(transaction, preSelfList, newMaterial.id);
  261. // // 复制调差清单工料关联表
  262. // // await this.ctx.service.materialList.copyPreMaterialList(transaction, preMaterial, newMaterial);
  263. // await this.ctx.service.materialList.copyPreMaterialList2(transaction, data.material_list, data.material_self_list, preNotJoinList, newMaterial, insertMaterialStage);
  264. // // 新增或删除list_gcl表
  265. // await this.ctx.service.materialListGcl.insertOrDelGcl(transaction, data.insertGclList, data.removeGclList, newMaterial.id);
  266. // // 设置list_gcl表old=>new更新
  267. // await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id);
  268. // // 修改本期应耗数量值和有效价差,需要剔除不参与调差的清单数据,并返回总金额
  269. // let m_tp = null;
  270. // let m_tax_tp = null;
  271. // let rate_tp = null;
  272. // if (data.is_stage_self) {
  273. // [m_tp, m_tax_tp, rate_tp] = await this.ctx.service.materialStageBills.insertBills(transaction, this.ctx.tender.id, newMaterial.id, newMaterial.stage_id, insertMaterialStage, JSON.parse(newMaterial.decimal), preMaterial.is_stage_self, data.qty_source, newMaterial.rate);
  274. // } else {
  275. // [m_tp, m_tax_tp, rate_tp] = await this.ctx.service.materialBills.updateNewMaterial(transaction, this.ctx.tender.id, newMaterial.id, this.ctx, newMaterial.stage_id, JSON.parse(newMaterial.decimal), preMaterial.is_stage_self, data.qty_source, newMaterial.rate);
  276. // }
  277. // // 计算得出本期总金额
  278. // // 找出当前人并更新tp_data
  279. // const tp_data = await this.ctx.service.materialAudit.getTpData(transaction, newMaterial.id, JSON.parse(newMaterial.decimal));
  280. // const updateMaterialData = {
  281. // id: newMaterial.id,
  282. // // m_tp,
  283. // // m_tax_tp,
  284. // // rate_tp,
  285. // // tp_data: JSON.stringify(tp_data),
  286. // };
  287. // // 修改现行价格指数,并返回调差基数json,
  288. if (!data.is_stage_self && !newMaterial.pre_exponent_node) {
  289. // const ex_calc = await this.ctx.service.materialExponent.updateNewMaterial(transaction, newMaterial.id, this.ctx, newMaterial.stage_id, preMaterial.ex_calc, JSON.parse(newMaterial.decimal), newMaterial.exponent_rate);
  290. await this.ctx.service.materialExponent.updateNewMaterial(transaction, newMaterial.id, this.ctx, newMaterial.stage_id, preMaterial.ex_calc, JSON.parse(newMaterial.exponent_decimal), newMaterial.exponent_rate);
  291. // updateMaterialData.ex_calc = JSON.stringify(ex_calc);
  292. }
  293. // await transaction.update(this.tableName, updateMaterialData);
  294. // // 删除material_list表冗余数据,减少表数据量
  295. // await transaction.delete(this.ctx.service.materialList.tableName, { tid: this.ctx.tender.id, gather_qty: null, is_self: 0 });
  296. }
  297. await transaction.commit();
  298. return newMaterial;
  299. } catch (err) {
  300. await transaction.rollback();
  301. throw err;
  302. }
  303. }
  304. /**
  305. * 编辑计量期
  306. *
  307. * @param {Number} mid - 第N期
  308. * @param {String} period - 开始-截止时间
  309. * @return {Promise<void>}
  310. */
  311. async saveMaterial(mid, period) {
  312. await this.db.update(this.tableName, {
  313. period,
  314. }, { where: { id: mid } });
  315. }
  316. /**
  317. * 删除材料调差期
  318. *
  319. * @param {Number} id - 期Id
  320. * @return {Promise<void>}
  321. */
  322. async deleteMaterial(id) {
  323. const transaction = await this.db.beginTransaction();
  324. try {
  325. // 删除文件
  326. const attList = await this.ctx.service.materialFile.getAllMaterialFiles(this.ctx.tender.id, id);
  327. await this.ctx.helper.delFiles(attList);
  328. await transaction.delete(this.ctx.service.materialAudit.tableName, { mid: id });
  329. await transaction.delete(this.ctx.service.materialBills.tableName, { mid: id });
  330. await transaction.delete(this.ctx.service.materialList.tableName, { mid: id });
  331. await transaction.delete(this.ctx.service.materialListGcl.tableName, { mid: id });
  332. await transaction.delete(this.ctx.service.materialListSelf.tableName, { mid: id });
  333. await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { mid: id });
  334. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { mid: id });
  335. await transaction.delete(this.ctx.service.materialFile.tableName, { mid: id });
  336. await transaction.delete(this.ctx.service.materialExponent.tableName, { mid: id });
  337. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, { mid: id });
  338. // 如果存在上一期,把上一期的quantity,expr,msg_tp,msg_times,msg_spread,m_up_risk,m_down_risk,m_spread,m_tp,pre_tp,orgin,is_summary添加到bill中
  339. const materialInfo = await this.getDataById(id);
  340. if (materialInfo.order > 1) {
  341. const sql = 'UPDATE ' + this.ctx.service.materialBills.tableName + ' as mb, ' +
  342. this.ctx.service.materialBillsHistory.tableName + ' as mbh ' +
  343. 'SET mb.`quantity` = mbh.`quantity`, mb.`expr` = mbh.`expr`, ' +
  344. 'mb.`msg_tp` = mbh.`msg_tp`, mb.`msg_times` = mbh.`msg_times`, ' +
  345. 'mb.`msg_spread` = mbh.`msg_spread`, mb.`m_up_risk` = mbh.`m_up_risk`, ' +
  346. 'mb.`m_down_risk` = mbh.`m_down_risk`, mb.`m_spread` = mbh.`m_spread`, ' +
  347. 'mb.`m_tp` = mbh.`m_tp`, mb.`pre_tp` = mbh.`pre_tp`, ' +
  348. 'mb.`m_tax_tp` = mbh.`m_tax_tp`, mb.`tax_pre_tp` = mbh.`tax_pre_tp`, ' +
  349. 'mb.`origin` = mbh.`origin`, mb.`is_summary` = mbh.`is_summary`, mb.`m_tax` = mbh.`m_tax` ' +
  350. 'WHERE mbh.`tid` = ? AND mbh.`order` = ? AND mbh.`mb_id` = mb.`id`';
  351. const sqlParam = [this.ctx.tender.id, materialInfo.order - 1];
  352. await transaction.query(sql, sqlParam);
  353. const sql2 = 'UPDATE ' + this.ctx.service.materialExponent.tableName + ' as me, ' +
  354. this.ctx.service.materialExponentHistory.tableName + ' as meh ' +
  355. 'SET me.`weight_num` = meh.`weight_num`, me.`basic_price` = meh.`basic_price`, ' +
  356. 'me.`basic_times` = meh.`basic_times`, me.`m_price` = meh.`m_price`, ' +
  357. 'me.`calc_num` = meh.`calc_num`, me.`is_summary` = meh.`is_summary` ' +
  358. 'WHERE meh.`tid` = ? AND meh.`order` = ? AND meh.`me_id` = me.`id`';
  359. const sqlParam2 = [this.ctx.tender.id, materialInfo.order - 1];
  360. await transaction.query(sql2, sqlParam2);
  361. }
  362. // 设置list_gcl表old => new更新
  363. await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id, 'old2new');
  364. // 还要从material_list表更新gcl的old数据,更新方法
  365. await this.ctx.service.materialListGcl.setOldFromLast(transaction, this.ctx.tender.id, materialInfo.order - 2);
  366. if (materialInfo.is_stage_self || materialInfo.exponent_node) {
  367. await transaction.delete(this.ctx.service.materialStage.tableName, { mid: id });
  368. await transaction.delete(this.ctx.service.materialStageBills.tableName, { mid: id });
  369. await transaction.delete(this.ctx.service.materialExponentShard.tableName, { mid: id });
  370. await transaction.delete(this.ctx.service.materialExponentNode.tableName, { mid: id });
  371. }
  372. await transaction.delete(this.tableName, { id });
  373. // 记录删除日志
  374. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.material, projectLogConst.status.delete, '第' + materialInfo.order + '期');
  375. await transaction.commit();
  376. return true;
  377. } catch (err) {
  378. await transaction.rollback();
  379. throw err;
  380. }
  381. }
  382. /**
  383. * 获取包含当前期之前的调差期id
  384. *
  385. * @param {Number} id - 期Id
  386. * @return {Promise<void>}
  387. */
  388. async getPreMidList(tid, order) {
  389. const midList = await this.getAllDataByCondition({
  390. where: { tid },
  391. columns: ['id'],
  392. limit: order,
  393. offset: 0,
  394. });
  395. const list = [];
  396. for (const ml of midList) {
  397. list.push(ml.id);
  398. }
  399. return list;
  400. }
  401. /**
  402. * 修改增税税率
  403. * @param {int} rate 税率
  404. * @return {Promise<*>}
  405. */
  406. async changeRate(rate) {
  407. const updateData = {
  408. id: this.ctx.material.id,
  409. rate,
  410. };
  411. return await this.db.update(this.tableName, updateData);
  412. }
  413. /**
  414. * 修改增税税率
  415. * @param {int} rate 税率
  416. * @return {Promise<*>}
  417. */
  418. async changeExponentRate(rate) {
  419. const transaction = await this.db.beginTransaction();
  420. try {
  421. const result = {};
  422. const info = {};
  423. const decimal = this.ctx.material.exponent_decimal;
  424. switch (this.ctx.material.exponentStatus) {
  425. case materialConst.exponent_status.shared_noNode:
  426. const updateData = {
  427. id: this.ctx.material.id,
  428. exponent_rate: rate,
  429. ex_tax_tp: this.ctx.material.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(this.ctx.material.ex_tp, 1 + rate / 100), decimal.tp) : null,
  430. };
  431. await transaction.update(this.tableName, updateData);
  432. result.ex_tax_tp = updateData.ex_tax_tp;
  433. break;
  434. case materialConst.exponent_status.shared_node:
  435. // 汇总到material上
  436. info.materialNodes = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  437. info.ex_tax_tp = 0;
  438. info.updateTaxTps = [];
  439. for (const mn of info.materialNodes) {
  440. const newExTaxTp = mn.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(mn.ex_tp, 1 + rate / 100), decimal.tp) : null;
  441. info.updateTaxTps.push({
  442. id: mn.id,
  443. ex_tax_tp: newExTaxTp,
  444. });
  445. info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  446. }
  447. if (info.updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialExponentNode.tableName, info.updateTaxTps);
  448. await transaction.update(this.tableName, {
  449. id: this.ctx.material.id,
  450. exponent_rate: rate,
  451. ex_tax_tp: info.ex_tax_tp,
  452. });
  453. result.ex_tax_tp = info.ex_tax_tp;
  454. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  455. break;
  456. case materialConst.exponent_status.self_noNode:
  457. // 汇总到material上
  458. info.materialStages = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  459. info.ex_tax_tp = 0;
  460. info.updateTaxTps = [];
  461. for (const ms of info.materialStages) {
  462. const newExTaxTp = ms.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(ms.ex_tp, 1 + rate / 100), decimal.tp) : null;
  463. info.updateTaxTps.push({
  464. id: ms.id,
  465. ex_tax_tp: newExTaxTp,
  466. });
  467. info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  468. }
  469. if (info.updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialStage.tableName, info.updateTaxTps);
  470. await transaction.update(this.tableName, {
  471. id: this.ctx.material.id,
  472. exponent_rate: rate,
  473. ex_tax_tp: info.ex_tax_tp,
  474. });
  475. result.ex_tax_tp = info.ex_tax_tp;
  476. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  477. break;
  478. case materialConst.exponent_status.self_node:
  479. // 汇总到material上
  480. info.materialStages = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  481. info.materialNodes = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  482. info.updateTaxTps = [];
  483. for (const mn of info.materialNodes) {
  484. const newExTaxTp = mn.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(mn.ex_tp, 1 + rate / 100), decimal.tp) : null;
  485. info.updateTaxTps.push({
  486. id: mn.id,
  487. ex_tax_tp: newExTaxTp,
  488. });
  489. mn.ex_tax_tp = newExTaxTp;
  490. // info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  491. }
  492. if (info.updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialExponentNode.tableName, info.updateTaxTps);
  493. info.ex_tax_tp = 0;
  494. info.updateStageTaxTps = [];
  495. for (const ms of info.materialStages) {
  496. const mnList = this._.filter(info.materialNodes, { ms_id: ms.id });
  497. const taxTpList = this._.map(mnList, 'ex_tax_tp');
  498. // 这里的this.ctx为undefined,所以用this._.reduce时需要传入this.ctx.helper
  499. const that = this;
  500. const newExTaxTp = taxTpList.length > 0 ? that._.reduce(taxTpList, function(sum, n) { return that.ctx.helper.add(sum, n); }, 0) : null;
  501. // const newExTaxTp = taxTpList.length > 0 ? this._.reduce(taxTpList, function(sum, n) { return this.ctx.helper.add(sum, n); }, 0) : null;
  502. info.updateStageTaxTps.push({
  503. id: ms.id,
  504. ex_tax_tp: newExTaxTp,
  505. });
  506. info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  507. }
  508. if (info.updateStageTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialStage.tableName, info.updateStageTaxTps);
  509. await transaction.update(this.tableName, {
  510. id: this.ctx.material.id,
  511. exponent_rate: rate,
  512. ex_tax_tp: info.ex_tax_tp,
  513. });
  514. result.ex_tax_tp = info.ex_tax_tp;
  515. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  516. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  517. break;
  518. default: break;
  519. }
  520. await transaction.commit();
  521. return result;
  522. } catch (err) {
  523. await transaction.rollback();
  524. throw err;
  525. }
  526. }
  527. /**
  528. * 修改调差基数
  529. * @param {int} rate 税率
  530. * @return {Promise<*>}
  531. */
  532. async changeExCalc(ex_calc, ms_id = null, mn_id = null) {
  533. const transaction = await this.db.beginTransaction();
  534. try {
  535. const result = {};
  536. const info = {};
  537. switch (this.ctx.material.exponentStatus) {
  538. case materialConst.exponent_status.shared_noNode:
  539. [result.ex_tp, result.ex_tax_tp, result.ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction, ex_calc);
  540. break;
  541. case materialConst.exponent_status.shared_node:
  542. if (!mn_id) throw '参数有误';
  543. info.mnInfo = await transaction.get(this.ctx.service.materialExponentNode.tableName, { mid: this.ctx.material.id, id: mn_id });
  544. if (!info.mnInfo) {
  545. throw '调差新增分项不存在';
  546. }
  547. await this.ctx.service.materialExponentShard.calcMaterialExTp(transaction, ex_calc, this.ctx.material.id, null, mn_id);
  548. [result.ex_tp, result.ex_tax_tp] = await this.ctx.service.materialExponent.calcTpByMaterialExponentNode(transaction, this.ctx.material.id);
  549. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id, id: mn_id } });
  550. break;
  551. case materialConst.exponent_status.self_noNode:
  552. if (!ms_id) throw '参数有误';
  553. info.msInfo = await transaction.get(this.ctx.service.materialStage.tableName, { mid: this.ctx.material.id, id: ms_id });
  554. if (!info.msInfo) {
  555. throw '调差独立期不存在';
  556. }
  557. await this.ctx.service.materialExponentShard.calcMaterialExTp(transaction, ex_calc, this.ctx.material.id, ms_id);
  558. [result.ex_tp, result.ex_tax_tp] = await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  559. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id, id: ms_id } });
  560. break;
  561. case materialConst.exponent_status.self_node:
  562. if (!ms_id || !mn_id) throw '参数有误';
  563. info.msInfo = await transaction.get(this.ctx.service.materialStage.tableName, { mid: this.ctx.material.id, id: ms_id });
  564. if (!info.msInfo) {
  565. throw '调差独立期不存在';
  566. }
  567. info.mnInfo = await transaction.get(this.ctx.service.materialExponentNode.tableName, { mid: this.ctx.material.id, id: mn_id });
  568. if (!info.mnInfo) {
  569. throw '调差新增分项不存在';
  570. }
  571. await this.ctx.service.materialExponentShard.calcMaterialExTp(transaction, ex_calc, this.ctx.material.id, ms_id, mn_id);
  572. [result.ex_tp, result.ex_tax_tp] = await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  573. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id, id: mn_id } });
  574. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id, id: ms_id } });
  575. break;
  576. default: break;
  577. }
  578. await transaction.commit();
  579. return result;
  580. } catch (err) {
  581. await transaction.rollback();
  582. throw err;
  583. }
  584. }
  585. /**
  586. * 取当前期截止上期含建筑税金额
  587. * @param {int} tid 标段id
  588. * @param {int} order 调差期数
  589. * @return {Promise<*>}
  590. */
  591. async getPreTpHs(tid, order, tp) {
  592. const sql = 'SELECT SUM(`rate_tp`) AS `pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  593. const sqlParam = [this.tableName, tid, 0, order];
  594. const result = await this.db.queryOne(sql, sqlParam);
  595. return result.pre_tp_hs;
  596. }
  597. /**
  598. * 取当前期截止上期含材料税金额
  599. * @param {int} tid 标段id
  600. * @param {int} order 调差期数
  601. * @return {Promise<*>}
  602. */
  603. async getTaxPreTpHs(tid, order) {
  604. const sql = 'SELECT SUM(`m_tax_tp`) AS `tax_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  605. const sqlParam = [this.tableName, tid, 1, order];
  606. const result = await this.db.queryOne(sql, sqlParam);
  607. return result.tax_pre_tp_hs;
  608. }
  609. /**
  610. * 取当前期截止上期含建筑税指数金额
  611. * @param {int} tid 标段id
  612. * @param {int} order 调差期数
  613. * @return {Promise<*>}
  614. */
  615. async getExPreTpHs(tid, order, tp) {
  616. const sql = 'SELECT SUM(ROUND(`ex_tp`*(1+ `exponent_rate`/100),' + tp + ')) AS `ex_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `order` < ?';
  617. const sqlParam = [this.tableName, tid, order];
  618. const result = await this.db.queryOne(sql, sqlParam);
  619. return result.ex_pre_tp_hs;
  620. }
  621. async updateMaterialTax(id, mtax) {
  622. const updateData = {
  623. id,
  624. material_tax: mtax,
  625. };
  626. return await this.db.update(this.tableName, updateData);
  627. }
  628. async getMaterialTaxTp(id) {
  629. const info = await this.getDataById(id);
  630. return info.m_tax_tp;
  631. }
  632. async getSumMaterial(tid) {
  633. const sql = 'Select sum(IFNULL(m_tp, 0) + IFNULL(ex_tp, 0)) as tp From ' + this.tableName + ' where tid = ?';
  634. const result = await this.db.queryOne(sql, [tid]);
  635. return result ? result.tp : 0;
  636. }
  637. async getOldMaterialTax(tid, order) {
  638. const sql = 'SELECT COUNT(id) as count FROM ?? WHERE `tid` = ? AND `order` <= ? AND `material_tax` = 1';
  639. const sqlParam = [this.tableName, tid, order];
  640. const result = await this.db.queryOne(sql, sqlParam);
  641. return result && result.count !== 0;
  642. }
  643. async saveDecimal(need, newUp, newTp, newQty, needExponent, newExponentUp, newExponentTp, newExponentQty) {
  644. const transaction = await this.db.beginTransaction();
  645. try {
  646. if (need) {
  647. await this.ctx.service.materialBills.resetDecimal(transaction, newUp, newTp, newQty);
  648. this.ctx.material.decimal.up = newUp;
  649. this.ctx.material.decimal.tp = newTp;
  650. this.ctx.material.decimal.qty = newQty;
  651. await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  652. }
  653. // let update_calc = false;
  654. if (needExponent) {
  655. this.ctx.material.exponent_decimal.up = newExponentUp;
  656. this.ctx.material.exponent_decimal.tp = newExponentTp;
  657. this.ctx.material.exponent_decimal.qty = newExponentQty;
  658. await this.ctx.service.materialExponent.resetDecimal(transaction, this.ctx.material.exponent_decimal);
  659. switch (this.ctx.material.exponentStatus) {
  660. case materialConst.exponent_status.shared_noNode:
  661. await this.ctx.service.materialExponent.calcMaterialExTp(transaction);
  662. break;
  663. case materialConst.exponent_status.shared_node:
  664. await this.ctx.service.materialExponentShard.calcMaterialAllExTpByNode(transaction, this.ctx.material.id, null, false);
  665. await this.ctx.service.materialExponent.calcTpByMaterialExponentNode(transaction, this.ctx.material.id);
  666. break;
  667. case materialConst.exponent_status.self_noNode:
  668. await this.ctx.service.materialExponentShard.calcMaterialAllExTpByStage(transaction, this.ctx.material.id);
  669. await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  670. break;
  671. case materialConst.exponent_status.self_node:
  672. await this.ctx.service.materialExponentShard.calcMaterialAllExTpByNode(transaction, this.ctx.material.id);
  673. await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  674. break;
  675. default: break;
  676. }
  677. }
  678. const updateData = {
  679. id: this.ctx.material.id,
  680. decimal: JSON.stringify(this.ctx.material.decimal),
  681. exponent_decimal: JSON.stringify(this.ctx.material.exponent_decimal),
  682. };
  683. // if (update_calc) updateData.ex_calc = this.ctx.material.ex_calc;
  684. await transaction.update(this.tableName, updateData);
  685. await transaction.commit();
  686. return true;
  687. } catch (err) {
  688. console.log(err);
  689. await transaction.rollback();
  690. return false;
  691. }
  692. }
  693. async saveQtySource(newQtySource) {
  694. const transaction = await this.db.beginTransaction();
  695. try {
  696. await this.ctx.service.materialBills.resetQuantityByQtySource(transaction, newQtySource);
  697. this.ctx.material.qty_source = newQtySource;
  698. const m_tp = await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  699. const updateData = {
  700. id: this.ctx.material.id,
  701. qty_source: newQtySource,
  702. };
  703. await transaction.update(this.tableName, updateData);
  704. await transaction.commit();
  705. return true;
  706. } catch (err) {
  707. console.log(err);
  708. await transaction.rollback();
  709. return false;
  710. }
  711. }
  712. async getListByArchives(tid, ids) {
  713. if (ids.length === 0) return [];
  714. const sql = 'SELECT c.* FROM ?? as c LEFT JOIN (SELECT mid, MAX(end_time) as end_time FROM ?? WHERE ' +
  715. 'tid = ? AND mid in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') GROUP BY mid) as ca ON c.id = ca.mid WHERE' +
  716. ' c.tid = ? AND c.id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') AND c.status = ? ORDER BY ca.end_time DESC';
  717. const params = [this.tableName, this.ctx.service.materialAudit.tableName, tid, tid, auditConst.status.checked];
  718. const list = await this.db.query(sql, params);
  719. return list;
  720. }
  721. async makeExponentTp(data) {
  722. if (!data.mid) {
  723. throw '参数错误';
  724. }
  725. const transaction = await this.db.beginTransaction();
  726. try {
  727. const material = await this.getDataById(data.mid);
  728. if (!material) {
  729. throw '调差不存在';
  730. }
  731. material.decimal = JSON.parse(material.decimal);
  732. if (!material.is_stage_self || material.is_new_exponent) {
  733. throw '独立期指数调差工料已生成或非独立期调差';
  734. }
  735. const materialStages = await this.ctx.service.materialStage.getAllDataByCondition({ where: { mid: data.mid } });
  736. let ex_tax_tp = 0;
  737. let total_ex_tp = 0;
  738. // const updateTaxTps = [];
  739. for (const ms of materialStages) {
  740. // const tax_tp = this.ctx.helper.round(this.ctx.helper.mul(ms.ex_tp, 1 + material.exponent_rate / 100), material.decimal.tp);
  741. // updateTaxTps.push({ id: ms.id, ex_tax_tp: tax_tp });
  742. ex_tax_tp = this.ctx.helper.add(ex_tax_tp, ms.ex_tax_tp);
  743. total_ex_tp = this.ctx.helper.add(total_ex_tp, ms.ex_tp || 0);
  744. }
  745. // if (updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialStage.tableName, updateTaxTps);
  746. await transaction.update(this.tableName, {
  747. id: material.id,
  748. ex_tp: total_ex_tp,
  749. ex_tax_tp,
  750. ex_expr: null,
  751. // ex_calc: null,
  752. is_new_exponent: 1,
  753. // exponent_decimal: JSON.stringify(materialConst.exponent_decimal),
  754. });
  755. await transaction.commit();
  756. return true;
  757. } catch (err) {
  758. await transaction.rollback();
  759. throw err;
  760. }
  761. }
  762. }
  763. return Material;
  764. };