material_bills.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 = this._.isNumber(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. if (this.ctx.material.is_stage_self) {
  284. result.billsData = await transaction.select(this.tableName, { where: { id: data.id } });
  285. }
  286. result.m_tp = await this.calcMaterialMTp(transaction);
  287. await transaction.commit();
  288. return result;
  289. } catch (err) {
  290. await transaction.rollback();
  291. throw err;
  292. }
  293. }
  294. async updateOneBillsData(transaction, data, ms_id) {
  295. // 当以下值和bills值不相同时,需要同步更新最新的计算值到stageBills表里
  296. const updateColsArray = ['t_type', 'm_tax', 'basic_price', 'm_up_risk', 'm_down_risk', 'is_summary'];
  297. let needUp = null;
  298. const mbInfo = await this.getDataById(data.id);
  299. for (const uc of updateColsArray) {
  300. if (data[uc] !== undefined && data[uc] !== mbInfo[uc]) {
  301. needUp = uc;
  302. break;
  303. }
  304. }
  305. if (needUp) {
  306. const msList = await this.ctx.service.materialStage.getAllDataByCondition({ where: { mid: this.ctx.material.id } });
  307. for (const ms of msList) {
  308. if (ms.id !== parseInt(ms_id)) {
  309. const msbInfo = await this.ctx.service.materialStageBills.getDataByCondition({
  310. mid: this.ctx.material.id,
  311. ms_id: ms.id,
  312. mb_id: data.id,
  313. });
  314. const updateData = {
  315. id: msbInfo.id,
  316. };
  317. if (needUp === 'm_tax') {
  318. 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);
  319. } else if (needUp === 'm_up_risk' || needUp === 'm_down_risk' || needUp === 'basic_price') {
  320. const basic_price = needUp === 'basic_price' ? data.basic_price : mbInfo.basic_price;
  321. const [msg_spread, m_spread] = await this.getSpread(mbInfo, msbInfo.msg_tp, this.ctx.material.decimal.up, basic_price);
  322. updateData.msg_spread = msg_spread;
  323. updateData.m_spread = m_spread;
  324. const newTp = this.ctx.helper.round(this.ctx.helper.mul(msbInfo.quantity, m_spread), this.ctx.material.decimal.tp);
  325. updateData.m_tp = newTp;
  326. 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);
  327. } else if (needUp === 't_type') {
  328. updateData.quantity = null;
  329. updateData.m_tp = null;
  330. updateData.m_tax_tp = null;
  331. } else if (needUp === 'is_summary') {
  332. updateData.is_summary = data.is_summary;
  333. }
  334. await transaction.update(this.ctx.service.materialStageBills.tableName, updateData);
  335. await this.ctx.service.materialStage.updateMtp(transaction, ms.id);
  336. }
  337. }
  338. }
  339. return needUp;
  340. }
  341. async saveOrigin(data) {
  342. if (!this.ctx.tender || !this.ctx.material) {
  343. throw '数据错误';
  344. }
  345. return await this.db.update(this.tableName, { id: data.mb_id, origin: data.value });
  346. }
  347. async saveOrigins(datas) {
  348. if (!this.ctx.tender || !this.ctx.material) {
  349. throw '数据错误';
  350. }
  351. const updateData = [];
  352. for (const data of datas) {
  353. updateData.push({
  354. id: data.mb_id,
  355. origin: data.origin,
  356. });
  357. }
  358. if (updateData.length > 0) await this.db.updateRows(this.tableName, updateData);
  359. return true;
  360. }
  361. /**
  362. * 修改工料信息
  363. * @param {Object} data 工料内容
  364. * @return {void}
  365. */
  366. async saveDatas(datas, ms_id = null) {
  367. if (!this.ctx.tender || !this.ctx.material) {
  368. throw '数据错误';
  369. }
  370. // 判断是否可修改
  371. // 判断t_type是否为费用
  372. const transaction = await this.db.beginTransaction();
  373. try {
  374. for (const data of datas) {
  375. delete data.in_time;
  376. let needUp = null;
  377. if (this.ctx.material.is_stage_self) {
  378. needUp = await this.updateOneBillsData(transaction, data, ms_id);
  379. const [one_m_tp, one_tax_tp] = await this.ctx.service.materialStageBills.update(transaction, data, ms_id);
  380. // 更新materialStage 值
  381. data.m_tp = this.ctx.helper.round(one_m_tp, this.ctx.material.decimal.tp);
  382. data.m_tax_tp = this.ctx.helper.round(one_tax_tp, this.ctx.material.decimal.tp);
  383. data.quantity = null;
  384. data.msg_tp = null;
  385. data.msg_times = null;
  386. data.msg_spread = null;
  387. data.msg_spread = null;
  388. data.m_spread = null;
  389. }
  390. // delete data.m_tp;
  391. // console.log(data);
  392. await transaction.update(this.tableName, data);
  393. }
  394. // 更新materialStage 值
  395. const result = {};
  396. if (this.ctx.material.is_stage_self) {
  397. await this.ctx.service.materialStage.updateMtp(transaction, ms_id);
  398. result.stageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id } });
  399. result.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  400. result.billsData = await transaction.select(this.tableName, { where: { mid: this.ctx.material.id } });
  401. }
  402. result.m_tp = await this.calcMaterialMTp(transaction);
  403. await transaction.commit();
  404. return result;
  405. } catch (err) {
  406. await transaction.rollback();
  407. throw err;
  408. }
  409. }
  410. /**
  411. * 更新新一期的quantity和截止上期金额并返回本期总金额
  412. * @param transaction
  413. * @param tid
  414. * @param mid
  415. * @returns {Promise<number>}
  416. */
  417. async updateNewMaterial(transaction, tid, mid, ctx, stage_id, decimal) {
  418. const materialBillsData = await this.getAllDataByCondition({ where: { tid } });
  419. let m_tp = 0;
  420. let m_tax_tp = 0;
  421. const materialCalculator = new MaterialCalculator(ctx, stage_id, ctx.tender.info);
  422. for (const mb of materialBillsData) {
  423. const [one_tp, one_tax_tp] = await this.calcQuantityByMB(transaction, mid, mb, materialCalculator, decimal);
  424. m_tp = this.ctx.helper.add(m_tp, one_tp);
  425. m_tax_tp = this.ctx.helper.add(m_tax_tp, one_tax_tp);
  426. }
  427. return [m_tp, m_tax_tp];
  428. }
  429. /**
  430. * 修改quantity,m_spread值和返回单条调差金额(新增一期)
  431. * @param transaction
  432. * @param mid
  433. * @param mb
  434. * @returns {Promise<*>}
  435. */
  436. async calcQuantityByMB(transaction, mid, mb, materialCalculator, decimal) {
  437. const [newmsg_spread, newm_spread] = await this.getSpread(mb, null, decimal.up);
  438. if (mb.t_type === materialConst.t_type[0].value) {
  439. const sql = 'SELECT SUM(`gather_qty`*`quantity`) as quantity FROM ' + this.ctx.service.materialList.tableName + ' WHERE `mid`=? AND `mb_id`=? AND `is_join`=1';
  440. const sqlParam = [mid, mb.id];
  441. const mb_quantity = await transaction.queryOne(sql, sqlParam);
  442. console.log(mb_quantity);
  443. // 取历史期记录获取截止上期调差金额,并清空本期单价和时间,来源地,重新计算价差和有效价差
  444. const newQuantity = this.ctx.helper.round(mb_quantity.quantity, decimal.qty);
  445. const newTp = this.ctx.helper.round(this.ctx.helper.mul(newQuantity, newm_spread), decimal.tp);
  446. const updateData = {
  447. id: mb.id,
  448. quantity: newQuantity,
  449. msg_tp: null,
  450. msg_times: null,
  451. msg_spread: newmsg_spread,
  452. m_spread: newm_spread,
  453. origin: null,
  454. m_tp: newTp,
  455. pre_tp: mb.m_tp !== null ? this.ctx.helper.add(mb.pre_tp, mb.m_tp) : mb.pre_tp,
  456. m_tax_tp: this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), decimal.tp),
  457. tax_pre_tp: mb.m_tax_tp !== null ? this.ctx.helper.add(mb.tax_pre_tp, mb.m_tax_tp) : mb.tax_pre_tp,
  458. };
  459. await transaction.update(this.tableName, updateData);
  460. const m_tp = mb.is_summary === 1 ? await this.ctx.helper.round(this.ctx.helper.mul(mb_quantity.quantity, newm_spread), decimal.tp) : 0;
  461. 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);
  462. return [m_tp, m_tax_tp];
  463. } else if (mb.t_type === materialConst.t_type[1].value) {
  464. const quantity = await materialCalculator.calculateExpr(mb.expr);
  465. 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;
  466. const updateData = {
  467. id: mb.id,
  468. quantity: quantity !== 0 && quantity !== null ? this.ctx.helper.round(quantity, decimal.qty) : null,
  469. msg_tp: null,
  470. msg_times: null,
  471. msg_spread: newmsg_spread,
  472. m_spread: newm_spread,
  473. origin: null,
  474. m_tp: newTp,
  475. pre_tp: mb.m_tp !== null ? this.ctx.helper.add(mb.pre_tp, mb.m_tp) : mb.pre_tp,
  476. m_tax_tp: this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), decimal.tp),
  477. tax_pre_tp: mb.m_tax_tp !== null ? this.ctx.helper.add(mb.tax_pre_tp, mb.m_tax_tp) : mb.tax_pre_tp,
  478. };
  479. await transaction.update(this.tableName, updateData);
  480. const m_tp = mb.is_summary === 1 ? await this.ctx.helper.round(this.ctx.helper.mul(quantity, newm_spread), decimal.tp) : 0;
  481. 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);
  482. return [m_tp, m_tax_tp];
  483. }
  484. }
  485. /**
  486. * 清空本期信息价后更新价差和有效价差
  487. * @param data
  488. * @returns {Promise<void>}
  489. */
  490. async getSpread(data, msg_tp, newDecimalUp = this.ctx.material.decimal.up, basic_price = null) {
  491. data.msg_tp = msg_tp;
  492. const newBp = basic_price ? basic_price : data.basic_price;
  493. const msg_spread = this.ctx.helper.round(this.ctx.helper.sub(data.msg_tp, newBp), newDecimalUp);
  494. 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));
  495. 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;
  496. return [msg_spread, m_spread];
  497. }
  498. /**
  499. * 修改 expr和quantity值,返回本期金额和单条数据
  500. * @param data
  501. * @returns {Promise<void>}
  502. */
  503. async updateFYQuantity(data) {
  504. if (!this.ctx.tender || !this.ctx.material) {
  505. throw '数据错误';
  506. }
  507. const transaction = await this.db.beginTransaction();
  508. try {
  509. const returnData = {};
  510. returnData.m_tp = this.ctx.material.m_tp;
  511. if (this.ctx.material.is_stage_self) {
  512. if (!data.ms_id) throw '参数有误';
  513. const mbInfo = await this.getDataById(data.id);
  514. const msInfo = await this.ctx.service.materialStage.getDataById(data.ms_id);
  515. const msbInfo = await this.ctx.service.materialStageBills.getDataByCondition({ mid: this.ctx.material.id, mb_id: data.id, ms_id: data.ms_id });
  516. // let all_m_tp = 0;
  517. // let all_tax_tp = 0;
  518. const materialCalculator = new MaterialCalculator(this.ctx, msInfo.sid, this.ctx.tender.info);
  519. const quantity = await materialCalculator.calculateExpr(data.expr);
  520. const newQuantity = quantity !== 0 ? this.ctx.helper.round(quantity, this.ctx.material.decimal.qty) : null;
  521. const m_tp = newQuantity ? this.ctx.helper.round(this.ctx.helper.mul(newQuantity, msbInfo.m_spread), this.ctx.material.decimal.tp) : null;
  522. const updateData = {
  523. id: data.id,
  524. quantity: newQuantity,
  525. expr: data.expr,
  526. m_tp,
  527. 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),
  528. };
  529. const [one_bill_m_tp, one_bill_tax_tp] = await this.ctx.service.materialStageBills.update(transaction, updateData, msInfo.id);
  530. await this.ctx.service.materialStage.updateMtp(transaction, msInfo.id);
  531. const all_m_tp = this.ctx.helper.round(one_bill_m_tp, this.ctx.material.decimal.tp);
  532. const all_tax_tp = this.ctx.helper.round(one_bill_tax_tp, this.ctx.material.decimal.tp);
  533. // for (const sid of this.ctx.material.stage_id.split(',')) {
  534. // const materialCalculator = new MaterialCalculator(this.ctx, sid, this.ctx.tender.info);
  535. // const quantity = await materialCalculator.calculateExpr(data.expr);
  536. // const msInfo = await this.ctx.service.materialStage.getDataByCondition({ mid: this.ctx.material.id, sid });
  537. // const msbInfo = await this.ctx.service.materialStageBills.getDataByCondition({ mid: this.ctx.material.id, mb_id: data.id, ms_id: msInfo.id });
  538. // const newQuantity = quantity !== 0 ? this.ctx.helper.round(quantity, this.ctx.material.decimal.qty) : null;
  539. // const m_tp = newQuantity ? this.ctx.helper.round(this.ctx.helper.mul(newQuantity, msbInfo.m_spread), this.ctx.material.decimal.tp) : null;
  540. // const updateData = {
  541. // id: data.id,
  542. // quantity: newQuantity,
  543. // m_tp,
  544. // 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),
  545. // };
  546. // const [one_bill_m_tp, one_bill_tax_tp] = await this.ctx.service.materialStageBills.update(transaction, updateData, msInfo.id);
  547. // await this.ctx.service.materialStage.updateMtp(transaction, msInfo.id);
  548. // all_m_tp = this.ctx.helper.round(one_bill_m_tp, this.ctx.material.decimal.tp);
  549. // all_tax_tp = this.ctx.helper.round(one_bill_tax_tp, this.ctx.material.decimal.tp);
  550. // }
  551. const updateBillsData = {
  552. id: data.id,
  553. // expr: data.expr,
  554. m_tp: all_m_tp ? all_m_tp : null,
  555. m_tax_tp: all_tax_tp ? all_tax_tp : null,
  556. };
  557. console.log(all_m_tp);
  558. await transaction.update(this.tableName, updateBillsData);
  559. returnData.m_tp = await this.calcMaterialMTp(transaction);
  560. returnData.stageBillsData = await transaction.select(this.ctx.service.materialStageBills.tableName, { where: { mid: this.ctx.material.id, mb_id: data.id } });
  561. returnData.stageData = await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } });
  562. } else {
  563. const materialCalculator = new MaterialCalculator(this.ctx, this.ctx.material.stage_id, this.ctx.tender.info);
  564. const quantity = await materialCalculator.calculateExpr(data.expr);
  565. // 更新quantity值并重新返回计算本期金额,截止本期金额
  566. const updateData = {
  567. id: data.id,
  568. quantity: quantity !== 0 ? this.ctx.helper.round(quantity, this.ctx.material.decimal.qty) : null,
  569. expr: data.expr,
  570. };
  571. const mbInfo = await this.getDataById(updateData.id);
  572. updateData.m_tp = this.ctx.helper.round(this.ctx.helper.mul(updateData.quantity, mbInfo.m_spread), this.ctx.material.decimal.tp);
  573. 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);
  574. await transaction.update(this.tableName, updateData);
  575. if (mbInfo.quantity !== updateData.quantity) {
  576. returnData.m_tp = await this.calcMaterialMTp(transaction);
  577. }
  578. }
  579. await transaction.commit();
  580. returnData.info = await this.getDataById(data.id);
  581. return returnData;
  582. } catch (err) {
  583. await transaction.rollback();
  584. throw err;
  585. }
  586. }
  587. // 更改计算总金额并返回值
  588. async calcMaterialMTp(transaction) {
  589. // 金额发生变化,则重新计算本期金额
  590. 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';
  591. const sqlParam = [this.ctx.tender.id];
  592. const tp = await transaction.queryOne(sql, sqlParam);
  593. const updateData2 = {
  594. id: this.ctx.material.id,
  595. m_tp: tp.total_price,
  596. m_tax_tp: tp.tax_total_price,
  597. };
  598. console.log(tp);
  599. // if (this.ctx.material.material_tax) {
  600. // updateData2.m_tax_tp = tp.tax_total_price;
  601. // }
  602. await transaction.update(this.ctx.service.material.tableName, updateData2);
  603. return tp.total_price;
  604. }
  605. // 小数位变化更新单价和金额
  606. async resetDecimal(transaction, newDecimalUp, newDecimalTp, newDecimalQty) {
  607. const mbList = await transaction.select(this.tableName, { where: { tid: this.ctx.tender.id }, orders: [['order', 'asc']] });
  608. const updateList = [];
  609. const material_month = this.ctx.material.months ? this.ctx.material.months.split(',') : [];
  610. const updateMonthList = [];
  611. const materialStageList = this.ctx.material.is_stage_self ? await transaction.select(this.ctx.service.materialStage.tableName, { where: { mid: this.ctx.material.id } }) : [];
  612. for (const mb of mbList) {
  613. const updateData = {
  614. id: mb.id,
  615. };
  616. if (this.ctx.material.is_stage_self) {
  617. const updateStageBillsList = [];
  618. for (const ms of materialStageList) {
  619. const msb = await transaction.get(this.ctx.service.materialStageBills.tableName, { mid: this.ctx.material.id, mb_id: mb.id, ms_id: ms.id });
  620. msb.m_up_risk = mb.m_up_risk;
  621. msb.m_down_risk = mb.m_down_risk;
  622. const updateStageBillData = {
  623. id: msb.id,
  624. };
  625. if (newDecimalQty !== this.ctx.material.decimal.qty) {
  626. // 通过管理重新算出quantity并保留小数位
  627. 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';
  628. const sqlParam = [this.ctx.material.id, mb.id, ms.id];
  629. const mb_quantity = await transaction.queryOne(sql, sqlParam);
  630. const newQuantity = this.ctx.helper.round(mb_quantity.quantity, newDecimalQty);
  631. if (newQuantity !== msb.quantity) {
  632. updateStageBillData.quantity = newQuantity;
  633. msb.quantity = newQuantity;
  634. }
  635. }
  636. if (newDecimalUp !== this.ctx.material.decimal.up) {
  637. const newmsg_tp = this.ctx.helper.round(msb.msg_tp, newDecimalUp);
  638. msb.msg_tp = newmsg_tp;
  639. const newbasic_price = this.ctx.helper.round(mb.basic_price, newDecimalUp);
  640. const [newmsg_spread, newm_spread] = await this.getSpread(msb, msb.msg_tp, newDecimalUp, newbasic_price);
  641. msb.m_spread = newm_spread;
  642. updateStageBillData.msg_tp = newmsg_tp;
  643. updateStageBillData.msg_spread = newmsg_spread;
  644. updateStageBillData.m_spread = newm_spread;
  645. }
  646. const newTp = this.ctx.helper.round(this.ctx.helper.mul(msb.quantity, msb.m_spread), newDecimalTp);
  647. updateStageBillData.m_tp = newTp;
  648. updateStageBillData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), newDecimalTp);
  649. updateStageBillsList.push(updateStageBillData);
  650. }
  651. if (newDecimalUp !== this.ctx.material.decimal.up) {
  652. const newbasic_price = this.ctx.helper.round(mb.basic_price, newDecimalUp);
  653. updateData.basic_price = newbasic_price;
  654. }
  655. if (updateStageBillsList.length > 0) await transaction.updateRows(this.ctx.service.materialStageBills.tableName, updateStageBillsList);
  656. 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';
  657. const sqlParam = [this.ctx.tender.id, this.ctx.material.id, mb.id];
  658. const tp = await transaction.queryOne(sql, sqlParam);
  659. updateData.m_tp = this.ctx.helper.round(tp.total_price, newDecimalTp);
  660. updateData.m_tax_tp = this.ctx.helper.round(tp.tax_total_price, newDecimalTp);
  661. updateList.push(updateData);
  662. } else {
  663. if (newDecimalUp !== this.ctx.material.decimal.up) {
  664. let newmsg_tp = this.ctx.helper.round(mb.msg_tp, newDecimalUp);
  665. mb.msg_tp = newmsg_tp;
  666. // 判断是否有月信息价,如果有则msg_tp值由月信息价的平均单价获得,并更新月信息价单价
  667. if (material_month.length > 0) {
  668. const monthList = await transaction.select(this.ctx.service.materialMonth.tableName, { where: { mb_id: mb.id, mid: this.ctx.material.id } });
  669. if (monthList.length !== 0) {
  670. for (const m of monthList) {
  671. // 更新月信息单价小数位
  672. const newMonthMsgTP = this.ctx.helper.round(m.msg_tp, newDecimalUp);
  673. if (m.msg_tp && newMonthMsgTP !== m.msg_tp) {
  674. m.msg_tp = newMonthMsgTP;
  675. updateMonthList.push({ id: m.id, msg_tp: m.msg_tp });
  676. }
  677. }
  678. const mb_msg_tp_sum = this._.sumBy(monthList, 'msg_tp');
  679. const month_num = material_month.length - this.ctx.helper.arrayCount(this._.map(monthList, 'msg_tp'), [null, '', 0]);
  680. newmsg_tp = month_num !== 0 ? this.ctx.helper.round(this.ctx.helper.div(mb_msg_tp_sum, month_num), newDecimalUp) : null;
  681. mb.msg_tp = newmsg_tp;
  682. }
  683. }
  684. const newbasic_price = this.ctx.helper.round(mb.basic_price, newDecimalUp);
  685. mb.basic_price = newbasic_price;
  686. const [newmsg_spread, newm_spread] = await this.getSpread(mb, mb.msg_tp, newDecimalUp);
  687. mb.m_spread = newm_spread;
  688. updateData.basic_price = newbasic_price;
  689. updateData.msg_tp = newmsg_tp;
  690. updateData.msg_spread = newmsg_spread;
  691. updateData.m_spread = newm_spread;
  692. }
  693. if (newDecimalQty !== this.ctx.material.decimal.qty) {
  694. // 通过管理重新算出quantity并保留小数位
  695. const sql = 'SELECT SUM(`gather_qty`*`quantity`) as quantity FROM ' + this.ctx.service.materialList.tableName + ' WHERE `mid`=? AND `mb_id`=? AND `is_join`=1';
  696. const sqlParam = [this.ctx.material.id, mb.id];
  697. const mb_quantity = await transaction.queryOne(sql, sqlParam);
  698. const newQuantity = this.ctx.helper.round(mb_quantity.quantity, newDecimalQty);
  699. mb.quantity = newQuantity;
  700. updateData.quantity = newQuantity;
  701. }
  702. const newTp = this.ctx.helper.round(this.ctx.helper.mul(mb.quantity, mb.m_spread), newDecimalTp);
  703. updateData.m_tp = newTp;
  704. updateData.m_tax_tp = this.ctx.helper.round(this.ctx.helper.mul(newTp, (1 + this.ctx.helper.div(mb.m_tax, 100))), newDecimalTp);
  705. updateList.push(updateData);
  706. }
  707. }
  708. if (updateMonthList.length > 0) await transaction.updateRows(this.ctx.service.materialMonth.tableName, updateMonthList);
  709. if (updateList.length > 0) await transaction.updateRows(this.tableName, updateList);
  710. if (this.ctx.material.is_stage_self) {
  711. for (const ms of materialStageList) {
  712. await this.ctx.service.materialStage.updateMtp(transaction, ms.id);
  713. }
  714. }
  715. }
  716. }
  717. return MaterialBills;
  718. };