# `Sp_System_CalcCurrentPeriodCost` (procedure)

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


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

## Parameters

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

## Body

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

## Narrative

**Business context:** 成本核算 → 订单成本分析 / 工单本期成本 — period-cost kernel: for every工单 (`accordercostanalysis` row) inside the requested closing period, recomputes 本期入库金额/数量/直接材料/人工/制造费用 and back-writes them onto the cost month-end table. Header (杨恒林 2021-05-23 封存) flags two subtleties: (1) 期初成本 comes from the work order's *most recent* prior month-end row, not necessarily the immediately preceding period; (2) 在制品 = orders whose cumulative入库数 still falls short of the order qty.

**What it does:** Loads the targeted accounting period (resolved from `sPeriod`/`tStartDate`/`tEndDate` against `sysaccountperiod`). For each `accordercostanalysis` row in scope, sums the period's 入库金额 from product inflow ledgers, 直接材料 from materials-issue history, 直接人工 from `accexpenseentryworkcenterslave`, 制造费用 / 部门费用 from `accdepart`/`accexpenseentrydepartmentmaster`, applies the carry-over 期初 amount looked up from the most recent prior month-end row of the same工单, and writes the resulting `dInMoney`/`dInQty`/`dEndMoney`/`dEndQty`/`d_*Cost` columns back. `sProInParam` lets the caller scope to a subset of orders; `sMakePerson` is recorded as the operator.

**Invocation:** Called by `Sp_CalcCost_BtnEventReCalcCost` (the 重新计算本期成本 button) and by `Sp_Cost_OrderCostAnalysis` (the 订单成本分析 entry point). Both upstream callers are dispatched by `GenericProcedureCallServiceImpl.doGenericProcedureCall()` from the 财务月结 / 成本核算 button toolbars. Install copies: `script/标版/30100101/cost/Sp_System_CalcCurrentPeriodCost.sql`, `Sp_CalcCost_BtnEventReCalcCost.sql`, `Sp_Cost_OrderCostAnalysis.sql`. Dated backup `Sp_System_CalcCurrentPeriodCost_1115` retains an older revision of the same proc.
