ALTER TRIGGER [dbo].[tr_pvtPagos_saldoDocto_Update]
ON [dbo].[pvtPagos]
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    IF EXISTS (
        SELECT 1
        FROM INSERTED i
        JOIN DELETED d ON i.numdoc = d.numdoc AND i.tipdoc = d.tipdoc
        WHERE i.monto <> d.monto
    )
    BEGIN
        DECLARE @PagosAfectados TABLE (
            tipdoc INT,
            numdoc INT,
            montoInsertado DECIMAL(18,4),
            montoEliminado DECIMAL(18,4),
            tipopago INT,
            tippag INT,
            docref1 INT,
            tipref1 INT,
            codsii INT
        )

        INSERT INTO @PagosAfectados (tipdoc, numdoc, montoInsertado, montoEliminado, tipopago, tippag, docref1, tipref1, codsii)
        SELECT
            i.tipdoc,
            i.numdoc,
            i.monto AS montoInsertado,
            d.monto AS montoEliminado,
            i.tipopago,
            f.tippag,
            ve.docref1,
            ve.tipref1,
            ve.codsii
        FROM INSERTED i
        JOIN DELETED d ON i.numdoc = d.numdoc AND i.tipdoc = d.tipdoc
        JOIN cobFormasPago f ON i.tipopago = f.codpag
        JOIN venEncabezado ve ON ve.numinv = i.numdoc AND ve.codsii = i.tipdoc
        WHERE f.tippag = 2 AND i.monto <> d.monto

        -- Notas de crédito
        UPDATE vs
        SET vs.saldo = vs.saldo - pa.montoInsertado
        FROM venSaldoDocumentos vs
        JOIN @PagosAfectados pa ON pa.tipdoc IN (60, 61, 112)
            AND vs.codsii = pa.tipref1
            AND vs.numinv = pa.docref1

        -- Notas de débito
        UPDATE vs
        SET vs.saldo = vs.saldo + pa.montoInsertado
        FROM venSaldoDocumentos vs
        JOIN @PagosAfectados pa ON pa.tipdoc IN (55, 56, 111)
            AND vs.codsii = pa.tipref1
            AND vs.numinv = pa.docref1

        -- Otros documentos
        UPDATE vs
        SET vs.saldo = pa.montoInsertado
        FROM venSaldoDocumentos vs
        JOIN @PagosAfectados pa ON pa.tipdoc NOT IN (55, 56, 60, 61, 111, 112)
            AND vs.codsii = pa.tipdoc
            AND vs.numinv = pa.numdoc
    END
END