# `Sp_System_ProductionCost` (procedure)

> @author:杨恒林
							@date:20210523 封存
							@describe: 从成本月结表中，拿到工单数据，计算本月成本数据后回写到成本月结表	注意点：
							1.本期期初成本从本工单最近一次月结成本表中获取，不一定就是上期
							2.在制品是指所有入库数小于工单数的工单


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

## Parameters

| # | Mode | Name | Type |
|---|---|---|---|
| 1 | IN | `sProInParam` | `varchar(10000)` |
| 2 | IN | `iSecond` | `int` |
| 3 | IN | `sMakePerson` | `varchar(100)` |
| 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_ProductionCost`'`._

## Narrative

**Business context:** 成本核算 / 生产成本核算 — per the procedure `COMMENT` (杨恒林, 2021-05-23): pulls 工单 data from the 成本月结表, recomputes this period's cost numbers, writes them back. Notes: (1) 期初成本 comes from the nearest prior 月结 row for the same 工单, not strictly the previous period; (2) 在制品 = 工单 where 入库数 < 工单数. This is the workhorse of the 工单成本核算 stage — runs after materials are priced (`Sp_System_MaterialsCost`) and after 期间初始化 (`Sp_System_InitCurrentPeriodCost`).

**What it does:** Validates `sProInParam` JSON of period ids; for each: reads `bCost`, refuses if already 已核算, calls `Sp_System_MaterialsCost` to pin material prices, then assembles the per-work-order cost via a cascade of temp tables — `TmpCostWorkOrder`, `TmpCostWorkOrder_BQ` (本期), `TmpCostWorkOrder_dAreaBlZreo` (面积比例零除护栏), `TmpCostWorkOrderSum`, `p_accordercostanalysis*`, `p_dProductQty_tmp`. INSERT/UPDATE/DELETE `accordercostanalysis` (主成本表), `accproductstore` (期末成品库存), and `accexpenseentrydepartmentmaster_dif` (差异回写). Calls `Sp_WorkCostCarryforward` for 期初 carry-forward, and self-`CALL`s `Sp_System_ProductionCost` recursively where the cost-frame model requires it.

**Invocation:** Called from `Sp_System_ProductionCost_new` and `Sp_System_ProductionCost24222` (variants), `Sp_System_ProductionCostBak` (backup), `Sp_System_ProductionCostTest` (test). No direct gdsmodule / form-master / xly-src caller — front-end button "生产成本计算" on the 月度成本 grid presumably routes here through `GenericProcedureCallServiceImpl.doGenericProcedureCall()`. Install scripts at `script/标版/30100101/cost/Sp_System_ProductionCost.sql` (plus `…AllSure` / `…AllReSure` confirm wrappers). Body 152K chars — bulk is temp-table assembly.
