Chingaderas
This commit is contained in:
82
BibliotecaDigitalApi/controllers/PrestamosController.cs
Normal file
82
BibliotecaDigitalApi/controllers/PrestamosController.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using BibliotecaAPI.Data;
|
||||
using BibliotecaAPI.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace BibliotecaAPI.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class PrestamosController : ControllerBase
|
||||
{
|
||||
private readonly BibliotecaContext _context;
|
||||
|
||||
public PrestamosController(BibliotecaContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// Crear préstamo
|
||||
[HttpPost("crear")]
|
||||
public async Task<ActionResult<Prestamo>> CrearPrestamo(Prestamo prestamo)
|
||||
{
|
||||
var libro = await _context.Libros.FindAsync(prestamo.LibroId);
|
||||
if (libro == null || libro.CopiasDisponibles <= 0)
|
||||
return BadRequest("Libro no disponible.");
|
||||
|
||||
libro.CopiasDisponibles--;
|
||||
_context.Prestamos.Add(prestamo);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(prestamo);
|
||||
}
|
||||
|
||||
// Registrar devolución
|
||||
[HttpPut("devolver/{id}")]
|
||||
public async Task<IActionResult> RegistrarDevolucion(int id)
|
||||
{
|
||||
var prestamo = await _context.Prestamos.Include(p => p.Libro).FirstOrDefaultAsync(p => p.Id == id);
|
||||
if (prestamo == null) return NotFound();
|
||||
|
||||
prestamo.Devuelto = true;
|
||||
prestamo.FechaDevolucion = DateTime.Now;
|
||||
prestamo.Libro.CopiasDisponibles++;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok("Devolución registrada con éxito.");
|
||||
}
|
||||
|
||||
// Consultar préstamos activos
|
||||
[HttpGet("activos")]
|
||||
public async Task<ActionResult<IEnumerable<Prestamo>>> GetActivos()
|
||||
{
|
||||
return await _context.Prestamos
|
||||
.Include(p => p.Libro)
|
||||
.Include(p => p.Usuario)
|
||||
.Where(p => !p.Devuelto)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
// Consultar préstamos vencidos (más de 15 días)
|
||||
[HttpGet("vencidos")]
|
||||
public async Task<ActionResult<IEnumerable<Prestamo>>> GetVencidos()
|
||||
{
|
||||
var hoy = DateTime.Now;
|
||||
return await _context.Prestamos
|
||||
.Include(p => p.Libro)
|
||||
.Include(p => p.Usuario)
|
||||
.Where(p => !p.Devuelto && (hoy - p.FechaPrestamo).TotalDays > 15)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
// Historial por usuario
|
||||
[HttpGet("historial/{usuarioId}")]
|
||||
public async Task<ActionResult<IEnumerable<Prestamo>>> GetHistorialUsuario(int usuarioId)
|
||||
{
|
||||
return await _context.Prestamos
|
||||
.Include(p => p.Libro)
|
||||
.Where(p => p.UsuarioId == usuarioId)
|
||||
.ToListAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user