# `Sp_System_CalcMaterialsPrice` (procedure)

> @author:杨恒林 
						@date:20210521 封存 
						@describe:全月加权计算价格后 期初金额 + 采购入库金额+期它入库金额/ 期初数量 + 采购入库金额+期它入库金额
						更新到其它各单据
						bUpdate = 0:第一次分摊，分切单主表分摊到从表。 第二次正常分摊


- **Type:** PROCEDURE
- **Deterministic:** NO
- **SQL data access:** CONTAINS SQL

## Parameters

| # | Mode | Name | Type |
|---|---|---|---|
| 1 | IN | `tStartDate` | `datetime` |
| 2 | IN | `tEndDate` | `datetime` |
| 3 | IN | `bUpdate` | `int` |
| 4 | IN | `sBrId` | `varchar(100)` |
| 5 | IN | `sSuId` | `varchar(100)` |
| 6 | OUT | `sReturn` | `varchar(4000)` |
| 7 | OUT | `sCode` | `int` |

## Body

_Body is not pre-cached. To inspect: `mysql --defaults-file=~/.my.cnf -e 'SHOW CREATE PROCEDURE `Sp_System_CalcMaterialsPrice`'`._

## Narrative

**Business context:** 成本核算 / 财务月结 → 计算材料价格 — period-level materials weighted-average pricer. For the closing period, computes 全月加权 unit price per material as `(期初金额 + 采购入库金额 + 其它入库金额) / (期初数量 + 采购入库数量 + 其它入库数量)`, then propagates that price back onto every materials movement in the period (生产领料、生产退料、材料调拨、材料报废、来料入库、其它入库、分切单, etc.). Header (杨恒林 2021-05-21 封存) notes `bUpdate=0` is the first pass — 分切单 master price split to slaves first; the second pass does the normal propagation.

**What it does:** Walks every material with a `[tStartDate, tEndDate]` movement. Loads `期初金额`/`期初数量` from the prior month-end materials store (`accmaterialsstore`), sums本期 input money/qty from `mitpurchaseinmaster`/`mitothermaterialsinmaster`/`mitmaterialsinmaster` etc., divides for the weighted-average unit price (`dMaterialsPrice`). Writes that price back onto each in-period materials slave (and the `viw_mitmaterialscheck` underlying tables), refreshing `dMaterialsMoney = qty * price` with `SysSystemSettings` decimal rounding. `bUpdate=1` 月末结帐 path additionally stores the period roll-up to the closing table; `bUpdate=0` is the materials-stock-value preview path that only updates prices.

**Invocation:** Called by `Sp_financialClosing_BtnEventCalcMaterialPrice` (the 计算材料价格 button on 财务月结), `Sp_CalcCost_BtnEventReCalcCost`, `Sp_CommonList_BtnEventCheck`, `Sp_Cost_CheckBusinessData`, and `Sp_financialClosing_BtnEventCalcYM_New` — each dispatched via `GenericProcedureCallServiceImpl.doGenericProcedureCall()` from the corresponding 月结 toolbar buttons. Install: `script/标版/30100101/cost/Sp_System_CalcMaterialsPrice.sql` (+ `Sp_CalcCost_BtnEventReCalcCost.sql`, `Sp_financialClosing_BtnEventCalcMaterialPrice.sql`, `Sp_CommonList_BtnEventCheck.sql`). Dated backups `_220709`, `_221111` retain older revisions.
