material.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. /**
  68. * 获取 最新一期 材料调差期计量
  69. * @param tenderId
  70. * @param includeUnCheck
  71. * @return {Promise<*>}
  72. */
  73. async getLastestMaterial(tenderId, includeUnCheck = false) {
  74. this.initSqlBuilder();
  75. this.sqlBuilder.setAndWhere('tid', {
  76. value: tenderId,
  77. operate: '=',
  78. });
  79. if (!includeUnCheck) {
  80. this.sqlBuilder.setAndWhere('status', {
  81. value: auditConst.status.uncheck,
  82. operate: '!=',
  83. });
  84. }
  85. this.sqlBuilder.orderBy = [['order', 'desc']];
  86. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  87. const material = await this.db.queryOne(sql, sqlParam);
  88. return material;
  89. }
  90. /**
  91. * 获取 最新一期 审批完成的 材料调差期计量
  92. * @param tenderId
  93. * @return {Promise<*>}
  94. */
  95. async getLastestCompleteMaterial(tenderId) {
  96. this.initSqlBuilder();
  97. this.sqlBuilder.setAndWhere('tid', {
  98. value: tenderId,
  99. operate: '=',
  100. });
  101. this.sqlBuilder.setAndWhere('status', {
  102. value: auditConst.status.checked,
  103. operate: '=',
  104. });
  105. this.sqlBuilder.orderBy = [['order', 'desc']];
  106. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  107. const material = await this.db.queryOne(sql, sqlParam);
  108. return material;
  109. }
  110. async checkMaterial(tid, order) {
  111. if (this.ctx.material) return;
  112. const materials = await this.getSelectMaterial(tid, order);
  113. this.ctx.material = materials[0];
  114. if (this.ctx.session.sessionUser.accountId === this.ctx.material.user_id) {
  115. this.ctx.material.curTimes = this.ctx.material.times;
  116. } else {
  117. this.ctx.material.curTimes = this.ctx.material.status === auditConst.status.checkNo ? this.ctx.material.times - 1 : this.ctx.material.times;
  118. }
  119. }
  120. /**
  121. * 获取标段下的全部计量期,按倒序
  122. * @param tenderId
  123. * @return {Promise<void>}
  124. */
  125. async getSelectMaterial(tenderId, order) {
  126. const materials = await this.db.select(this.tableName, {
  127. where: { tid: tenderId, order },
  128. });
  129. if (materials.length > 0 && materials[0].status !== auditConst.status.checked) {
  130. const material = materials[0];
  131. const curAuditor = await this.ctx.service.materialAudit.getCurAuditor(material.id, material.times);
  132. const isActive = curAuditor ? curAuditor.aid === this.ctx.session.sessionUser.accountId : material.user_id === this.ctx.session.sessionUser.accountId;
  133. if (isActive) {
  134. material.curTimes = material.times;
  135. material.curOrder = curAuditor ? curAuditor.order : 0;
  136. }
  137. }
  138. return materials;
  139. }
  140. async getValidMaterials(tenderId) {
  141. const materials = await this.db.select(this.tableName, {
  142. where: { tid: tenderId },
  143. orders: [['order', 'desc']],
  144. });
  145. if (materials.length !== 0) {
  146. const lastMaterial = materials[materials.length - 1];
  147. if (lastMaterial.status === auditConst.status.uncheck && lastMaterial.user_id !== this.ctx.session.sessionUser.accountId && !this.ctx.tender.isTourist && !this.ctx.session.sessionUser.is_admin) {
  148. materials.splice(materials.length - 1, 1);
  149. }
  150. }
  151. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  152. if (materials.length > 0 && materials[0].status !== auditConst.status.checked) {
  153. const material = materials[0];
  154. const curAuditors = await this.ctx.service.materialAudit.getCurAuditors(material.id, material.times);
  155. const isActive = curAuditors && curAuditors.length > 0 ? this._.findIndex(curAuditors, { aid: this.ctx.session.sessionUser.accountId }) !== -1 : material.user_id === this.ctx.session.sessionUser.accountId;
  156. if (isActive) {
  157. material.curTimes = material.times;
  158. material.curOrder = curAuditors && curAuditors.length > 0 ? curAuditors[0].order : 0;
  159. }
  160. }
  161. return materials;
  162. }
  163. /**
  164. * 添加材料调差期
  165. * @param tenderId - 标段id
  166. * @param data - post的数据
  167. * @return {Promise<void>}
  168. */
  169. async addMaterial(tenderId, data) {
  170. const materials = await this.getAllDataByCondition({
  171. where: { tid: tenderId },
  172. order: ['order'],
  173. });
  174. const preMaterial = materials[materials.length - 1];
  175. if (materials.length > 0 && materials[materials.length - 1].status !== auditConst.status.checked) {
  176. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  177. }
  178. const order = materials.length + 1;
  179. const newMaterial = {
  180. tid: tenderId,
  181. order,
  182. period: data.period,
  183. in_time: new Date(),
  184. times: 1,
  185. status: auditConst.status.uncheck,
  186. user_id: this.ctx.session.sessionUser.accountId,
  187. stage_id: data.stage_id.join(','),
  188. s_order: data.s_order,
  189. material_tax: this.ctx.subProject.page_show.openMaterialTax,
  190. decimal: preMaterial && preMaterial.decimal ? preMaterial.decimal : JSON.stringify(materialConst.decimal),
  191. is_new: 1,
  192. is_stage_self: data.is_stage_self,
  193. qty_source: data.qty_source,
  194. is_new_qty: 1,
  195. rate: 9,
  196. calc_stage: data.stage_id.join(','),
  197. calc_tp: 1,
  198. };
  199. const transaction = await this.db.beginTransaction();
  200. try {
  201. if (preMaterial) {
  202. newMaterial.rate = preMaterial.rate;
  203. newMaterial.exponent_rate = preMaterial.exponent_rate;
  204. newMaterial.pre_tp = this.ctx.helper.add(preMaterial.m_tp, preMaterial.pre_tp);
  205. newMaterial.ex_pre_tp = this.ctx.helper.add(preMaterial.ex_tp, preMaterial.ex_pre_tp);
  206. 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;
  207. newMaterial.calc_stage = '';
  208. newMaterial.calc_tp = 0;
  209. }
  210. // 新增期记录
  211. const result = await transaction.insert(this.tableName, newMaterial);
  212. if (result.affectedRows === 1) {
  213. newMaterial.id = result.insertId;
  214. } else {
  215. throw '新增期数据失败';
  216. }
  217. const insertMaterialStage = [];
  218. if (data.is_stage_self) {
  219. // 新建多期单独单价表,工料表
  220. for (const [i, d] of data.stage_id.entries()) {
  221. insertMaterialStage.push({
  222. tid: tenderId,
  223. mid: newMaterial.id,
  224. sid: d,
  225. order: data.s_order.split(',')[i],
  226. });
  227. }
  228. if (insertMaterialStage.length > 0) {
  229. const resultStage = await transaction.insert(this.ctx.service.materialStage.tableName, insertMaterialStage);
  230. // 获取刚批量添加的所有list
  231. for (let j = 0; j < insertMaterialStage.length; j++) {
  232. insertMaterialStage[j].id = resultStage.insertId + j;
  233. }
  234. }
  235. }
  236. // 存在上一期时,复制上一期审批流程、不参与调差的清单、上期清单并算本期有效价差,本期应耗数量,并算本期总金额
  237. if (preMaterial) {
  238. const auditResult = await this.ctx.service.materialAudit.copyPreMaterialAuditors(transaction, preMaterial, newMaterial);
  239. if (!auditResult) {
  240. throw '复制上一期审批流程失败';
  241. }
  242. // 复制不参与调差或不计算数量变更清单
  243. const preNotJoinList = await this.ctx.service.materialListNotjoin.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  244. await this.ctx.service.materialListNotjoin.copyNewStageNotJoinList(transaction, preNotJoinList, newMaterial.id);
  245. // 复制单独计量调差清单
  246. const preSelfList = await this.ctx.service.materialListSelf.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  247. await this.ctx.service.materialListSelf.copyNewStageSelfList(transaction, preSelfList, newMaterial.id);
  248. // // 复制调差清单工料关联表
  249. // // await this.ctx.service.materialList.copyPreMaterialList(transaction, preMaterial, newMaterial);
  250. // await this.ctx.service.materialList.copyPreMaterialList2(transaction, data.material_list, data.material_self_list, preNotJoinList, newMaterial, insertMaterialStage);
  251. // // 新增或删除list_gcl表
  252. // await this.ctx.service.materialListGcl.insertOrDelGcl(transaction, data.insertGclList, data.removeGclList, newMaterial.id);
  253. // // 设置list_gcl表old=>new更新
  254. // await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id);
  255. // // 修改本期应耗数量值和有效价差,需要剔除不参与调差的清单数据,并返回总金额
  256. // let m_tp = null;
  257. // let m_tax_tp = null;
  258. // let rate_tp = null;
  259. // if (data.is_stage_self) {
  260. // [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);
  261. // } else {
  262. // [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);
  263. // }
  264. // 修改现行价格指数,并返回调差基数json
  265. const ex_calc = await this.ctx.service.materialExponent.updateNewMaterial(transaction, newMaterial.id, this.ctx, newMaterial.stage_id, preMaterial.ex_calc, JSON.parse(newMaterial.decimal));
  266. // // 计算得出本期总金额
  267. // // 找出当前人并更新tp_data
  268. // const tp_data = await this.ctx.service.materialAudit.getTpData(transaction, newMaterial.id, JSON.parse(newMaterial.decimal));
  269. const updateMaterialData = {
  270. id: newMaterial.id,
  271. // m_tp,
  272. // m_tax_tp,
  273. // rate_tp,
  274. ex_calc: JSON.stringify(ex_calc),
  275. // tp_data: JSON.stringify(tp_data),
  276. };
  277. await transaction.update(this.tableName, updateMaterialData);
  278. // // 删除material_list表冗余数据,减少表数据量
  279. // await transaction.delete(this.ctx.service.materialList.tableName, { tid: this.ctx.tender.id, gather_qty: null, is_self: 0 });
  280. }
  281. await transaction.commit();
  282. return newMaterial;
  283. } catch (err) {
  284. await transaction.rollback();
  285. throw err;
  286. }
  287. }
  288. /**
  289. * 编辑计量期
  290. *
  291. * @param {Number} mid - 第N期
  292. * @param {String} period - 开始-截止时间
  293. * @return {Promise<void>}
  294. */
  295. async saveMaterial(mid, period) {
  296. await this.db.update(this.tableName, {
  297. period,
  298. }, { where: { id: mid } });
  299. }
  300. /**
  301. * 删除材料调差期
  302. *
  303. * @param {Number} id - 期Id
  304. * @return {Promise<void>}
  305. */
  306. async deleteMaterial(id) {
  307. const transaction = await this.db.beginTransaction();
  308. try {
  309. // 删除文件
  310. const attList = await this.ctx.service.materialFile.getAllMaterialFiles(this.ctx.tender.id, id);
  311. await this.ctx.helper.delFiles(attList);
  312. await transaction.delete(this.ctx.service.materialAudit.tableName, { mid: id });
  313. await transaction.delete(this.ctx.service.materialBills.tableName, { mid: id });
  314. await transaction.delete(this.ctx.service.materialList.tableName, { mid: id });
  315. await transaction.delete(this.ctx.service.materialListGcl.tableName, { mid: id });
  316. await transaction.delete(this.ctx.service.materialListSelf.tableName, { mid: id });
  317. await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { mid: id });
  318. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { mid: id });
  319. await transaction.delete(this.ctx.service.materialFile.tableName, { mid: id });
  320. await transaction.delete(this.ctx.service.materialExponent.tableName, { mid: id });
  321. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, { mid: id });
  322. // 如果存在上一期,把上一期的quantity,expr,msg_tp,msg_times,msg_spread,m_up_risk,m_down_risk,m_spread,m_tp,pre_tp,orgin,is_summary添加到bill中
  323. const materialInfo = await this.getDataById(id);
  324. if (materialInfo.order > 1) {
  325. const sql = 'UPDATE ' + this.ctx.service.materialBills.tableName + ' as mb, ' +
  326. this.ctx.service.materialBillsHistory.tableName + ' as mbh ' +
  327. 'SET mb.`quantity` = mbh.`quantity`, mb.`expr` = mbh.`expr`, ' +
  328. 'mb.`msg_tp` = mbh.`msg_tp`, mb.`msg_times` = mbh.`msg_times`, ' +
  329. 'mb.`msg_spread` = mbh.`msg_spread`, mb.`m_up_risk` = mbh.`m_up_risk`, ' +
  330. 'mb.`m_down_risk` = mbh.`m_down_risk`, mb.`m_spread` = mbh.`m_spread`, ' +
  331. 'mb.`m_tp` = mbh.`m_tp`, mb.`pre_tp` = mbh.`pre_tp`, ' +
  332. 'mb.`m_tax_tp` = mbh.`m_tax_tp`, mb.`tax_pre_tp` = mbh.`tax_pre_tp`, ' +
  333. 'mb.`origin` = mbh.`origin`, mb.`is_summary` = mbh.`is_summary`, mb.`m_tax` = mbh.`m_tax` ' +
  334. 'WHERE mbh.`tid` = ? AND mbh.`order` = ? AND mbh.`mb_id` = mb.`id`';
  335. const sqlParam = [this.ctx.tender.id, materialInfo.order - 1];
  336. await transaction.query(sql, sqlParam);
  337. const sql2 = 'UPDATE ' + this.ctx.service.materialExponent.tableName + ' as me, ' +
  338. this.ctx.service.materialExponentHistory.tableName + ' as meh ' +
  339. 'SET me.`weight_num` = meh.`weight_num`, me.`basic_price` = meh.`basic_price`, ' +
  340. 'me.`basic_times` = meh.`basic_times`, me.`m_price` = meh.`m_price`, ' +
  341. 'me.`calc_num` = meh.`calc_num`, me.`is_summary` = meh.`is_summary` ' +
  342. 'WHERE meh.`tid` = ? AND meh.`order` = ? AND meh.`me_id` = me.`id`';
  343. const sqlParam2 = [this.ctx.tender.id, materialInfo.order - 1];
  344. await transaction.query(sql2, sqlParam2);
  345. }
  346. // 设置list_gcl表old => new更新
  347. await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id, 'old2new');
  348. // 还要从material_list表更新gcl的old数据,更新方法
  349. await this.ctx.service.materialListGcl.setOldFromLast(transaction, this.ctx.tender.id, materialInfo.order - 2);
  350. if (materialInfo.is_stage_self) {
  351. await transaction.delete(this.ctx.service.materialStage.tableName, { mid: id });
  352. await transaction.delete(this.ctx.service.materialStageBills.tableName, { mid: id });
  353. }
  354. await transaction.delete(this.tableName, { id });
  355. // 记录删除日志
  356. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.material, projectLogConst.status.delete, '第' + materialInfo.order + '期');
  357. await transaction.commit();
  358. return true;
  359. } catch (err) {
  360. await transaction.rollback();
  361. throw err;
  362. }
  363. }
  364. /**
  365. * 获取包含当前期之前的调差期id
  366. *
  367. * @param {Number} id - 期Id
  368. * @return {Promise<void>}
  369. */
  370. async getPreMidList(tid, order) {
  371. const midList = await this.getAllDataByCondition({
  372. where: { tid },
  373. columns: ['id'],
  374. limit: order,
  375. offset: 0,
  376. });
  377. const list = [];
  378. for (const ml of midList) {
  379. list.push(ml.id);
  380. }
  381. return list;
  382. }
  383. /**
  384. * 修改增税税率
  385. * @param {int} rate 税率
  386. * @return {Promise<*>}
  387. */
  388. async changeRate(rate) {
  389. const updateData = {
  390. id: this.ctx.material.id,
  391. rate,
  392. };
  393. return await this.db.update(this.tableName, updateData);
  394. }
  395. /**
  396. * 修改增税税率
  397. * @param {int} rate 税率
  398. * @return {Promise<*>}
  399. */
  400. async changeExponentRate(rate) {
  401. const updateData = {
  402. id: this.ctx.material.id,
  403. exponent_rate: rate,
  404. };
  405. return await this.db.update(this.tableName, updateData);
  406. }
  407. /**
  408. * 修改调差基数
  409. * @param {int} rate 税率
  410. * @return {Promise<*>}
  411. */
  412. async changeExCalc(ex_calc) {
  413. const transaction = await this.db.beginTransaction();
  414. try {
  415. const updateData = {
  416. id: this.ctx.material.id,
  417. ex_calc: JSON.stringify(ex_calc),
  418. };
  419. await transaction.update(this.tableName, updateData);
  420. const [ex_tp, ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction, ex_calc);
  421. await transaction.commit();
  422. return [ex_tp, ex_expr];
  423. } catch (err) {
  424. await transaction.rollback();
  425. throw err;
  426. }
  427. }
  428. /**
  429. * 取当前期截止上期含建筑税金额
  430. * @param {int} tid 标段id
  431. * @param {int} order 调差期数
  432. * @return {Promise<*>}
  433. */
  434. async getPreTpHs(tid, order, tp) {
  435. const sql = 'SELECT SUM(`rate_tp`) AS `pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  436. const sqlParam = [this.tableName, tid, 0, order];
  437. const result = await this.db.queryOne(sql, sqlParam);
  438. return result.pre_tp_hs;
  439. }
  440. /**
  441. * 取当前期截止上期含材料税金额
  442. * @param {int} tid 标段id
  443. * @param {int} order 调差期数
  444. * @return {Promise<*>}
  445. */
  446. async getTaxPreTpHs(tid, order) {
  447. const sql = 'SELECT SUM(`m_tax_tp`) AS `tax_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  448. const sqlParam = [this.tableName, tid, 1, order];
  449. const result = await this.db.queryOne(sql, sqlParam);
  450. return result.tax_pre_tp_hs;
  451. }
  452. /**
  453. * 取当前期截止上期含建筑税指数金额
  454. * @param {int} tid 标段id
  455. * @param {int} order 调差期数
  456. * @return {Promise<*>}
  457. */
  458. async getExPreTpHs(tid, order, tp) {
  459. const sql = 'SELECT SUM(ROUND(`ex_tp`*(1+ `exponent_rate`/100),' + tp + ')) AS `ex_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `order` < ?';
  460. const sqlParam = [this.tableName, tid, order];
  461. const result = await this.db.queryOne(sql, sqlParam);
  462. return result.ex_pre_tp_hs;
  463. }
  464. async updateMaterialTax(id, mtax) {
  465. const updateData = {
  466. id,
  467. material_tax: mtax,
  468. };
  469. return await this.db.update(this.tableName, updateData);
  470. }
  471. async getMaterialTaxTp(id) {
  472. const info = await this.getDataById(id);
  473. return info.m_tax_tp;
  474. }
  475. async getSumMaterial(tid) {
  476. const sql = 'Select sum(IFNULL(m_tp, 0) + IFNULL(ex_tp, 0)) as tp From ' + this.tableName + ' where tid = ?';
  477. const result = await this.db.queryOne(sql, [tid]);
  478. return result ? result.tp : 0;
  479. }
  480. async getOldMaterialTax(tid, order) {
  481. const sql = 'SELECT COUNT(id) as count FROM ?? WHERE `tid` = ? AND `order` <= ? AND `material_tax` = 1';
  482. const sqlParam = [this.tableName, tid, order];
  483. const result = await this.db.queryOne(sql, sqlParam);
  484. return result && result.count !== 0;
  485. }
  486. async saveDecimal(newUp, newTp, newQty) {
  487. const transaction = await this.db.beginTransaction();
  488. try {
  489. await this.ctx.service.materialBills.resetDecimal(transaction, newUp, newTp, newQty);
  490. this.ctx.material.decimal.up = newUp;
  491. this.ctx.material.decimal.tp = newTp;
  492. this.ctx.material.decimal.qty = newQty;
  493. const m_tp = await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  494. let update_calc = false;
  495. if (this.ctx.material.ex_calc) {
  496. const ex_calc = JSON.parse(this.ctx.material.ex_calc);
  497. const zdy = this._.find(ex_calc, { code: 'zdy' });
  498. zdy.value = this.ctx.helper.round(zdy.value, newTp);
  499. this.ctx.material.ex_calc = JSON.stringify(ex_calc);
  500. update_calc = true;
  501. }
  502. const [ex_tp, ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction);
  503. const updateData = {
  504. id: this.ctx.material.id,
  505. decimal: JSON.stringify(this.ctx.material.decimal),
  506. };
  507. if (update_calc) updateData.ex_calc = this.ctx.material.ex_calc;
  508. await transaction.update(this.tableName, updateData);
  509. await transaction.commit();
  510. return true;
  511. } catch (err) {
  512. console.log(err);
  513. await transaction.rollback();
  514. return false;
  515. }
  516. }
  517. async saveQtySource(newQtySource) {
  518. const transaction = await this.db.beginTransaction();
  519. try {
  520. await this.ctx.service.materialBills.resetQuantityByQtySource(transaction, newQtySource);
  521. this.ctx.material.qty_source = newQtySource;
  522. const m_tp = await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  523. const updateData = {
  524. id: this.ctx.material.id,
  525. qty_source: newQtySource,
  526. };
  527. await transaction.update(this.tableName, updateData);
  528. await transaction.commit();
  529. return true;
  530. } catch (err) {
  531. console.log(err);
  532. await transaction.rollback();
  533. return false;
  534. }
  535. }
  536. async getListByArchives(tid, ids) {
  537. if (ids.length === 0) return [];
  538. const sql = 'SELECT c.* FROM ?? as c LEFT JOIN (SELECT mid, MAX(end_time) as end_time FROM ?? WHERE ' +
  539. 'tid = ? AND mid in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') GROUP BY mid) as ca ON c.id = ca.mid WHERE' +
  540. ' c.tid = ? AND c.id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') AND c.status = ? ORDER BY ca.end_time DESC';
  541. const params = [this.tableName, this.ctx.service.materialAudit.tableName, tid, tid, auditConst.status.checked];
  542. const list = await this.db.query(sql, params);
  543. return list;
  544. }
  545. }
  546. return Material;
  547. };