﻿IF OBJECT_ID('dbo.sp_remPagoBancario_Excel_BITAU_ENLINEA', 'P') IS NOT NULL
	DROP PROCEDURE dbo.sp_remPagoBancario_Excel_BITAU_ENLINEA
GO

CREATE PROCEDURE dbo.sp_remPagoBancario_Excel_BITAU_ENLINEA
(
	@fichaini INT = 0,
	@fichafin INT = 99999999,
	@unineg INT = 0,
	@idconcepto INT = 0,
	@periodo INT = 0,
	@mes INT = 0
)
AS

SELECT
	-- RUT con dígito verificador, sin puntos ni guión (así lo trae la plantilla de Itaú)
	CONVERT(VARCHAR(12), T.rut) + UPPER(LTRIM(RTRIM(CONVERT(VARCHAR(1), T.dv))))		AS rutBeneficiario,
	LTRIM(RTRIM(T.apePaterno)) + ' ' + LTRIM(RTRIM(T.apeMaterno)) + ' ' + LTRIM(RTRIM(T.nombres))	AS nombreBeneficiario,
	CONVERT(INT, RM.valor)																AS monto,
	'Abono en Cuenta'																	AS medioPago,
	-- Código SBIF del banco del trabajador (1 Chile, 12 Estado, 39 Itaú, etc.)
	T.banco																				AS codigoBanco,
	-- Tipo de cuenta según la forma de pago de la ficha; por defecto Cuenta Corriente
	CASE
		WHEN FP.descripcion LIKE '%VISTA%'  THEN 'Cuenta Vista'
		WHEN FP.descripcion LIKE '%AHORRO%' THEN 'Cuenta de Ahorro'
		ELSE 'Cuenta Corriente'
	END																					AS tipoCuenta,
	ISNULL(T.numCuenta, '')																AS numeroCuenta,
	ISNULL(T.correoPart, '')															AS email
FROM remTrabajadores T
INNER JOIN remMovimientosRM RM ON T.ficha = RM.ficha
	AND T.periodo = RM.periodo
	AND T.mes = RM.mes
LEFT JOIN remFormasPago FP ON FP.idFormaPago = T.formaPago
WHERE (T.ficha BETWEEN @fichaini AND @fichafin)
AND (T.unidadNegocios = @unineg OR @unineg = 0)
AND RM.tipoConcepto = 'R'
AND RM.idConcepto = @idconcepto
AND T.periodo = @periodo
AND T.mes = @mes
AND T.activo = 1
AND T.formaPago >= 3
AND RM.valor > 0
ORDER BY nombreBeneficiario ASC
GO