ALTER PROCEDURE [dbo].[sp_cobPagoDocumentosDel]
@id int,
@banco int,
@serie varchar(20),
@rut int,
@fecha as datetime
AS
declare @tippag int
declare @origen_excedente as int
BEGIN
	SET NOCOUNT ON;
	/****** 
	tippag = 1 , excedente disponible
	tippag = 2, pago realizado con excedentes
	tippag = 0, pago normal
	******/
	(SELECT @tippag = tippag , @origen_excedente = origen_excedente 
	 FROM cobPagoDocumentos 
	 WHERE id = @id )
	IF @tippag = 2 and @origen_excedente = -1
	BEGIN
		IF EXISTS (SELECT 1 
					FROM cobPagoDocumentos 
					WHERE rut = (SELECT rut 
									FROM cobPagoDocumentos 
									WHERE id = @id) 
									AND dv = (SELECT dv 
												FROM cobPagoDocumentos 
												WHERE id = @id) 
												AND tippag = 1  
												AND ndcto = (SELECT ndocumento 
																FROM cobPagoDocumentos 
																WHERE id = @id) 
																AND serie = (SELECT serie 
																				FROM cobPagoDocumentos 
																				WHERE id = @id) 
																				AND banco = (SELECT banco 
																								FROM cobPagoDocumentos 
																								WHERE id = @id) 
																								AND fecha = (SELECT fecha 
																												FROM cobPagoDocumentos 
																												WHERE id = @id)) 
			BEGIN
				UPDATE cobPagoDocumentos  
				SET monto = monto + (SELECT monto 
										FROM cobPagoDocumentos 
										WHERE id = @id) ,tipondcto = tipo 
				WHERE rut = (SELECT rut 
								FROM cobPagoDocumentos 
								WHERE id = @id) 
				AND dv = (SELECT dv 
							FROM cobPagoDocumentos 
							WHERE id = @id) 
				AND tippag = 1  
				AND ndcto = (SELECT ndocumento 
								FROM cobPagoDocumentos 
								WHERE id = @id) 
				AND serie = (SELECT serie 
								FROM cobPagoDocumentos 
								WHERE id = @id) 
				AND banco = (SELECT banco 
								FROM cobPagoDocumentos 
								WHERE id = @id) 
				AND fecha = (SELECT fecha 
								FROM cobPagoDocumentos 
								WHERE id = @id)
				
				DELETE FROM cobPagoDocumentos WHERE id = @id
			END
		ELSE
			BEGIN	
				UPDATE cobPagoDocumentos  
				SET ndcto = ndocumento, tippag = 1 , tipondcto = tipo 
				WHERE id = @id
			END
	END
	ELSE
	BEGIN
		DECLARE @id_anticipo int
		SET @id_anticipo = (SELECT id_anticipo FROM cobPagoDocumentos WHERE id = @id)
		IF @id_anticipo <> 0
			BEGIN
				UPDATE cobAnticipos
				SET
					saldo += (SELECT monto FROM cobPagoDocumentos WHERE id = @id)
				WHERE id_anticipo = @id_anticipo
		END
		IF @banco = -1 AND @serie = -1
		BEGIN
			DELETE FROM cobPagoDocumentos 
			WHERE id = @id
		END
		ELSE
		BEGIN
			DELETE FROM cobPagoDocumentos 
			WHERE serie = @serie 
			AND banco = @banco 
			AND rut = @rut 
			AND fecha = @fecha
		END
	END
END