321 lines
14 KiB
C#
321 lines
14 KiB
C#
using System.Configuration;
|
|
using System.Formats.Asn1;
|
|
using System.Text.Json;
|
|
using AlquilaFacil.Builder;
|
|
using AlquilaFacil.Config;
|
|
using Entidades;
|
|
using Entidades.Dto;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Minio;
|
|
using Minio.DataModel.Args;
|
|
using Modelo;
|
|
|
|
namespace AlquilaFacil.Controllers;
|
|
[ApiController]
|
|
public class VentaController:ControllerBase {
|
|
|
|
[HttpPost("/api/ventas/ejercerOpcionVenta")]
|
|
public IActionResult EjercerOpcionVenta([FromHeader(Name="Auth")]string Auth, [FromQuery]long idcontrato=0) {
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
if (idcontrato <= 0) return BadRequest(new { message = "No pueden hacer cotratos con id 0 o menor"});
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
Contrato? cont = RepositorioVentas.Singleton.ObtenerVentaPorContrato(idcontrato);
|
|
if (cont == null || cont.IdventaNavigation == null) return BadRequest(new { message = "no hay un contrato por esa id"});
|
|
if (cont.Tieneopcionventa == 0) return BadRequest(new { message = "No tiene opcion de venta"});
|
|
if (puedeEjercer(cont) == false) return BadRequest(new { message = "No cumple con los requisitos para ejercer la opcion de compra"});
|
|
|
|
Venta venta = cont.IdventaNavigation;
|
|
venta.IdVendedor = cont.Dnipropietario;
|
|
venta.IdComprador = cont.Dniinquilino;
|
|
venta.Idpropiedad = cont.Idpropiedad;
|
|
venta.Fechainicio = DateTime.Now;
|
|
|
|
bool ret = RepositorioVentas.Singleton.PatchVenta(venta);
|
|
|
|
return ret?
|
|
Ok(new { message = "Se ejercio la opcion de venta"}):
|
|
BadRequest(new { message = "No se pude ejercer la opcion de venta"});
|
|
}
|
|
|
|
[HttpPost("/api/ventas/subirReciboPago")]
|
|
public async Task<IActionResult> SubirRecibo([FromHeader(Name="Auth")]string Auth, [FromForm]IFormFile file, long idventa ) {
|
|
if (String.IsNullOrWhiteSpace(Auth)) return Unauthorized();
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
|
|
if (idventa <=0) return BadRequest(new { message = "Las id 0 o menor no son validas" });
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
Venta? venta = RepositorioVentas.Singleton.ObtenerVentaPorId(idventa);
|
|
if (venta == null) return BadRequest(new { message = "no hay una venta por esa id"});
|
|
|
|
if (cli.Dni !=venta.IdComprador && cli.Dni != venta.IdVendedor) return Unauthorized();
|
|
|
|
if (file == null) return BadRequest(new { message = "Debe subir un archivo." });
|
|
if (file.ContentType != "application/pdf") return BadRequest(new { message = "El archivo debe ser un documento PDF." });
|
|
if (!Path.GetExtension(file.FileName).Equals(".pdf", StringComparison.OrdinalIgnoreCase)) return BadRequest(new { message = "El archivo debe tener la extensión .pdf." });
|
|
|
|
string nuevoNombreArchivo = $"id:{venta.Id}-comprador:{venta.IdComprador}-vendedor:{venta.IdVendedor}-idprop:{venta.Idpropiedad}.pdf";
|
|
bool ret = await subirContrato(file, nuevoNombreArchivo);
|
|
if(ret == false) return BadRequest(new {message = "No se pudo subir el archivo"});
|
|
|
|
ret = RepositorioVentas.Singleton.SetUrlRecibo(venta.Id, nuevoNombreArchivo);
|
|
if (ret == false) return BadRequest(new { message = "no se pudo guardar el nombre del archivo subido"});
|
|
|
|
return Ok(new { message = "Se Subio el Recibo"});
|
|
|
|
}
|
|
private readonly IMinioClient mc;
|
|
public VentaController(IMinioClient minioClient) {
|
|
mc = minioClient;
|
|
if (mc == null){
|
|
MinioConfigcus? mcon = JsonSerializer.Deserialize<MinioConfigcus>(System.IO.File.ReadAllText("./settings.json"))?? null;
|
|
if (mcon == null) throw new Exception();
|
|
|
|
mc = new MinioClient().WithCredentials(mcon.usr, mcon.scrt)
|
|
.WithEndpoint("192.168.1.11:9000")
|
|
.WithSSL(false)
|
|
.Build();
|
|
}
|
|
}
|
|
private async Task<bool> subirContrato(IFormFile f, string flname) {
|
|
try {
|
|
var buck = new BucketExistsArgs().WithBucket("alquilafacil");
|
|
bool encontrado = await mc.BucketExistsAsync(buck).ConfigureAwait(false);
|
|
|
|
if(!encontrado){
|
|
var mb = new MakeBucketArgs().WithBucket("alquilafacil");
|
|
await mc.MakeBucketAsync(mb).ConfigureAwait(false);
|
|
}
|
|
using (var stream = new MemoryStream()){
|
|
await f.CopyToAsync(stream);
|
|
stream.Position=0;
|
|
PutObjectArgs putbj = new PutObjectArgs()
|
|
.WithBucket("alquilafacil")
|
|
.WithObject(flname)
|
|
.WithStreamData(stream)
|
|
.WithContentType("application/pdf")
|
|
.WithObjectSize(stream.Length);
|
|
await mc.PutObjectAsync(putbj);
|
|
}
|
|
return true;
|
|
} catch (Exception e ) {
|
|
Console.Error.WriteLine(e.Message);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
[HttpGet("/api/ventas/verRecibo")]
|
|
public IActionResult verRecibo([FromHeader(Name="Auth")]string Auth, long idventa=0){
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
if (idventa <= 0) return BadRequest(new { message = "No existen ventas validas para la id 0"});
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
Venta? venta = RepositorioVentas.Singleton.ObtenerVentaPorId(idventa);
|
|
if (venta == null) return BadRequest(new { message = "no hay una venta con esa id"});
|
|
if (cli.Dni != venta.IdComprador && cli.Dni != venta.IdVendedor) return Unauthorized();
|
|
|
|
try{
|
|
var memstream = new MemoryStream();
|
|
|
|
var goa = new GetObjectArgs()
|
|
.WithBucket("alquilafacil")
|
|
.WithObject(venta.UrlRecibo)
|
|
.WithCallbackStream(stream => {
|
|
memstream.Position=0;
|
|
stream.CopyTo(memstream);
|
|
});
|
|
|
|
mc.GetObjectAsync(goa).Wait();
|
|
memstream.Position = 0;
|
|
|
|
if (memstream.Length == 0) return BadRequest(new { message = "El archivo está vacío" });
|
|
|
|
return File(memstream, "application/pdf", venta.UrlRecibo);
|
|
|
|
} catch (Exception e){
|
|
Console.Error.WriteLine(e);
|
|
return BadRequest(new { message = "Fallo al intentar obtener el archivo del almacenamiento o este no existe"});
|
|
}
|
|
}
|
|
|
|
|
|
[HttpPost("/api/ventas/propietarioverifica")]
|
|
public IActionResult PropietarioVerifica([FromHeader(Name="Auth")]string Auth, long idventa=0) {
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
if (idventa <= 0) return BadRequest(new { message = "No existen ventas validas para la id 0"});
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
var ventas = RepositorioVentas.Singleton.ObtenerVentaPorId(idventa);
|
|
if (ventas == null) return BadRequest(new { message ="No hay una venta con ese id"});
|
|
if (ventas.IdVendedor != cli.Dni) return Unauthorized();
|
|
|
|
bool ret = RepositorioVentas.Singleton.EfectuarVenta(idventa);
|
|
return ret ? Ok(new { message = "Se traspaso la propiedad"}): BadRequest(new { message = ""});
|
|
}
|
|
|
|
|
|
[HttpGet("/api/venta")]
|
|
public IActionResult ObtenerVenta([FromHeader(Name="Auth")]string Auth, long idventa=0) {
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
if (idventa <= 0) return BadRequest(new { message = "No existen ventas validas para la id 0"});
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
var ventas = RepositorioVentas.Singleton.ObtenerVentaPorId(idventa);
|
|
if (ventas == null) return BadRequest(new { message ="No hay una venta con ese id"});
|
|
if (ventas.IdVendedor !=cli.Dni && ventas.IdComprador != cli.Dni) return Unauthorized();
|
|
|
|
var v = new VentasDtoBuilder()
|
|
.SetId(ventas.Id)
|
|
.SetMonto(ventas.Monto)
|
|
.SetDivisa(ventas.IddivisaNavigation.Signo)
|
|
.SetUbicacion(ventas.IdpropiedadNavigation.Ubicacion)
|
|
.SetNombreVendedor($"{ventas.IdVendedorNavigation.Nombre} {ventas.IdVendedorNavigation.Apellido}")
|
|
.SetIdVendedor(ventas.IdVendedor??0)
|
|
.SetNombreComprador($"{ventas.IdCompradorNavigation.Nombre} {ventas.IdCompradorNavigation.Apellido}")
|
|
.SetIdComprador(ventas.IdComprador??0)
|
|
.SetEstado(ventas.IdestadoNavigation.Descripcion??"")
|
|
.Build();
|
|
|
|
return Ok(new { data = v, iscomprador = (ventas.IdComprador==cli.Dni)?true:false,
|
|
necesitaRecibo = ventas.UrlRecibo==null?true:false});
|
|
}
|
|
|
|
[HttpGet("/api/ventas")]
|
|
public IActionResult ObtenerVentas([FromHeader(Name="Auth")]string Auth) {
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
var ventas = RepositorioVentas.Singleton.ObtenerVentasPorDni(cli.Dni);
|
|
if (ventas == null) return BadRequest(new { message ="no estas involucrado en ninguna venta o compra"});
|
|
|
|
List<VentasDto> lista = new();
|
|
foreach (var i in ventas) {
|
|
var v = new VentasDtoBuilder()
|
|
.SetId(i.Id)
|
|
.SetMonto(i.Monto)
|
|
.SetDivisa(i.IddivisaNavigation.Signo)
|
|
.SetUbicacion(i.IdpropiedadNavigation.Ubicacion)
|
|
.SetNombreVendedor($"{i.IdVendedorNavigation.Nombre} {i.IdVendedorNavigation.Apellido}")
|
|
.SetIdVendedor(i.IdVendedor??0)
|
|
.SetNombreComprador($"{i.IdCompradorNavigation.Nombre} {i.IdCompradorNavigation.Apellido}")
|
|
.SetIdComprador(i.IdComprador??0)
|
|
.SetEstado(i.IdestadoNavigation.Descripcion??"")
|
|
.Build();
|
|
lista.Add(v);
|
|
}
|
|
return Ok(lista);
|
|
}
|
|
|
|
[HttpGet("/api/opcionventa")]
|
|
public IActionResult ObtenerDto([FromHeader(Name="Auth")]string Auth, long idcontrato=0) {
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
if (idcontrato == 0) return BadRequest(new { message = "No existen contatos validos para la id 0"});
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
Contrato? cont = RepositorioVentas.Singleton.ObtenerVentaPorContrato(idcontrato);
|
|
if (cont == null) return BadRequest(new { message = "No hay un contrato por esa id"});
|
|
|
|
var dto = new OpcionVentaDtoBuilder()
|
|
.SetId(cont.Idventa??0)
|
|
.SetMonto(cont.IdventaNavigation.Monto)
|
|
.SetDivisa(cont.IdventaNavigation.IddivisaNavigation.Signo)
|
|
.SetEnOrden(puedeEjercer(cont))
|
|
.SetFueEjercido(cont.IdventaNavigation.Idestado??0)
|
|
.Build();
|
|
|
|
return Ok(dto);
|
|
}
|
|
|
|
private bool puedeEjercer(Contrato c) {
|
|
bool ret = c.Idcanons.All(x => x.Pagado == 1);
|
|
|
|
if (ret) {
|
|
var canonConFechaMasTardia = c.Idcanons.OrderByDescending(x => x.Fecha).FirstOrDefault();
|
|
|
|
if (canonConFechaMasTardia != null && canonConFechaMasTardia.Fecha.Year >= DateTime.Now.Year
|
|
&& canonConFechaMasTardia.Fecha.Month >= DateTime.Now.Month) {
|
|
ret = true;
|
|
}else{
|
|
ret = false;
|
|
}
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
[HttpGet("/api/contrato/tieneopcionventa")]
|
|
public IActionResult TieneOpcionVenta([FromHeader(Name="Auth")]string Auth, long idcontrato=0) {
|
|
var validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Propietario");
|
|
if (validacion1 == false){
|
|
validacion1 = RepositorioGrupos.Singleton.CheckGrupos(Auth, "Inquilino");
|
|
if (validacion1 == false) {
|
|
return Unauthorized();
|
|
}
|
|
}
|
|
|
|
if (idcontrato == 0) return BadRequest(new { message = "No existen contatos validos para la id 0"});
|
|
|
|
Cliente? cli = RepositorioUsuarios.Singleton.ObtenerClientePorToken(Auth);
|
|
if (cli == null) return Unauthorized();
|
|
|
|
Contrato? cont = RepositorioContratos.Singleton.ObtenerContratoPorId(idcontrato);
|
|
if (cont == null) return BadRequest(new { message = "No hay un contrato por esa id"});
|
|
if (cont.Dniinquilino !=cli.Dni && cont.Dnipropietario != cli.Dni) return Unauthorized();
|
|
|
|
return Ok( new { message = cont.Tieneopcionventa});
|
|
}
|
|
} |