> ## Documentation Index
> Fetch the complete documentation index at: https://docs.smartpyme.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Crear venta (facturación)

> Crea y procesa una venta usando la lógica de facturación interna.

- Idempotencia: si se envía `referencia_externa` o `referencia` y ya existe una venta con ese valor, devuelve la venta existente (HTTP 200).
- Sucursal: enviar `id_sucursal` o `sucursal` (nombre).
- Productos: en `detalles`, usar `id_producto` o `codigo_producto`.
- Estados permitidos: Pagada, Completada, Pendiente, Cotizacion.
- Máximo 100 líneas por venta.




## OpenAPI

````yaml /openapi.yaml post /sales
openapi: 3.0.0
info:
  title: SmartPYME External API
  description: >
    API Externa de SmartPYME para proveedores terceros.


    Permite consultar y registrar ventas, consultar inventario y devoluciones, e
    importar paquetes usando autenticación por API Key.


    ## Autenticación

    Todas las requests requieren un API Key válido en el header Authorization:

    ```

    Authorization: Bearer {tu_api_key}

    ```


    ## Rate Limiting

    - Sin filtros de fecha: 1000 requests/hora

    - Con filtros de fecha: 2000 requests/hora


    ## Paginación

    Todos los endpoints de lista soportan paginación:

    - `page`: Número de página (default: 1)

    - `per_page`: Registros por página (1-200, default: 100)
  version: 1.4.0
  contact:
    name: SmartPYME Support
    email: soporte@smartpyme.com
  license:
    name: Propietario
    url: https://smartpyme.com/terms
servers:
  - url: https://tu-dominio.com/api/external/v1
    description: Servidor de Producción
  - url: http://localhost/api/external/v1
    description: Servidor de Desarrollo
security:
  - ApiKeyAuth: []
paths:
  /sales:
    post:
      tags:
        - Ventas
      summary: Crear venta (facturación)
      description: >
        Crea y procesa una venta usando la lógica de facturación interna.


        - Idempotencia: si se envía `referencia_externa` o `referencia` y ya
        existe una venta con ese valor, devuelve la venta existente (HTTP 200).

        - Sucursal: enviar `id_sucursal` o `sucursal` (nombre).

        - Productos: en `detalles`, usar `id_producto` o `codigo_producto`.

        - Estados permitidos: Pagada, Completada, Pendiente, Cotizacion.

        - Máximo 100 líneas por venta.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/StoreExternalSaleRequest'
            example:
              referencia_externa: ORD-2025-00042
              fecha: '2025-06-10'
              estado: Pagada
              sucursal: Sucursal Centro
              id_bodega: 1
              id_documento: 5
              id_canal: 2
              forma_pago: Efectivo
              monto_pago: 150.75
              detalles:
                - codigo_producto: PROD-001
                  cantidad: 2
                  precio: 75
      responses:
        '200':
          description: Venta ya existente (idempotencia)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SaleCreateResponse'
        '201':
          description: Venta creada exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SaleCreateResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          description: Error de validación o regla de negocio
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '429':
          $ref: '#/components/responses/RateLimitExceeded'
        '500':
          $ref: '#/components/responses/InternalServerError'
components:
  schemas:
    StoreExternalSaleRequest:
      type: object
      required:
        - fecha
        - estado
        - id_bodega
        - id_documento
        - detalles
      properties:
        referencia_externa:
          type: string
          description: Referencia del sistema externo (idempotencia)
        referencia:
          type: string
          description: Alias de referencia_externa
        fecha:
          type: string
          format: date
        estado:
          type: string
          enum:
            - Pagada
            - Completada
            - Pendiente
            - Cotizacion
        id_sucursal:
          type: integer
          description: Obligatorio si no se envía sucursal
        sucursal:
          type: string
          description: Nombre de sucursal activa. Obligatorio si no se envía id_sucursal
        id_bodega:
          type: integer
        id_documento:
          type: integer
        id_canal:
          type: integer
          description: Obligatorio salvo cotizaciones
        id_cliente:
          type: integer
          description: Obligatorio para ventas Pendiente
        cotizacion:
          type: boolean
        fecha_expiracion:
          type: string
          format: date
        forma_pago:
          type: string
        observaciones:
          type: string
          maxLength: 1000
        monto_pago:
          type: number
          minimum: 0
        cambio:
          type: number
          minimum: 0
        detalles:
          type: array
          minItems: 1
          maxItems: 100
          items:
            $ref: '#/components/schemas/ExternalSaleDetailInput'
    SaleCreateResponse:
      allOf:
        - $ref: '#/components/schemas/BaseResponse'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/Sale'
            meta:
              type: object
              properties:
                empresa:
                  type: string
                timestamp:
                  type: string
                  format: date-time
                idempotent:
                  type: boolean
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          description: Mensaje de error
        code:
          type: integer
          description: Código de error HTTP
      required:
        - success
        - error
        - code
    ExternalSaleDetailInput:
      type: object
      required:
        - cantidad
      properties:
        id:
          type: integer
          description: ID de línea de detalle (solo en actualización)
        id_producto:
          type: integer
          description: ID del producto (obligatorio si no se envía codigo_producto)
        codigo_producto:
          type: string
          description: Código/SKU del producto (obligatorio si no se envía id_producto)
        cantidad:
          type: number
          minimum: 0.0001
        precio:
          type: number
          minimum: 0
          description: Precio unitario con IVA (opcional, usa precio del producto)
        descuento:
          type: number
          minimum: 0
        id_presentacion:
          type: integer
        porcentaje_impuesto:
          type: number
          minimum: 0
          maximum: 100
    BaseResponse:
      type: object
      properties:
        success:
          type: boolean
          description: Indica si la operación fue exitosa
        meta:
          $ref: '#/components/schemas/Meta'
      required:
        - success
    Sale:
      type: object
      properties:
        id:
          type: integer
          example: 12345
        fecha:
          type: string
          format: date
          example: '2025-01-15'
        correlativo:
          type: string
          nullable: true
          example: FAC-001
        referencia:
          type: string
          nullable: true
          example: ORD-2025-00042
        referencia_externa:
          type: string
          nullable: true
          example: ORD-2025-00042
        cotizacion:
          type: boolean
          example: false
        estado:
          type: string
          enum:
            - Completada
            - Pendiente
            - Anulada
            - Cotizacion
          example: Completada
        forma_pago:
          type: string
          nullable: true
          example: Efectivo
        total:
          type: number
          format: float
          example: 150.75
        iva:
          type: number
          format: float
          nullable: true
          example: 13.5
        sub_total:
          type: number
          format: float
          nullable: true
          example: 137.25
        descuento:
          type: number
          format: float
          nullable: true
          example: 0
        nombre_cliente:
          type: string
          nullable: true
          example: Juan Pérez
        nombre_usuario:
          type: string
          nullable: true
          example: Admin User
        nombre_vendedor:
          type: string
          nullable: true
          example: Vendedor 1
        saldo:
          type: number
          format: float
          nullable: true
          example: 0
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        detalles:
          type: array
          items:
            $ref: '#/components/schemas/SaleDetail'
      required:
        - fecha
        - estado
        - total
    ValidationErrorResponse:
      allOf:
        - $ref: '#/components/schemas/ErrorResponse'
        - type: object
          properties:
            details:
              type: object
              description: Detalles de errores de validación
              example:
                fecha_inicio:
                  - El campo fecha inicio debe ser una fecha válida.
                per_page:
                  - El campo per page no puede ser mayor que 200.
    Meta:
      type: object
      properties:
        empresa:
          type: string
          description: Nombre de la empresa
          example: Mi Empresa S.A.
        timestamp:
          type: string
          format: date-time
          description: Timestamp de la respuesta
        filters_applied:
          type: object
          description: Filtros aplicados en la consulta
      required:
        - empresa
        - timestamp
    SaleDetail:
      type: object
      properties:
        descripcion:
          type: string
          nullable: true
          example: Producto A
        cantidad:
          type: number
          format: float
          example: 2
        precio:
          type: number
          format: float
          example: 75
        total:
          type: number
          format: float
          example: 150
        nombre_producto:
          type: string
          nullable: true
          example: Producto A
        codigo:
          type: string
          nullable: true
          example: PROD-001
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
      required:
        - cantidad
        - precio
        - total
  responses:
    BadRequest:
      description: Parámetros inválidos
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ValidationErrorResponse'
    Unauthorized:
      description: API Key inválido o faltante
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            error: API key inválido o empresa inactiva
            code: 401
    RateLimitExceeded:
      description: Rate limit excedido
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            error: >-
              Rate limit excedido. Máximo 1000 requests por hora (2000 con
              filtros de fecha).
            code: 429
    InternalServerError:
      description: Error interno del servidor
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            error: Error interno del servidor
            code: 500
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API Key de la empresa en formato Bearer token.

        Ejemplo: `Authorization: Bearer G8RCjH11DabBNjnX7wO5`

````