# `Sp_saveReturn_sOpkg` (procedure)

> 发外发票单据反写


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

## Parameters

| # | Mode | Name | Type |
|---|---|---|---|
| 1 | IN | `sGuid` | `longtext` |
| 2 | IN | `sBrId` | `varchar(100)` |
| 3 | IN | `sSuId` | `varchar(100)` |
| 4 | IN | `iTag` | `int` |
| 5 | OUT | `sCode` | `int` |
| 6 | OUT | `sReturn` | `longtext` |

## Body

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

## Narrative

**Business context:** KPI流程操作菜单 → 发外加工流程 → 发外对账 — when a 发外对账单 is saved (the reconciliation that locks the supplier's outsource quantities before invoicing), back-writes the reconciled qty onto the upstream 整单发外入库 slave (`OpsOutsideInStoreSlave`), updates the supplier ledger (`CahSupplyInit`), and posts financial adjustments (`cahfinancialadjustslave`). Despite the body comment reading `发外发票单据反写`, the table targets and the bound form make this the reconciliation back-write — the comment is a copy-paste artefact.

**What it does:** Splits `sGuid` into `p_t_sId`, materialises every reconciled `sSrcSlaveId` into `p_sSrcSlaveId_tmp`, sums the reconciliation qty/amount (with `iTag=1` zeroing the in-flight batch) into `t_data_temp`, then updates `OpsOutsideInStoreSlave`, `cahfinancialadjustslave`, and `CahSupplyInit` rows for matching ids.

**Invocation:** Called by `Sp_beforeSave_sOpkg` (`iTag=1`) and `Sp_afterSave_sOpkg` (`iTag=2`). The beforeSave wrapper is bound on `gdsmodule.sSaveProNameBefore` for 发外对账 (`192116810113315235850403280`) under 发外加工流程 — fired by `BusinessBaseServiceImpl` save hooks. `Sp_Invalid_backwriting` / `Sp_delete_backwriting` re-route to `Sp_beforeSave_sOpkg` for the same form id on cancel/delete. No xly-src callers.
