# `Sp_System_InitCurrentPeriodCost` (procedure)

> @author:杨恒林
							@date:20210523 封存
							@describe: 获取当前月份要进行成本核算的工单号,在月末结帐时并存入成本月结表,只有结构数据,
							暂无成本数据,等实际的费用分摊单据数据出来后，调用成本核算过程，更新成本数据 主要思路如下：
							1.月末结帐时调用本过程
							2.本月核算工单 = 本月成品入库+发外对帐对应的工单号和本月装配单号从表对应的工单 + 没有完工的工单号(入库数<工单数 或者单据完工)
							3.把上面工单存入本月月度成本表，为成本核算做准备


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

## Parameters

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

## Body

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

## Narrative

**Business context:** 成本核算 / 月末结帐 — populates the per-period cost ledger skeleton at month-end close. Per the procedure `COMMENT` (杨恒林, 2021-05-23): the current period's 工单 set = (this-period 成品入库) + (this-period 发外对帐 工单) + (this-period 装配单从表 工单) + (open 工单 where 入库数<工单数 or marked 完工). The proc selects those 工单s and inserts structure-only rows into the 成本月结表 family (`CotOrderCostAnalysis`/`accordercostanalysis*`), ready for the subsequent `Sp_System_MaterialsCost` / `Sp_System_ProductionCost` runs to fill in money.

**What it does:** Pulls `tStartDate/tEndDate/sPeriodId`, looks up `DATABASE()` and `EleWorkCenter` / `EleCostFrame` counts (refuses to run when either base table is empty), then assembles dynamic SQL (`p_sSumSql`, `p_sSumSqlBl`, `p_updateSql`, `p_sSetSql`) that joins `mftworkordermaster` to `pitproductstoremaster`, `mftvinvoiceslave` (发外发票), `mftassemblyslave` (装配从表) and the prior period's 成本月结 row, and bulk-inserts the in-scope 工单s into `accordercostanalysis` / cost-frame slaves with `iType` codes for each category. Mostly INSERT-with-cost-zero placeholders; later cost procs UPDATE them.

**Invocation:** Called by `Sp_financialClosing_BtnEventCalcMaterialPrice` (月末结帐 button — after `Sp_System_CalcMaterialsPrice` and `Sp_System_CalcProductPrice_new`), and additionally by `Sp_CalcCost_BtnEventReCalcCost`, `Sp_Cost_CheckBusinessData`, `Sp_System_ReCostStructure`, and `Sp_System_ReCostStructure_new`. Install scripts at `script/标版/30100101/cost/Sp_System_InitCurrentPeriodCost.sql` plus an `financialClosing_BtnEventCalcMaterialPrice.sql` upgrade copy.
