# `Sp_saveReturn_sPiv` (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_sPiv`'`._

## Narrative

**Business context:** 采购管理 → 采购发票 — back-write helper for 采购发票 (`PurPurchaseInvoiceMaster`). When an invoice is saved or cancelled, it re-syncs the invoiced amount back to the matched 采购对账 line, the 采购退货 line, the supplier opening balance, and the 财务调整 record so the invoice→payment chain reflects the new state.

**What it does:** Builds `t_data_temp` with `sSrcSlaveId` aggregates from invoice slaves, then updates `PurPurchaseCheckingSlave`, `purpurchaserejectslave`, `CahSupplyInit`, `CahFinancialAdjust`, and `PurPurchaseInvoiceMaster` (its own audit columns). `iTag=1` excludes the current invoice (before-save / delete); `iTag=2` includes it (after-save / uncancel).

**Invocation:** Wrapped by `Sp_afterSave_sPiv` (iTag=2) and `Sp_beforeSave_sPiv` (iTag=1). On the 采购发票 `gdsmodule` row, `Sp_Check_sPiv` is `sSaveProName` and `Sp_beforeSave_sPiv` is `sSaveProNameBefore`; `Sp_afterSave_sPiv` is reached via `Sp_Invalid_backwriting` on cancel/un-cancel. Note the proc COMMENT reads "保存前反写报价数量" — wording predates a refactor; current body adjusts amounts, not quotation quantities.
