# `Sp_System_CalcProductPrice` (procedure)

> @author:杨恒林
							@date:20210521 封存
							@describe: 计算库存产品商品价值并存入月结表 主要思路如下：
							从本月月末之前最近一次订单取价格，如果取不到 从 产品客户表中取 ，再取不到 从产品表中取，再取不到,从最近取对帐
							bUpdate = 1 时，表示月末结帐时调用，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 | `sLoginId` | `varchar(100)` |
| 5 | IN | `sBrId` | `varchar(100)` |
| 6 | IN | `sSuId` | `varchar(100)` |
| 7 | OUT | `sReturn` | `varchar(4000)` |
| 8 | OUT | `sCode` | `int` |

## Body

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

## Narrative

**Business context:** 成本核算 / 财务月结 → 计算产品价格 — period-level成品价值 pricer; product-side counterpart of `Sp_System_CalcMaterialsPrice`. Header (杨恒林 2021-05-21 封存) spells out the price-discovery cascade: first, the most-recent in-period 销售订单价; falling back to `eleproductcustomer` (产品客户特价); then `eleproduct.dProductPrice` default; lastly the nearest 销售对账价. `bUpdate=1` 月末结帐 also stores the period snapshot into the成品库存价值结存表; `bUpdate=0` is the 库存商品价值表 UI preview path.

**What it does:** Walks every product touched by an in-period成品 movement (送货单/成品入库/退货单/成品调拨/成品报废/发外入库/成品盘点). For each product, runs the price-discovery cascade against the cut-off `tEndDate` to pick `dProductPrice`. Writes that price back onto every in-period成品 stock line (`accproductstore` slave rows and feed tables), recomputes `dProductMoney = dProductQty * dProductPrice` honouring `NetMoney`/`NetPrice` decimal settings, and on `bUpdate=1` consolidates the period totals into the成品 month-end / inventory-value snapshot.

**Invocation:** Called by `Sp_CalcCost_BtnEventReCalcCost` (重新计算本期成本), `Sp_Cost_CheckBusinessData` (close-time business-data validation), `Sp_financialClosing_BtnEventCalcMaterialPrice` (财务月结 → 计算材料价格 button, which also kicks off product-side pricing), `Sp_financialClosing_BtnEventCalcYM_New`, and `Sp_Product_BtnEventCheck` (成品入库 audit). Each upstream caller is dispatched dynamically by `GenericProcedureCallServiceImpl.doGenericProcedureCall()` from the corresponding 月结 / 成本核算 toolbar buttons. Install: `script/标版/30100101/cost/Sp_System_CalcProductPrice.sql` (+ caller scripts). Customer override: `script/客户/千彩/Sp_Inventory_ProductInOutStoreStock.sql`. `_new` revision exists with a reduced caller set.
