Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6ac0ab6125 | |||
|
|
fc6f5fd1de | ||
| 047c1a7ddb | |||
| f7426e16d9 | |||
| 3c2513a567 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -234,6 +234,7 @@ PublishScripts/
|
|||||||
# NuGet v3's project.json files produces more ignorable files
|
# NuGet v3's project.json files produces more ignorable files
|
||||||
*.nuget.props
|
*.nuget.props
|
||||||
*.nuget.targets
|
*.nuget.targets
|
||||||
|
nuget.config
|
||||||
|
|
||||||
# Microsoft Azure Build Output
|
# Microsoft Azure Build Output
|
||||||
csx/
|
csx/
|
||||||
|
|||||||
27
CampusWorkshops.Tests/CampusWorkshops.Tests.csproj
Normal file
27
CampusWorkshops.Tests/CampusWorkshops.Tests.csproj
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.10.0" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||||
|
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.2" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Workshop10-API\Workshop10-API.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
|
||||||
|
// CampusWorkshops.Tests/Registration/RegistrationPolicyTests.cs
|
||||||
|
using System;
|
||||||
|
using CampusWorkshops.Api.Domain.Registration;
|
||||||
|
using CampusWorkshops.Api.Models; // Workshop do seu projeto
|
||||||
|
using Microsoft.Extensions.Time.Testing;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Tests.Registration
|
||||||
|
{
|
||||||
|
public class RegistrationPolicyTests
|
||||||
|
{
|
||||||
|
private static (RegistrationPolicy Policy, FakeTimeProvider Time) BuildSut(DateTimeOffset nowUtc)
|
||||||
|
{
|
||||||
|
var time = new FakeTimeProvider(nowUtc.UtcDateTime);
|
||||||
|
var policy = new RegistrationPolicy(time);
|
||||||
|
return (policy, time);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Workshop W(int capacity, DateTimeOffset startAt)
|
||||||
|
=> new Workshop
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Title = "Qualquer título",
|
||||||
|
StartAt = startAt.UtcDateTime, // se seu StartAt for DateTimeOffset, use .StartAt = startAt
|
||||||
|
EndAt = startAt.UtcDateTime.AddHours(2),
|
||||||
|
Capacity = capacity,
|
||||||
|
IsOnline = true
|
||||||
|
};
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Rejects_When_Window_Closed_At_24h()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 10, startAt: now.AddHours(RegistrationPolicy.CloseWindowLeadHours));
|
||||||
|
var enrolled = 0;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(RegistrationOutcome.Rejected, decision.Outcome);
|
||||||
|
Assert.Contains("Registration window closed.", decision.Reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Accepts_When_Seats_Available()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 10, startAt: now.AddHours(36));
|
||||||
|
var enrolled = 9;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(RegistrationOutcome.Accepted, decision.Outcome);
|
||||||
|
Assert.Contains("Accepted", decision.Reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Rejects_When_Full()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 10, startAt: now.AddHours(36));
|
||||||
|
var enrolled = 10;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(RegistrationOutcome.Rejected, decision.Outcome);
|
||||||
|
Assert.Contains("No seats available.", decision.Reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(30, RegistrationOutcome.Accepted)]
|
||||||
|
[InlineData(24, RegistrationOutcome.Rejected)]
|
||||||
|
[InlineData(10, RegistrationOutcome.Rejected)]
|
||||||
|
public void Window_Rules(int hoursToStart, RegistrationOutcome expected)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = DateTimeOffset.Parse("2025-03-01T12:00:00Z");
|
||||||
|
var (policy, _) = BuildSut(now);
|
||||||
|
var w = W(capacity: 5, startAt: now.AddHours(hoursToStart));
|
||||||
|
var enrolled = 0;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var decision = policy.Decide(w, enrolled);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.Equal(expected, decision.Outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
10
CampusWorkshops.Tests/UnitTest1.cs
Normal file
10
CampusWorkshops.Tests/UnitTest1.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
namespace CampusWorkshops.Tests;
|
||||||
|
|
||||||
|
public class UnitTest1
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Test1()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
|
|
||||||
using CampusWorkshops.Api.Dtos;
|
|
||||||
using CampusWorkshops.Api.Models;
|
|
||||||
using CampusWorkshops.Api.Repositories;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace CampusWorkshops.Api.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/[controller]")]
|
|
||||||
public class WorkshopsController : ControllerBase
|
|
||||||
{
|
|
||||||
private readonly IWorkshopRepository _repo;
|
|
||||||
|
|
||||||
public WorkshopsController(IWorkshopRepository repo) => _repo = repo;
|
|
||||||
|
|
||||||
/// <summary>Lista workshops com filtros opcionais.</summary>
|
|
||||||
[HttpGet]
|
|
||||||
public Task<IActionResult> GetAll([FromQuery] DateTimeOffset? from, [FromQuery] DateTimeOffset? to, [FromQuery] string? q, CancellationToken ct)
|
|
||||||
{
|
|
||||||
// TODO: implementar usando _repo.GetAllAsync e mapear para WorkshopResponse
|
|
||||||
return Task.FromResult<IActionResult>(Ok(Array.Empty<WorkshopResponse>()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Obtém um workshop por Id.</summary>
|
|
||||||
[HttpGet("{id:guid}")]
|
|
||||||
public Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
// TODO: implementar usando _repo.GetByIdAsync
|
|
||||||
return Task.FromResult<IActionResult>(NotFound());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Cria um novo workshop.</summary>
|
|
||||||
[HttpPost]
|
|
||||||
public Task<IActionResult> Create([FromBody] CreateWorkshopRequest body, CancellationToken ct)
|
|
||||||
{
|
|
||||||
// TODO: validar ModelState, regras de negócio e chamar _repo.AddAsync; retornar CreatedAtAction
|
|
||||||
return Task.FromResult<IActionResult>(BadRequest());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
|
|
||||||
namespace CampusWorkshops.Api.Dtos;
|
|
||||||
|
|
||||||
// DTO para criação de Workshop.
|
|
||||||
public record CreateWorkshopRequest(
|
|
||||||
string? Title,
|
|
||||||
string? Description,
|
|
||||||
DateTimeOffset StartAt,
|
|
||||||
DateTimeOffset EndAt,
|
|
||||||
string? Location,
|
|
||||||
int Capacity,
|
|
||||||
bool IsOnline
|
|
||||||
);
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
|
|
||||||
namespace CampusWorkshops.Api.Models;
|
|
||||||
|
|
||||||
// Modelo mínimo para Workshop.Completar as validações
|
|
||||||
// e ajustar os tipos/atributos durante a atividade.
|
|
||||||
public class Workshop
|
|
||||||
{
|
|
||||||
// Identificador único
|
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
|
||||||
|
|
||||||
// TODO: adicionar [Required], [StringLength(120, MinimumLength = 3)]
|
|
||||||
public string? Title { get; set; }
|
|
||||||
|
|
||||||
// TODO: limitar tamanho (ex.: 2000)
|
|
||||||
public string? Description { get; set; }
|
|
||||||
|
|
||||||
// TODO: usar DateTimeOffset com formato ISO 8601
|
|
||||||
public DateTimeOffset StartAt { get; set; }
|
|
||||||
|
|
||||||
public DateTimeOffset EndAt { get; set; }
|
|
||||||
|
|
||||||
// Location deve ser obrigatório se IsOnline == false
|
|
||||||
public string? Location { get; set; }
|
|
||||||
|
|
||||||
// TODO: validar Capacity >= 1
|
|
||||||
public int Capacity { get; set; } = 1;
|
|
||||||
|
|
||||||
public bool IsOnline { get; set; }
|
|
||||||
}
|
|
||||||
56
Program.cs
56
Program.cs
@@ -1,56 +0,0 @@
|
|||||||
// Note: repository implementation removed for workshop exercise (TODOs in project files)
|
|
||||||
using Microsoft.AspNetCore.Diagnostics;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
|
||||||
|
|
||||||
// Add services
|
|
||||||
builder.Services.AddControllers();
|
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
|
||||||
builder.Services.AddSwaggerGen(o =>
|
|
||||||
{
|
|
||||||
o.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
|
|
||||||
{
|
|
||||||
Title = "CampusWorkshops API",
|
|
||||||
Version = "v1",
|
|
||||||
Description = "API para gestão de workshops do campus (MVP in-memory)."
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// DI
|
|
||||||
|
|
||||||
var app = builder.Build();
|
|
||||||
|
|
||||||
// Exception handler that returns RFC7807 ProblemDetails for unhandled errors
|
|
||||||
app.UseExceptionHandler(errApp =>
|
|
||||||
{
|
|
||||||
errApp.Run(async context =>
|
|
||||||
{
|
|
||||||
var feature = context.Features.Get<IExceptionHandlerFeature>();
|
|
||||||
var ex = feature?.Error;
|
|
||||||
|
|
||||||
var pd = new ProblemDetails
|
|
||||||
{
|
|
||||||
Title = "An unexpected error occurred.",
|
|
||||||
Status = StatusCodes.Status500InternalServerError,
|
|
||||||
Detail = app.Environment.IsDevelopment() ? ex?.Message : null
|
|
||||||
};
|
|
||||||
|
|
||||||
context.Response.StatusCode = pd.Status.Value;
|
|
||||||
context.Response.ContentType = "application/problem+json";
|
|
||||||
await context.Response.WriteAsJsonAsync(pd);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
app.UseHttpsRedirection();
|
|
||||||
|
|
||||||
app.UseSwagger();
|
|
||||||
app.UseSwaggerUI(c =>
|
|
||||||
{
|
|
||||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CampusWorkshops API v1");
|
|
||||||
c.RoutePrefix = "swagger"; // serve at /swagger
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapControllers();
|
|
||||||
|
|
||||||
app.Run();
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
|
|
||||||
using CampusWorkshops.Api.Models;
|
|
||||||
|
|
||||||
namespace CampusWorkshops.Api.Repositories;
|
|
||||||
|
|
||||||
// In-memory repository stub
|
|
||||||
public class InMemoryWorkshopRepository : IWorkshopRepository
|
|
||||||
{
|
|
||||||
public InMemoryWorkshopRepository()
|
|
||||||
{
|
|
||||||
// TODO: Adicionar workshops iniciais
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<IReadOnlyList<Workshop>> GetAllAsync(DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct)
|
|
||||||
{
|
|
||||||
// TODO: retornar uma lista filtrada e ordenada por StartAt
|
|
||||||
return Task.FromResult<IReadOnlyList<Workshop>>(Array.Empty<Workshop>());
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
// TODO: buscar por id
|
|
||||||
return Task.FromResult<Workshop?>(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct)
|
|
||||||
{
|
|
||||||
// TODO: adicionar à lista em memória e retornar criado
|
|
||||||
return Task.FromResult(workshop);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<RootNamespace>Workshop10_API</RootNamespace>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
|
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,19 +1,46 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
# Visual Studio Version 17
|
# Visual Studio Version 17
|
||||||
VisualStudioVersion = 17.5.2.0
|
VisualStudioVersion = 17.5.2.0
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Workshop10-API", "Workshop10-API.csproj", "{5106011C-9EE5-2CD0-05A5-164233706862}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Workshop10-API", "Workshop10-API\Workshop10-API.csproj", "{A51E3052-20C8-4154-905F-4AE95A131FB1}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CampusWorkshops.Tests", "CampusWorkshops.Tests\CampusWorkshops.Tests.csproj", "{3327A641-9CFC-40DA-9E4E-0E6BD3390068}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Debug|x64 = Debug|x64
|
||||||
|
Debug|x86 = Debug|x86
|
||||||
Release|Any CPU = Release|Any CPU
|
Release|Any CPU = Release|Any CPU
|
||||||
|
Release|x64 = Release|x64
|
||||||
|
Release|x86 = Release|x86
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
{5106011C-9EE5-2CD0-05A5-164233706862}.Release|Any CPU.Build.0 = Release|Any CPU
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{A51E3052-20C8-4154-905F-4AE95A131FB1}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{3327A641-9CFC-40DA-9E4E-0E6BD3390068}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
57
Workshop10-API/Controllers/AuthController.cs
Normal file
57
Workshop10-API/Controllers/AuthController.cs
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class AuthController : ControllerBase
|
||||||
|
{
|
||||||
|
// Usuários de exemplo (NÃO use plaintext em produção)
|
||||||
|
private static readonly Dictionary<string,(string Password, string[] Roles)> Users = new()
|
||||||
|
{
|
||||||
|
["admin@campus"] = ("admin123", new[] { "Admin", "Instructor" }),
|
||||||
|
["inst@campus"] = ("inst123", new[] { "Instructor" }),
|
||||||
|
["aluno@campus"] = ("aluno123", Array.Empty<string>())
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly IConfiguration _cfg;
|
||||||
|
public AuthController(IConfiguration cfg) => _cfg = cfg;
|
||||||
|
|
||||||
|
public record LoginRequest(string Username, string Password);
|
||||||
|
public record TokenResponse(string AccessToken, DateTime ExpiresAt);
|
||||||
|
|
||||||
|
[HttpPost("login")]
|
||||||
|
[ProducesResponseType(typeof(TokenResponse), 200)]
|
||||||
|
[ProducesResponseType(401)]
|
||||||
|
public IActionResult Login([FromBody] LoginRequest body)
|
||||||
|
{
|
||||||
|
if (!Users.TryGetValue(body.Username, out var u) || u.Password != body.Password)
|
||||||
|
return Unauthorized();
|
||||||
|
|
||||||
|
var jwt = _cfg.GetSection("Jwt");
|
||||||
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt["Key"]!));
|
||||||
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||||
|
|
||||||
|
var claims = new List<Claim>
|
||||||
|
{
|
||||||
|
new(JwtRegisteredClaimNames.Sub, body.Username),
|
||||||
|
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
||||||
|
};
|
||||||
|
claims.AddRange(u.Roles.Select(r => new Claim(ClaimTypes.Role, r)));
|
||||||
|
|
||||||
|
var expires = DateTime.UtcNow.AddHours(2);
|
||||||
|
var token = new JwtSecurityToken(
|
||||||
|
issuer: jwt["Issuer"],
|
||||||
|
audience: jwt["Audience"],
|
||||||
|
claims: claims,
|
||||||
|
expires: expires,
|
||||||
|
signingCredentials: creds
|
||||||
|
);
|
||||||
|
var encoded = new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
|
return Ok(new TokenResponse(encoded, expires));
|
||||||
|
}
|
||||||
|
}
|
||||||
59
Workshop10-API/Controllers/DiDemoController.cs
Normal file
59
Workshop10-API/Controllers/DiDemoController.cs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[AllowAnonymous] // Deixe aberto para facilitar o teste
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DiDemoController : ControllerBase
|
||||||
|
{
|
||||||
|
// Visualiza os IDs por lifetime
|
||||||
|
[HttpGet("lifetimes")]
|
||||||
|
public IActionResult Lifetimes(
|
||||||
|
[FromServices] IRequestIdTransient t1,
|
||||||
|
[FromServices] IRequestIdTransient t2,
|
||||||
|
[FromServices] IRequestIdScoped s1,
|
||||||
|
[FromServices] IRequestIdScoped s2,
|
||||||
|
[FromServices] IRequestIdSingleton g1,
|
||||||
|
[FromServices] IRequestIdSingleton g2)
|
||||||
|
{
|
||||||
|
return Ok(new {
|
||||||
|
transient1 = t1.Id, transient2 = t2.Id, // normalmente diferentes NA MESMA chamada
|
||||||
|
scoped1 = s1.Id, scoped2 = s2.Id, // iguais NA MESMA chamada; mudam entre chamadas
|
||||||
|
singleton1 = g1.Id, singleton2 = g2.Id // sempre iguais
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Demonstra o "cativeiro" do transient dentro de um singleton
|
||||||
|
[HttpGet("captive-transient")]
|
||||||
|
public IActionResult Captive(
|
||||||
|
[FromServices] ReportingSingleton singleton,
|
||||||
|
[FromServices] IPerRequestClock clockTransient)
|
||||||
|
{
|
||||||
|
// clockTransient é Transient: CreatedAt muda entre requisições
|
||||||
|
var transientCreatedAtNow = clockTransient.CreatedAt;
|
||||||
|
|
||||||
|
// GetClockCreatedAt (TODO) deveria retornar o CreatedAt visto pelo singleton
|
||||||
|
DateTimeOffset? singletonClockCreatedAt = null;
|
||||||
|
string? error = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
singletonClockCreatedAt = singleton.GetClockCreatedAt();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
error = $"{ex.GetType().Name}: {ex.Message}";
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(new {
|
||||||
|
transientCreatedAtNow,
|
||||||
|
singletonClockCreatedAt,
|
||||||
|
esperado = "Valores DIFERENTES por requisição",
|
||||||
|
observacao = "Mas como o transient foi resolvido DENTRO do singleton, ele congelou e não muda",
|
||||||
|
todoImplementado = error is null,
|
||||||
|
errorAoChamarSingleton = error
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
221
Workshop10-API/Controllers/WorkshopsController.cs
Normal file
221
Workshop10-API/Controllers/WorkshopsController.cs
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
|
||||||
|
using CampusWorkshops.Api.Dtos;
|
||||||
|
using CampusWorkshops.Api.Models;
|
||||||
|
using CampusWorkshops.Api.Repositories;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class WorkshopsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IWorkshopRepository _repo;
|
||||||
|
|
||||||
|
public WorkshopsController(IWorkshopRepository repo) => _repo = repo;
|
||||||
|
|
||||||
|
/// <summary>Lista workshops com filtros opcionais.</summary>
|
||||||
|
[HttpGet]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> GetAll([FromQuery] DateTimeOffset? from, [FromQuery] DateTimeOffset? to, [FromQuery] string? q, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var workshops = await _repo.GetAllAsync(from, to, q, ct);
|
||||||
|
|
||||||
|
var response = workshops.Select(w => new WorkshopResponse(
|
||||||
|
w.Id,
|
||||||
|
w.Title,
|
||||||
|
w.Description,
|
||||||
|
w.StartAt,
|
||||||
|
w.EndAt,
|
||||||
|
w.Location,
|
||||||
|
w.Capacity,
|
||||||
|
w.IsOnline
|
||||||
|
)).ToList();
|
||||||
|
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Obtém um workshop por Id.</summary>
|
||||||
|
[HttpGet("{id:guid}")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var workshop = await _repo.GetByIdAsync(id, ct);
|
||||||
|
|
||||||
|
if (workshop == null)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
var response = new WorkshopResponse(
|
||||||
|
workshop.Id,
|
||||||
|
workshop.Title,
|
||||||
|
workshop.Description,
|
||||||
|
workshop.StartAt,
|
||||||
|
workshop.EndAt,
|
||||||
|
workshop.Location,
|
||||||
|
workshop.Capacity,
|
||||||
|
workshop.IsOnline
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cria um novo workshop.</summary>
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize(Policy = "CanWriteWorkshops")]
|
||||||
|
public async Task<IActionResult> Create([FromBody] CreateWorkshopRequest body, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
{
|
||||||
|
return BadRequest(ModelState);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validações de negócio
|
||||||
|
if (body.StartAt >= body.EndAt)
|
||||||
|
{
|
||||||
|
return BadRequest("Data de início deve ser anterior à data de fim.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.StartAt < DateTimeOffset.UtcNow)
|
||||||
|
{
|
||||||
|
return BadRequest("Data de início deve ser no futuro.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!body.IsOnline && string.IsNullOrWhiteSpace(body.Location))
|
||||||
|
{
|
||||||
|
return BadRequest("Location é obrigatório para workshops presenciais.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.Capacity < 1)
|
||||||
|
{
|
||||||
|
return BadRequest("Capacidade deve ser pelo menos 1.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var workshop = new Workshop
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Title = body.Title,
|
||||||
|
Description = body.Description,
|
||||||
|
StartAt = body.StartAt,
|
||||||
|
EndAt = body.EndAt,
|
||||||
|
Location = body.Location,
|
||||||
|
Capacity = body.Capacity,
|
||||||
|
IsOnline = body.IsOnline
|
||||||
|
};
|
||||||
|
|
||||||
|
var createdWorkshop = await _repo.AddAsync(workshop, ct);
|
||||||
|
|
||||||
|
var response = new WorkshopResponse(
|
||||||
|
createdWorkshop.Id,
|
||||||
|
createdWorkshop.Title,
|
||||||
|
createdWorkshop.Description,
|
||||||
|
createdWorkshop.StartAt,
|
||||||
|
createdWorkshop.EndAt,
|
||||||
|
createdWorkshop.Location,
|
||||||
|
createdWorkshop.Capacity,
|
||||||
|
createdWorkshop.IsOnline
|
||||||
|
);
|
||||||
|
|
||||||
|
return CreatedAtAction(nameof(GetById), new { id = createdWorkshop.Id }, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Atualiza parcialmente um workshop existente.</summary>
|
||||||
|
[HttpPatch("{id:guid}")]
|
||||||
|
[Authorize(Policy = "CanWriteWorkshops")]
|
||||||
|
|
||||||
|
public async Task<IActionResult> Patch(Guid id, [FromBody] PatchWorkshopRequest body, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
{
|
||||||
|
return BadRequest(ModelState);
|
||||||
|
}
|
||||||
|
|
||||||
|
var existingWorkshop = await _repo.GetByIdAsync(id, ct);
|
||||||
|
if (existingWorkshop == null)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aplicar apenas os campos fornecidos
|
||||||
|
if (body.Title != null)
|
||||||
|
existingWorkshop.Title = body.Title;
|
||||||
|
|
||||||
|
if (body.Description != null)
|
||||||
|
existingWorkshop.Description = body.Description;
|
||||||
|
|
||||||
|
if (body.StartAt.HasValue)
|
||||||
|
{
|
||||||
|
if (body.StartAt.Value < DateTimeOffset.UtcNow)
|
||||||
|
{
|
||||||
|
return BadRequest("Data de início deve ser no futuro.");
|
||||||
|
}
|
||||||
|
existingWorkshop.StartAt = body.StartAt.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.EndAt.HasValue)
|
||||||
|
existingWorkshop.EndAt = body.EndAt.Value;
|
||||||
|
|
||||||
|
if (body.Location != null)
|
||||||
|
existingWorkshop.Location = body.Location;
|
||||||
|
|
||||||
|
if (body.Capacity.HasValue)
|
||||||
|
{
|
||||||
|
if (body.Capacity.Value < 1)
|
||||||
|
{
|
||||||
|
return BadRequest("Capacidade deve ser pelo menos 1.");
|
||||||
|
}
|
||||||
|
existingWorkshop.Capacity = body.Capacity.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.IsOnline.HasValue)
|
||||||
|
existingWorkshop.IsOnline = body.IsOnline.Value;
|
||||||
|
|
||||||
|
// Validações de negócio após aplicar mudanças
|
||||||
|
if (existingWorkshop.StartAt >= existingWorkshop.EndAt)
|
||||||
|
{
|
||||||
|
return BadRequest("Data de início deve ser anterior à data de fim.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!existingWorkshop.IsOnline && string.IsNullOrWhiteSpace(existingWorkshop.Location))
|
||||||
|
{
|
||||||
|
return BadRequest("Location é obrigatório para workshops presenciais.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var updatedWorkshop = await _repo.UpdateAsync(existingWorkshop, ct);
|
||||||
|
if (updatedWorkshop == null)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
var response = new WorkshopResponse(
|
||||||
|
updatedWorkshop.Id,
|
||||||
|
updatedWorkshop.Title,
|
||||||
|
updatedWorkshop.Description,
|
||||||
|
updatedWorkshop.StartAt,
|
||||||
|
updatedWorkshop.EndAt,
|
||||||
|
updatedWorkshop.Location,
|
||||||
|
updatedWorkshop.Capacity,
|
||||||
|
updatedWorkshop.IsOnline
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Remove um workshop.</summary>
|
||||||
|
[HttpDelete("{id:guid}")]
|
||||||
|
[Authorize(Policy = "CanDeleteWorkshops")]
|
||||||
|
|
||||||
|
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var workshop = await _repo.GetByIdAsync(id, ct);
|
||||||
|
if (workshop == null)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
await _repo.DeleteAsync(id, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using CampusWorkshops.Api.Models; // <-- Workshop do seu projeto
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Domain.Registration
|
||||||
|
{
|
||||||
|
public enum RegistrationOutcome { Accepted, Rejected }
|
||||||
|
|
||||||
|
public sealed record RegistrationDecision(RegistrationOutcome Outcome, IReadOnlyList<string> Reasons);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Regra simples de registro para Workshop.
|
||||||
|
/// Regras:
|
||||||
|
/// - Janela fecha quando faltar <= 24h para o StartAt.
|
||||||
|
/// - Se há assentos (Capacity - enrolled > 0) → Accepted; senão → Rejected.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RegistrationPolicy
|
||||||
|
{
|
||||||
|
public const int CloseWindowLeadHours = 24;
|
||||||
|
|
||||||
|
private readonly TimeProvider _time;
|
||||||
|
|
||||||
|
public RegistrationPolicy(TimeProvider time)
|
||||||
|
{
|
||||||
|
_time = time ?? throw new ArgumentNullException(nameof(time));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decide usando apenas o Workshop e o número ATUAL de inscritos (enrolled).
|
||||||
|
/// </summary>
|
||||||
|
public RegistrationDecision Decide(Workshop w, int enrolled)
|
||||||
|
{
|
||||||
|
if (w is null) throw new ArgumentNullException(nameof(w));
|
||||||
|
var reasons = new List<string>();
|
||||||
|
|
||||||
|
// (1) Janela de inscrição
|
||||||
|
var now = _time.GetUtcNow();
|
||||||
|
// Se StartAt for DateTime (não Offset) no seu modelo, troque por:
|
||||||
|
// var startAtUtc = DateTime.SpecifyKind(w.StartAt, DateTimeKind.Utc);
|
||||||
|
// if (startAtUtc - now <= TimeSpan.FromHours(CloseWindowLeadHours)) { ... }
|
||||||
|
if (w.StartAt - now <= TimeSpan.FromHours(CloseWindowLeadHours))
|
||||||
|
{
|
||||||
|
reasons.Add("Registration window closed.");
|
||||||
|
return new RegistrationDecision(RegistrationOutcome.Rejected, reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
// (2) Capacidade
|
||||||
|
var seatsLeft = w.Capacity - enrolled;
|
||||||
|
if (seatsLeft > 0)
|
||||||
|
{
|
||||||
|
reasons.Add("Accepted");
|
||||||
|
return new RegistrationDecision(RegistrationOutcome.Accepted, reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
reasons.Add("No seats available.");
|
||||||
|
return new RegistrationDecision(RegistrationOutcome.Rejected, reasons);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
28
Workshop10-API/Dtos/CreateWorkshopRequest.cs
Normal file
28
Workshop10-API/Dtos/CreateWorkshopRequest.cs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Dtos;
|
||||||
|
|
||||||
|
// DTO para criação de Workshop com validações
|
||||||
|
public record CreateWorkshopRequest(
|
||||||
|
[Required(ErrorMessage = "Título é obrigatório")]
|
||||||
|
[StringLength(120, MinimumLength = 3, ErrorMessage = "Título deve ter entre 3 e 120 caracteres")]
|
||||||
|
string Title,
|
||||||
|
|
||||||
|
[StringLength(2000, ErrorMessage = "Descrição não pode exceder 2000 caracteres")]
|
||||||
|
string? Description,
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Data de início é obrigatória")]
|
||||||
|
DateTimeOffset StartAt,
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Data de fim é obrigatória")]
|
||||||
|
DateTimeOffset EndAt,
|
||||||
|
|
||||||
|
[StringLength(200, ErrorMessage = "Localização não pode exceder 200 caracteres")]
|
||||||
|
string? Location,
|
||||||
|
|
||||||
|
[Range(1, 1000, ErrorMessage = "Capacidade deve estar entre 1 e 1000")]
|
||||||
|
int Capacity,
|
||||||
|
|
||||||
|
bool IsOnline
|
||||||
|
);
|
||||||
23
Workshop10-API/Dtos/PatchWorkshopRequest.cs
Normal file
23
Workshop10-API/Dtos/PatchWorkshopRequest.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Dtos;
|
||||||
|
|
||||||
|
// DTO para atualização parcial de Workshop.
|
||||||
|
public record PatchWorkshopRequest(
|
||||||
|
[StringLength(120, MinimumLength = 3, ErrorMessage = "Título deve ter entre 3 e 120 caracteres")]
|
||||||
|
string? Title,
|
||||||
|
|
||||||
|
[StringLength(2000, ErrorMessage = "Descrição não pode exceder 2000 caracteres")]
|
||||||
|
string? Description,
|
||||||
|
|
||||||
|
DateTimeOffset? StartAt,
|
||||||
|
DateTimeOffset? EndAt,
|
||||||
|
|
||||||
|
[StringLength(200, ErrorMessage = "Localização não pode exceder 200 caracteres")]
|
||||||
|
string? Location,
|
||||||
|
|
||||||
|
[Range(1, 1000, ErrorMessage = "Capacidade deve estar entre 1 e 1000")]
|
||||||
|
int? Capacity,
|
||||||
|
|
||||||
|
bool? IsOnline
|
||||||
|
);
|
||||||
25
Workshop10-API/Infraestructure/Data/WorkshopDBContext.cs
Normal file
25
Workshop10-API/Infraestructure/Data/WorkshopDBContext.cs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using CampusWorkshops.Api.Models;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Infrastructure.Data;
|
||||||
|
|
||||||
|
public class WorkshopsDbContext : DbContext
|
||||||
|
{
|
||||||
|
public WorkshopsDbContext(DbContextOptions<WorkshopsDbContext> options) : base(options) {}
|
||||||
|
|
||||||
|
public DbSet<Workshop> Workshops => Set<Workshop>();
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
modelBuilder.Entity<Workshop>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("Workshops");
|
||||||
|
e.HasKey(w => w.Id);
|
||||||
|
e.Property(w => w.Title).IsRequired().HasMaxLength(120);
|
||||||
|
e.Property(w => w.Description).HasMaxLength(2000);
|
||||||
|
e.Property(w => w.Location).HasMaxLength(200);
|
||||||
|
e.Property(w => w.Capacity).HasDefaultValue(1);
|
||||||
|
e.HasIndex(w => w.StartAt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
65
Workshop10-API/Migrations/20250903175616_InitialCreate.Designer.cs
generated
Normal file
65
Workshop10-API/Migrations/20250903175616_InitialCreate.Designer.cs
generated
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using CampusWorkshops.Api.Infrastructure.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Workshop10_API.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(WorkshopsDbContext))]
|
||||||
|
[Migration("20250903175616_InitialCreate")]
|
||||||
|
partial class InitialCreate
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "9.0.8");
|
||||||
|
|
||||||
|
modelBuilder.Entity("CampusWorkshops.Api.Models.Workshop", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int>("Capacity")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER")
|
||||||
|
.HasDefaultValue(1);
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasMaxLength(2000)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("EndAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("IsOnline")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Location")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("StartAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Title")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(120)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("StartAt");
|
||||||
|
|
||||||
|
b.ToTable("Workshops", (string)null);
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
45
Workshop10-API/Migrations/20250903175616_InitialCreate.cs
Normal file
45
Workshop10-API/Migrations/20250903175616_InitialCreate.cs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Workshop10_API.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class InitialCreate : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Workshops",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||||
|
Title = table.Column<string>(type: "TEXT", maxLength: 120, nullable: false),
|
||||||
|
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
|
||||||
|
StartAt = table.Column<DateTimeOffset>(type: "TEXT", nullable: false),
|
||||||
|
EndAt = table.Column<DateTimeOffset>(type: "TEXT", nullable: false),
|
||||||
|
Location = table.Column<string>(type: "TEXT", maxLength: 200, nullable: true),
|
||||||
|
Capacity = table.Column<int>(type: "INTEGER", nullable: false, defaultValue: 1),
|
||||||
|
IsOnline = table.Column<bool>(type: "INTEGER", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Workshops", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Workshops_StartAt",
|
||||||
|
table: "Workshops",
|
||||||
|
column: "StartAt");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Workshops");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
62
Workshop10-API/Migrations/WorkshopsDbContextModelSnapshot.cs
Normal file
62
Workshop10-API/Migrations/WorkshopsDbContextModelSnapshot.cs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using CampusWorkshops.Api.Infrastructure.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Workshop10_API.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(WorkshopsDbContext))]
|
||||||
|
partial class WorkshopsDbContextModelSnapshot : ModelSnapshot
|
||||||
|
{
|
||||||
|
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "9.0.8");
|
||||||
|
|
||||||
|
modelBuilder.Entity("CampusWorkshops.Api.Models.Workshop", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int>("Capacity")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER")
|
||||||
|
.HasDefaultValue(1);
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasMaxLength(2000)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("EndAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("IsOnline")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Location")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("StartAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Title")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(120)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("StartAt");
|
||||||
|
|
||||||
|
b.ToTable("Workshops", (string)null);
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
33
Workshop10-API/Models/Workshop.cs
Normal file
33
Workshop10-API/Models/Workshop.cs
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Models;
|
||||||
|
|
||||||
|
// Modelo mínimo para Workshop com validações
|
||||||
|
public class Workshop
|
||||||
|
{
|
||||||
|
// Identificador único
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Título é obrigatório")]
|
||||||
|
[StringLength(120, MinimumLength = 3, ErrorMessage = "Título deve ter entre 3 e 120 caracteres")]
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
[StringLength(2000, ErrorMessage = "Descrição não pode exceder 2000 caracteres")]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Data de início é obrigatória")]
|
||||||
|
public DateTimeOffset StartAt { get; set; }
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Data de fim é obrigatória")]
|
||||||
|
public DateTimeOffset EndAt { get; set; }
|
||||||
|
|
||||||
|
// Location deve ser obrigatório se IsOnline == false (validado no controller)
|
||||||
|
[StringLength(200, ErrorMessage = "Localização não pode exceder 200 caracteres")]
|
||||||
|
public string? Location { get; set; }
|
||||||
|
|
||||||
|
[Range(1, 1000, ErrorMessage = "Capacidade deve estar entre 1 e 1000")]
|
||||||
|
public int Capacity { get; set; } = 1;
|
||||||
|
|
||||||
|
public bool IsOnline { get; set; }
|
||||||
|
}
|
||||||
164
Workshop10-API/Program.cs
Normal file
164
Workshop10-API/Program.cs
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
// Note: repository implementation removed for workshop exercise (TODOs in project files)
|
||||||
|
using Microsoft.AspNetCore.Diagnostics;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using CampusWorkshops.Api.Repositories;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using CampusWorkshops.Api.Infrastructure.Data;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Microsoft.OpenApi.Models;
|
||||||
|
using CampusWorkshops.Api.Services;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using CampusWorkshops.Api.Domain.Registration;
|
||||||
|
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
// JWT
|
||||||
|
var jwt = builder.Configuration.GetSection("Jwt");
|
||||||
|
var keyBytes = Encoding.UTF8.GetBytes(jwt["Key"]!);
|
||||||
|
|
||||||
|
builder.Services
|
||||||
|
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||||
|
.AddJwtBearer(options =>
|
||||||
|
{
|
||||||
|
options.TokenValidationParameters = new()
|
||||||
|
{
|
||||||
|
ValidateIssuer = true,
|
||||||
|
ValidateAudience = true,
|
||||||
|
ValidateIssuerSigningKey = true,
|
||||||
|
ValidIssuer = jwt["Issuer"],
|
||||||
|
ValidAudience = jwt["Audience"],
|
||||||
|
IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
|
||||||
|
ClockSkew = TimeSpan.FromMinutes(1) // previsível para testes
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddAuthorization();
|
||||||
|
|
||||||
|
builder.Services.AddAuthorization(options =>
|
||||||
|
{
|
||||||
|
options.AddPolicy("CanWriteWorkshops", p => p.RequireRole("Instructor","Admin"));
|
||||||
|
options.AddPolicy("CanDeleteWorkshops", p => p.RequireRole("Admin"));
|
||||||
|
options.AddPolicy("CanViewAnalytics", p => p.RequireRole("Admin"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add services
|
||||||
|
builder.Services.AddDbContext<WorkshopsDbContext>(options =>
|
||||||
|
options.UseSqlite(builder.Configuration.GetConnectionString("WorkshopsDb")));
|
||||||
|
|
||||||
|
builder.Services.AddMemoryCache();
|
||||||
|
builder.Services.Configure<CacheSettings>(builder.Configuration.GetSection("Cache"));
|
||||||
|
|
||||||
|
|
||||||
|
// Primeiro registramos a implementação EF concreta
|
||||||
|
builder.Services.AddScoped<EfWorkshopRepository>();
|
||||||
|
|
||||||
|
// tempo do sistema para produção:
|
||||||
|
builder.Services.AddSingleton<TimeProvider>(TimeProvider.System);
|
||||||
|
// regra de domínio (stateless); pode ser Singleton
|
||||||
|
builder.Services.AddSingleton<RegistrationPolicy>();
|
||||||
|
|
||||||
|
// Depois expomos IWorkshopRepository como o "EF envelopado por cache"
|
||||||
|
builder.Services.AddScoped<IWorkshopRepository>(sp =>
|
||||||
|
new CachedWorkshopRepository(
|
||||||
|
sp.GetRequiredService<EfWorkshopRepository>(),
|
||||||
|
sp.GetRequiredService<IMemoryCache>(),
|
||||||
|
sp.GetRequiredService<IOptionsSnapshot<CacheSettings>>()));
|
||||||
|
|
||||||
|
// Lifetimes de exemplo
|
||||||
|
builder.Services.AddTransient<IRequestIdTransient, RequestIdTransient>();
|
||||||
|
builder.Services.AddScoped<IRequestIdScoped, RequestIdScoped>();
|
||||||
|
builder.Services.AddSingleton<IRequestIdSingleton, RequestIdSingleton>();
|
||||||
|
|
||||||
|
// Exemplo de "captive dependency"
|
||||||
|
builder.Services.AddTransient<IPerRequestClock, PerRequestClock>(); // Transient
|
||||||
|
builder.Services.AddSingleton<ReportingSingleton>();
|
||||||
|
|
||||||
|
|
||||||
|
// Removendo para ativar o cached repository
|
||||||
|
// builder.Services.AddScoped<IWorkshopRepository, EfWorkshopRepository>();
|
||||||
|
builder.Services.AddControllers();
|
||||||
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
|
builder.Services.AddSwaggerGen(o =>
|
||||||
|
{
|
||||||
|
o.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
|
||||||
|
{
|
||||||
|
Title = "CampusWorkshops API",
|
||||||
|
Version = "v1",
|
||||||
|
Description = "API para gestão de workshops do campus (MVP in-memory)."
|
||||||
|
});
|
||||||
|
var bearerScheme = new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Name = "Authorization",
|
||||||
|
Description = "Cole apenas o JWT (sem 'Bearer ').",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
Type = SecuritySchemeType.Http, // <- IMPORTANTE
|
||||||
|
Scheme = "bearer", // <- minúsculo
|
||||||
|
BearerFormat = "JWT",
|
||||||
|
Reference = new OpenApiReference // <- garante que o requirement aponte para esta definição
|
||||||
|
{
|
||||||
|
Type = ReferenceType.SecurityScheme,
|
||||||
|
Id = "Bearer"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
o.AddSecurityDefinition("Bearer", bearerScheme);
|
||||||
|
|
||||||
|
o.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||||
|
{
|
||||||
|
{
|
||||||
|
new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Reference = new OpenApiReference
|
||||||
|
{
|
||||||
|
Type = ReferenceType.SecurityScheme,
|
||||||
|
Id = "Bearer"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Array.Empty<string>()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// DI
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
// Exception handler that returns RFC7807 ProblemDetails for unhandled errors
|
||||||
|
app.UseExceptionHandler(errApp =>
|
||||||
|
{
|
||||||
|
errApp.Run(async context =>
|
||||||
|
{
|
||||||
|
var feature = context.Features.Get<IExceptionHandlerFeature>();
|
||||||
|
var ex = feature?.Error;
|
||||||
|
|
||||||
|
var pd = new ProblemDetails
|
||||||
|
{
|
||||||
|
Title = "An unexpected error occurred.",
|
||||||
|
Status = StatusCodes.Status500InternalServerError,
|
||||||
|
Detail = app.Environment.IsDevelopment() ? ex?.Message : null
|
||||||
|
};
|
||||||
|
|
||||||
|
context.Response.StatusCode = pd.Status.Value;
|
||||||
|
context.Response.ContentType = "application/problem+json";
|
||||||
|
await context.Response.WriteAsJsonAsync(pd);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
|
app.UseAuthentication(); // <-- antes
|
||||||
|
app.UseAuthorization(); // <-- depois
|
||||||
|
|
||||||
|
app.UseSwagger();
|
||||||
|
app.UseSwaggerUI(c =>
|
||||||
|
{
|
||||||
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CampusWorkshops API v1");
|
||||||
|
c.RoutePrefix = "swagger"; // serve at /swagger
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapControllers();
|
||||||
|
|
||||||
|
app.Run();
|
||||||
82
Workshop10-API/Repositories/CachedWorkshopRepository.cs
Normal file
82
Workshop10-API/Repositories/CachedWorkshopRepository.cs
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
using CampusWorkshops.Api.Models;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Repositories;
|
||||||
|
|
||||||
|
public sealed class CachedWorkshopRepository : IWorkshopRepository
|
||||||
|
{
|
||||||
|
private readonly IWorkshopRepository _inner;
|
||||||
|
private readonly IMemoryCache _cache;
|
||||||
|
private readonly TimeSpan _ttl;
|
||||||
|
|
||||||
|
public CachedWorkshopRepository(
|
||||||
|
IWorkshopRepository inner,
|
||||||
|
IMemoryCache cache,
|
||||||
|
IOptionsSnapshot<CampusWorkshops.Api.Services.CacheSettings> opts)
|
||||||
|
{
|
||||||
|
_inner = inner;
|
||||||
|
_cache = cache;
|
||||||
|
_ttl = TimeSpan.FromSeconds(opts.Value.DefaultTtlSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string KeyById(Guid id) => $"workshops:byId:{id}";
|
||||||
|
private static string KeyList(DateTimeOffset? from, DateTimeOffset? to, string? q)
|
||||||
|
=> $"workshops:list:{from?.ToUnixTimeSeconds()}:{to?.ToUnixTimeSeconds()}:{q?.Trim().ToLowerInvariant()}";
|
||||||
|
public async Task<IReadOnlyList<Workshop>> GetAllAsync(
|
||||||
|
DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct)
|
||||||
|
{
|
||||||
|
// Implementação final
|
||||||
|
var key = KeyList(from, to, q);
|
||||||
|
if (_cache.TryGetValue(key, out IReadOnlyList<Workshop>? cached) && cached is not null)
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var data = await _inner.GetAllAsync(from, to, q, ct);
|
||||||
|
_cache.Set(key, data, _ttl);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var key = KeyById(id);
|
||||||
|
if (_cache.TryGetValue(key, out Workshop? cached) && cached is not null)
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var w = await _inner.GetByIdAsync(id, ct);
|
||||||
|
if (w is not null) _cache.Set(key, w, _ttl);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ações de escrita: apenas encaminham e limpam entradas simples
|
||||||
|
public async Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _inner.AddAsync(workshop, ct);
|
||||||
|
_cache.Remove(KeyById(w.Id));
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Workshop?> UpdateAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _inner.UpdateAsync(workshop, ct);
|
||||||
|
if (w is not null) _cache.Remove(KeyById(w.Id));
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var ok = await _inner.DeleteAsync(id, ct);
|
||||||
|
if (ok) _cache.Remove(KeyById(id));
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> ExistsAsync(Guid id, CancellationToken ct)
|
||||||
|
=> _inner.ExistsAsync(id, ct);
|
||||||
|
|
||||||
|
public async Task<Workshop?> UpdatePartialAsync(Guid id, Action<Workshop> updateAction, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _inner.UpdatePartialAsync(id, updateAction, ct);
|
||||||
|
if (w is not null) _cache.Remove(KeyById(w.Id));
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
}
|
||||||
71
Workshop10-API/Repositories/EfWorkshopRepository.cs
Normal file
71
Workshop10-API/Repositories/EfWorkshopRepository.cs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
using CampusWorkshops.Api.Models;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using CampusWorkshops.Api.Infrastructure.Data;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Repositories;
|
||||||
|
|
||||||
|
public class EfWorkshopRepository : IWorkshopRepository
|
||||||
|
{
|
||||||
|
private readonly WorkshopsDbContext _db;
|
||||||
|
public EfWorkshopRepository(WorkshopsDbContext db) => _db = db;
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<Workshop>> GetAllAsync(DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var query = _db.Workshops.AsNoTracking().AsQueryable();
|
||||||
|
if (from.HasValue)
|
||||||
|
{
|
||||||
|
query = query.Where(w => w.StartAt >= from.Value);
|
||||||
|
}
|
||||||
|
if (to.HasValue)
|
||||||
|
{
|
||||||
|
query = query.Where(w => w.EndAt >= to.Value);
|
||||||
|
}
|
||||||
|
if (!string.IsNullOrWhiteSpace(q))
|
||||||
|
{
|
||||||
|
var termo = q.ToLowerInvariant();
|
||||||
|
query = query.Where(w => w.Title.Contains(termo)|| w.Description.Contains(termo));
|
||||||
|
}
|
||||||
|
Console.WriteLine(query.ToQueryString());
|
||||||
|
return await query.ToListAsync(ct);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct)
|
||||||
|
=> await _db.Workshops.AsNoTracking().FirstOrDefaultAsync(w => w.Id == id, ct);
|
||||||
|
|
||||||
|
public async Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
_db.Workshops.Add(workshop);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
return workshop;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Workshop?> UpdateAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
_db.Workshops.Update(workshop);
|
||||||
|
await _db.SaveChangesAsync(ct);
|
||||||
|
return workshop;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var encontrado = await _db.Workshops.FindAsync([id]);
|
||||||
|
if (encontrado == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_db.Workshops.Remove(encontrado);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> ExistsAsync(Guid id, CancellationToken ct)
|
||||||
|
=> _db.Workshops.AnyAsync(w => w.Id == id, ct);
|
||||||
|
|
||||||
|
public async Task<Workshop?> UpdatePartialAsync(Guid id, Action<Workshop> updateAction, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var w = await _db.Workshops.FirstOrDefaultAsync(x => x.Id == id, ct);
|
||||||
|
// TODO: implementar o UpdatePartial
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,4 +9,8 @@ public interface IWorkshopRepository
|
|||||||
Task<IReadOnlyList<Workshop>> GetAllAsync(DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct);
|
Task<IReadOnlyList<Workshop>> GetAllAsync(DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct);
|
||||||
Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct);
|
Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct);
|
||||||
Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct);
|
Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct);
|
||||||
|
Task<Workshop?> UpdateAsync(Workshop workshop, CancellationToken ct);
|
||||||
|
Task<bool> DeleteAsync(Guid id, CancellationToken ct);
|
||||||
|
Task<bool> ExistsAsync(Guid id, CancellationToken ct);
|
||||||
|
Task<Workshop?> UpdatePartialAsync(Guid id, Action<Workshop> updateAction, CancellationToken ct);
|
||||||
}
|
}
|
||||||
220
Workshop10-API/Repositories/InMemoryWorkshopRepository.cs
Normal file
220
Workshop10-API/Repositories/InMemoryWorkshopRepository.cs
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
|
||||||
|
using CampusWorkshops.Api.Models;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Repositories;
|
||||||
|
|
||||||
|
// In-memory repository stub
|
||||||
|
public class InMemoryWorkshopRepository : IWorkshopRepository
|
||||||
|
{
|
||||||
|
List<Workshop> _workshops = new();
|
||||||
|
|
||||||
|
private void Seed()
|
||||||
|
{
|
||||||
|
// Base de datas: sempre a partir da próxima semana, para não “envelhecer” o seed
|
||||||
|
var baseDate = DateTimeOffset.UtcNow.Date.AddDays(7);
|
||||||
|
|
||||||
|
var w1 = new Workshop
|
||||||
|
{
|
||||||
|
Id = Guid.Parse("8a0b9f1b-6c9b-4a2a-9d5e-1c2f3a4b5c6d"),
|
||||||
|
Title = "APIs RESTful — visão geral",
|
||||||
|
Description = "Modelagem de recursos, status codes e boas práticas.",
|
||||||
|
StartAt = baseDate.AddHours(12), // daqui a 7 dias, 12:00 UTC
|
||||||
|
EndAt = baseDate.AddHours(15), // 15:00 UTC
|
||||||
|
Location = "Lab 101",
|
||||||
|
Capacity = 25,
|
||||||
|
IsOnline = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var w2 = new Workshop
|
||||||
|
{
|
||||||
|
Id = Guid.Parse("1c3d5e7f-9a2b-4c6d-8e0f-1a2b3c4d5e6f"),
|
||||||
|
Title = "Entity Framework — mapeamentos e LINQ",
|
||||||
|
Description = "Relações, consultas eficientes e boas práticas.",
|
||||||
|
StartAt = baseDate.AddDays(2).AddHours(12), // +2 dias, 12:00 UTC
|
||||||
|
EndAt = baseDate.AddDays(2).AddHours(14), // 14:00 UTC
|
||||||
|
Location = null, // online
|
||||||
|
Capacity = 40,
|
||||||
|
IsOnline = true
|
||||||
|
};
|
||||||
|
|
||||||
|
var w3 = new Workshop
|
||||||
|
{
|
||||||
|
Id = Guid.Parse("f0e1d2c3-b4a5-6789-9a8b-7c6d5e4f3a2b"),
|
||||||
|
Title = "Construindo contratos com Swagger/OpenAPI",
|
||||||
|
Description = "Documentação viva, exemplos e testes via Swagger UI.",
|
||||||
|
StartAt = baseDate.AddDays(5).AddHours(13), // +5 dias, 13:00 UTC
|
||||||
|
EndAt = baseDate.AddDays(5).AddHours(16), // 16:00 UTC
|
||||||
|
Location = "Auditório Central",
|
||||||
|
Capacity = 80,
|
||||||
|
IsOnline = false
|
||||||
|
};
|
||||||
|
|
||||||
|
_workshops.Add(w1);
|
||||||
|
_workshops.Add(w2);
|
||||||
|
_workshops.Add(w3);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public InMemoryWorkshopRepository()
|
||||||
|
{
|
||||||
|
Seed();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<Workshop>> GetAllAsync(DateTimeOffset? from, DateTimeOffset? to, string? q, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var query = _workshops.AsQueryable();
|
||||||
|
|
||||||
|
// Filtro por data início (from)
|
||||||
|
if (from.HasValue)
|
||||||
|
{
|
||||||
|
query = query.Where(w => w.StartAt >= from.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtro por data fim (to)
|
||||||
|
if (to.HasValue)
|
||||||
|
{
|
||||||
|
query = query.Where(w => w.StartAt <= to.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtro por texto (q) - busca no título e descrição
|
||||||
|
if (!string.IsNullOrWhiteSpace(q))
|
||||||
|
{
|
||||||
|
var searchTerm = q.Trim().ToLowerInvariant();
|
||||||
|
query = query.Where(w =>
|
||||||
|
(w.Title != null && w.Title.ToLowerInvariant().Contains(searchTerm)) ||
|
||||||
|
(w.Description != null && w.Description.ToLowerInvariant().Contains(searchTerm))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordenar por data de início
|
||||||
|
var result = query.OrderBy(w => w.StartAt).ToList();
|
||||||
|
|
||||||
|
return Task.FromResult<IReadOnlyList<Workshop>>(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<Workshop?> GetByIdAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var workshop = _workshops.FirstOrDefault(w => w.Id == id);
|
||||||
|
return Task.FromResult(workshop);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<Workshop> AddAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
// Gerar novo ID se não foi fornecido ou se já existe
|
||||||
|
if (workshop.Id == Guid.Empty || _workshops.Any(w => w.Id == workshop.Id))
|
||||||
|
{
|
||||||
|
workshop.Id = Guid.NewGuid();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validações de negócio que serão úteis quando migrar para banco
|
||||||
|
ValidateWorkshop(workshop);
|
||||||
|
|
||||||
|
_workshops.Add(workshop);
|
||||||
|
return Task.FromResult(workshop);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<Workshop?> UpdateAsync(Workshop workshop, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var existingIndex = _workshops.FindIndex(w => w.Id == workshop.Id);
|
||||||
|
if (existingIndex < 0)
|
||||||
|
{
|
||||||
|
return Task.FromResult<Workshop?>(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validações de negócio
|
||||||
|
ValidateWorkshop(workshop);
|
||||||
|
|
||||||
|
_workshops[existingIndex] = workshop;
|
||||||
|
return Task.FromResult<Workshop?>(workshop);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> DeleteAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var workshop = _workshops.FirstOrDefault(w => w.Id == id);
|
||||||
|
if (workshop == null)
|
||||||
|
{
|
||||||
|
return Task.FromResult(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
_workshops.Remove(workshop);
|
||||||
|
return Task.FromResult(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> ExistsAsync(Guid id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var exists = _workshops.Any(w => w.Id == id);
|
||||||
|
return Task.FromResult(exists);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<Workshop?> UpdatePartialAsync(Guid id, Action<Workshop> updateAction, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var workshop = _workshops.FirstOrDefault(w => w.Id == id);
|
||||||
|
if (workshop == null)
|
||||||
|
{
|
||||||
|
return Task.FromResult<Workshop?>(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aplicar as modificações
|
||||||
|
updateAction(workshop);
|
||||||
|
|
||||||
|
// Validar após modificações
|
||||||
|
ValidateWorkshop(workshop);
|
||||||
|
|
||||||
|
return Task.FromResult<Workshop?>(workshop);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ValidateWorkshop(Workshop workshop)
|
||||||
|
{
|
||||||
|
var errors = new List<string>();
|
||||||
|
|
||||||
|
// Validação de título
|
||||||
|
if (string.IsNullOrWhiteSpace(workshop.Title))
|
||||||
|
{
|
||||||
|
errors.Add("Title is required");
|
||||||
|
}
|
||||||
|
else if (workshop.Title.Length < 3 || workshop.Title.Length > 120)
|
||||||
|
{
|
||||||
|
errors.Add("Title must be between 3 and 120 characters");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validação de descrição
|
||||||
|
if (!string.IsNullOrWhiteSpace(workshop.Description) && workshop.Description.Length > 2000)
|
||||||
|
{
|
||||||
|
errors.Add("Description cannot exceed 2000 characters");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validação de datas
|
||||||
|
if (workshop.EndAt <= workshop.StartAt)
|
||||||
|
{
|
||||||
|
errors.Add("End date must be after start date");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (workshop.StartAt <= DateTimeOffset.UtcNow)
|
||||||
|
{
|
||||||
|
errors.Add("Start date must be in the future");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validação de capacidade
|
||||||
|
if (workshop.Capacity < 1)
|
||||||
|
{
|
||||||
|
errors.Add("Capacity must be at least 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validação de localização para workshops presenciais
|
||||||
|
if (!workshop.IsOnline && string.IsNullOrWhiteSpace(workshop.Location))
|
||||||
|
{
|
||||||
|
errors.Add("Location is required for in-person workshops");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validação de localização para workshops online
|
||||||
|
if (workshop.IsOnline && !string.IsNullOrWhiteSpace(workshop.Location))
|
||||||
|
{
|
||||||
|
errors.Add("Location should not be specified for online workshops");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errors.Any())
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"Workshop validation failed: {string.Join(", ", errors)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
Workshop10-API/Services/CacheSettings.cs
Normal file
6
Workshop10-API/Services/CacheSettings.cs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
public sealed class CacheSettings
|
||||||
|
{
|
||||||
|
public int DefaultTtlSeconds { get; set; } = 15;
|
||||||
|
}
|
||||||
12
Workshop10-API/Services/PerRequestClock.cs
Normal file
12
Workshop10-API/Services/PerRequestClock.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
public interface IPerRequestClock
|
||||||
|
{
|
||||||
|
// Carimbo criado no CONSTRUTOR (não muda depois)
|
||||||
|
DateTimeOffset CreatedAt { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PerRequestClock : IPerRequestClock
|
||||||
|
{
|
||||||
|
public DateTimeOffset CreatedAt { get; } = DateTimeOffset.UtcNow;
|
||||||
|
}
|
||||||
23
Workshop10-API/Services/ReportingSingleton.cs
Normal file
23
Workshop10-API/Services/ReportingSingleton.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Singleton que recebe um Transient (IPerRequestClock).
|
||||||
|
/// Na prática, o Transient é resolvido uma única vez, na construção do Singleton,
|
||||||
|
/// e "vira" efetivamente singleton dentro dele.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ReportingSingleton
|
||||||
|
{
|
||||||
|
private readonly IPerRequestClock _clock;
|
||||||
|
|
||||||
|
public ReportingSingleton(IPerRequestClock clock)
|
||||||
|
{
|
||||||
|
_clock = clock;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DateTimeOffset GetClockCreatedAt()
|
||||||
|
{
|
||||||
|
return _clock.CreatedAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
9
Workshop10-API/Services/RequestId.cs
Normal file
9
Workshop10-API/Services/RequestId.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace CampusWorkshops.Api.Services;
|
||||||
|
|
||||||
|
public interface IRequestIdTransient { Guid Id { get; } }
|
||||||
|
public interface IRequestIdScoped { Guid Id { get; } }
|
||||||
|
public interface IRequestIdSingleton { Guid Id { get; } }
|
||||||
|
|
||||||
|
internal sealed class RequestIdTransient : IRequestIdTransient { public Guid Id { get; } = Guid.NewGuid(); }
|
||||||
|
internal sealed class RequestIdScoped : IRequestIdScoped { public Guid Id { get; } = Guid.NewGuid(); }
|
||||||
|
internal sealed class RequestIdSingleton : IRequestIdSingleton { public Guid Id { get; } = Guid.NewGuid(); }
|
||||||
26
Workshop10-API/Workshop10-API.csproj
Normal file
26
Workshop10-API/Workshop10-API.csproj
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<RootNamespace>Workshop10_API</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.9" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.8" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.8">
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.8" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.8">
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
{
|
{
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"WorkshopsDb": "Data Source=workshops.db"
|
||||||
|
},
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
"AllowedHosts": "*"
|
|
||||||
}
|
}
|
||||||
15
Workshop10-API/appsettings.json
Normal file
15
Workshop10-API/appsettings.json
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Jwt": {
|
||||||
|
"Issuer": "CampusWorkshops",
|
||||||
|
"Audience": "CampusWorkshops.Api",
|
||||||
|
"Key": "some-key-that-is-super-secret-always-secured"
|
||||||
|
},
|
||||||
|
"Cache": { "DefaultTtlSeconds": 15 },
|
||||||
|
"AllowedHosts": "*"
|
||||||
|
}
|
||||||
BIN
Workshop10-API/workshops.db
Normal file
BIN
Workshop10-API/workshops.db
Normal file
Binary file not shown.
@@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"Logging": {
|
|
||||||
"LogLevel": {
|
|
||||||
"Default": "Information",
|
|
||||||
"Microsoft.AspNetCore": "Warning"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user