material.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. };
  197. const transaction = await this.db.beginTransaction();
  198. try {
  199. if (preMaterial) {
  200. newMaterial.rate = preMaterial.rate;
  201. newMaterial.exponent_rate = preMaterial.exponent_rate;
  202. newMaterial.pre_tp = this.ctx.helper.add(preMaterial.m_tp, preMaterial.pre_tp);
  203. newMaterial.ex_pre_tp = this.ctx.helper.add(preMaterial.ex_tp, preMaterial.ex_pre_tp);
  204. 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;
  205. }
  206. // 新增期记录
  207. const result = await transaction.insert(this.tableName, newMaterial);
  208. if (result.affectedRows === 1) {
  209. newMaterial.id = result.insertId;
  210. } else {
  211. throw '新增期数据失败';
  212. }
  213. const insertMaterialStage = [];
  214. if (data.is_stage_self) {
  215. // 新建多期单独单价表,工料表
  216. for (const [i, d] of data.stage_id.entries()) {
  217. insertMaterialStage.push({
  218. tid: tenderId,
  219. mid: newMaterial.id,
  220. sid: d,
  221. order: data.s_order.split(',')[i],
  222. });
  223. }
  224. if (insertMaterialStage.length > 0) {
  225. const resultStage = await transaction.insert(this.ctx.service.materialStage.tableName, insertMaterialStage);
  226. // 获取刚批量添加的所有list
  227. for (let j = 0; j < insertMaterialStage.length; j++) {
  228. insertMaterialStage[j].id = resultStage.insertId + j;
  229. }
  230. }
  231. }
  232. // 存在上一期时,复制上一期审批流程、不参与调差的清单、上期清单并算本期有效价差,本期应耗数量,并算本期总金额
  233. if (preMaterial) {
  234. const auditResult = await this.ctx.service.materialAudit.copyPreMaterialAuditors(transaction, preMaterial, newMaterial);
  235. if (!auditResult) {
  236. throw '复制上一期审批流程失败';
  237. }
  238. // 复制不参与调差或不计算数量变更清单
  239. const preNotJoinList = await this.ctx.service.materialListNotjoin.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  240. await this.ctx.service.materialListNotjoin.copyNewStageNotJoinList(transaction, preNotJoinList, newMaterial.id);
  241. // 复制单独计量调差清单
  242. const preSelfList = await this.ctx.service.materialListSelf.getAllDataByCondition({ where: { tid: this.ctx.tender.id, mid: preMaterial.id } });
  243. await this.ctx.service.materialListSelf.copyNewStageSelfList(transaction, preSelfList, newMaterial.id);
  244. // 复制调差清单工料关联表
  245. // await this.ctx.service.materialList.copyPreMaterialList(transaction, preMaterial, newMaterial);
  246. await this.ctx.service.materialList.copyPreMaterialList2(transaction, data.material_list, data.material_self_list, preNotJoinList, newMaterial, insertMaterialStage);
  247. // 新增或删除list_gcl表
  248. await this.ctx.service.materialListGcl.insertOrDelGcl(transaction, data.insertGclList, data.removeGclList, newMaterial.id);
  249. // 设置list_gcl表old=>new更新
  250. await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id);
  251. // 修改本期应耗数量值和有效价差,需要剔除不参与调差的清单数据,并返回总金额
  252. let m_tp = null;
  253. let m_tax_tp = null;
  254. let rate_tp = null;
  255. if (data.is_stage_self) {
  256. [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);
  257. } else {
  258. [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);
  259. }
  260. // 修改现行价格指数,并返回调差基数json
  261. const ex_calc = await this.ctx.service.materialExponent.updateNewMaterial(transaction, newMaterial.id, this.ctx, newMaterial.stage_id, preMaterial.ex_calc, JSON.parse(newMaterial.decimal));
  262. // 计算得出本期总金额
  263. // 找出当前人并更新tp_data
  264. const tp_data = await this.ctx.service.materialAudit.getTpData(transaction, newMaterial.id, JSON.parse(newMaterial.decimal));
  265. const updateMaterialData = {
  266. id: newMaterial.id,
  267. m_tp,
  268. m_tax_tp,
  269. rate_tp,
  270. ex_calc: JSON.stringify(ex_calc),
  271. tp_data: JSON.stringify(tp_data),
  272. };
  273. await transaction.update(this.tableName, updateMaterialData);
  274. // 删除material_list表冗余数据,减少表数据量
  275. await transaction.delete(this.ctx.service.materialList.tableName, { tid: this.ctx.tender.id, gather_qty: null, is_self: 0 });
  276. }
  277. await transaction.commit();
  278. return newMaterial;
  279. } catch (err) {
  280. await transaction.rollback();
  281. throw err;
  282. }
  283. }
  284. /**
  285. * 编辑计量期
  286. *
  287. * @param {Number} mid - 第N期
  288. * @param {String} period - 开始-截止时间
  289. * @return {Promise<void>}
  290. */
  291. async saveMaterial(mid, period) {
  292. await this.db.update(this.tableName, {
  293. period,
  294. }, { where: { id: mid } });
  295. }
  296. /**
  297. * 删除材料调差期
  298. *
  299. * @param {Number} id - 期Id
  300. * @return {Promise<void>}
  301. */
  302. async deleteMaterial(id) {
  303. const transaction = await this.db.beginTransaction();
  304. try {
  305. // 删除文件
  306. const attList = await this.ctx.service.materialFile.getAllMaterialFiles(this.ctx.tender.id, id);
  307. await this.ctx.helper.delFiles(attList);
  308. await transaction.delete(this.ctx.service.materialAudit.tableName, { mid: id });
  309. await transaction.delete(this.ctx.service.materialBills.tableName, { mid: id });
  310. await transaction.delete(this.ctx.service.materialList.tableName, { mid: id });
  311. await transaction.delete(this.ctx.service.materialListGcl.tableName, { mid: id });
  312. await transaction.delete(this.ctx.service.materialListSelf.tableName, { mid: id });
  313. await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { mid: id });
  314. await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { mid: id });
  315. await transaction.delete(this.ctx.service.materialFile.tableName, { mid: id });
  316. await transaction.delete(this.ctx.service.materialExponent.tableName, { mid: id });
  317. await transaction.delete(this.ctx.service.materialExponentHistory.tableName, { mid: id });
  318. // 如果存在上一期,把上一期的quantity,expr,msg_tp,msg_times,msg_spread,m_up_risk,m_down_risk,m_spread,m_tp,pre_tp,orgin,is_summary添加到bill中
  319. const materialInfo = await this.getDataById(id);
  320. if (materialInfo.order > 1) {
  321. const sql = 'UPDATE ' + this.ctx.service.materialBills.tableName + ' as mb, ' +
  322. this.ctx.service.materialBillsHistory.tableName + ' as mbh ' +
  323. 'SET mb.`quantity` = mbh.`quantity`, mb.`expr` = mbh.`expr`, ' +
  324. 'mb.`msg_tp` = mbh.`msg_tp`, mb.`msg_times` = mbh.`msg_times`, ' +
  325. 'mb.`msg_spread` = mbh.`msg_spread`, mb.`m_up_risk` = mbh.`m_up_risk`, ' +
  326. 'mb.`m_down_risk` = mbh.`m_down_risk`, mb.`m_spread` = mbh.`m_spread`, ' +
  327. 'mb.`m_tp` = mbh.`m_tp`, mb.`pre_tp` = mbh.`pre_tp`, ' +
  328. 'mb.`m_tax_tp` = mbh.`m_tax_tp`, mb.`tax_pre_tp` = mbh.`tax_pre_tp`, ' +
  329. 'mb.`origin` = mbh.`origin`, mb.`is_summary` = mbh.`is_summary`, mb.`m_tax` = mbh.`m_tax` ' +
  330. 'WHERE mbh.`tid` = ? AND mbh.`order` = ? AND mbh.`mb_id` = mb.`id`';
  331. const sqlParam = [this.ctx.tender.id, materialInfo.order - 1];
  332. await transaction.query(sql, sqlParam);
  333. const sql2 = 'UPDATE ' + this.ctx.service.materialExponent.tableName + ' as me, ' +
  334. this.ctx.service.materialExponentHistory.tableName + ' as meh ' +
  335. 'SET me.`weight_num` = meh.`weight_num`, me.`basic_price` = meh.`basic_price`, ' +
  336. 'me.`basic_times` = meh.`basic_times`, me.`m_price` = meh.`m_price`, ' +
  337. 'me.`calc_num` = meh.`calc_num`, me.`is_summary` = meh.`is_summary` ' +
  338. 'WHERE meh.`tid` = ? AND meh.`order` = ? AND meh.`me_id` = me.`id`';
  339. const sqlParam2 = [this.ctx.tender.id, materialInfo.order - 1];
  340. await transaction.query(sql2, sqlParam2);
  341. }
  342. // 设置list_gcl表old => new更新
  343. await this.ctx.service.materialListGcl.setNewOldData(transaction, this.ctx.tender.id, 'old2new');
  344. // 还要从material_list表更新gcl的old数据,更新方法
  345. await this.ctx.service.materialListGcl.setOldFromLast(transaction, this.ctx.tender.id, materialInfo.order - 2);
  346. if (materialInfo.is_stage_self) {
  347. await transaction.delete(this.ctx.service.materialStage.tableName, { mid: id });
  348. await transaction.delete(this.ctx.service.materialStageBills.tableName, { mid: id });
  349. }
  350. await transaction.delete(this.tableName, { id });
  351. // 记录删除日志
  352. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.material, projectLogConst.status.delete, '第' + materialInfo.order + '期');
  353. await transaction.commit();
  354. return true;
  355. } catch (err) {
  356. await transaction.rollback();
  357. throw err;
  358. }
  359. }
  360. /**
  361. * 获取包含当前期之前的调差期id
  362. *
  363. * @param {Number} id - 期Id
  364. * @return {Promise<void>}
  365. */
  366. async getPreMidList(tid, order) {
  367. const midList = await this.getAllDataByCondition({
  368. where: { tid },
  369. columns: ['id'],
  370. limit: order,
  371. offset: 0,
  372. });
  373. const list = [];
  374. for (const ml of midList) {
  375. list.push(ml.id);
  376. }
  377. return list;
  378. }
  379. /**
  380. * 修改增税税率
  381. * @param {int} rate 税率
  382. * @return {Promise<*>}
  383. */
  384. async changeRate(rate) {
  385. const updateData = {
  386. id: this.ctx.material.id,
  387. rate,
  388. };
  389. return await this.db.update(this.tableName, updateData);
  390. }
  391. /**
  392. * 修改增税税率
  393. * @param {int} rate 税率
  394. * @return {Promise<*>}
  395. */
  396. async changeExponentRate(rate) {
  397. const updateData = {
  398. id: this.ctx.material.id,
  399. exponent_rate: rate,
  400. };
  401. return await this.db.update(this.tableName, updateData);
  402. }
  403. /**
  404. * 修改调差基数
  405. * @param {int} rate 税率
  406. * @return {Promise<*>}
  407. */
  408. async changeExCalc(ex_calc) {
  409. const transaction = await this.db.beginTransaction();
  410. try {
  411. const updateData = {
  412. id: this.ctx.material.id,
  413. ex_calc: JSON.stringify(ex_calc),
  414. };
  415. await transaction.update(this.tableName, updateData);
  416. const [ex_tp, ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction, ex_calc);
  417. await transaction.commit();
  418. return [ex_tp, ex_expr];
  419. } catch (err) {
  420. await transaction.rollback();
  421. throw err;
  422. }
  423. }
  424. /**
  425. * 取当前期截止上期含建筑税金额
  426. * @param {int} tid 标段id
  427. * @param {int} order 调差期数
  428. * @return {Promise<*>}
  429. */
  430. async getPreTpHs(tid, order, tp) {
  431. const sql = 'SELECT SUM(`rate_tp`) AS `pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  432. const sqlParam = [this.tableName, tid, 0, order];
  433. const result = await this.db.queryOne(sql, sqlParam);
  434. return result.pre_tp_hs;
  435. }
  436. /**
  437. * 取当前期截止上期含材料税金额
  438. * @param {int} tid 标段id
  439. * @param {int} order 调差期数
  440. * @return {Promise<*>}
  441. */
  442. async getTaxPreTpHs(tid, order) {
  443. const sql = 'SELECT SUM(`m_tax_tp`) AS `tax_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `material_tax` = ? AND `order` < ?';
  444. const sqlParam = [this.tableName, tid, 1, order];
  445. const result = await this.db.queryOne(sql, sqlParam);
  446. return result.tax_pre_tp_hs;
  447. }
  448. /**
  449. * 取当前期截止上期含建筑税指数金额
  450. * @param {int} tid 标段id
  451. * @param {int} order 调差期数
  452. * @return {Promise<*>}
  453. */
  454. async getExPreTpHs(tid, order, tp) {
  455. const sql = 'SELECT SUM(ROUND(`ex_tp`*(1+ `exponent_rate`/100),' + tp + ')) AS `ex_pre_tp_hs` FROM ?? WHERE `tid` = ? AND `order` < ?';
  456. const sqlParam = [this.tableName, tid, order];
  457. const result = await this.db.queryOne(sql, sqlParam);
  458. return result.ex_pre_tp_hs;
  459. }
  460. async updateMaterialTax(id, mtax) {
  461. const updateData = {
  462. id,
  463. material_tax: mtax,
  464. };
  465. return await this.db.update(this.tableName, updateData);
  466. }
  467. async getMaterialTaxTp(id) {
  468. const info = await this.getDataById(id);
  469. return info.m_tax_tp;
  470. }
  471. async getSumMaterial(tid) {
  472. const sql = 'Select sum(IFNULL(m_tp, 0) + IFNULL(ex_tp, 0)) as tp From ' + this.tableName + ' where tid = ?';
  473. const result = await this.db.queryOne(sql, [tid]);
  474. return result ? result.tp : 0;
  475. }
  476. async getOldMaterialTax(tid, order) {
  477. const sql = 'SELECT COUNT(id) as count FROM ?? WHERE `tid` = ? AND `order` <= ? AND `material_tax` = 1';
  478. const sqlParam = [this.tableName, tid, order];
  479. const result = await this.db.queryOne(sql, sqlParam);
  480. return result && result.count !== 0;
  481. }
  482. async saveDecimal(newUp, newTp, newQty) {
  483. const transaction = await this.db.beginTransaction();
  484. try {
  485. await this.ctx.service.materialBills.resetDecimal(transaction, newUp, newTp, newQty);
  486. this.ctx.material.decimal.up = newUp;
  487. this.ctx.material.decimal.tp = newTp;
  488. this.ctx.material.decimal.qty = newQty;
  489. const m_tp = await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  490. let update_calc = false;
  491. if (this.ctx.material.ex_calc) {
  492. const ex_calc = JSON.parse(this.ctx.material.ex_calc);
  493. const zdy = this._.find(ex_calc, { code: 'zdy' });
  494. zdy.value = this.ctx.helper.round(zdy.value, newTp);
  495. this.ctx.material.ex_calc = JSON.stringify(ex_calc);
  496. update_calc = true;
  497. }
  498. const [ex_tp, ex_expr] = await this.ctx.service.materialExponent.calcMaterialExTp(transaction);
  499. const updateData = {
  500. id: this.ctx.material.id,
  501. decimal: JSON.stringify(this.ctx.material.decimal),
  502. };
  503. if (update_calc) updateData.ex_calc = this.ctx.material.ex_calc;
  504. await transaction.update(this.tableName, updateData);
  505. await transaction.commit();
  506. return true;
  507. } catch (err) {
  508. console.log(err);
  509. await transaction.rollback();
  510. return false;
  511. }
  512. }
  513. async saveQtySource(newQtySource) {
  514. const transaction = await this.db.beginTransaction();
  515. try {
  516. await this.ctx.service.materialBills.resetQuantityByQtySource(transaction, newQtySource);
  517. this.ctx.material.qty_source = newQtySource;
  518. const m_tp = await this.ctx.service.materialBills.calcMaterialMTp(transaction);
  519. const updateData = {
  520. id: this.ctx.material.id,
  521. qty_source: newQtySource,
  522. };
  523. await transaction.update(this.tableName, updateData);
  524. await transaction.commit();
  525. return true;
  526. } catch (err) {
  527. console.log(err);
  528. await transaction.rollback();
  529. return false;
  530. }
  531. }
  532. async getListByArchives(tid, ids) {
  533. if (ids.length === 0) return [];
  534. const sql = 'SELECT c.* FROM ?? as c LEFT JOIN (SELECT mid, MAX(end_time) as end_time FROM ?? WHERE ' +
  535. 'tid = ? AND mid in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') GROUP BY mid) as ca ON c.id = ca.mid WHERE' +
  536. ' c.tid = ? AND c.id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ') AND c.status = ? ORDER BY ca.end_time DESC';
  537. const params = [this.tableName, this.ctx.service.materialAudit.tableName, tid, tid, auditConst.status.checked];
  538. const list = await this.db.query(sql, params);
  539. return list;
  540. }
  541. }
  542. return Material;
  543. };