call spQuery_Pagos_CxC(1,1,NULL,NULL, NULL, NULL);

DROP PROCEDURE IF EXISTS spQuery_Pagos_CxC;
CREATE PROCEDURE spQuery_Pagos_CxC(
  varEmpresa    int,
	varCliente    int,
  varFechaIni   date,
	varFechaFin   date,
  varField      varchar(60),
  varOrder      varchar(5)
)
BEGIN
  DECLARE varCadCod, varCadNom, varCadIni, varCadFin, varCadCli  text default '';
  DECLARE varCadOrd TEXT DEFAULT ' ORDER BY CLIENTE, FECHA';
  
  IF IFNULL(varCliente,0) <> 0 THEN
    SET varCadCli = CONCAT(" and P.id_cliente = ", varCliente);  
  END IF;
  
  IF varFechaIni IS NOT NULL THEN
    SET varCadIni = CONCAT(" and P.fecha >= '", varFechaIni, "' ");
  END IF;
  
  IF varFechaFin IS NOT NULL THEN
    SET varCadFin = CONCAT(" and P.fecha <= '", varFechaFin, "' ");
  END IF;
  
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'M._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'M._date_update'
                        ELSE varField
                   END;
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrder is not null and varOrder <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrder, " ");      
    END IF;
  END IF;
  
  SET @sql = CONCAT("select P.id_pago_cxc as CPAG, ",
                    "P.id_cliente as CCLI, C.nombre as CLIENTE, ",
                    "CONCAT(T.abrev,' ', V.nro_serie,'-', V.nro_preimpreso) as DOCUMENTO, ",
                    "P.id_forma_pago as CTIP, TP.nombre as TIPO, P.nro_doc_pago as NPAGO, ",
                    "date_format(P.fecha,'%d/%m/%Y') as FECHA, P.MONTO, ",
                    "date_format(P._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(P._date_update,'%d/%m/%Y %h:%i:%s %p') AS FECHA_MODIFI, ",
                    "UPPER(UN.usuario) as USER_CREADO, ",
                    "UPPER(UU.usuario) as USER_MODIFI ",
                    "from _sv_pago_cxc P ",
                    "inner join _sv_forma_pago TP ON P.id_forma_pago = TP.id_forma_pago ",
                    "inner join _sv_cliente C ON P.id_cliente = C.id_cliente ",
                    "inner join _sv_venta V On P.id_venta = V.id_venta ",
                    "inner join _sv_tipo_doc_venta T ON V.id_tipo_doc = T.id_tipo_doc ",
                    "inner join _sys_usuario UN ON P._user_create = UN.id_usuario ",
                    "inner join _sys_usuario UU ON P._user_update = UU.id_usuario ",
                    "where P._estado = 'A' ",
                    "and P.id_empresa = ", varEmpresa,
                    varCadCli, varCadIni, varCadFin,
                    varCadOrd);
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;