material.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. await transaction.delete(this.ctx.service.materialListQty.tableName, { mid: id });
  339. // 如果存在上一期,把上一期的quantity,expr,msg_tp,msg_times,msg_spread,m_up_risk,m_down_risk,m_spread,m_tp,pre_tp,orgin,is_summary添加到bill中
  340. const materialInfo = await this.getDataById(id);
  341. if (materialInfo.order > 1) {
  342. const sql = 'UPDATE ' + this.ctx.service.materialBills.tableName + ' as mb, ' +
  343. this.ctx.service.materialBillsHistory.tableName + ' as mbh ' +
  344. 'SET mb.`quantity` = mbh.`quantity`, mb.`expr` = mbh.`expr`, ' +
  345. 'mb.`msg_tp` = mbh.`msg_tp`, mb.`msg_times` = mbh.`msg_times`, ' +
  346. 'mb.`msg_spread` = mbh.`msg_spread`, mb.`m_up_risk` = mbh.`m_up_risk`, ' +
  347. 'mb.`m_down_risk` = mbh.`m_down_risk`, mb.`m_spread` = mbh.`m_spread`, ' +
  348. 'mb.`m_tp` = mbh.`m_tp`, mb.`pre_tp` = mbh.`pre_tp`, ' +
  349. 'mb.`m_tax_tp` = mbh.`m_tax_tp`, mb.`tax_pre_tp` = mbh.`tax_pre_tp`, ' +
  350. 'mb.`origin` = mbh.`origin`, mb.`is_summary` = mbh.`is_summary`, mb.`m_tax` = mbh.`m_tax` ' +
  351. 'WHERE mbh.`tid` = ? AND mbh.`order` = ? AND mbh.`mb_id` = mb.`id`';
  352. const sqlParam = [this.ctx.tender.id, materialInfo.order - 1];
  353. await transaction.query(sql, sqlParam);
  354. const sql2 = 'UPDATE ' + this.ctx.service.materialExponent.tableName + ' as me, ' +
  355. this.ctx.service.materialExponentHistory.tableName + ' as meh ' +
  356. 'SET me.`weight_num` = meh.`weight_num`, me.`basic_price` = meh.`basic_price`, ' +
  357. 'me.`basic_times` = meh.`basic_times`, me.`m_price` = meh.`m_price`, ' +
  358. 'me.`calc_num` = meh.`calc_num`, me.`is_summary` = meh.`is_summary` ' +
  359. 'WHERE meh.`tid` = ? AND meh.`order` = ? AND meh.`me_id` = me.`id`';
  360. const sqlParam2 = [this.ctx.tender.id, materialInfo.order - 1];
  361. await transaction.query(sql2, sqlParam2);
  362. }
  363. // 设置list_gcl表old => new更新
  364. await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id, 'old2new');
  365. // 还要从material_list表更新gcl的old数据,更新方法
  366. await this.ctx.service.materialListGcl.setOldFromLast(transaction, this.ctx.tender.id, materialInfo.order - 2);
  367. if (materialInfo.is_stage_self || materialInfo.exponent_node) {
  368. await transaction.delete(this.ctx.service.materialStage.tableName, { mid: id });
  369. await transaction.delete(this.ctx.service.materialStageBills.tableName, { mid: id });
  370. await transaction.delete(this.ctx.service.materialExponentShard.tableName, { mid: id });
  371. await transaction.delete(this.ctx.service.materialExponentNode.tableName, { mid: id });
  372. }
  373. await transaction.delete(this.tableName, { id });
  374. // 记录删除日志
  375. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.material, projectLogConst.status.delete, '第' + materialInfo.order + '期');
  376. await transaction.commit();
  377. return true;
  378. } catch (err) {
  379. await transaction.rollback();
  380. throw err;
  381. }
  382. }
  383. /**
  384. * 获取包含当前期之前的调差期id
  385. *
  386. * @param {Number} id - 期Id
  387. * @return {Promise<void>}
  388. */
  389. async getPreMidList(tid, order) {
  390. const midList = await this.getAllDataByCondition({
  391. where: { tid },
  392. columns: ['id'],
  393. limit: order,
  394. offset: 0,
  395. });
  396. const list = [];
  397. for (const ml of midList) {
  398. list.push(ml.id);
  399. }
  400. return list;
  401. }
  402. /**
  403. * 修改增税税率
  404. * @param {int} rate 税率
  405. * @return {Promise<*>}
  406. */
  407. async changeRate(rate) {
  408. const updateData = {
  409. id: this.ctx.material.id,
  410. rate,
  411. };
  412. return await this.db.update(this.tableName, updateData);
  413. }
  414. /**
  415. * 修改增税税率
  416. * @param {int} rate 税率
  417. * @return {Promise<*>}
  418. */
  419. async changeExponentRate(rate) {
  420. const transaction = await this.db.beginTransaction();
  421. try {
  422. const result = {};
  423. const info = {};
  424. const decimal = this.ctx.material.exponent_decimal;
  425. switch (this.ctx.material.exponentStatus) {
  426. case materialConst.exponent_status.shared_noNode:
  427. const updateData = {
  428. id: this.ctx.material.id,
  429. exponent_rate: rate,
  430. 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,
  431. };
  432. await transaction.update(this.tableName, updateData);
  433. result.ex_tax_tp = updateData.ex_tax_tp;
  434. break;
  435. case materialConst.exponent_status.shared_node:
  436. // 汇总到material上
  437. info.materialNodes = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  438. info.ex_tax_tp = 0;
  439. info.updateTaxTps = [];
  440. for (const mn of info.materialNodes) {
  441. const newExTaxTp = mn.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(mn.ex_tp, 1 + rate / 100), decimal.tp) : null;
  442. info.updateTaxTps.push({
  443. id: mn.id,
  444. ex_tax_tp: newExTaxTp,
  445. });
  446. info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  447. }
  448. if (info.updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialExponentNode.tableName, info.updateTaxTps);
  449. await transaction.update(this.tableName, {
  450. id: this.ctx.material.id,
  451. exponent_rate: rate,
  452. ex_tax_tp: info.ex_tax_tp,
  453. });
  454. result.ex_tax_tp = info.ex_tax_tp;
  455. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  456. break;
  457. case materialConst.exponent_status.self_noNode:
  458. // 汇总到material上
  459. info.materialStages = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  460. info.ex_tax_tp = 0;
  461. info.updateTaxTps = [];
  462. for (const ms of info.materialStages) {
  463. const newExTaxTp = ms.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(ms.ex_tp, 1 + rate / 100), decimal.tp) : null;
  464. info.updateTaxTps.push({
  465. id: ms.id,
  466. ex_tax_tp: newExTaxTp,
  467. });
  468. info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  469. }
  470. if (info.updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialStage.tableName, info.updateTaxTps);
  471. await transaction.update(this.tableName, {
  472. id: this.ctx.material.id,
  473. exponent_rate: rate,
  474. ex_tax_tp: info.ex_tax_tp,
  475. });
  476. result.ex_tax_tp = info.ex_tax_tp;
  477. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  478. break;
  479. case materialConst.exponent_status.self_node:
  480. // 汇总到material上
  481. info.materialStages = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  482. info.materialNodes = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  483. info.updateTaxTps = [];
  484. for (const mn of info.materialNodes) {
  485. const newExTaxTp = mn.ex_tp !== null ? this.ctx.helper.round(this.ctx.helper.mul(mn.ex_tp, 1 + rate / 100), decimal.tp) : null;
  486. info.updateTaxTps.push({
  487. id: mn.id,
  488. ex_tax_tp: newExTaxTp,
  489. });
  490. mn.ex_tax_tp = newExTaxTp;
  491. // info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  492. }
  493. if (info.updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialExponentNode.tableName, info.updateTaxTps);
  494. info.ex_tax_tp = 0;
  495. info.updateStageTaxTps = [];
  496. for (const ms of info.materialStages) {
  497. const mnList = this._.filter(info.materialNodes, { ms_id: ms.id });
  498. const taxTpList = this._.map(mnList, 'ex_tax_tp');
  499. // 这里的this.ctx为undefined,所以用this._.reduce时需要传入this.ctx.helper
  500. const that = this;
  501. const newExTaxTp = taxTpList.length > 0 ? that._.reduce(taxTpList, function(sum, n) { return that.ctx.helper.add(sum, n); }, 0) : null;
  502. // const newExTaxTp = taxTpList.length > 0 ? this._.reduce(taxTpList, function(sum, n) { return this.ctx.helper.add(sum, n); }, 0) : null;
  503. info.updateStageTaxTps.push({
  504. id: ms.id,
  505. ex_tax_tp: newExTaxTp,
  506. });
  507. info.ex_tax_tp = this.ctx.helper.add(info.ex_tax_tp, newExTaxTp);
  508. }
  509. if (info.updateStageTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialStage.tableName, info.updateStageTaxTps);
  510. await transaction.update(this.tableName, {
  511. id: this.ctx.material.id,
  512. exponent_rate: rate,
  513. ex_tax_tp: info.ex_tax_tp,
  514. });
  515. result.ex_tax_tp = info.ex_tax_tp;
  516. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  517. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id } });
  518. break;
  519. default: break;
  520. }
  521. await transaction.commit();
  522. return result;
  523. } catch (err) {
  524. await transaction.rollback();
  525. throw err;
  526. }
  527. }
  528. /**
  529. * 修改调差基数
  530. * @param {int} rate 税率
  531. * @return {Promise<*>}
  532. */
  533. async changeExCalc(ex_calc, ms_id = null, mn_id = null) {
  534. const transaction = await this.db.beginTransaction();
  535. try {
  536. const result = {};
  537. const info = {};
  538. switch (this.ctx.material.exponentStatus) {
  539. case materialConst.exponent_status.shared_noNode:
  540. [result.ex_tp, result.ex_tax_tp, result.ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction, ex_calc);
  541. break;
  542. case materialConst.exponent_status.shared_node:
  543. if (!mn_id) throw '参数有误';
  544. info.mnInfo = await transaction.get(this.ctx.service.materialExponentNode.tableName, { mid: this.ctx.material.id, id: mn_id });
  545. if (!info.mnInfo) {
  546. throw '调差新增分项不存在';
  547. }
  548. await this.ctx.service.materialExponentShard.calcMaterialExTp(transaction, ex_calc, this.ctx.material.id, null, mn_id);
  549. [result.ex_tp, result.ex_tax_tp] = await this.ctx.service.materialExponent.calcTpByMaterialExponentNode(transaction, this.ctx.material.id);
  550. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id, id: mn_id } });
  551. break;
  552. case materialConst.exponent_status.self_noNode:
  553. if (!ms_id) throw '参数有误';
  554. info.msInfo = await transaction.get(this.ctx.service.materialStage.tableName, { mid: this.ctx.material.id, id: ms_id });
  555. if (!info.msInfo) {
  556. throw '调差独立期不存在';
  557. }
  558. await this.ctx.service.materialExponentShard.calcMaterialExTp(transaction, ex_calc, this.ctx.material.id, ms_id);
  559. [result.ex_tp, result.ex_tax_tp] = await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  560. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id, id: ms_id } });
  561. break;
  562. case materialConst.exponent_status.self_node:
  563. if (!ms_id || !mn_id) throw '参数有误';
  564. info.msInfo = await transaction.get(this.ctx.service.materialStage.tableName, { mid: this.ctx.material.id, id: ms_id });
  565. if (!info.msInfo) {
  566. throw '调差独立期不存在';
  567. }
  568. info.mnInfo = await transaction.get(this.ctx.service.materialExponentNode.tableName, { mid: this.ctx.material.id, id: mn_id });
  569. if (!info.mnInfo) {
  570. throw '调差新增分项不存在';
  571. }
  572. await this.ctx.service.materialExponentShard.calcMaterialExTp(transaction, ex_calc, this.ctx.material.id, ms_id, mn_id);
  573. [result.ex_tp, result.ex_tax_tp] = await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  574. result.nodeData = await transaction.select(this.ctx.service.materialExponentNode.tableName, { where: { mid: this.ctx.material.id, id: mn_id } });
  575. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id, id: ms_id } });
  576. break;
  577. default: break;
  578. }
  579. await transaction.commit();
  580. return result;
  581. } catch (err) {
  582. await transaction.rollback();
  583. throw err;
  584. }
  585. }
  586. /**
  587. * 取当前期截止上期含建筑税金额
  588. * @param {int} tid 标段id
  589. * @param {int} order 调差期数
  590. * @return {Promise<*>}
  591. */
  592. async getPreTpHs(tid, order, tp) {
  593. const sql = 'SELECT SUM(`rate_tp`) AS `pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  594. const sqlParam = [this.tableName, tid, 0, order];
  595. const result = await this.db.queryOne(sql, sqlParam);
  596. return result.pre_tp_hs;
  597. }
  598. /**
  599. * 取当前期截止上期含材料税金额
  600. * @param {int} tid 标段id
  601. * @param {int} order 调差期数
  602. * @return {Promise<*>}
  603. */
  604. async getTaxPreTpHs(tid, order) {
  605. const sql = 'SELECT SUM(`m_tax_tp`) AS `tax_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  606. const sqlParam = [this.tableName, tid, 1, order];
  607. const result = await this.db.queryOne(sql, sqlParam);
  608. return result.tax_pre_tp_hs;
  609. }
  610. /**
  611. * 取当前期截止上期含建筑税指数金额
  612. * @param {int} tid 标段id
  613. * @param {int} order 调差期数
  614. * @return {Promise<*>}
  615. */
  616. async getExPreTpHs(tid, order, tp) {
  617. const sql = 'SELECT SUM(ROUND(`ex_tp`*(1+ `exponent_rate`/100),' + tp + ')) AS `ex_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `order` < ?';
  618. const sqlParam = [this.tableName, tid, order];
  619. const result = await this.db.queryOne(sql, sqlParam);
  620. return result.ex_pre_tp_hs;
  621. }
  622. async updateMaterialTax(id, mtax) {
  623. const updateData = {
  624. id,
  625. material_tax: mtax,
  626. };
  627. return await this.db.update(this.tableName, updateData);
  628. }
  629. async getMaterialTaxTp(id) {
  630. const info = await this.getDataById(id);
  631. return info.m_tax_tp;
  632. }
  633. async getSumMaterial(tid) {
  634. const sql = 'Select sum(IFNULL(m_tp, 0) + IFNULL(ex_tp, 0)) as tp From ' + this.tableName + ' where tid = ?';
  635. const result = await this.db.queryOne(sql, [tid]);
  636. return result ? result.tp : 0;
  637. }
  638. async getOldMaterialTax(tid, order) {
  639. const sql = 'SELECT COUNT(id) as count FROM ?? WHERE `tid` = ? AND `order` <= ? AND `material_tax` = 1';
  640. const sqlParam = [this.tableName, tid, order];
  641. const result = await this.db.queryOne(sql, sqlParam);
  642. return result && result.count !== 0;
  643. }
  644. async saveDecimal(need, newUp, newTp, newQty, needExponent, newExponentUp, newExponentTp, newExponentQty) {
  645. const transaction = await this.db.beginTransaction();
  646. try {
  647. if (need) {
  648. await this.ctx.service.materialBills.resetDecimal(transaction, newUp, newTp, newQty);
  649. this.ctx.material.decimal.up = newUp;
  650. this.ctx.material.decimal.tp = newTp;
  651. this.ctx.material.decimal.qty = newQty;
  652. await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  653. }
  654. // let update_calc = false;
  655. if (needExponent) {
  656. this.ctx.material.exponent_decimal.up = newExponentUp;
  657. this.ctx.material.exponent_decimal.tp = newExponentTp;
  658. this.ctx.material.exponent_decimal.qty = newExponentQty;
  659. await this.ctx.service.materialExponent.resetDecimal(transaction, this.ctx.material.exponent_decimal);
  660. switch (this.ctx.material.exponentStatus) {
  661. case materialConst.exponent_status.shared_noNode:
  662. await this.ctx.service.materialExponent.calcMaterialExTp(transaction);
  663. break;
  664. case materialConst.exponent_status.shared_node:
  665. await this.ctx.service.materialExponentShard.calcMaterialAllExTpByNode(transaction, this.ctx.material.id, null, false);
  666. await this.ctx.service.materialExponent.calcTpByMaterialExponentNode(transaction, this.ctx.material.id);
  667. break;
  668. case materialConst.exponent_status.self_noNode:
  669. await this.ctx.service.materialExponentShard.calcMaterialAllExTpByStage(transaction, this.ctx.material.id);
  670. await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  671. break;
  672. case materialConst.exponent_status.self_node:
  673. await this.ctx.service.materialExponentShard.calcMaterialAllExTpByNode(transaction, this.ctx.material.id);
  674. await this.ctx.service.materialExponent.calcTpByMaterialStageExponent(transaction, this.ctx.material.id);
  675. break;
  676. default: break;
  677. }
  678. }
  679. const updateData = {
  680. id: this.ctx.material.id,
  681. decimal: JSON.stringify(this.ctx.material.decimal),
  682. exponent_decimal: JSON.stringify(this.ctx.material.exponent_decimal),
  683. };
  684. // if (update_calc) updateData.ex_calc = this.ctx.material.ex_calc;
  685. await transaction.update(this.tableName, updateData);
  686. await transaction.commit();
  687. return true;
  688. } catch (err) {
  689. console.log(err);
  690. await transaction.rollback();
  691. return false;
  692. }
  693. }
  694. async saveQtySource(newQtySource) {
  695. const transaction = await this.db.beginTransaction();
  696. try {
  697. await this.ctx.service.materialBills.resetQuantityByQtySource(transaction, newQtySource);
  698. this.ctx.material.qty_source = newQtySource;
  699. const m_tp = await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  700. const updateData = {
  701. id: this.ctx.material.id,
  702. qty_source: newQtySource,
  703. };
  704. await transaction.update(this.tableName, updateData);
  705. await transaction.commit();
  706. return true;
  707. } catch (err) {
  708. console.log(err);
  709. await transaction.rollback();
  710. return false;
  711. }
  712. }
  713. async getListByArchives(tid, ids) {
  714. if (ids.length === 0) return [];
  715. const sql = 'SELECT c.* FROM ?? as c LEFT JOIN (SELECT mid, MAX(end_time) as end_time FROM ?? WHERE ' +
  716. 'tid = ? AND mid in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') GROUP BY mid) as ca ON c.id = ca.mid WHERE' +
  717. ' c.tid = ? AND c.id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') AND c.status = ? ORDER BY ca.end_time DESC';
  718. const params = [this.tableName, this.ctx.service.materialAudit.tableName, tid, tid, auditConst.status.checked];
  719. const list = await this.db.query(sql, params);
  720. return list;
  721. }
  722. async makeExponentTp(data) {
  723. if (!data.mid) {
  724. throw '参数错误';
  725. }
  726. const transaction = await this.db.beginTransaction();
  727. try {
  728. const material = await this.getDataById(data.mid);
  729. if (!material) {
  730. throw '调差不存在';
  731. }
  732. material.decimal = JSON.parse(material.decimal);
  733. if (!material.is_stage_self || material.is_new_exponent) {
  734. throw '独立期指数调差工料已生成或非独立期调差';
  735. }
  736. const materialStages = await this.ctx.service.materialStage.getAllDataByCondition({ where: { mid: data.mid } });
  737. let ex_tax_tp = 0;
  738. let total_ex_tp = 0;
  739. // const updateTaxTps = [];
  740. for (const ms of materialStages) {
  741. // const tax_tp = this.ctx.helper.round(this.ctx.helper.mul(ms.ex_tp, 1 + material.exponent_rate / 100), material.decimal.tp);
  742. // updateTaxTps.push({ id: ms.id, ex_tax_tp: tax_tp });
  743. ex_tax_tp = this.ctx.helper.add(ex_tax_tp, ms.ex_tax_tp);
  744. total_ex_tp = this.ctx.helper.add(total_ex_tp, ms.ex_tp || 0);
  745. }
  746. // if (updateTaxTps.length > 0) await transaction.updateRows(this.ctx.service.materialStage.tableName, updateTaxTps);
  747. await transaction.update(this.tableName, {
  748. id: material.id,
  749. ex_tp: total_ex_tp,
  750. ex_tax_tp,
  751. ex_expr: null,
  752. // ex_calc: null,
  753. is_new_exponent: 1,
  754. // exponent_decimal: JSON.stringify(materialConst.exponent_decimal),
  755. });
  756. await transaction.commit();
  757. return true;
  758. } catch (err) {
  759. await transaction.rollback();
  760. throw err;
  761. }
  762. }
  763. }
  764. return Material;
  765. };