material_bills.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 materialConst = require('../const/material');
  11. const MaterialCalculator = require('../lib/material_calc');
  12. module.exports = app => {
  13. class MaterialBills extends app.BaseService {
  14. /**
  15. * 构造函数
  16. *
  17. * @param {Object} ctx - egg全局变量
  18. * @return {void}
  19. */
  20. constructor(ctx) {
  21. super(ctx);
  22. this.tableName = 'material_bills';
  23. }
  24. /**
  25. * 添加工料
  26. * @return {void}
  27. */
  28. async add() {
  29. if (!this.ctx.tender || !this.ctx.material) {
  30. throw '数据错误';
  31. }
  32. const order = await this._getMaxOrder(this.ctx.tender.id);
  33. const transaction = await this.db.beginTransaction();
  34. try {
  35. const resultData = {};
  36. const newBills = {
  37. tid: this.ctx.tender.id,
  38. mid: this.ctx.material.id,
  39. order: order + 1,
  40. in_time: new Date(),
  41. };
  42. // 新增工料
  43. const result = await transaction.insert(this.tableName, newBills);
  44. if (result.affectedRows !== 1) {
  45. throw '新增工料数据失败';
  46. }
  47. if (this.ctx.material.is_stage_self) {
  48. await this.ctx.service.materialStageBills.add(transaction, result.insertId);
  49. resultData.pushStageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id, mb_id: result.insertId } });
  50. }
  51. const insertArray = [];
  52. const material_month = this.ctx.material.months ? this.ctx.material.months.split(',') : [];
  53. for (const ym of material_month) {
  54. const one_month = {
  55. tid: this.ctx.tender.id,
  56. mid: this.ctx.material.id,
  57. mb_id: result.insertId,
  58. msg_tp: null,
  59. yearmonth: ym,
  60. };
  61. insertArray.push(one_month);
  62. }
  63. if (insertArray.length !== 0) await transaction.insert(this.ctx.service.materialMonth.tableName, insertArray);
  64. await transaction.commit();
  65. resultData.info = await this.getDataById(result.insertId);
  66. return resultData;
  67. } catch (error) {
  68. console.log(error);
  69. await transaction.rollback();
  70. throw error;
  71. }
  72. }
  73. /**
  74. * 添加工料
  75. * @return {void}
  76. */
  77. async addByGlj(data, order = null) {
  78. if (!this.ctx.tender || !this.ctx.material) {
  79. throw '数据错误';
  80. }
  81. const newOrder = order ? parseInt(order) + 1 : await this._getMaxOrder(this.ctx.tender.id);
  82. const transaction = await this.db.beginTransaction();
  83. try {
  84. // order以下的工料+1
  85. await this._syncOrder(transaction, this.ctx.tender.id, newOrder, '+');
  86. const resultData = {};
  87. const newBills = {
  88. tid: this.ctx.tender.id,
  89. mid: this.ctx.material.id,
  90. code: data.code,
  91. name: data.name,
  92. unit: data.unit,
  93. m_up_risk: data.rise_range,
  94. m_down_risk: data.fall_range,
  95. spec: data.spec,
  96. m_type: data.type,
  97. remark: data.memo,
  98. order: newOrder,
  99. in_time: new Date(),
  100. };
  101. // 新增工料
  102. const result = await transaction.insert(this.tableName, newBills);
  103. if (result.affectedRows !== 1) {
  104. throw '新增工料数据失败';
  105. }
  106. if (this.ctx.material.is_stage_self) {
  107. await this.ctx.service.materialStageBills.add(transaction, result.insertId, data.memo);
  108. resultData.pushStageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id, mb_id: result.insertId } });
  109. }
  110. const insertArray = [];
  111. const material_month = this.ctx.material.months ? this.ctx.material.months.split(',') : [];
  112. for (const ym of material_month) {
  113. const one_month = {
  114. tid: this.ctx.tender.id,
  115. mid: this.ctx.material.id,
  116. mb_id: result.insertId,
  117. msg_tp: null,
  118. yearmonth: ym,
  119. };
  120. insertArray.push(one_month);
  121. }
  122. if (insertArray.length !== 0) await transaction.insert(this.ctx.service.materialMonth.tableName, insertArray);
  123. await transaction.commit();
  124. resultData.info = await this.getDataById(result.insertId);
  125. return resultData;
  126. } catch (error) {
  127. console.log(error);
  128. await transaction.rollback();
  129. throw error;
  130. }
  131. }
  132. /**
  133. * 移除清单时,同步其后清单order
  134. * @param transaction - 事务
  135. * @param {Number} cid - 变更cid
  136. * @param {Number} order - order之后的
  137. * @return {Promise<*>}
  138. * @private
  139. */
  140. async _syncOrder(transaction, tid, order, selfOperate = '-', num = 1) {
  141. this.initSqlBuilder();
  142. this.sqlBuilder.setAndWhere('tid', {
  143. value: this.db.escape(tid),
  144. operate: '=',
  145. });
  146. this.sqlBuilder.setAndWhere('order', {
  147. value: order,
  148. operate: '>=',
  149. });
  150. this.sqlBuilder.setUpdateData('order', {
  151. value: num,
  152. selfOperate,
  153. });
  154. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  155. const data = await transaction.query(sql, sqlParam);
  156. return data;
  157. }
  158. async _getMaxOrder(tenderId) {
  159. const sql = 'SELECT Max(??) As value FROM ?? Where tid = ' + tenderId;
  160. const sqlParam = ['order', this.tableName];
  161. const queryResult = await this.db.queryOne(sql, sqlParam);
  162. return queryResult.value ? queryResult.value : 0;
  163. }
  164. /**
  165. * 删除工料
  166. * @param {int} id 工料id
  167. * @return {void}
  168. */
  169. async del(id) {
  170. if (!this.ctx.tender || !this.ctx.material) {
  171. throw '数据错误';
  172. }
  173. // 判断t_type是否为费用,且存在quantity,m_spread值
  174. const transaction = await this.db.beginTransaction();
  175. try {
  176. // 防止多页面操作时,清单工料含量存在时工料可删
  177. const materialListNum = await this.ctx.service.materialList.count({ tid: this.ctx.tender.id, mb_id: id });
  178. if (materialListNum > 0) {
  179. throw '该工料已存在对应的清单工料含量,删除失败';
  180. }
  181. const mbInfo = await this.getDataById(id);
  182. await transaction.delete(this.tableName, { id });
  183. const m_tp = this.ctx.material.m_tp;
  184. const result = { m_tp };
  185. if (this.ctx.material.is_stage_self) {
  186. await transaction.delete(this.ctx.service.materialStageBills.tableName, { mb_id: id });
  187. // 金额发生变化,则重新计算本期金额
  188. for (const sid of this.ctx.material.stage_id.split(',')) {
  189. const msInfo = await transaction.get(this.ctx.service.materialStage.tableName, { tid: this.ctx.tender.id, sid });
  190. await this.ctx.service.materialStage.updateMtp(transaction, msInfo.id);
  191. }
  192. result.stageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id } });
  193. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  194. result.m_tp = await this.calcMaterialMTp(transaction);
  195. } else if (mbInfo.t_type === materialConst.t_type[1].value && mbInfo.quantity !== null && mbInfo.m_spread !== null) {
  196. // 金额发生变化,则重新计算本期金额
  197. result.m_tp = await this.calcMaterialMTp(transaction);
  198. }
  199. const material_month = this.ctx.material.months ? this.ctx.material.months.split(',') : [];
  200. if (material_month.length > 0) {
  201. await transaction.delete(this.ctx.service.materialMonth.tableName, { mb_id: id });
  202. }
  203. // order以下的清单-1
  204. await this._syncOrder(transaction, this.ctx.tender.id, mbInfo.order, '-');
  205. await transaction.commit();
  206. return result;
  207. } catch (err) {
  208. await transaction.rollback();
  209. throw err;
  210. }
  211. }
  212. /**
  213. * 交换两个工料的顺序
  214. * @param {Number} id1 - 工料1的id
  215. * @param {Number} id2 - 工料2的id
  216. * @returns {Promise<void>}
  217. */
  218. async changeOrder(datas) {
  219. if (!this.ctx.tender || !this.ctx.material) {
  220. throw '数据错误';
  221. }
  222. // const bill1 = await this.getDataByCondition({ tid: this.ctx.tender.id, id: id1 });
  223. // const bill2 = await this.getDataByCondition({ tid: this.ctx.tender.id, id: id2 });
  224. // if (!bill1 || !bill2) {
  225. // throw '数据错误';
  226. // }
  227. const transaction = await this.db.beginTransaction();
  228. try {
  229. // const order = bill1.order;
  230. // bill1.order = bill2.order;
  231. // bill2.order = order;
  232. // await transaction.update(this.tableName, { id: bill1.id, order: bill1.order });
  233. // await transaction.update(this.tableName, { id: bill2.id, order: bill2.order });
  234. await transaction.updateRows(this.tableName, datas);
  235. await transaction.commit();
  236. return true;
  237. } catch (err) {
  238. await transaction.rollback();
  239. throw err;
  240. }
  241. }
  242. /**
  243. * 修改工料信息
  244. * @param {Object} data 工料内容
  245. * @return {void}
  246. */
  247. async save(data, ms_id = null) {
  248. if (!this.ctx.tender || !this.ctx.material) {
  249. throw '数据错误';
  250. }
  251. delete data.in_time;
  252. // delete data.m_tp;
  253. // 判断是否可修改
  254. // 判断t_type是否为费用
  255. const transaction = await this.db.beginTransaction();
  256. try {
  257. const result = {};
  258. if (this.ctx.material.is_stage_self) {
  259. if (!ms_id) {
  260. throw '期参数有误';
  261. }
  262. const needUp = await this.updateOneBillsData(transaction, data, ms_id);
  263. const [one_m_tp, one_tax_tp] = await this.ctx.service.materialStageBills.update(transaction, data, ms_id);
  264. // 更新materialStage 值
  265. data.m_tp = this.ctx.helper.round(one_m_tp, this.ctx.material.decimal.tp);
  266. data.m_tax_tp = this.ctx.helper.round(one_tax_tp, this.ctx.material.decimal.tp);
  267. data.quantity = null;
  268. data.msg_tp = null;
  269. data.msg_times = null;
  270. data.msg_spread = null;
  271. data.m_spread = null;
  272. delete data.ms_id;
  273. // 更新materialStage 值
  274. await this.ctx.service.materialStage.updateMtp(transaction, ms_id);
  275. result.stageBillsData = this.ctx.material.is_stage_self && needUp ?
  276. await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id, mb_id: data.id } }) :
  277. await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id, ms_id, mb_id: data.id } });
  278. result.stageData = this.ctx.material.is_stage_self && needUp ?
  279. await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } }) :
  280. await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id, id: ms_id } });
  281. }
  282. await transaction.update(this.tableName, data);
  283. result.m_tp = await this.calcMaterialMTp(transaction);
  284. await transaction.commit();
  285. return result;
  286. } catch (err) {
  287. await transaction.rollback();
  288. throw err;
  289. }
  290. }
  291. async updateOneBillsData(transaction, data, ms_id) {
  292. // 当以下值和bills值不相同时,需要同步更新最新的计算值到stageBills表里
  293. const updateColsArray = ['t_type', 'm_tax', 'basic_price', 'm_up_risk', 'm_down_risk', 'is_summary'];
  294. let needUp = null;
  295. const mbInfo = await this.getDataById(data.id);
  296. for (const uc of updateColsArray) {
  297. if (data[uc] !== undefined && data[uc] !== mbInfo[uc]) {
  298. needUp = uc;
  299. break;
  300. }
  301. }
  302. if (needUp) {
  303. const msList = await this.ctx.service.materialStage.getAllDataByCondition({ where: { mid: this.ctx.material.id } });
  304. for (const ms of msList) {
  305. if (ms.id !== parseInt(ms_id)) {
  306. const msbInfo = await this.ctx.service.materialStageBills.getDataByCondition({
  307. mid: this.ctx.material.id,
  308. ms_id: ms.id,
  309. mb_id: data.id,
  310. });
  311. const updateData = {
  312. id: msbInfo.id,
  313. };
  314. if (needUp === 'm_tax') {
  315. updateData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(msbInfo.m_tp, (1 + this.ctx.helper.div(data.m_tax, 100))), this.ctx.material.decimal.tp);
  316. } else if (needUp === 'm_up_risk' || needUp === 'm_down_risk' || needUp === 'basic_price') {
  317. const basic_price = needUp === 'basic_price' ? data.basic_price : mbInfo.basic_price;
  318. const [msg_spread, m_spread] = await this.getSpread(mbInfo, msbInfo.msg_tp, this.ctx.material.decimal.up, basic_price);
  319. updateData.msg_spread = msg_spread;
  320. updateData.m_spread = m_spread;
  321. const newTp = this.ctx.helper.round(this.ctx.helper.mul(msbInfo.quantity, m_spread), this.ctx.material.decimal.tp);
  322. updateData.m_tp = newTp;
  323. updateData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mbInfo.m_tax, 100))), this.ctx.material.decimal.tp);
  324. } else if (needUp === 't_type') {
  325. updateData.quantity = null;
  326. updateData.m_tp = null;
  327. updateData.m_tax_tp = null;
  328. } else if (needUp === 'is_summary') {
  329. updateData.is_summary = data.is_summary;
  330. }
  331. await transaction.update(this.ctx.service.materialStageBills.tableName, updateData);
  332. await this.ctx.service.materialStage.updateMtp(transaction, ms.id);
  333. }
  334. }
  335. }
  336. return needUp;
  337. }
  338. async saveOrigin(data) {
  339. if (!this.ctx.tender || !this.ctx.material) {
  340. throw '数据错误';
  341. }
  342. return await this.db.update(this.tableName, { id: data.mb_id, origin: data.value });
  343. }
  344. async saveOrigins(datas) {
  345. if (!this.ctx.tender || !this.ctx.material) {
  346. throw '数据错误';
  347. }
  348. const updateData = [];
  349. for (const data of datas) {
  350. updateData.push({
  351. id: data.mb_id,
  352. origin: data.origin,
  353. });
  354. }
  355. if (updateData.length > 0) await this.db.updateRows(this.tableName, updateData);
  356. return true;
  357. }
  358. /**
  359. * 修改工料信息
  360. * @param {Object} data 工料内容
  361. * @return {void}
  362. */
  363. async saveDatas(datas, ms_id = null) {
  364. if (!this.ctx.tender || !this.ctx.material) {
  365. throw '数据错误';
  366. }
  367. // 判断是否可修改
  368. // 判断t_type是否为费用
  369. const transaction = await this.db.beginTransaction();
  370. try {
  371. for (const data of datas) {
  372. delete data.in_time;
  373. let needUp = null;
  374. if (this.ctx.material.is_stage_self) {
  375. needUp = await this.updateOneBillsData(transaction, data, ms_id);
  376. const [one_m_tp, one_tax_tp] = await this.ctx.service.materialStageBills.update(transaction, data, ms_id);
  377. // 更新materialStage 值
  378. data.m_tp = this.ctx.helper.round(one_m_tp, this.ctx.material.decimal.tp);
  379. data.m_tax_tp = this.ctx.helper.round(one_tax_tp, this.ctx.material.decimal.tp);
  380. data.quantity = null;
  381. data.msg_tp = null;
  382. data.msg_times = null;
  383. data.msg_spread = null;
  384. data.msg_spread = null;
  385. data.m_spread = null;
  386. }
  387. // delete data.m_tp;
  388. // console.log(data);
  389. await transaction.update(this.tableName, data);
  390. }
  391. // 更新materialStage 值
  392. const result = {};
  393. if (this.ctx.material.is_stage_self) {
  394. await this.ctx.service.materialStage.updateMtp(transaction, ms_id);
  395. result.stageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id } });
  396. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  397. }
  398. result.m_tp = await this.calcMaterialMTp(transaction);
  399. await transaction.commit();
  400. return result;
  401. } catch (err) {
  402. await transaction.rollback();
  403. throw err;
  404. }
  405. }
  406. /**
  407. * 更新新一期的quantity和截止上期金额并返回本期总金额
  408. * @param transaction
  409. * @param tid
  410. * @param mid
  411. * @returns {Promise<number>}
  412. */
  413. async updateNewMaterial(transaction, tid, mid, ctx, stage_id, decimal) {
  414. const materialBillsData = await this.getAllDataByCondition({ where: { tid } });
  415. let m_tp = 0;
  416. let m_tax_tp = 0;
  417. const materialCalculator = new MaterialCalculator(ctx, stage_id, ctx.tender.info);
  418. for (const mb of materialBillsData) {
  419. const [one_tp, one_tax_tp] = await this.calcQuantityByMB(transaction, mid, mb, materialCalculator, decimal);
  420. m_tp = this.ctx.helper.add(m_tp, one_tp);
  421. m_tax_tp = this.ctx.helper.add(m_tax_tp, one_tax_tp);
  422. }
  423. return [m_tp, m_tax_tp];
  424. }
  425. /**
  426. * 修改quantity,m_spread值和返回单条调差金额(新增一期)
  427. * @param transaction
  428. * @param mid
  429. * @param mb
  430. * @returns {Promise<*>}
  431. */
  432. async calcQuantityByMB(transaction, mid, mb, materialCalculator, decimal) {
  433. const [newmsg_spread, newm_spread] = await this.getSpread(mb, null, decimal.up);
  434. if (mb.t_type === materialConst.t_type[0].value) {
  435. const sql = 'SELECT SUM(`gather_qty`*`quantity`) as quantity FROM ' + this.ctx.service.materialList.tableName + ' WHERE `mid`=? AND `mb_id`=? AND `is_join`=1';
  436. const sqlParam = [mid, mb.id];
  437. const mb_quantity = await transaction.queryOne(sql, sqlParam);
  438. console.log(mb_quantity);
  439. // 取历史期记录获取截止上期调差金额,并清空本期单价和时间,来源地,重新计算价差和有效价差
  440. const newQuantity = this.ctx.helper.round(mb_quantity.quantity, decimal.qty);
  441. const newTp = this.ctx.helper.round(this.ctx.helper.mul(newQuantity, newm_spread), decimal.tp);
  442. const updateData = {
  443. id: mb.id,
  444. quantity: newQuantity,
  445. msg_tp: null,
  446. msg_times: null,
  447. msg_spread: newmsg_spread,
  448. m_spread: newm_spread,
  449. origin: null,
  450. m_tp: newTp,
  451. pre_tp: mb.m_tp !== null ? this.ctx.helper.add(mb.pre_tp, mb.m_tp) : mb.pre_tp,
  452. m_tax_tp: this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), decimal.tp),
  453. tax_pre_tp: mb.m_tax_tp !== null ? this.ctx.helper.add(mb.tax_pre_tp, mb.m_tax_tp) : mb.tax_pre_tp,
  454. };
  455. await transaction.update(this.tableName, updateData);
  456. const m_tp = mb.is_summary === 1 ? await this.ctx.helper.round(this.ctx.helper.mul(mb_quantity.quantity, newm_spread), decimal.tp) : 0;
  457. const m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(m_tp, (1 + this.ctx.helper.div(mb.m_tax, 100))), decimal.tp);
  458. return [m_tp, m_tax_tp];
  459. } else if (mb.t_type === materialConst.t_type[1].value) {
  460. const quantity = await materialCalculator.calculateExpr(mb.expr);
  461. const newTp = quantity !== 0 && quantity !== null ? this.ctx.helper.round(this.ctx.helper.mul(this.ctx.helper.round(quantity, decimal.qty), newm_spread), decimal.tp) : null;
  462. const updateData = {
  463. id: mb.id,
  464. quantity: quantity !== 0 && quantity !== null ? this.ctx.helper.round(quantity, decimal.qty) : null,
  465. msg_tp: null,
  466. msg_times: null,
  467. msg_spread: newmsg_spread,
  468. m_spread: newm_spread,
  469. origin: null,
  470. m_tp: newTp,
  471. pre_tp: mb.m_tp !== null ? this.ctx.helper.add(mb.pre_tp, mb.m_tp) : mb.pre_tp,
  472. m_tax_tp: this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), decimal.tp),
  473. tax_pre_tp: mb.m_tax_tp !== null ? this.ctx.helper.add(mb.tax_pre_tp, mb.m_tax_tp) : mb.tax_pre_tp,
  474. };
  475. await transaction.update(this.tableName, updateData);
  476. const m_tp = mb.is_summary === 1 ? await this.ctx.helper.round(this.ctx.helper.mul(quantity, newm_spread), decimal.tp) : 0;
  477. const m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(m_tp, (1 + this.ctx.helper.div(mb.m_tax, 100))), decimal.tp);
  478. return [m_tp, m_tax_tp];
  479. }
  480. }
  481. /**
  482. * 清空本期信息价后更新价差和有效价差
  483. * @param data
  484. * @returns {Promise<void>}
  485. */
  486. async getSpread(data, msg_tp, newDecimalUp = this.ctx.material.decimal.up, basic_price = null) {
  487. data.msg_tp = msg_tp;
  488. const newBp = basic_price ? basic_price : data.basic_price;
  489. const msg_spread = this.ctx.helper.round(this.ctx.helper.sub(data.msg_tp, newBp), newDecimalUp);
  490. const cor = msg_spread >= 0 ? this.ctx.helper.mul(newBp, this.ctx.helper.div(data.m_up_risk, 100)) : this.ctx.helper.mul(newBp, this.ctx.helper.div(data.m_down_risk, 100));
  491. const m_spread = Math.abs(msg_spread) > Math.abs(cor) ? (msg_spread > 0 ? this.ctx.helper.round(this.ctx.helper.sub(msg_spread, cor), newDecimalUp) : this.ctx.helper.round(this.ctx.helper.add(msg_spread, cor), newDecimalUp)) : 0;
  492. return [msg_spread, m_spread];
  493. }
  494. /**
  495. * 修改 expr和quantity值,返回本期金额和单条数据
  496. * @param data
  497. * @returns {Promise<void>}
  498. */
  499. async updateFYQuantity(data) {
  500. if (!this.ctx.tender || !this.ctx.material) {
  501. throw '数据错误';
  502. }
  503. const transaction = await this.db.beginTransaction();
  504. try {
  505. const returnData = {};
  506. returnData.m_tp = this.ctx.material.m_tp;
  507. if (this.ctx.material.is_stage_self) {
  508. const mbInfo = await this.getDataById(data.id);
  509. let all_m_tp = 0;
  510. let all_tax_tp = 0;
  511. for (const sid of this.ctx.material.stage_id.split(',')) {
  512. const materialCalculator = new MaterialCalculator(this.ctx, sid, this.ctx.tender.info);
  513. const quantity = await materialCalculator.calculateExpr(data.expr);
  514. const msInfo = await this.ctx.service.materialStage.getDataByCondition({ mid: this.ctx.material.id, sid });
  515. const msbInfo = await this.ctx.service.materialStageBills.getDataByCondition({ mid: this.ctx.material.id, mb_id: data.id, ms_id: msInfo.id });
  516. const newQuantity = quantity !== 0 ? this.ctx.helper.round(quantity, this.ctx.material.decimal.qty) : null;
  517. const m_tp = newQuantity ? this.ctx.helper.round(this.ctx.helper.mul(newQuantity, msbInfo.m_spread), this.ctx.material.decimal.tp) : null;
  518. const updateData = {
  519. id: data.id,
  520. quantity: newQuantity,
  521. m_tp,
  522. m_tax_tp: this.ctx.helper.round(this.ctx.helper.mul(m_tp, (1 + this.ctx.helper.div(mbInfo.m_tax, 100))), this.ctx.material.decimal.tp),
  523. };
  524. const [one_bill_m_tp, one_bill_tax_tp] = await this.ctx.service.materialStageBills.update(transaction, updateData, msInfo.id);
  525. await this.ctx.service.materialStage.updateMtp(transaction, msInfo.id);
  526. all_m_tp = this.ctx.helper.round(one_bill_m_tp, this.ctx.material.decimal.tp);
  527. all_tax_tp = this.ctx.helper.round(one_bill_tax_tp, this.ctx.material.decimal.tp);
  528. }
  529. const updateBillsData = {
  530. id: data.id,
  531. expr: data.expr,
  532. m_tp: all_m_tp ? all_m_tp : null,
  533. m_tax_tp: all_tax_tp ? all_tax_tp : null,
  534. };
  535. console.log(all_m_tp);
  536. await transaction.update(this.tableName, updateBillsData);
  537. returnData.m_tp = await this.calcMaterialMTp(transaction);
  538. returnData.stageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id, mb_id: data.id } });
  539. returnData.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  540. } else {
  541. const materialCalculator = new MaterialCalculator(this.ctx, this.ctx.material.stage_id, this.ctx.tender.info);
  542. const quantity = await materialCalculator.calculateExpr(data.expr);
  543. // 更新quantity值并重新返回计算本期金额,截止本期金额
  544. const updateData = {
  545. id: data.id,
  546. quantity: quantity !== 0 ? this.ctx.helper.round(quantity, this.ctx.material.decimal.qty) : null,
  547. expr: data.expr,
  548. };
  549. const mbInfo = await this.getDataById(updateData.id);
  550. updateData.m_tp = this.ctx.helper.round(this.ctx.helper.mul(updateData.quantity, mbInfo.m_spread), this.ctx.material.decimal.tp);
  551. updateData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(updateData.m_tp, (1 + this.ctx.helper.div(mbInfo.m_tax, 100))), this.ctx.material.decimal.tp);
  552. await transaction.update(this.tableName, updateData);
  553. if (mbInfo.quantity !== updateData.quantity) {
  554. returnData.m_tp = await this.calcMaterialMTp(transaction);
  555. }
  556. }
  557. await transaction.commit();
  558. returnData.info = await this.getDataById(data.id);
  559. return returnData;
  560. } catch (err) {
  561. await transaction.rollback();
  562. throw err;
  563. }
  564. }
  565. // 更改计算总金额并返回值
  566. async calcMaterialMTp(transaction) {
  567. // 金额发生变化,则重新计算本期金额
  568. const sql = 'SELECT SUM(`m_tp`) as total_price, SUM(IF(`m_tax_tp` is null, `m_tp`, `m_tax_tp`)) as tax_total_price FROM ' + this.tableName + ' WHERE `tid` = ? AND `is_summary` = 1';
  569. const sqlParam = [this.ctx.tender.id];
  570. const tp = await transaction.queryOne(sql, sqlParam);
  571. const updateData2 = {
  572. id: this.ctx.material.id,
  573. m_tp: tp.total_price,
  574. m_tax_tp: tp.tax_total_price,
  575. };
  576. console.log(tp);
  577. // if (this.ctx.material.material_tax) {
  578. // updateData2.m_tax_tp = tp.tax_total_price;
  579. // }
  580. await transaction.update(this.ctx.service.material.tableName, updateData2);
  581. return tp.total_price;
  582. }
  583. // 小数位变化更新单价和金额
  584. async resetDecimal(transaction, newDecimalUp, newDecimalTp, newDecimalQty) {
  585. const mbList = await transaction.select(this.tableName, { where: { tid: this.ctx.tender.id }, orders: [['order', 'asc']] });
  586. const updateList = [];
  587. const material_month = this.ctx.material.months ? this.ctx.material.months.split(',') : [];
  588. const updateMonthList = [];
  589. const materialStageList = this.ctx.material.is_stage_self ? await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } }) : [];
  590. for (const mb of mbList) {
  591. const updateData = {
  592. id: mb.id,
  593. };
  594. if (this.ctx.material.is_stage_self) {
  595. const updateStageBillsList = [];
  596. for (const ms of materialStageList) {
  597. const msb = await transaction.get(this.ctx.service.materialStageBills.tableName, { mid: this.ctx.material.id, mb_id: mb.id, ms_id: ms.id });
  598. msb.m_up_risk = mb.m_up_risk;
  599. msb.m_down_risk = mb.m_down_risk;
  600. const updateStageBillData = {
  601. id: msb.id,
  602. };
  603. if (newDecimalQty !== this.ctx.material.decimal.qty) {
  604. // 通过管理重新算出quantity并保留小数位
  605. const sql = 'SELECT SUM(`gather_qty`*`quantity`) as quantity FROM ' + this.ctx.service.materialList.tableName + ' WHERE `mid`=? AND `mb_id`=? AND `ms_id`=? AND `is_join`=1';
  606. const sqlParam = [this.ctx.material.id, mb.id, ms.id];
  607. const mb_quantity = await transaction.queryOne(sql, sqlParam);
  608. const newQuantity = this.ctx.helper.round(mb_quantity.quantity, newDecimalQty);
  609. if (newQuantity !== msb.quantity) {
  610. updateStageBillData.quantity = newQuantity;
  611. msb.quantity = newQuantity;
  612. }
  613. }
  614. if (newDecimalUp !== this.ctx.material.decimal.up) {
  615. const newmsg_tp = this.ctx.helper.round(msb.msg_tp, newDecimalUp);
  616. msb.msg_tp = newmsg_tp;
  617. const newbasic_price = this.ctx.helper.round(mb.basic_price, newDecimalUp);
  618. const [newmsg_spread, newm_spread] = await this.getSpread(msb, msb.msg_tp, newDecimalUp, newbasic_price);
  619. msb.m_spread = newm_spread;
  620. updateStageBillData.msg_tp = newmsg_tp;
  621. updateStageBillData.msg_spread = newmsg_spread;
  622. updateStageBillData.m_spread = newm_spread;
  623. }
  624. const newTp = this.ctx.helper.round(this.ctx.helper.mul(msb.quantity, msb.m_spread), newDecimalTp);
  625. updateStageBillData.m_tp = newTp;
  626. updateStageBillData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), newDecimalTp);
  627. updateStageBillsList.push(updateStageBillData);
  628. }
  629. if (newDecimalUp !== this.ctx.material.decimal.up) {
  630. const newbasic_price = this.ctx.helper.round(mb.basic_price, newDecimalUp);
  631. updateData.basic_price = newbasic_price;
  632. }
  633. if (updateStageBillsList.length > 0) await transaction.updateRows(this.ctx.service.materialStageBills.tableName, updateStageBillsList);
  634. const sql = 'SELECT SUM(`m_tp`) as total_price, SUM(IF(`m_tax_tp` is null, `m_tp`, `m_tax_tp`)) as tax_total_price FROM ' + this.ctx.service.materialStageBills.tableName + ' WHERE `tid` = ? AND `mid` = ? AND `mb_id` = ? AND `is_summary` = 1';
  635. const sqlParam = [this.ctx.tender.id, this.ctx.material.id, mb.id];
  636. const tp = await transaction.queryOne(sql, sqlParam);
  637. updateData.m_tp = this.ctx.helper.round(tp.total_price, newDecimalTp);
  638. updateData.m_tax_tp = this.ctx.helper.round(tp.tax_total_price, newDecimalTp);
  639. updateList.push(updateData);
  640. } else {
  641. if (newDecimalUp !== this.ctx.material.decimal.up) {
  642. let newmsg_tp = this.ctx.helper.round(mb.msg_tp, newDecimalUp);
  643. mb.msg_tp = newmsg_tp;
  644. // 判断是否有月信息价,如果有则msg_tp值由月信息价的平均单价获得,并更新月信息价单价
  645. if (material_month.length > 0) {
  646. const monthList = await transaction.select(this.ctx.service.materialMonth.tableName, { where: { mb_id: mb.id, mid: this.ctx.material.id } });
  647. if (monthList.length !== 0) {
  648. for (const m of monthList) {
  649. // 更新月信息单价小数位
  650. const newMonthMsgTP = this.ctx.helper.round(m.msg_tp, newDecimalUp);
  651. if (m.msg_tp && newMonthMsgTP !== m.msg_tp) {
  652. m.msg_tp = newMonthMsgTP;
  653. updateMonthList.push({ id: m.id, msg_tp: m.msg_tp });
  654. }
  655. }
  656. const mb_msg_tp_sum = this._.sumBy(monthList, 'msg_tp');
  657. const month_num = material_month.length - this.ctx.helper.arrayCount(this._.map(monthList, 'msg_tp'), [null, '', 0]);
  658. newmsg_tp = month_num !== 0 ? this.ctx.helper.round(this.ctx.helper.div(mb_msg_tp_sum, month_num), newDecimalUp) : null;
  659. mb.msg_tp = newmsg_tp;
  660. }
  661. }
  662. const newbasic_price = this.ctx.helper.round(mb.basic_price, newDecimalUp);
  663. mb.basic_price = newbasic_price;
  664. const [newmsg_spread, newm_spread] = await this.getSpread(mb, mb.msg_tp, newDecimalUp);
  665. mb.m_spread = newm_spread;
  666. updateData.basic_price = newbasic_price;
  667. updateData.msg_tp = newmsg_tp;
  668. updateData.msg_spread = newmsg_spread;
  669. updateData.m_spread = newm_spread;
  670. }
  671. if (newDecimalQty !== this.ctx.material.decimal.qty) {
  672. // 通过管理重新算出quantity并保留小数位
  673. const sql = 'SELECT SUM(`gather_qty`*`quantity`) as quantity FROM ' + this.ctx.service.materialList.tableName + ' WHERE `mid`=? AND `mb_id`=? AND `is_join`=1';
  674. const sqlParam = [this.ctx.material.id, mb.id];
  675. const mb_quantity = await transaction.queryOne(sql, sqlParam);
  676. const newQuantity = this.ctx.helper.round(mb_quantity.quantity, newDecimalQty);
  677. mb.quantity = newQuantity;
  678. updateData.quantity = newQuantity;
  679. }
  680. const newTp = this.ctx.helper.round(this.ctx.helper.mul(mb.quantity, mb.m_spread), newDecimalTp);
  681. updateData.m_tp = newTp;
  682. updateData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), newDecimalTp);
  683. updateList.push(updateData);
  684. }
  685. }
  686. if (updateMonthList.length > 0) await transaction.updateRows(this.ctx.service.materialMonth.tableName, updateMonthList);
  687. if (updateList.length > 0) await transaction.updateRows(this.tableName, updateList);
  688. if (this.ctx.material.is_stage_self) {
  689. for (const ms of materialStageList) {
  690. await this.ctx.service.materialStage.updateMtp(transaction, ms.id);
  691. }
  692. }
  693. }
  694. }
  695. return MaterialBills;
  696. };