IF OBJECT_ID('dbo.sp_Api5_pvtMovCajaEncRedondeoApply','P') IS NOT NULL
    DROP PROCEDURE dbo.sp_Api5_pvtMovCajaEncRedondeoApply;
GO
CREATE PROCEDURE dbo.sp_Api5_pvtMovCajaEncRedondeoApply
    @correlativocierre BIGINT,
    @sucursal          NVARCHAR(20),
    @caja              NVARCHAR(20),
    @login_id          NVARCHAR(150),
    @cajero            INT            = NULL,
    @resetPrevious     BIT            = 1,
    @itemsXml          NVARCHAR(MAX)  = NULL   -- XML opcional
AS
BEGIN
    SET XACT_ABORT ON;

    -- 1) Limpiar redondeos previos si corresponde
    IF @resetPrevious = 1
    BEGIN
        DELETE FROM dbo.pvtMovCajaEnc WITH (ROWLOCK)
         WHERE tipomovimiento = 99
           AND tipo IN (2,3)
           AND correlativocierre = @correlativocierre;
    END

    -- 2) Parsear XML a tabla variable (si viene)
    DECLARE @x XML =
        CASE WHEN @itemsXml IS NULL OR LTRIM(RTRIM(@itemsXml)) = '' THEN NULL
             ELSE TRY_CAST(@itemsXml AS XML) END;

    DECLARE @items TABLE (
        Tipo        INT             NOT NULL,
        Correlativo BIGINT          NULL,
        Monto       DECIMAL(18,2)   NOT NULL
    );

    IF @x IS NOT NULL AND @x.exist('/items/item') = 1
    BEGIN
        INSERT INTO @items (Tipo, Correlativo, Monto)
        SELECT  T.N.value('@tipo','int'),
                NULLIF(T.N.value('@correlativo','bigint'),0),
                ABS(T.N.value('@monto','decimal(18,2)'))
        FROM @x.nodes('/items/item') AS T(N)
        WHERE T.N.value('@tipo','int') IN (2,3)
          AND T.N.exist('@monto') = 1;
    END

    DECLARE @out TABLE (tipo INT, correlativo BIGINT);

    IF EXISTS (SELECT 1 FROM @items)
    BEGIN
        ;WITH maxs AS (
            SELECT tipo, MAX(correlativo) AS maxCorr
            FROM dbo.pvtMovCajaEnc WITH (READCOMMITTEDLOCK)
            WHERE tipo IN (2,3)
            GROUP BY tipo
        ),
        src AS (
            SELECT  i.Tipo,
                    i.Correlativo,
                    i.Monto,
                    ROW_NUMBER() OVER (PARTITION BY i.Tipo ORDER BY (SELECT 1)) AS rn
            FROM @items i
        ),
        norm AS (
            SELECT  s.Tipo,
                    COALESCE(s.Correlativo, ISNULL(m.maxCorr,0) + s.rn) AS correlativo,
                    s.Monto AS monto
            FROM src s
            LEFT JOIN maxs m ON m.tipo = s.Tipo
        )
        -- UPDATE si existe
        UPDATE m
           SET m.tipomovimiento    = 99,
               m.caja              = @caja,
               m.sucursal          = @sucursal,
               m.cajero            = ISNULL(@cajero, ISNULL(m.cajero,0)),
               m.fechainicio       = COALESCE(m.fechainicio, GETDATE()),
               m.montocaja         = 0,
               m.monto             = n.monto,
               m.fechacierre       = NULL,
               m.correlativocierre = @correlativocierre,
               m.comentario        = 'REDONDEO',
               m.estado            = 0,
               m.logmod            = @login_id,
               m.fecmod            = GETDATE()
         OUTPUT inserted.tipo, inserted.correlativo INTO @out(tipo, correlativo)
         FROM dbo.pvtMovCajaEnc m WITH (READCOMMITTEDLOCK)
         INNER JOIN norm n
                 ON n.tipo = m.tipo
                AND n.correlativo = m.correlativo;

        -- INSERT si no existe
        INSERT INTO dbo.pvtMovCajaEnc
        (
            correlativo, tipo, tipomovimiento, caja, sucursal, cajero,
            fechainicio, montocaja, monto, fechacierre, correlativocierre,
            comentario, estado, loging, logmod, fecing, fecmod, unineg, tipdoc, numdoc
        )
        OUTPUT inserted.tipo, inserted.correlativo INTO @out(tipo, correlativo)
        SELECT  n.correlativo, n.tipo, 99, @caja, @sucursal, ISNULL(@cajero,0),
                GETDATE(), 0, n.monto, NULL, @correlativocierre,
                'REDONDEO', 0, @login_id, @login_id, GETDATE(), GETDATE(), NULL, NULL, NULL
        FROM norm n
        WHERE NOT EXISTS (
            SELECT 1
            FROM dbo.pvtMovCajaEnc x WITH (READCOMMITTEDLOCK)
            WHERE x.tipo = n.tipo AND x.correlativo = n.correlativo
        );
    END
    ELSE
    BEGIN
        -- 3) Sin XML: calcula desde pvtPagos (tu lógica original)
        DECLARE @montoEntrada DECIMAL(18,2) = 0,
                @montoSalida  DECIMAL(18,2) = 0,
                @corr2 BIGINT, @corr3 BIGINT;

        SELECT @montoEntrada = ISNULL(SUM(redondeo),0)
          FROM dbo.pvtPagos WITH (READCOMMITTEDLOCK)
         WHERE redondeo > 0 AND idcierre = @correlativocierre;

        SELECT @montoSalida = ABS(ISNULL(SUM(redondeo),0))
          FROM dbo.pvtPagos WITH (READCOMMITTEDLOCK)
         WHERE redondeo < 0 AND idcierre = @correlativocierre;

        IF @montoEntrada <> 0
        BEGIN
            SELECT @corr2 = ISNULL(MAX(correlativo),0) + 1
              FROM dbo.pvtMovCajaEnc WITH (READCOMMITTEDLOCK)
             WHERE tipo = 2;

            INSERT INTO dbo.pvtMovCajaEnc
            (
                correlativo, tipo, tipomovimiento, caja, sucursal, cajero,
                fechainicio, montocaja, monto, fechacierre, correlativocierre,
                comentario, estado, loging, logmod, fecing, fecmod, unineg, tipdoc, numdoc
            )
            OUTPUT inserted.tipo, inserted.correlativo INTO @out(tipo, correlativo)
            VALUES
            (
                @corr2, 2, 99, @caja, @sucursal, ISNULL(@cajero,0),
                GETDATE(), 0, ABS(@montoEntrada), NULL, @correlativocierre,
                'REDONDEO', 0, @login_id, @login_id, GETDATE(), GETDATE(), NULL, NULL, NULL
            );
        END

        IF @montoSalida <> 0
        BEGIN
            SELECT @corr3 = ISNULL(MAX(correlativo),0) + 1
              FROM dbo.pvtMovCajaEnc WITH (READCOMMITTEDLOCK)
             WHERE tipo = 3;

            INSERT INTO dbo.pvtMovCajaEnc
            (
                correlativo, tipo, tipomovimiento, caja, sucursal, cajero,
                fechainicio, montocaja, monto, fechacierre, correlativocierre,
                comentario, estado, loging, logmod, fecing, fecmod, unineg, tipdoc, numdoc
            )
            OUTPUT inserted.tipo, inserted.correlativo INTO @out(tipo, correlativo)
            VALUES
            (
                @corr3, 3, 99, @caja, @sucursal, ISNULL(@cajero,0),
                GETDATE(), 0, ABS(@montoSalida), NULL, @correlativocierre,
                'REDONDEO', 0, @login_id, @login_id, GETDATE(), GETDATE(), NULL, NULL, NULL
            );
        END
    END

    -- 4) *** AQUÍ ESTABA EL ERROR ***  → faltaba el FROM @out
    SELECT
        COUNT(1) AS rowsAffected,
        MAX(CASE WHEN o.tipo = 2 THEN o.correlativo END) AS correlativoEntrada,
        MAX(CASE WHEN o.tipo = 3 THEN o.correlativo END) AS correlativoSalida
    FROM @out AS o;
END
GO
