# UpdateSalesInvoice

## Permission Scope

salesBilling

## Overview

UpdateSalesInvoice revises mutable draft invoice fields before issue. It supports correction of line composition, customer-facing references, and draft billing metadata.

## Business Rules

- Only DRAFT invoices may be updated directly.
- Updated invoice lines must still satisfy quantity and reference validity rules.
- Each `updateLines` or `removeLineIds` entry must target an existing invoice line.
- In-place line updates preserve the line's id and createdAt.

## Process Flow

```mermaid
flowchart TD
    A[Receive update request] --> B[Load invoice]
    B --> C{Status is DRAFT?}
    C -->|No| D[Return INVOICE_NOT_EDITABLE]
    C -->|Yes| E[Validate changed fields and lines]
    E --> F[Persist updates]
    F --> G[Return updated invoice]
```

## External Dependencies

- [getSalesInvoice](../query/GetSalesInvoice.md) - Load current invoice state before applying changes.

## Error Scenarios

- **SALES_INVOICE_NOT_FOUND**: Referenced sales invoice does not exist
- **INVOICE_NOT_EDITABLE**: Only DRAFT invoices may be updated.
- **INVALID_INVOICE_LINE**: Invoice line content is incomplete or invalid
- **LINE_NOT_FOUND**: Referenced line does not exist on the target document
- **EMPTY_SALES_INVOICE_LINES**: No sales-invoice lines were provided

## Test Cases

- updates draft invoice metadata
- updates a line in place so its id and createdAt survive the edit
- adds an invoice line via addLines
- removes an invoice line via removeLineIds
- returns error when invoice does not exist
- returns error when updating an issued invoice
- returns error when an update targets a missing line
- returns error when a removal would leave the invoice without lines
- returns error when an added line references an invalid sales-order line
