# CreatePurchasePaymentTerm

## Overview

CreatePurchasePaymentTerm creates a new company-scoped supplier payment term in `ACTIVE` status with one or more schedule lines and optional early-payment discount metadata.

## Business Rules

- `companyId`, name, and at least one schedule line are required
- Percentage-based installment lines must total 100 percent
- Schedule lines must not contain negative percentages or negative fixed amounts
- Discount cutoff must occur on or before the generated final due date
- Discount base must be explicitly `GROSS_AMOUNT` or `NET_AMOUNT` when discounting is enabled
- New payment terms are created in `ACTIVE` status

## Process Flow

```mermaid
flowchart TD
    A[Receive create request] --> B{Company exists?}
    B -->|No| C[Return company error]
    B -->|Yes| D{At least one schedule line?}
    D -->|No| E[Return EMPTY_SCHEDULE]
    D -->|Yes| F{Lines valid and percentages balanced?}
    F -->|No| G[Return schedule validation error]
    F -->|Yes| H{Discount metadata valid?}
    H -->|No| I[Return discount validation error]
    H -->|Yes| J[Insert payment term and lines in ACTIVE]
    J --> K[Return created term]
```

## External Dependencies

- [organization::GetCompany](../../../organization/docs/queries/GetCompany.md) - Validate company scope for the new payment term

## Error Scenarios

- **COMPANY_NOT_FOUND**: Referenced company does not exist
- **EMPTY_SCHEDULE**: No payment term schedule lines were provided
- **INVALID_INSTALLMENT_TOTAL**: Percentage-based installment lines do not total 100 percent
- **INVALID_SCHEDULE_LINE**: A schedule line contains a negative percentage or negative fixed amount
- **INVALID_DISCOUNT_CONFIGURATION**: Discount metadata is incomplete or inconsistent with the final due date

## Test Cases

- creates an active payment term with one schedule line
- creates an installment payment term when percentages total 100 percent
- returns error when company does not exist
- returns error when no schedule lines are provided
- returns error when installment percentages do not total 100 percent
- returns error when a schedule line contains a negative amount or percentage
- returns error when discount cutoff is after the final due date
