MODELS AND CONTROLLERS

This commit is contained in:
MARIFER HERNANDEZ GONZALEZ
2025-10-28 19:40:21 -06:00
parent 7b037ee769
commit e873c3f903
14 changed files with 279 additions and 32 deletions

View File

@@ -1,13 +1,17 @@
using BibliotecaAPI.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
// Activar Swagger para probar endpoints
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
@@ -15,30 +19,7 @@ if (app.Environment.IsDevelopment())
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.UseAuthorization();
app.MapControllers();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

View File

@@ -13,10 +13,10 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("BibliotecaDigitalApi")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+7b037ee7692fed1179b172f2163d0f866cb8e57d")]
[assembly: System.Reflection.AssemblyProductAttribute("BibliotecaDigitalApi")]
[assembly: System.Reflection.AssemblyTitleAttribute("BibliotecaDigitalApi")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
// Generado por la clase WriteCodeFragment de MSBuild.

View File

@@ -1 +1 @@
6ed0a80a11b43174ad50914035db8ef21ed9a2256f21b1d4e57a6b5c8f6a8e18
fe9b27aa300c3789229c7b6b1cb8aa68e1db82d30fd78e439c90942c46816c80

View File

@@ -0,0 +1,17 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute("Microsoft.AspNetCore.OpenApi")]
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartAttribute("Swashbuckle.AspNetCore.SwaggerGen")]
// Generado por la clase WriteCodeFragment de MSBuild.

View File

@@ -0,0 +1 @@
90de409f17a71d4aa851b14ec70bdf8c6d47c7ea53281b0480308c94120b5983

View File

@@ -0,0 +1,7 @@
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.csproj.AssemblyReference.cache
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.GeneratedMSBuildEditorConfig.editorconfig
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.AssemblyInfoInputs.cache
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.AssemblyInfo.cs
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.csproj.CoreCompileInputs.cache
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.MvcApplicationPartsAssemblyInfo.cs
C:\Users\CHIOH\source\repos\BibliotecaDigital\BibliotecaDigitalApi\obj\Debug\net8.0\BibliotecaDigitalApi.MvcApplicationPartsAssemblyInfo.cache

View File

@@ -0,0 +1,14 @@
using Microsoft.EntityFrameworkCore;
using BibliotecaAPI.Models;
namespace BibliotecaAPI.Data
{
public class BibliotecaContext : DbContext
{
public BibliotecaContext(DbContextOptions<BibliotecaContext> options) : base(options) { }
public DbSet<Libro> Libros { get; set; }
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<Prestamo> Prestamos { get; set; }
}
}

16
Models/Libro.cs Normal file
View File

@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace BibliotecaAPI.Models
{
public class Libro
{
[Key]
public int Id { get; set; }
public string Titulo { get; set; } = string.Empty;
public string Autor { get; set; } = string.Empty;
public string ISBN { get; set; } = string.Empty;
public int Año { get; set; }
public string Categoria { get; set; } = string.Empty;
public int CopiasDisponibles { get; set; }
}
}

24
Models/Prestamo.cs Normal file
View File

@@ -0,0 +1,24 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BibliotecaAPI.Models
{
public class Prestamo
{
[Key]
public int Id { get; set; }
[ForeignKey("Usuario")]
public int UsuarioId { get; set; }
public Usuario? Usuario { get; set; }
[ForeignKey("Libro")]
public int LibroId { get; set; }
public Libro? Libro { get; set; }
public DateTime FechaPrestamo { get; set; } = DateTime.Now;
public DateTime? FechaDevolucion { get; set; }
public bool Devuelto { get; set; } = false;
}
}

12
Models/Usuario.cs Normal file
View File

@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace BibliotecaAPI.Models
{
public class Usuario
{
[Key]
public int Id { get; set; }
public string Nombre { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,60 @@
using Microsoft.AspNetCore.Mvc;
using BibliotecaAPI.Data;
using BibliotecaAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace BibliotecaAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LibrosController : ControllerBase
{
private readonly BibliotecaContext _context;
public LibrosController(BibliotecaContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Libro>>> GetLibros()
{
return await _context.Libros.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Libro>> GetLibro(int id)
{
var libro = await _context.Libros.FindAsync(id);
if (libro == null) return NotFound();
return libro;
}
[HttpPost]
public async Task<ActionResult<Libro>> PostLibro(Libro libro)
{
_context.Libros.Add(libro);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetLibro), new { id = libro.Id }, libro);
}
[HttpPut("{id}")]
public async Task<IActionResult> PutLibro(int id, Libro libro)
{
if (id != libro.Id) return BadRequest();
_context.Entry(libro).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteLibro(int id)
{
var libro = await _context.Libros.FindAsync(id);
if (libro == null) return NotFound();
_context.Libros.Remove(libro);
await _context.SaveChangesAsync();
return NoContent();
}
}
}

View 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();
}
}
}

View File

@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
using BibliotecaAPI.Data;
using BibliotecaAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace BibliotecaAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsuariosController : ControllerBase
{
private readonly BibliotecaContext _context;
public UsuariosController(BibliotecaContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Usuario>>> GetUsuarios()
{
return await _context.Usuarios.ToListAsync();
}
[HttpPost]
public async Task<ActionResult<Usuario>> PostUsuario(Usuario usuario)
{
_context.Usuarios.Add(usuario);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetUsuarios), new { id = usuario.Id }, usuario);
}
}
}