material.js 29 KB

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