ALTER TRIGGER [dbo].[finInsertaSaldoDocumento] 
ON [dbo].[FinPagoDetalle]
AFTER INSERT, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    -- INSERT: Descontar monto del saldo
    IF EXISTS (SELECT * FROM INSERTED)
    BEGIN
        UPDATE CSD
        SET CSD.saldo = CSD.saldo - T.MONTODOCTO
        FROM conSaldoDocumento CSD
        INNER JOIN (
            SELECT I.numdocto, I.tipodocto, I.MONTODOCTO, F.rut
            FROM INSERTED I
            INNER JOIN FinPago F ON F.idpago = I.idpago
        ) AS T
        ON CSD.numdocto = T.numdocto
        AND CSD.tipodocto = T.tipodocto
        AND CSD.rut = T.rut
    END

    -- DELETE: Devolver monto al saldo
    IF EXISTS (SELECT * FROM DELETED)
    BEGIN
        UPDATE CSD
        SET CSD.saldo = CSD.saldo + T.MONTODOCTO
        FROM conSaldoDocumento CSD
        INNER JOIN (
            SELECT D.numdocto, D.tipodocto, D.MONTODOCTO, F.rut
            FROM DELETED D
            INNER JOIN FinPago F ON F.idpago = D.idpago
        ) AS T
        ON CSD.numdocto = T.numdocto
        AND CSD.tipodocto = T.tipodocto
        AND CSD.rut = T.rut
    END
END
