Project Init

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Yaojia Wang
2025-11-02 23:55:18 +01:00
commit 014d62bcc2
169 changed files with 28867 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Scalar.AspNetCore" Version="2.9.0" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Modules\ProjectManagement\ColaFlow.Modules.ProjectManagement.Application\ColaFlow.Modules.ProjectManagement.Application.csproj" />
<ProjectReference Include="..\Modules\ProjectManagement\ColaFlow.Modules.ProjectManagement.Infrastructure\ColaFlow.Modules.ProjectManagement.Infrastructure.csproj" />
<ProjectReference Include="..\Shared\ColaFlow.Shared.Kernel\ColaFlow.Shared.Kernel.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="11.1.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@ColaFlow.API_HostAddress = http://localhost:5167
GET {{ColaFlow.API_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,62 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateProject;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetProjectById;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetProjects;
namespace ColaFlow.API.Controllers;
/// <summary>
/// Projects API Controller
/// </summary>
[ApiController]
[Route("api/v1/[controller]")]
public class ProjectsController : ControllerBase
{
private readonly IMediator _mediator;
public ProjectsController(IMediator mediator)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
/// <summary>
/// Get all projects
/// </summary>
[HttpGet]
[ProducesResponseType(typeof(List<ProjectDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetProjects(CancellationToken cancellationToken = default)
{
var query = new GetProjectsQuery();
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Get project by ID
/// </summary>
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(ProjectDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetProject(Guid id, CancellationToken cancellationToken = default)
{
var query = new GetProjectByIdQuery(id);
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Create a new project
/// </summary>
[HttpPost]
[ProducesResponseType(typeof(ProjectDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateProject(
[FromBody] CreateProjectCommand command,
CancellationToken cancellationToken = default)
{
var result = await _mediator.Send(command, cancellationToken);
return CreatedAtAction(nameof(GetProject), new { id = result.Id }, result);
}
}

View File

@@ -0,0 +1,46 @@
using Microsoft.EntityFrameworkCore;
using FluentValidation;
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.Behaviors;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateProject;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;
using ColaFlow.Modules.ProjectManagement.Infrastructure.Repositories;
namespace ColaFlow.API.Extensions;
/// <summary>
/// Extension methods for registering modules
/// </summary>
public static class ModuleExtensions
{
/// <summary>
/// Register ProjectManagement Module
/// </summary>
public static IServiceCollection AddProjectManagementModule(
this IServiceCollection services,
IConfiguration configuration)
{
// Register DbContext
var connectionString = configuration.GetConnectionString("PMDatabase");
services.AddDbContext<PMDbContext>(options =>
options.UseNpgsql(connectionString));
// Register repositories
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
// Register MediatR handlers from Application assembly
services.AddMediatR(typeof(CreateProjectCommand).Assembly);
// Register FluentValidation validators
services.AddValidatorsFromAssembly(typeof(CreateProjectCommand).Assembly);
// Register pipeline behaviors
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
Console.WriteLine("[ProjectManagement] Module registered");
return services;
}
}

View File

@@ -0,0 +1,96 @@
using System.Net;
using System.Text.Json;
using FluentValidation;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.API.Middleware;
/// <summary>
/// Global exception handler middleware
/// </summary>
public class GlobalExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
public GlobalExceptionHandlerMiddleware(
RequestDelegate next,
ILogger<GlobalExceptionHandlerMiddleware> logger)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
var (statusCode, response) = exception switch
{
ValidationException validationEx => (
StatusCodes.Status400BadRequest,
new
{
StatusCode = StatusCodes.Status400BadRequest,
Message = "Validation failed",
Errors = validationEx.Errors.Select(e => new
{
Property = e.PropertyName,
Message = e.ErrorMessage
})
}),
DomainException domainEx => (
StatusCodes.Status400BadRequest,
new
{
StatusCode = StatusCodes.Status400BadRequest,
Message = domainEx.Message
}),
NotFoundException notFoundEx => (
StatusCodes.Status404NotFound,
new
{
StatusCode = StatusCodes.Status404NotFound,
Message = notFoundEx.Message
}),
_ => (
StatusCodes.Status500InternalServerError,
new
{
StatusCode = StatusCodes.Status500InternalServerError,
Message = "An internal server error occurred"
})
};
context.Response.StatusCode = statusCode;
// Log with appropriate level
if (statusCode >= 500)
{
_logger.LogError(exception, "Internal server error occurred: {Message}", exception.Message);
}
else if (statusCode >= 400)
{
_logger.LogWarning(exception, "Client error occurred: {Message}", exception.Message);
}
var jsonResponse = JsonSerializer.Serialize(response, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
await context.Response.WriteAsync(jsonResponse);
}
}

View File

@@ -0,0 +1,31 @@
using ColaFlow.API.Extensions;
using ColaFlow.API.Middleware;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Register ProjectManagement Module
builder.Services.AddProjectManagementModule(builder.Configuration);
// Add controllers
builder.Services.AddControllers();
// Configure OpenAPI/Scalar
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
// Global exception handler (should be first in pipeline)
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

View File

@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5167",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7295;http://localhost:5167",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,12 @@
{
"ConnectionStrings": {
"PMDatabase": "Host=localhost;Port=5432;Database=colaflow_pm;Username=colaflow;Password=colaflow_dev_password"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Information"
}
}
}

View File

@@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"PMDatabase": "Host=localhost;Port=5432;Database=colaflow;Username=colaflow;Password=colaflow_dev_password"
}
}