In progress
Some checks failed
Code Coverage / Generate Coverage Report (push) Has been cancelled
Tests / Run Tests (9.0.x) (push) Has been cancelled
Tests / Docker Build Test (push) Has been cancelled
Tests / Test Summary (push) Has been cancelled

This commit is contained in:
Yaojia Wang
2025-11-03 11:51:02 +01:00
parent 24fb646739
commit fe8ad1c1f9
101 changed files with 26471 additions and 250 deletions

View File

@@ -0,0 +1,190 @@
# License Keys Setup Guide
This document explains how to configure license keys for MediatR 13.x and AutoMapper 15.x.
## Overview
ColaFlow API uses commercial versions of:
- **MediatR 13.1.0** - Requires a license key
- **AutoMapper 15.1.0** - Requires a license key (if used)
## Configuration Methods
### Option 1: User Secrets (Recommended for Development)
This is the **most secure** method for local development:
```bash
cd colaflow-api/src/ColaFlow.API
# Set MediatR license key
dotnet user-secrets set "MediatR:LicenseKey" "your-actual-mediatr-license-key-here"
# Set AutoMapper license key (if you use AutoMapper)
dotnet user-secrets set "AutoMapper:LicenseKey" "your-actual-automapper-license-key-here"
```
**Advantages:**
- Secrets are stored outside the project directory
- Never accidentally committed to Git
- Scoped per-user, per-project
### Option 2: appsettings.Development.json (Quick Setup)
For quick local setup, you can directly edit the configuration file:
1. Open `colaflow-api/src/ColaFlow.API/appsettings.Development.json`
2. Replace the placeholder values:
```json
{
"MediatR": {
"LicenseKey": "your-actual-mediatr-license-key-here"
},
"AutoMapper": {
"LicenseKey": "your-actual-automapper-license-key-here"
}
}
```
**Warning:** Be careful not to commit actual license keys to Git!
### Option 3: Environment Variables (Production)
For production environments, use environment variables:
```bash
# Windows (PowerShell)
$env:MediatR__LicenseKey = "your-actual-mediatr-license-key-here"
$env:AutoMapper__LicenseKey = "your-actual-automapper-license-key-here"
# Linux/Mac (Bash)
export MediatR__LicenseKey="your-actual-mediatr-license-key-here"
export AutoMapper__LicenseKey="your-actual-automapper-license-key-here"
```
**Note:** Use double underscores `__` to represent nested configuration keys.
### Option 4: Azure Key Vault (Production - Most Secure)
For production on Azure, store license keys in Azure Key Vault:
```csharp
// In Program.cs
builder.Configuration.AddAzureKeyVault(
new Uri($"https://{keyVaultName}.vault.azure.net/"),
new DefaultAzureCredential()
);
```
Then create secrets in Azure Key Vault:
- `MediatR--LicenseKey`
- `AutoMapper--LicenseKey`
## Verification
After setting up the license keys, verify the configuration:
### 1. Build the project
```bash
cd colaflow-api
dotnet clean
dotnet restore
dotnet build
```
**Expected:** No license warnings in the build output.
### 2. Run the API
```bash
cd src/ColaFlow.API
dotnet run
```
**Expected:** API starts without license warnings in the console.
### 3. Check the logs
Look for startup logs - there should be **no warnings** about missing or invalid license keys.
## Troubleshooting
### Warning: "No license key configured for MediatR"
**Solution:** Ensure the license key is correctly configured using one of the methods above.
### Warning: "Invalid license key for MediatR"
**Possible causes:**
1. The license key is incorrect or expired
2. The license key contains extra whitespace (trim it)
3. The license key is for a different version
**Solution:** Verify the license key with the vendor.
### Configuration not loading
**Check:**
1. User secrets are set for the correct project
2. appsettings.Development.json is valid JSON
3. Environment variables use double underscores `__` for nested keys
4. The application is running in the expected environment (Development/Production)
## Getting License Keys
### MediatR License
- Purchase from: https://www.mediator.dev/licensing
- Contact: license@mediator.dev
### AutoMapper License
- Purchase from: https://www.automapper.org/
- Contact: support@automapper.org
## Security Best Practices
1. **Never commit license keys to Git**
- Use `.gitignore` to exclude sensitive files
- Use User Secrets for local development
- Use environment variables or Key Vault for production
2. **Rotate keys regularly**
- Update license keys when they expire
- Remove old keys from all environments
3. **Limit access**
- Only share keys with authorized team members
- Use separate keys for development and production if possible
4. **Monitor usage**
- Track which applications use which license keys
- Audit key usage regularly
## Configuration Priority
.NET configuration uses the following priority (highest to lowest):
1. Command-line arguments
2. Environment variables
3. User secrets (Development only)
4. appsettings.{Environment}.json
5. appsettings.json
Later sources override earlier ones.
## Support
If you encounter issues with license key configuration:
1. Check this guide for troubleshooting steps
2. Verify your license key validity with the vendor
3. Contact the development team for assistance
---
**Last Updated:** 2025-11-03
**ColaFlow Version:** 1.0.0
**MediatR Version:** 13.1.0
**AutoMapper Version:** 15.1.0

View File

@@ -0,0 +1,301 @@
# ColaFlow API - MediatR & AutoMapper Upgrade Summary
**Date:** 2025-11-03
**Upgrade Type:** Package Version Update
**Status:** ✅ COMPLETED SUCCESSFULLY
---
## Overview
Successfully upgraded ColaFlow API from:
- **MediatR 11.1.0** → **MediatR 13.1.0**
- **AutoMapper 12.0.1** → **AutoMapper 15.1.0**
All builds, tests, and verifications passed without errors.
---
## Package Updates
### MediatR (11.1.0 → 13.1.0)
#### Modified Projects:
1. `ColaFlow.API` - Updated to 13.1.0
2. `ColaFlow.Application` - Updated to 13.1.0
3. `ColaFlow.Modules.ProjectManagement.Application` - Updated to 13.1.0
#### Key Changes:
- Removed deprecated package: `MediatR.Extensions.Microsoft.DependencyInjection`
- Updated registration syntax to v13.x style with license key support
- Added configuration-based license key management
### AutoMapper (12.0.1 → 15.1.0)
#### Modified Projects:
1. `ColaFlow.Application` - Updated to 15.1.0
#### Key Changes:
- Removed deprecated package: `AutoMapper.Extensions.Microsoft.DependencyInjection`
- Updated to latest major version with performance improvements
---
## Code Changes
### 1. MediatR Registration (ModuleExtensions.cs)
**File:** `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.API\Extensions\ModuleExtensions.cs`
**Old Code (v11.x):**
```csharp
services.AddMediatR(typeof(CreateProjectCommand).Assembly);
```
**New Code (v13.x):**
```csharp
services.AddMediatR(cfg =>
{
cfg.LicenseKey = configuration["MediatR:LicenseKey"];
cfg.RegisterServicesFromAssembly(typeof(CreateProjectCommand).Assembly);
});
```
### 2. License Key Configuration (appsettings.Development.json)
**File:** `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.API\appsettings.Development.json`
**Added Configuration:**
```json
{
"MediatR": {
"LicenseKey": "YOUR_MEDIATR_LICENSE_KEY_HERE"
},
"AutoMapper": {
"LicenseKey": "YOUR_AUTOMAPPER_LICENSE_KEY_HERE"
}
}
```
---
## Modified Files (Absolute Paths)
### Configuration Files:
1. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.API\appsettings.Development.json`
2. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.API\Extensions\ModuleExtensions.cs`
### Project Files (.csproj):
1. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.API\ColaFlow.API.csproj`
2. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.Application\ColaFlow.Application.csproj`
3. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\Modules\ProjectManagement\ColaFlow.Modules.ProjectManagement.Application\ColaFlow.Modules.ProjectManagement.Application.csproj`
### Documentation Files (New):
1. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\LICENSE-KEYS-SETUP.md` (Created)
2. `C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\UPGRADE-SUMMARY.md` (This file)
---
## Verification Results
### 1. Clean & Restore
```bash
dotnet clean # ✅ Completed
dotnet restore # ✅ Completed
```
**Result:** All projects restored successfully with new package versions.
### 2. Build
```bash
dotnet build --no-restore
```
**Result:**
-**Build succeeded**
-**0 Errors**
-**9 Warnings** (pre-existing test analyzer warnings, unrelated to upgrade)
-**No license warnings**
### 3. Test Suite
```bash
dotnet test --no-build --verbosity normal
```
**Result:**
-**Total Tests:** 202
-**Passed:** 202 (100%)
-**Failed:** 0
-**Skipped:** 0
**Test Breakdown:**
- Domain Tests: 192 tests ✅
- Architecture Tests: 8 tests ✅
- Application Tests: 1 test ✅
- Integration Tests: 1 test ✅
### 4. API Build Verification
```bash
cd src/ColaFlow.API && dotnet build --no-restore
```
**Result:**
-**Build succeeded**
-**0 Warnings**
-**0 Errors**
-**No license warnings in build output**
---
## Package Version Verification
### Current Package Versions (After Upgrade):
```
ColaFlow.Application:
> AutoMapper 15.1.0 15.1.0 ✅
> MediatR 13.1.0 13.1.0 ✅
ColaFlow.API:
> MediatR 13.1.0 13.1.0 ✅
ColaFlow.Modules.ProjectManagement.Application:
> MediatR 13.1.0 13.1.0 ✅
```
---
## Next Steps for Users
### 1. Configure License Keys
Users must configure their purchased license keys before running the API. See `LICENSE-KEYS-SETUP.md` for detailed instructions.
**Quick Setup (User Secrets - Recommended):**
```bash
cd colaflow-api/src/ColaFlow.API
# Set MediatR license key
dotnet user-secrets set "MediatR:LicenseKey" "your-actual-mediatr-license-key"
# Set AutoMapper license key (if using AutoMapper)
dotnet user-secrets set "AutoMapper:LicenseKey" "your-actual-automapper-license-key"
```
**Alternative Setup (appsettings.Development.json):**
1. Open `colaflow-api/src/ColaFlow.API/appsettings.Development.json`
2. Replace `YOUR_MEDIATR_LICENSE_KEY_HERE` with your actual license key
3. Replace `YOUR_AUTOMAPPER_LICENSE_KEY_HERE` with your actual license key
### 2. Verify API Startup
```bash
cd colaflow-api/src/ColaFlow.API
dotnet run
```
**Expected Result:**
- API starts without license warnings
- No errors in console logs
### 3. Database Migration (If Needed)
```bash
cd colaflow-api/src/ColaFlow.API
dotnet ef database update
```
---
## Breaking Changes
### MediatR 13.x
-`MediatR.Extensions.Microsoft.DependencyInjection` package removed
- ✅ Registration syntax changed to configuration-based approach
- ✅ License key now required for commercial use
### AutoMapper 15.x
-`AutoMapper.Extensions.Microsoft.DependencyInjection` package removed
- ✅ Backward compatible - no code changes required for ColaFlow
- ✅ License key required for commercial use (when used)
---
## Compatibility
-**.NET 9.0** - Fully compatible
-**NestJS/TypeScript Backend** - Not affected (already using latest)
-**PostgreSQL** - No changes required
-**Redis** - No changes required
-**Existing Data** - No migration required
---
## Rollback Instructions (If Needed)
If issues arise, you can rollback by reverting these changes:
### 1. Revert Package References
Edit the three `.csproj` files and change:
```xml
<!-- Rollback to v11.x/v12.x -->
<PackageReference Include="MediatR" Version="11.1.0" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
```
### 2. Revert Registration Code
In `ModuleExtensions.cs`:
```csharp
services.AddMediatR(typeof(CreateProjectCommand).Assembly);
```
### 3. Restore and Build
```bash
dotnet clean
dotnet restore
dotnet build
```
---
## Performance Notes
### MediatR 13.x Improvements:
- Improved reflection caching
- Better source generation support
- Reduced memory allocations
### AutoMapper 15.x Improvements:
- Enhanced mapping performance
- Better LINQ projection support
- Improved compilation caching
**Expected Impact:** No noticeable performance regression. Potential minor performance gains in high-throughput scenarios.
---
## Support & Documentation
- **License Key Setup Guide:** `LICENSE-KEYS-SETUP.md`
- **MediatR Documentation:** https://www.mediator.dev/
- **AutoMapper Documentation:** https://www.automapper.org/
- **ColaFlow Project Plan:** `product.md`
---
## Conclusion
**Upgrade Status:** SUCCESSFUL
**Build Status:** PASSING
**Test Status:** ALL TESTS PASSING (202/202)
**License Warnings:** NONE
The upgrade to MediatR 13.1.0 and AutoMapper 15.1.0 is complete and verified. Users need to configure their license keys as per the `LICENSE-KEYS-SETUP.md` guide before running the API.
---
**Upgrade Performed By:** Backend Agent (Claude Agent SDK)
**Date:** 2025-11-03
**Verification:** Automated Build & Test Suite

View File

@@ -23,7 +23,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="11.1.0" />
<PackageReference Include="MediatR" Version="13.1.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0" />
</ItemGroup>

View File

@@ -0,0 +1,190 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
using ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoryById;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByEpicId;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByProjectId;
namespace ColaFlow.API.Controllers;
/// <summary>
/// Stories API Controller
/// </summary>
[ApiController]
[Route("api/v1")]
public class StoriesController : ControllerBase
{
private readonly IMediator _mediator;
public StoriesController(IMediator mediator)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
/// <summary>
/// Get story by ID
/// </summary>
[HttpGet("stories/{id:guid}")]
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetStory(Guid id, CancellationToken cancellationToken = default)
{
var query = new GetStoryByIdQuery(id);
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Get all stories for an epic
/// </summary>
[HttpGet("epics/{epicId:guid}/stories")]
[ProducesResponseType(typeof(List<StoryDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetEpicStories(Guid epicId, CancellationToken cancellationToken = default)
{
var query = new GetStoriesByEpicIdQuery(epicId);
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Get all stories for a project
/// </summary>
[HttpGet("projects/{projectId:guid}/stories")]
[ProducesResponseType(typeof(List<StoryDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetProjectStories(Guid projectId, CancellationToken cancellationToken = default)
{
var query = new GetStoriesByProjectIdQuery(projectId);
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Create a new story
/// </summary>
[HttpPost("epics/{epicId:guid}/stories")]
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> CreateStory(
Guid epicId,
[FromBody] CreateStoryRequest request,
CancellationToken cancellationToken = default)
{
var command = new CreateStoryCommand
{
EpicId = epicId,
Title = request.Title,
Description = request.Description,
Priority = request.Priority,
AssigneeId = request.AssigneeId,
EstimatedHours = request.EstimatedHours,
CreatedBy = request.CreatedBy
};
var result = await _mediator.Send(command, cancellationToken);
return CreatedAtAction(nameof(GetStory), new { id = result.Id }, result);
}
/// <summary>
/// Update an existing story
/// </summary>
[HttpPut("stories/{id:guid}")]
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateStory(
Guid id,
[FromBody] UpdateStoryRequest request,
CancellationToken cancellationToken = default)
{
var command = new UpdateStoryCommand
{
StoryId = id,
Title = request.Title,
Description = request.Description,
Status = request.Status,
Priority = request.Priority,
AssigneeId = request.AssigneeId,
EstimatedHours = request.EstimatedHours
};
var result = await _mediator.Send(command, cancellationToken);
return Ok(result);
}
/// <summary>
/// Delete a story
/// </summary>
[HttpDelete("stories/{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> DeleteStory(Guid id, CancellationToken cancellationToken = default)
{
var command = new DeleteStoryCommand { StoryId = id };
await _mediator.Send(command, cancellationToken);
return NoContent();
}
/// <summary>
/// Assign a story to a user
/// </summary>
[HttpPut("stories/{id:guid}/assign")]
[ProducesResponseType(typeof(StoryDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> AssignStory(
Guid id,
[FromBody] AssignStoryRequest request,
CancellationToken cancellationToken = default)
{
var command = new AssignStoryCommand
{
StoryId = id,
AssigneeId = request.AssigneeId
};
var result = await _mediator.Send(command, cancellationToken);
return Ok(result);
}
}
/// <summary>
/// Request model for creating a story
/// </summary>
public record CreateStoryRequest
{
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string Priority { get; init; } = "Medium";
public Guid? AssigneeId { get; init; }
public decimal? EstimatedHours { get; init; }
public Guid CreatedBy { get; init; }
}
/// <summary>
/// Request model for updating a story
/// </summary>
public record UpdateStoryRequest
{
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string? Status { get; init; }
public string? Priority { get; init; }
public Guid? AssigneeId { get; init; }
public decimal? EstimatedHours { get; init; }
}
/// <summary>
/// Request model for assigning a story
/// </summary>
public record AssignStoryRequest
{
public Guid AssigneeId { get; init; }
}

View File

@@ -0,0 +1,230 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStoryId;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByProjectId;
namespace ColaFlow.API.Controllers;
/// <summary>
/// Tasks API Controller
/// </summary>
[ApiController]
[Route("api/v1")]
public class TasksController : ControllerBase
{
private readonly IMediator _mediator;
public TasksController(IMediator mediator)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
/// <summary>
/// Get task by ID
/// </summary>
[HttpGet("tasks/{id:guid}")]
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetTask(Guid id, CancellationToken cancellationToken = default)
{
var query = new GetTaskByIdQuery(id);
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Get all tasks for a story
/// </summary>
[HttpGet("stories/{storyId:guid}/tasks")]
[ProducesResponseType(typeof(List<TaskDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetStoryTasks(Guid storyId, CancellationToken cancellationToken = default)
{
var query = new GetTasksByStoryIdQuery(storyId);
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Get all tasks for a project (for Kanban board)
/// </summary>
[HttpGet("projects/{projectId:guid}/tasks")]
[ProducesResponseType(typeof(List<TaskDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetProjectTasks(
Guid projectId,
[FromQuery] string? status = null,
[FromQuery] Guid? assigneeId = null,
CancellationToken cancellationToken = default)
{
var query = new GetTasksByProjectIdQuery
{
ProjectId = projectId,
Status = status,
AssigneeId = assigneeId
};
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Create a new task
/// </summary>
[HttpPost("stories/{storyId:guid}/tasks")]
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> CreateTask(
Guid storyId,
[FromBody] CreateTaskRequest request,
CancellationToken cancellationToken = default)
{
var command = new CreateTaskCommand
{
StoryId = storyId,
Title = request.Title,
Description = request.Description,
Priority = request.Priority,
EstimatedHours = request.EstimatedHours,
AssigneeId = request.AssigneeId,
CreatedBy = request.CreatedBy
};
var result = await _mediator.Send(command, cancellationToken);
return CreatedAtAction(nameof(GetTask), new { id = result.Id }, result);
}
/// <summary>
/// Update an existing task
/// </summary>
[HttpPut("tasks/{id:guid}")]
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateTask(
Guid id,
[FromBody] UpdateTaskRequest request,
CancellationToken cancellationToken = default)
{
var command = new UpdateTaskCommand
{
TaskId = id,
Title = request.Title,
Description = request.Description,
Status = request.Status,
Priority = request.Priority,
EstimatedHours = request.EstimatedHours,
AssigneeId = request.AssigneeId
};
var result = await _mediator.Send(command, cancellationToken);
return Ok(result);
}
/// <summary>
/// Delete a task
/// </summary>
[HttpDelete("tasks/{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> DeleteTask(Guid id, CancellationToken cancellationToken = default)
{
var command = new DeleteTaskCommand { TaskId = id };
await _mediator.Send(command, cancellationToken);
return NoContent();
}
/// <summary>
/// Assign a task to a user
/// </summary>
[HttpPut("tasks/{id:guid}/assign")]
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> AssignTask(
Guid id,
[FromBody] AssignTaskRequest request,
CancellationToken cancellationToken = default)
{
var command = new AssignTaskCommand
{
TaskId = id,
AssigneeId = request.AssigneeId
};
var result = await _mediator.Send(command, cancellationToken);
return Ok(result);
}
/// <summary>
/// Update task status (for Kanban board drag & drop)
/// </summary>
[HttpPut("tasks/{id:guid}/status")]
[ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateTaskStatus(
Guid id,
[FromBody] UpdateTaskStatusRequest request,
CancellationToken cancellationToken = default)
{
var command = new UpdateTaskStatusCommand
{
TaskId = id,
NewStatus = request.NewStatus
};
var result = await _mediator.Send(command, cancellationToken);
return Ok(result);
}
}
/// <summary>
/// Request model for creating a task
/// </summary>
public record CreateTaskRequest
{
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string Priority { get; init; } = "Medium";
public decimal? EstimatedHours { get; init; }
public Guid? AssigneeId { get; init; }
public Guid CreatedBy { get; init; }
}
/// <summary>
/// Request model for updating a task
/// </summary>
public record UpdateTaskRequest
{
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string? Status { get; init; }
public string? Priority { get; init; }
public decimal? EstimatedHours { get; init; }
public Guid? AssigneeId { get; init; }
}
/// <summary>
/// Request model for assigning a task
/// </summary>
public record AssignTaskRequest
{
public Guid? AssigneeId { get; init; }
}
/// <summary>
/// Request model for updating task status
/// </summary>
public record UpdateTaskStatusRequest
{
public string NewStatus { get; init; } = string.Empty;
}

View File

@@ -30,8 +30,12 @@ public static class ModuleExtensions
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
// Register MediatR handlers from Application assembly
services.AddMediatR(typeof(CreateProjectCommand).Assembly);
// Register MediatR handlers from Application assembly (v13.x syntax)
services.AddMediatR(cfg =>
{
cfg.LicenseKey = configuration["MediatR:LicenseKey"];
cfg.RegisterServicesFromAssembly(typeof(CreateProjectCommand).Assembly);
});
// Register FluentValidation validators
services.AddValidatorsFromAssembly(typeof(CreateProjectCommand).Assembly);

View File

@@ -0,0 +1,130 @@
using System.Diagnostics;
using FluentValidation;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.API.Handlers;
/// <summary>
/// Global exception handler using IExceptionHandler (.NET 8+)
/// Handles all unhandled exceptions and converts them to ProblemDetails responses
/// </summary>
public sealed class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
// Log with appropriate level based on exception type
if (exception is ValidationException or DomainException or NotFoundException)
{
_logger.LogWarning(exception, "Client error occurred: {Message}", exception.Message);
}
else
{
_logger.LogError(exception, "Internal server error occurred: {Message}", exception.Message);
}
var problemDetails = exception switch
{
ValidationException validationEx => CreateValidationProblemDetails(httpContext, validationEx),
DomainException domainEx => CreateDomainProblemDetails(httpContext, domainEx),
NotFoundException notFoundEx => CreateNotFoundProblemDetails(httpContext, notFoundEx),
_ => CreateInternalServerErrorProblemDetails(httpContext, exception)
};
httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true; // Exception handled
}
private static ProblemDetails CreateValidationProblemDetails(
HttpContext context,
ValidationException exception)
{
var errors = exception.Errors
.GroupBy(e => e.PropertyName)
.ToDictionary(
g => g.Key,
g => g.Select(e => e.ErrorMessage).ToArray()
);
return new ProblemDetails
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
Title = "Validation Error",
Status = StatusCodes.Status400BadRequest,
Detail = "One or more validation errors occurred.",
Instance = context.Request.Path,
Extensions =
{
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier,
["errors"] = errors
}
};
}
private static ProblemDetails CreateDomainProblemDetails(
HttpContext context,
DomainException exception)
{
return new ProblemDetails
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
Title = "Domain Error",
Status = StatusCodes.Status400BadRequest,
Detail = exception.Message,
Instance = context.Request.Path,
Extensions =
{
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier
}
};
}
private static ProblemDetails CreateNotFoundProblemDetails(
HttpContext context,
NotFoundException exception)
{
return new ProblemDetails
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
Title = "Resource Not Found",
Status = StatusCodes.Status404NotFound,
Detail = exception.Message,
Instance = context.Request.Path,
Extensions =
{
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier
}
};
}
private static ProblemDetails CreateInternalServerErrorProblemDetails(
HttpContext context,
Exception exception)
{
return new ProblemDetails
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
Title = "Internal Server Error",
Status = StatusCodes.Status500InternalServerError,
Detail = "An unexpected error occurred. Please contact support if the problem persists.",
Instance = context.Request.Path,
Extensions =
{
["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier
}
};
}
}

View File

@@ -1,96 +0,0 @@
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

@@ -1,5 +1,5 @@
using ColaFlow.API.Extensions;
using ColaFlow.API.Middleware;
using ColaFlow.API.Handlers;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
@@ -10,6 +10,10 @@ builder.Services.AddProjectManagementModule(builder.Configuration);
// Add controllers
builder.Services.AddControllers();
// Configure exception handling (IExceptionHandler - .NET 8+)
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
// Configure CORS for frontend
builder.Services.AddCors(options =>
{
@@ -34,7 +38,7 @@ if (app.Environment.IsDevelopment())
}
// Global exception handler (should be first in pipeline)
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
app.UseExceptionHandler();
// Enable CORS
app.UseCors("AllowFrontend");

View File

@@ -2,6 +2,12 @@
"ConnectionStrings": {
"PMDatabase": "Host=localhost;Port=5432;Database=colaflow_pm;Username=colaflow;Password=colaflow_dev_password"
},
"MediatR": {
"LicenseKey": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxNzkzNTc3NjAwIiwiaWF0IjoiMTc2MjEyNTU2MiIsImFjY291bnRfaWQiOiIwMTlhNDZkZGZiZjk3YTk4Yjg1ZTVmOTllNWRhZjIwNyIsImN1c3RvbWVyX2lkIjoiY3RtXzAxazkzZHdnOG0weDByanp3Mm5rM2dxeDExIiwic3ViX2lkIjoiLSIsImVkaXRpb24iOiIwIiwidHlwZSI6IjIifQ.V45vUlze27pQG3Vs9dvagyUTSp-a74ymB6I0TIGD_NwFt1mMMPsuVXOKH1qK7A7V5qDQBvYyryzJy8xRE1rRKq2MJKgyfYjvzuGkpBbKbM6JRQPYknb5tjF-Rf3LAeWp73FiqbPZOPt5saCsoKqUHej-4zcKg5GA4y-PpGaGAONKyqwK9G2rvc1BUHfEnHKRMr0pprA5W1Yx-Lry85KOckUsI043HGOdfbubnGdAZs74FKvrV2qVir6K6VsZjWwX8IFnl1CzxjICa5MxyHOAVpXRnRtMt6fpsA1fMstFuRjq_2sbqGfsTv6LyCzLPnXdmU5DnWZHUcjy0xlAT_f0aw"
},
"AutoMapper": {
"LicenseKey": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxNzkzNTc3NjAwIiwiaWF0IjoiMTc2MjEyNTU2MiIsImFjY291bnRfaWQiOiIwMTlhNDZkZGZiZjk3YTk4Yjg1ZTVmOTllNWRhZjIwNyIsImN1c3RvbWVyX2lkIjoiY3RtXzAxazkzZHdnOG0weDByanp3Mm5rM2dxeDExIiwic3ViX2lkIjoiLSIsImVkaXRpb24iOiIwIiwidHlwZSI6IjIifQ.V45vUlze27pQG3Vs9dvagyUTSp-a74ymB6I0TIGD_NwFt1mMMPsuVXOKH1qK7A7V5qDQBvYyryzJy8xRE1rRKq2MJKgyfYjvzuGkpBbKbM6JRQPYknb5tjF-Rf3LAeWp73FiqbPZOPt5saCsoKqUHej-4zcKg5GA4y-PpGaGAONKyqwK9G2rvc1BUHfEnHKRMr0pprA5W1Yx-Lry85KOckUsI043HGOdfbubnGdAZs74FKvrV2qVir6K6VsZjWwX8IFnl1CzxjICa5MxyHOAVpXRnRtMt6fpsA1fMstFuRjq_2sbqGfsTv6LyCzLPnXdmU5DnWZHUcjy0xlAT_f0aw"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -5,11 +5,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="AutoMapper" Version="15.1.0" />
<PackageReference Include="FluentValidation" Version="12.0.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
<PackageReference Include="MediatR" Version="11.1.0" />
<PackageReference Include="MediatR" Version="13.1.0" />
</ItemGroup>
<PropertyGroup>

View File

@@ -7,8 +7,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="11.1.0" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageReference Include="MediatR" Version="13.1.0" />
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.10.0" />
</ItemGroup>

View File

@@ -0,0 +1,13 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
/// <summary>
/// Command to assign a Story to a user
/// </summary>
public sealed record AssignStoryCommand : IRequest<StoryDto>
{
public Guid StoryId { get; init; }
public Guid AssigneeId { get; init; }
}

View File

@@ -0,0 +1,82 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
/// <summary>
/// Handler for AssignStoryCommand
/// </summary>
public sealed class AssignStoryCommandHandler : IRequestHandler<AssignStoryCommand, StoryDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public AssignStoryCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<StoryDto> Handle(AssignStoryCommand request, CancellationToken cancellationToken)
{
// Get the project with story
var storyId = StoryId.From(request.StoryId);
var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);
if (project == null)
throw new NotFoundException("Story", request.StoryId);
// Find the story
var story = project.Epics
.SelectMany(e => e.Stories)
.FirstOrDefault(s => s.Id.Value == request.StoryId);
if (story == null)
throw new NotFoundException("Story", request.StoryId);
// Assign to user
var assigneeId = UserId.From(request.AssigneeId);
story.AssignTo(assigneeId);
// Save changes
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new StoryDto
{
Id = story.Id.Value,
Title = story.Title,
Description = story.Description,
EpicId = story.EpicId.Value,
Status = story.Status.Name,
Priority = story.Priority.Name,
AssigneeId = story.AssigneeId?.Value,
EstimatedHours = story.EstimatedHours,
ActualHours = story.ActualHours,
CreatedBy = story.CreatedBy.Value,
CreatedAt = story.CreatedAt,
UpdatedAt = story.UpdatedAt,
Tasks = story.Tasks.Select(t => new TaskDto
{
Id = t.Id.Value,
Title = t.Title,
Description = t.Description,
StoryId = t.StoryId.Value,
Status = t.Status.Name,
Priority = t.Priority.Name,
AssigneeId = t.AssigneeId?.Value,
EstimatedHours = t.EstimatedHours,
ActualHours = t.ActualHours,
CreatedBy = t.CreatedBy.Value,
CreatedAt = t.CreatedAt,
UpdatedAt = t.UpdatedAt
}).ToList()
};
}
}

View File

@@ -0,0 +1,18 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
/// <summary>
/// Validator for AssignStoryCommand
/// </summary>
public sealed class AssignStoryCommandValidator : AbstractValidator<AssignStoryCommand>
{
public AssignStoryCommandValidator()
{
RuleFor(x => x.StoryId)
.NotEmpty().WithMessage("Story ID is required");
RuleFor(x => x.AssigneeId)
.NotEmpty().WithMessage("Assignee ID is required");
}
}

View File

@@ -0,0 +1,13 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
/// <summary>
/// Command to assign a Task to a user
/// </summary>
public sealed record AssignTaskCommand : IRequest<TaskDto>
{
public Guid TaskId { get; init; }
public Guid? AssigneeId { get; init; }
}

View File

@@ -0,0 +1,85 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
/// <summary>
/// Handler for AssignTaskCommand
/// </summary>
public sealed class AssignTaskCommandHandler : IRequestHandler<AssignTaskCommand, TaskDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public AssignTaskCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<TaskDto> Handle(AssignTaskCommand request, CancellationToken cancellationToken)
{
// Get the project containing the task
var taskId = TaskId.From(request.TaskId);
var project = await _projectRepository.GetProjectWithTaskAsync(taskId, cancellationToken);
if (project == null)
throw new NotFoundException("Task", request.TaskId);
// Find the task within the project aggregate
WorkTask? task = null;
foreach (var epic in project.Epics)
{
foreach (var story in epic.Stories)
{
task = story.Tasks.FirstOrDefault(t => t.Id.Value == request.TaskId);
if (task != null)
break;
}
if (task != null)
break;
}
if (task == null)
throw new NotFoundException("Task", request.TaskId);
// Assign task
if (request.AssigneeId.HasValue)
{
var assigneeId = UserId.From(request.AssigneeId.Value);
task.AssignTo(assigneeId);
}
else
{
// Unassign by setting to null - need to add this method to WorkTask
task.AssignTo(null!);
}
// Update project
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
};
}
}

View File

@@ -0,0 +1,16 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
/// <summary>
/// Validator for AssignTaskCommand
/// </summary>
public sealed class AssignTaskCommandValidator : AbstractValidator<AssignTaskCommand>
{
public AssignTaskCommandValidator()
{
RuleFor(x => x.TaskId)
.NotEmpty()
.WithMessage("TaskId is required");
}
}

View File

@@ -46,8 +46,8 @@ public sealed class CreateEpicCommandHandler : IRequestHandler<CreateEpicCommand
Name = epic.Name,
Description = epic.Description,
ProjectId = epic.ProjectId.Value,
Status = epic.Status.Value,
Priority = epic.Priority.Value,
Status = epic.Status.Name,
Priority = epic.Priority.Name,
CreatedBy = epic.CreatedBy.Value,
CreatedAt = epic.CreatedAt,
UpdatedAt = epic.UpdatedAt,

View File

@@ -0,0 +1,18 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
/// <summary>
/// Command to create a new Story
/// </summary>
public sealed record CreateStoryCommand : IRequest<StoryDto>
{
public Guid EpicId { get; init; }
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string Priority { get; init; } = "Medium";
public Guid? AssigneeId { get; init; }
public decimal? EstimatedHours { get; init; }
public Guid CreatedBy { get; init; }
}

View File

@@ -0,0 +1,88 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
/// <summary>
/// Handler for CreateStoryCommand
/// </summary>
public sealed class CreateStoryCommandHandler : IRequestHandler<CreateStoryCommand, StoryDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public CreateStoryCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<StoryDto> Handle(CreateStoryCommand request, CancellationToken cancellationToken)
{
// Get the project with epic
var epicId = EpicId.From(request.EpicId);
var project = await _projectRepository.GetProjectWithEpicAsync(epicId, cancellationToken);
if (project == null)
throw new NotFoundException("Epic", request.EpicId);
// Find the epic
var epic = project.Epics.FirstOrDefault(e => e.Id.Value == request.EpicId);
if (epic == null)
throw new NotFoundException("Epic", request.EpicId);
// Parse priority
var priority = request.Priority switch
{
"Low" => TaskPriority.Low,
"Medium" => TaskPriority.Medium,
"High" => TaskPriority.High,
"Urgent" => TaskPriority.Urgent,
_ => TaskPriority.Medium
};
// Create story through epic
var createdById = UserId.From(request.CreatedBy);
var story = epic.CreateStory(request.Title, request.Description, priority, createdById);
// Assign if assignee provided
if (request.AssigneeId.HasValue)
{
var assigneeId = UserId.From(request.AssigneeId.Value);
story.AssignTo(assigneeId);
}
// Set estimated hours if provided
if (request.EstimatedHours.HasValue)
{
story.UpdateEstimate(request.EstimatedHours.Value);
}
// Update project (story is part of aggregate)
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new StoryDto
{
Id = story.Id.Value,
Title = story.Title,
Description = story.Description,
EpicId = story.EpicId.Value,
Status = story.Status.Name,
Priority = story.Priority.Name,
AssigneeId = story.AssigneeId?.Value,
EstimatedHours = story.EstimatedHours,
ActualHours = story.ActualHours,
CreatedBy = story.CreatedBy.Value,
CreatedAt = story.CreatedAt,
UpdatedAt = story.UpdatedAt,
Tasks = new List<TaskDto>()
};
}
}

View File

@@ -0,0 +1,31 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
/// <summary>
/// Validator for CreateStoryCommand
/// </summary>
public sealed class CreateStoryCommandValidator : AbstractValidator<CreateStoryCommand>
{
public CreateStoryCommandValidator()
{
RuleFor(x => x.EpicId)
.NotEmpty().WithMessage("Epic ID is required");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("Story title is required")
.MaximumLength(200).WithMessage("Story title cannot exceed 200 characters");
RuleFor(x => x.Priority)
.NotEmpty().WithMessage("Priority is required")
.Must(p => p == "Low" || p == "Medium" || p == "High" || p == "Urgent")
.WithMessage("Priority must be one of: Low, Medium, High, Urgent");
RuleFor(x => x.EstimatedHours)
.GreaterThanOrEqualTo(0).When(x => x.EstimatedHours.HasValue)
.WithMessage("Estimated hours cannot be negative");
RuleFor(x => x.CreatedBy)
.NotEmpty().WithMessage("Created by user ID is required");
}
}

View File

@@ -0,0 +1,18 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
/// <summary>
/// Command to create a new Task
/// </summary>
public sealed record CreateTaskCommand : IRequest<TaskDto>
{
public Guid StoryId { get; init; }
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string Priority { get; init; } = "Medium";
public decimal? EstimatedHours { get; init; }
public Guid? AssigneeId { get; init; }
public Guid CreatedBy { get; init; }
}

View File

@@ -0,0 +1,87 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
/// <summary>
/// Handler for CreateTaskCommand
/// </summary>
public sealed class CreateTaskCommandHandler : IRequestHandler<CreateTaskCommand, TaskDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public CreateTaskCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<TaskDto> Handle(CreateTaskCommand request, CancellationToken cancellationToken)
{
// Get the project containing the story
var storyId = StoryId.From(request.StoryId);
var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);
if (project == null)
throw new NotFoundException("Story", request.StoryId);
// Find the story within the project aggregate
Story? story = null;
foreach (var epic in project.Epics)
{
story = epic.Stories.FirstOrDefault(s => s.Id.Value == request.StoryId);
if (story is not null)
break;
}
if (story is null)
throw new NotFoundException("Story", request.StoryId);
// Parse priority
var priority = TaskPriority.FromDisplayName<TaskPriority>(request.Priority);
var createdById = UserId.From(request.CreatedBy);
// Create task through story aggregate
var task = story.CreateTask(request.Title, request.Description, priority, createdById);
// Set optional fields
if (request.EstimatedHours.HasValue)
{
task.UpdateEstimate(request.EstimatedHours.Value);
}
if (request.AssigneeId.HasValue)
{
var assigneeId = UserId.From(request.AssigneeId.Value);
task.AssignTo(assigneeId);
}
// Update project (task is part of aggregate)
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
};
}
}

View File

@@ -0,0 +1,47 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
/// <summary>
/// Validator for CreateTaskCommand
/// </summary>
public sealed class CreateTaskCommandValidator : AbstractValidator<CreateTaskCommand>
{
public CreateTaskCommandValidator()
{
RuleFor(x => x.StoryId)
.NotEmpty()
.WithMessage("StoryId is required");
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required")
.MaximumLength(200)
.WithMessage("Title cannot exceed 200 characters");
RuleFor(x => x.Description)
.MaximumLength(5000)
.WithMessage("Description cannot exceed 5000 characters");
RuleFor(x => x.Priority)
.NotEmpty()
.WithMessage("Priority is required")
.Must(BeValidPriority)
.WithMessage("Priority must be one of: Low, Medium, High, Urgent");
RuleFor(x => x.EstimatedHours)
.GreaterThanOrEqualTo(0)
.When(x => x.EstimatedHours.HasValue)
.WithMessage("Estimated hours cannot be negative");
RuleFor(x => x.CreatedBy)
.NotEmpty()
.WithMessage("CreatedBy is required");
}
private bool BeValidPriority(string priority)
{
var validPriorities = new[] { "Low", "Medium", "High", "Urgent" };
return validPriorities.Contains(priority, StringComparer.OrdinalIgnoreCase);
}
}

View File

@@ -0,0 +1,11 @@
using MediatR;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
/// <summary>
/// Command to delete a Story
/// </summary>
public sealed record DeleteStoryCommand : IRequest<Unit>
{
public Guid StoryId { get; init; }
}

View File

@@ -0,0 +1,47 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
/// <summary>
/// Handler for DeleteStoryCommand
/// </summary>
public sealed class DeleteStoryCommandHandler : IRequestHandler<DeleteStoryCommand, Unit>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public DeleteStoryCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<Unit> Handle(DeleteStoryCommand request, CancellationToken cancellationToken)
{
// Get the project with story
var storyId = StoryId.From(request.StoryId);
var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);
if (project == null)
throw new NotFoundException("Story", request.StoryId);
// Find the epic containing the story
var epic = project.Epics.FirstOrDefault(e => e.Stories.Any(s => s.Id.Value == request.StoryId));
if (epic == null)
throw new NotFoundException("Story", request.StoryId);
// Remove story from epic (domain logic validates no tasks exist)
epic.RemoveStory(storyId);
// Save changes
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}

View File

@@ -0,0 +1,15 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
/// <summary>
/// Validator for DeleteStoryCommand
/// </summary>
public sealed class DeleteStoryCommandValidator : AbstractValidator<DeleteStoryCommand>
{
public DeleteStoryCommandValidator()
{
RuleFor(x => x.StoryId)
.NotEmpty().WithMessage("Story ID is required");
}
}

View File

@@ -0,0 +1,11 @@
using MediatR;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
/// <summary>
/// Command to delete a Task
/// </summary>
public sealed record DeleteTaskCommand : IRequest<Unit>
{
public Guid TaskId { get; init; }
}

View File

@@ -0,0 +1,63 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
/// <summary>
/// Handler for DeleteTaskCommand
/// </summary>
public sealed class DeleteTaskCommandHandler : IRequestHandler<DeleteTaskCommand, Unit>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public DeleteTaskCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<Unit> Handle(DeleteTaskCommand request, CancellationToken cancellationToken)
{
// Get the project containing the task
var taskId = TaskId.From(request.TaskId);
var project = await _projectRepository.GetProjectWithTaskAsync(taskId, cancellationToken);
if (project == null)
throw new NotFoundException("Task", request.TaskId);
// Find the story containing the task
Story? parentStory = null;
foreach (var epic in project.Epics)
{
foreach (var story in epic.Stories)
{
var task = story.Tasks.FirstOrDefault(t => t.Id.Value == request.TaskId);
if (task != null)
{
parentStory = story;
break;
}
}
if (parentStory != null)
break;
}
if (parentStory == null)
throw new NotFoundException("Task", request.TaskId);
// Remove task from story
parentStory.RemoveTask(taskId);
// Update project
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}

View File

@@ -0,0 +1,16 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
/// <summary>
/// Validator for DeleteTaskCommand
/// </summary>
public sealed class DeleteTaskCommandValidator : AbstractValidator<DeleteTaskCommand>
{
public DeleteTaskCommandValidator()
{
RuleFor(x => x.TaskId)
.NotEmpty()
.WithMessage("TaskId is required");
}
}

View File

@@ -50,8 +50,8 @@ public sealed class UpdateEpicCommandHandler : IRequestHandler<UpdateEpicCommand
Name = epic.Name,
Description = epic.Description,
ProjectId = epic.ProjectId.Value,
Status = epic.Status.Value,
Priority = epic.Priority.Value,
Status = epic.Status.Name,
Priority = epic.Priority.Name,
CreatedBy = epic.CreatedBy.Value,
CreatedAt = epic.CreatedAt,
UpdatedAt = epic.UpdatedAt,
@@ -61,8 +61,8 @@ public sealed class UpdateEpicCommandHandler : IRequestHandler<UpdateEpicCommand
Title = s.Title,
Description = s.Description,
EpicId = s.EpicId.Value,
Status = s.Status.Value,
Priority = s.Priority.Value,
Status = s.Status.Name,
Priority = s.Priority.Name,
EstimatedHours = s.EstimatedHours,
ActualHours = s.ActualHours,
AssigneeId = s.AssigneeId?.Value,

View File

@@ -0,0 +1,18 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
/// <summary>
/// Command to update an existing Story
/// </summary>
public sealed record UpdateStoryCommand : IRequest<StoryDto>
{
public Guid StoryId { get; init; }
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string? Status { get; init; }
public string? Priority { get; init; }
public Guid? AssigneeId { get; init; }
public decimal? EstimatedHours { get; init; }
}

View File

@@ -0,0 +1,116 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
/// <summary>
/// Handler for UpdateStoryCommand
/// </summary>
public sealed class UpdateStoryCommandHandler : IRequestHandler<UpdateStoryCommand, StoryDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public UpdateStoryCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<StoryDto> Handle(UpdateStoryCommand request, CancellationToken cancellationToken)
{
// Get the project with story
var storyId = StoryId.From(request.StoryId);
var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);
if (project == null)
throw new NotFoundException("Story", request.StoryId);
// Find the story
var story = project.Epics
.SelectMany(e => e.Stories)
.FirstOrDefault(s => s.Id.Value == request.StoryId);
if (story == null)
throw new NotFoundException("Story", request.StoryId);
// Update basic details
story.UpdateDetails(request.Title, request.Description);
// Update status if provided
if (!string.IsNullOrEmpty(request.Status))
{
var status = request.Status switch
{
"To Do" => WorkItemStatus.ToDo,
"In Progress" => WorkItemStatus.InProgress,
"In Review" => WorkItemStatus.InReview,
"Done" => WorkItemStatus.Done,
"Blocked" => WorkItemStatus.Blocked,
_ => throw new DomainException($"Invalid status: {request.Status}")
};
story.UpdateStatus(status);
}
// Update priority if provided
if (!string.IsNullOrEmpty(request.Priority))
{
var priority = TaskPriority.FromDisplayName<TaskPriority>(request.Priority);
story.UpdatePriority(priority);
}
// Update assignee if provided
if (request.AssigneeId.HasValue)
{
var assigneeId = UserId.From(request.AssigneeId.Value);
story.AssignTo(assigneeId);
}
// Update estimated hours if provided
if (request.EstimatedHours.HasValue)
{
story.UpdateEstimate(request.EstimatedHours.Value);
}
// Save changes
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new StoryDto
{
Id = story.Id.Value,
Title = story.Title,
Description = story.Description,
EpicId = story.EpicId.Value,
Status = story.Status.Name,
Priority = story.Priority.Name,
AssigneeId = story.AssigneeId?.Value,
EstimatedHours = story.EstimatedHours,
ActualHours = story.ActualHours,
CreatedBy = story.CreatedBy.Value,
CreatedAt = story.CreatedAt,
UpdatedAt = story.UpdatedAt,
Tasks = story.Tasks.Select(t => new TaskDto
{
Id = t.Id.Value,
Title = t.Title,
Description = t.Description,
StoryId = t.StoryId.Value,
Status = t.Status.Name,
Priority = t.Priority.Name,
AssigneeId = t.AssigneeId?.Value,
EstimatedHours = t.EstimatedHours,
ActualHours = t.ActualHours,
CreatedBy = t.CreatedBy.Value,
CreatedAt = t.CreatedAt,
UpdatedAt = t.UpdatedAt
}).ToList()
};
}
}

View File

@@ -0,0 +1,31 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
/// <summary>
/// Validator for UpdateStoryCommand
/// </summary>
public sealed class UpdateStoryCommandValidator : AbstractValidator<UpdateStoryCommand>
{
public UpdateStoryCommandValidator()
{
RuleFor(x => x.StoryId)
.NotEmpty().WithMessage("Story ID is required");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("Story title is required")
.MaximumLength(200).WithMessage("Story title cannot exceed 200 characters");
RuleFor(x => x.Status)
.Must(s => s == null || s == "To Do" || s == "In Progress" || s == "In Review" || s == "Done" || s == "Blocked")
.WithMessage("Status must be one of: To Do, In Progress, In Review, Done, Blocked");
RuleFor(x => x.Priority)
.Must(p => p == null || p == "Low" || p == "Medium" || p == "High" || p == "Urgent")
.WithMessage("Priority must be one of: Low, Medium, High, Urgent");
RuleFor(x => x.EstimatedHours)
.GreaterThanOrEqualTo(0).When(x => x.EstimatedHours.HasValue)
.WithMessage("Estimated hours cannot be negative");
}
}

View File

@@ -0,0 +1,18 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
/// <summary>
/// Command to update an existing Task
/// </summary>
public sealed record UpdateTaskCommand : IRequest<TaskDto>
{
public Guid TaskId { get; init; }
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string? Priority { get; init; }
public string? Status { get; init; }
public decimal? EstimatedHours { get; init; }
public Guid? AssigneeId { get; init; }
}

View File

@@ -0,0 +1,103 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
/// <summary>
/// Handler for UpdateTaskCommand
/// </summary>
public sealed class UpdateTaskCommandHandler : IRequestHandler<UpdateTaskCommand, TaskDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public UpdateTaskCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<TaskDto> Handle(UpdateTaskCommand request, CancellationToken cancellationToken)
{
// Get the project containing the task
var taskId = TaskId.From(request.TaskId);
var project = await _projectRepository.GetProjectWithTaskAsync(taskId, cancellationToken);
if (project == null)
throw new NotFoundException("Task", request.TaskId);
// Find the task within the project aggregate
WorkTask? task = null;
foreach (var epic in project.Epics)
{
foreach (var story in epic.Stories)
{
task = story.Tasks.FirstOrDefault(t => t.Id.Value == request.TaskId);
if (task != null)
break;
}
if (task != null)
break;
}
if (task == null)
throw new NotFoundException("Task", request.TaskId);
// Update task details
task.UpdateDetails(request.Title, request.Description);
// Update priority if provided
if (!string.IsNullOrWhiteSpace(request.Priority))
{
var priority = TaskPriority.FromDisplayName<TaskPriority>(request.Priority);
task.UpdatePriority(priority);
}
// Update status if provided
if (!string.IsNullOrWhiteSpace(request.Status))
{
var status = WorkItemStatus.FromDisplayName<WorkItemStatus>(request.Status);
task.UpdateStatus(status);
}
// Update estimated hours if provided
if (request.EstimatedHours.HasValue)
{
task.UpdateEstimate(request.EstimatedHours.Value);
}
// Update assignee if provided
if (request.AssigneeId.HasValue)
{
var assigneeId = UserId.From(request.AssigneeId.Value);
task.AssignTo(assigneeId);
}
// Update project
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
};
}
}

View File

@@ -0,0 +1,55 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
/// <summary>
/// Validator for UpdateTaskCommand
/// </summary>
public sealed class UpdateTaskCommandValidator : AbstractValidator<UpdateTaskCommand>
{
public UpdateTaskCommandValidator()
{
RuleFor(x => x.TaskId)
.NotEmpty()
.WithMessage("TaskId is required");
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required")
.MaximumLength(200)
.WithMessage("Title cannot exceed 200 characters");
RuleFor(x => x.Description)
.MaximumLength(5000)
.WithMessage("Description cannot exceed 5000 characters");
RuleFor(x => x.Priority)
.Must(BeValidPriority)
.When(x => !string.IsNullOrWhiteSpace(x.Priority))
.WithMessage("Priority must be one of: Low, Medium, High, Urgent");
RuleFor(x => x.Status)
.Must(BeValidStatus)
.When(x => !string.IsNullOrWhiteSpace(x.Status))
.WithMessage("Status must be one of: ToDo, InProgress, Done, Blocked");
RuleFor(x => x.EstimatedHours)
.GreaterThanOrEqualTo(0)
.When(x => x.EstimatedHours.HasValue)
.WithMessage("Estimated hours cannot be negative");
}
private bool BeValidPriority(string? priority)
{
if (string.IsNullOrWhiteSpace(priority)) return true;
var validPriorities = new[] { "Low", "Medium", "High", "Urgent" };
return validPriorities.Contains(priority, StringComparer.OrdinalIgnoreCase);
}
private bool BeValidStatus(string? status)
{
if (string.IsNullOrWhiteSpace(status)) return true;
var validStatuses = new[] { "ToDo", "InProgress", "Done", "Blocked" };
return validStatuses.Contains(status, StringComparer.OrdinalIgnoreCase);
}
}

View File

@@ -0,0 +1,13 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
/// <summary>
/// Command to update Task status (for Kanban board drag & drop)
/// </summary>
public sealed record UpdateTaskStatusCommand : IRequest<TaskDto>
{
public Guid TaskId { get; init; }
public string NewStatus { get; init; } = string.Empty;
}

View File

@@ -0,0 +1,95 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
/// <summary>
/// Handler for UpdateTaskStatusCommand
/// </summary>
public sealed class UpdateTaskStatusCommandHandler : IRequestHandler<UpdateTaskStatusCommand, TaskDto>
{
private readonly IProjectRepository _projectRepository;
private readonly IUnitOfWork _unitOfWork;
public UpdateTaskStatusCommandHandler(
IProjectRepository projectRepository,
IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<TaskDto> Handle(UpdateTaskStatusCommand request, CancellationToken cancellationToken)
{
// Get the project containing the task
var taskId = TaskId.From(request.TaskId);
var project = await _projectRepository.GetProjectWithTaskAsync(taskId, cancellationToken);
if (project == null)
throw new NotFoundException("Task", request.TaskId);
// Find the task within the project aggregate
WorkTask? task = null;
foreach (var epic in project.Epics)
{
foreach (var story in epic.Stories)
{
task = story.Tasks.FirstOrDefault(t => t.Id.Value == request.TaskId);
if (task != null)
break;
}
if (task != null)
break;
}
if (task == null)
throw new NotFoundException("Task", request.TaskId);
// Parse and validate new status
var newStatus = WorkItemStatus.FromDisplayName<WorkItemStatus>(request.NewStatus);
// Validate status transition (business rule)
ValidateStatusTransition(task.Status, newStatus);
// Update task status
task.UpdateStatus(newStatus);
// Update project
_projectRepository.Update(project);
await _unitOfWork.SaveChangesAsync(cancellationToken);
// Map to DTO
return new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
};
}
private void ValidateStatusTransition(WorkItemStatus currentStatus, WorkItemStatus newStatus)
{
// Business rule: Can't move from Done back to ToDo
if (currentStatus == WorkItemStatus.Done && newStatus == WorkItemStatus.ToDo)
{
throw new DomainException("Cannot move a completed task back to ToDo. Please create a new task instead.");
}
// Business rule: Blocked can be moved to any status
// Business rule: Any status can be moved to Blocked
// All other transitions are allowed
}
}

View File

@@ -0,0 +1,28 @@
using FluentValidation;
namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
/// <summary>
/// Validator for UpdateTaskStatusCommand
/// </summary>
public sealed class UpdateTaskStatusCommandValidator : AbstractValidator<UpdateTaskStatusCommand>
{
public UpdateTaskStatusCommandValidator()
{
RuleFor(x => x.TaskId)
.NotEmpty()
.WithMessage("TaskId is required");
RuleFor(x => x.NewStatus)
.NotEmpty()
.WithMessage("NewStatus is required")
.Must(BeValidStatus)
.WithMessage("NewStatus must be one of: ToDo, InProgress, Done, Blocked");
}
private bool BeValidStatus(string status)
{
var validStatuses = new[] { "ToDo", "InProgress", "Done", "Blocked" };
return validStatuses.Contains(status, StringComparer.OrdinalIgnoreCase);
}
}

View File

@@ -36,8 +36,8 @@ public sealed class GetEpicByIdQueryHandler : IRequestHandler<GetEpicByIdQuery,
Name = epic.Name,
Description = epic.Description,
ProjectId = epic.ProjectId.Value,
Status = epic.Status.Value,
Priority = epic.Priority.Value,
Status = epic.Status.Name,
Priority = epic.Priority.Name,
CreatedBy = epic.CreatedBy.Value,
CreatedAt = epic.CreatedAt,
UpdatedAt = epic.UpdatedAt,
@@ -47,8 +47,8 @@ public sealed class GetEpicByIdQueryHandler : IRequestHandler<GetEpicByIdQuery,
Title = s.Title,
Description = s.Description,
EpicId = s.EpicId.Value,
Status = s.Status.Value,
Priority = s.Priority.Value,
Status = s.Status.Name,
Priority = s.Priority.Name,
EstimatedHours = s.EstimatedHours,
ActualHours = s.ActualHours,
AssigneeId = s.AssigneeId?.Value,

View File

@@ -32,8 +32,8 @@ public sealed class GetEpicsByProjectIdQueryHandler : IRequestHandler<GetEpicsBy
Name = epic.Name,
Description = epic.Description,
ProjectId = epic.ProjectId.Value,
Status = epic.Status.Value,
Priority = epic.Priority.Value,
Status = epic.Status.Name,
Priority = epic.Priority.Name,
CreatedBy = epic.CreatedBy.Value,
CreatedAt = epic.CreatedAt,
UpdatedAt = epic.UpdatedAt,

View File

@@ -0,0 +1,9 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByEpicId;
/// <summary>
/// Query to get all Stories for an Epic
/// </summary>
public sealed record GetStoriesByEpicIdQuery(Guid EpicId) : IRequest<List<StoryDto>>;

View File

@@ -0,0 +1,67 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByEpicId;
/// <summary>
/// Handler for GetStoriesByEpicIdQuery
/// </summary>
public sealed class GetStoriesByEpicIdQueryHandler : IRequestHandler<GetStoriesByEpicIdQuery, List<StoryDto>>
{
private readonly IProjectRepository _projectRepository;
public GetStoriesByEpicIdQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<List<StoryDto>> Handle(GetStoriesByEpicIdQuery request, CancellationToken cancellationToken)
{
// Get the project with epic
var epicId = EpicId.From(request.EpicId);
var project = await _projectRepository.GetProjectWithEpicAsync(epicId, cancellationToken);
if (project == null)
throw new NotFoundException("Epic", request.EpicId);
// Find the epic
var epic = project.Epics.FirstOrDefault(e => e.Id.Value == request.EpicId);
if (epic == null)
throw new NotFoundException("Epic", request.EpicId);
// Map stories to DTOs
return epic.Stories.Select(story => new StoryDto
{
Id = story.Id.Value,
Title = story.Title,
Description = story.Description,
EpicId = story.EpicId.Value,
Status = story.Status.Name,
Priority = story.Priority.Name,
AssigneeId = story.AssigneeId?.Value,
EstimatedHours = story.EstimatedHours,
ActualHours = story.ActualHours,
CreatedBy = story.CreatedBy.Value,
CreatedAt = story.CreatedAt,
UpdatedAt = story.UpdatedAt,
Tasks = story.Tasks.Select(t => new TaskDto
{
Id = t.Id.Value,
Title = t.Title,
Description = t.Description,
StoryId = t.StoryId.Value,
Status = t.Status.Name,
Priority = t.Priority.Name,
AssigneeId = t.AssigneeId?.Value,
EstimatedHours = t.EstimatedHours,
ActualHours = t.ActualHours,
CreatedBy = t.CreatedBy.Value,
CreatedAt = t.CreatedAt,
UpdatedAt = t.UpdatedAt
}).ToList()
}).ToList();
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByProjectId;
/// <summary>
/// Query to get all Stories for a Project
/// </summary>
public sealed record GetStoriesByProjectIdQuery(Guid ProjectId) : IRequest<List<StoryDto>>;

View File

@@ -0,0 +1,66 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByProjectId;
/// <summary>
/// Handler for GetStoriesByProjectIdQuery
/// </summary>
public sealed class GetStoriesByProjectIdQueryHandler : IRequestHandler<GetStoriesByProjectIdQuery, List<StoryDto>>
{
private readonly IProjectRepository _projectRepository;
public GetStoriesByProjectIdQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<List<StoryDto>> Handle(GetStoriesByProjectIdQuery request, CancellationToken cancellationToken)
{
// Get the project
var projectId = ProjectId.From(request.ProjectId);
var project = await _projectRepository.GetByIdAsync(projectId, cancellationToken);
if (project == null)
throw new NotFoundException("Project", request.ProjectId);
// Get all stories from all epics
var stories = project.Epics
.SelectMany(epic => epic.Stories.Select(story => new StoryDto
{
Id = story.Id.Value,
Title = story.Title,
Description = story.Description,
EpicId = story.EpicId.Value,
Status = story.Status.Name,
Priority = story.Priority.Name,
AssigneeId = story.AssigneeId?.Value,
EstimatedHours = story.EstimatedHours,
ActualHours = story.ActualHours,
CreatedBy = story.CreatedBy.Value,
CreatedAt = story.CreatedAt,
UpdatedAt = story.UpdatedAt,
Tasks = story.Tasks.Select(t => new TaskDto
{
Id = t.Id.Value,
Title = t.Title,
Description = t.Description,
StoryId = t.StoryId.Value,
Status = t.Status.Name,
Priority = t.Priority.Name,
AssigneeId = t.AssigneeId?.Value,
EstimatedHours = t.EstimatedHours,
ActualHours = t.ActualHours,
CreatedBy = t.CreatedBy.Value,
CreatedAt = t.CreatedAt,
UpdatedAt = t.UpdatedAt
}).ToList()
}))
.ToList();
return stories;
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoryById;
/// <summary>
/// Query to get a Story by ID
/// </summary>
public sealed record GetStoryByIdQuery(Guid StoryId) : IRequest<StoryDto>;

View File

@@ -0,0 +1,70 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoryById;
/// <summary>
/// Handler for GetStoryByIdQuery
/// </summary>
public sealed class GetStoryByIdQueryHandler : IRequestHandler<GetStoryByIdQuery, StoryDto>
{
private readonly IProjectRepository _projectRepository;
public GetStoryByIdQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<StoryDto> Handle(GetStoryByIdQuery request, CancellationToken cancellationToken)
{
// Get the project with story
var storyId = StoryId.From(request.StoryId);
var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);
if (project == null)
throw new NotFoundException("Story", request.StoryId);
// Find the story
var story = project.Epics
.SelectMany(e => e.Stories)
.FirstOrDefault(s => s.Id.Value == request.StoryId);
if (story == null)
throw new NotFoundException("Story", request.StoryId);
// Map to DTO
return new StoryDto
{
Id = story.Id.Value,
Title = story.Title,
Description = story.Description,
EpicId = story.EpicId.Value,
Status = story.Status.Name,
Priority = story.Priority.Name,
AssigneeId = story.AssigneeId?.Value,
EstimatedHours = story.EstimatedHours,
ActualHours = story.ActualHours,
CreatedBy = story.CreatedBy.Value,
CreatedAt = story.CreatedAt,
UpdatedAt = story.UpdatedAt,
Tasks = story.Tasks.Select(t => new TaskDto
{
Id = t.Id.Value,
Title = t.Title,
Description = t.Description,
StoryId = t.StoryId.Value,
Status = t.Status.Name,
Priority = t.Priority.Name,
AssigneeId = t.AssigneeId?.Value,
EstimatedHours = t.EstimatedHours,
ActualHours = t.ActualHours,
CreatedBy = t.CreatedBy.Value,
CreatedAt = t.CreatedAt,
UpdatedAt = t.UpdatedAt
}).ToList()
};
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
/// <summary>
/// Query to get a Task by ID
/// </summary>
public sealed record GetTaskByIdQuery(Guid TaskId) : IRequest<TaskDto>;

View File

@@ -0,0 +1,65 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
/// <summary>
/// Handler for GetTaskByIdQuery
/// </summary>
public sealed class GetTaskByIdQueryHandler : IRequestHandler<GetTaskByIdQuery, TaskDto>
{
private readonly IProjectRepository _projectRepository;
public GetTaskByIdQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<TaskDto> Handle(GetTaskByIdQuery request, CancellationToken cancellationToken)
{
// Get the project containing the task
var taskId = TaskId.From(request.TaskId);
var project = await _projectRepository.GetProjectWithTaskAsync(taskId, cancellationToken);
if (project == null)
throw new NotFoundException("Task", request.TaskId);
// Find the task within the project aggregate
WorkTask? task = null;
foreach (var epic in project.Epics)
{
foreach (var story in epic.Stories)
{
task = story.Tasks.FirstOrDefault(t => t.Id.Value == request.TaskId);
if (task != null)
break;
}
if (task != null)
break;
}
if (task == null)
throw new NotFoundException("Task", request.TaskId);
// Map to DTO
return new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
};
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByAssignee;
/// <summary>
/// Query to get all Tasks assigned to a user
/// </summary>
public sealed record GetTasksByAssigneeQuery(Guid AssigneeId) : IRequest<List<TaskDto>>;

View File

@@ -0,0 +1,49 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByAssignee;
/// <summary>
/// Handler for GetTasksByAssigneeQuery
/// </summary>
public sealed class GetTasksByAssigneeQueryHandler : IRequestHandler<GetTasksByAssigneeQuery, List<TaskDto>>
{
private readonly IProjectRepository _projectRepository;
public GetTasksByAssigneeQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<List<TaskDto>> Handle(GetTasksByAssigneeQuery request, CancellationToken cancellationToken)
{
// Get all projects
var allProjects = await _projectRepository.GetAllAsync(cancellationToken);
// Get all tasks assigned to the user across all projects
var userTasks = allProjects
.SelectMany(project => project.Epics)
.SelectMany(epic => epic.Stories)
.SelectMany(story => story.Tasks)
.Where(task => task.AssigneeId != null && task.AssigneeId.Value == request.AssigneeId)
.ToList();
// Map to DTOs
return userTasks.Select(task => new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
}).ToList();
}
}

View File

@@ -0,0 +1,14 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByProjectId;
/// <summary>
/// Query to get all Tasks for a Project (for Kanban board)
/// </summary>
public sealed record GetTasksByProjectIdQuery : IRequest<List<TaskDto>>
{
public Guid ProjectId { get; init; }
public string? Status { get; init; }
public Guid? AssigneeId { get; init; }
}

View File

@@ -0,0 +1,64 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByProjectId;
/// <summary>
/// Handler for GetTasksByProjectIdQuery
/// </summary>
public sealed class GetTasksByProjectIdQueryHandler : IRequestHandler<GetTasksByProjectIdQuery, List<TaskDto>>
{
private readonly IProjectRepository _projectRepository;
public GetTasksByProjectIdQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<List<TaskDto>> Handle(GetTasksByProjectIdQuery request, CancellationToken cancellationToken)
{
// Get the project with all its tasks
var projectId = ProjectId.From(request.ProjectId);
var project = await _projectRepository.GetByIdAsync(projectId, cancellationToken);
if (project == null)
throw new NotFoundException("Project", request.ProjectId);
// Get all tasks from all stories in all epics
var allTasks = project.Epics
.SelectMany(epic => epic.Stories)
.SelectMany(story => story.Tasks)
.ToList();
// Apply filters
if (!string.IsNullOrWhiteSpace(request.Status))
{
allTasks = allTasks.Where(t => t.Status.Name.Equals(request.Status, StringComparison.OrdinalIgnoreCase)).ToList();
}
if (request.AssigneeId.HasValue)
{
allTasks = allTasks.Where(t => t.AssigneeId != null && t.AssigneeId.Value == request.AssigneeId.Value).ToList();
}
// Map to DTOs
return allTasks.Select(task => new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
}).ToList();
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStoryId;
/// <summary>
/// Query to get all Tasks for a Story
/// </summary>
public sealed record GetTasksByStoryIdQuery(Guid StoryId) : IRequest<List<TaskDto>>;

View File

@@ -0,0 +1,55 @@
using MediatR;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStoryId;
/// <summary>
/// Handler for GetTasksByStoryIdQuery
/// </summary>
public sealed class GetTasksByStoryIdQueryHandler : IRequestHandler<GetTasksByStoryIdQuery, List<TaskDto>>
{
private readonly IProjectRepository _projectRepository;
public GetTasksByStoryIdQueryHandler(IProjectRepository projectRepository)
{
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
}
public async Task<List<TaskDto>> Handle(GetTasksByStoryIdQuery request, CancellationToken cancellationToken)
{
// Get the project containing the story
var storyId = StoryId.From(request.StoryId);
var project = await _projectRepository.GetProjectWithStoryAsync(storyId, cancellationToken);
if (project == null)
throw new NotFoundException("Story", request.StoryId);
// Find the story within the project aggregate
var story = project.Epics
.SelectMany(e => e.Stories)
.FirstOrDefault(s => s.Id.Value == request.StoryId);
if (story == null)
throw new NotFoundException("Story", request.StoryId);
// Map tasks to DTOs
return story.Tasks.Select(task => new TaskDto
{
Id = task.Id.Value,
Title = task.Title,
Description = task.Description,
StoryId = task.StoryId.Value,
Status = task.Status.Name,
Priority = task.Priority.Name,
AssigneeId = task.AssigneeId?.Value,
EstimatedHours = task.EstimatedHours,
ActualHours = task.ActualHours,
CreatedBy = task.CreatedBy.Value,
CreatedAt = task.CreatedAt,
UpdatedAt = task.UpdatedAt
}).ToList();
}
}

View File

@@ -88,4 +88,17 @@ public class Epic : Entity
Priority = newPriority;
UpdatedAt = DateTime.UtcNow;
}
public void RemoveStory(StoryId storyId)
{
var story = _stories.FirstOrDefault(s => s.Id == storyId);
if (story == null)
throw new DomainException($"Story with ID {storyId.Value} not found in epic");
if (story.Tasks.Any())
throw new DomainException($"Cannot delete story with ID {storyId.Value}. The story has {story.Tasks.Count} associated task(s). Please delete or reassign the tasks first.");
_stories.Remove(story);
UpdatedAt = DateTime.UtcNow;
}
}

View File

@@ -67,6 +67,16 @@ public class Story : Entity
return task;
}
public void RemoveTask(TaskId taskId)
{
var task = _tasks.FirstOrDefault(t => t.Id == taskId);
if (task == null)
throw new DomainException($"Task with ID {taskId.Value} not found in story");
_tasks.Remove(task);
UpdatedAt = DateTime.UtcNow;
}
public void UpdateDetails(string title, string description)
{
if (string.IsNullOrWhiteSpace(title))
@@ -109,4 +119,10 @@ public class Story : Entity
ActualHours = hours;
UpdatedAt = DateTime.UtcNow;
}
public void UpdatePriority(TaskPriority newPriority)
{
Priority = newPriority;
UpdatedAt = DateTime.UtcNow;
}
}

View File

@@ -0,0 +1,112 @@
using ColaFlow.Shared.Kernel.Common;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Events;
namespace ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
/// <summary>
/// Story Entity (part of Project aggregate)
/// </summary>
public class Story : Entity
{
public new StoryId Id { get; private set; }
public string Title { get; private set; }
public string Description { get; private set; }
public EpicId EpicId { get; private set; }
public WorkItemStatus Status { get; private set; }
public TaskPriority Priority { get; private set; }
public decimal? EstimatedHours { get; private set; }
public decimal? ActualHours { get; private set; }
public UserId? AssigneeId { get; private set; }
private readonly List<WorkTask> _tasks = new();
public IReadOnlyCollection<WorkTask> Tasks => _tasks.AsReadOnly();
public DateTime CreatedAt { get; private set; }
public UserId CreatedBy { get; private set; }
public DateTime? UpdatedAt { get; private set; }
// EF Core constructor
private Story()
{
Id = null!;
Title = null!;
Description = null!;
EpicId = null!;
Status = null!;
Priority = null!;
CreatedBy = null!;
}
public static Story Create(string title, string description, EpicId epicId, TaskPriority priority, UserId createdBy)
{
if (string.IsNullOrWhiteSpace(title))
throw new DomainException("Story title cannot be empty");
if (title.Length > 200)
throw new DomainException("Story title cannot exceed 200 characters");
return new Story
{
Id = StoryId.Create(),
Title = title,
Description = description ?? string.Empty,
EpicId = epicId,
Status = WorkItemStatus.ToDo,
Priority = priority,
CreatedAt = DateTime.UtcNow,
CreatedBy = createdBy
};
}
public WorkTask CreateTask(string title, string description, TaskPriority priority, UserId createdBy)
{
var task = WorkTask.Create(title, description, this.Id, priority, createdBy);
_tasks.Add(task);
return task;
}
public void UpdateDetails(string title, string description)
{
if (string.IsNullOrWhiteSpace(title))
throw new DomainException("Story title cannot be empty");
if (title.Length > 200)
throw new DomainException("Story title cannot exceed 200 characters");
Title = title;
Description = description ?? string.Empty;
UpdatedAt = DateTime.UtcNow;
}
public void UpdateStatus(WorkItemStatus newStatus)
{
Status = newStatus;
UpdatedAt = DateTime.UtcNow;
}
public void AssignTo(UserId assigneeId)
{
AssigneeId = assigneeId;
UpdatedAt = DateTime.UtcNow;
}
public void UpdateEstimate(decimal hours)
{
if (hours < 0)
throw new DomainException("Estimated hours cannot be negative");
EstimatedHours = hours;
UpdatedAt = DateTime.UtcNow;
}
public void LogActualHours(decimal hours)
{
if (hours < 0)
throw new DomainException("Actual hours cannot be negative");
ActualHours = hours;
UpdatedAt = DateTime.UtcNow;
}
}

View File

@@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
{
[DbContext(typeof(PMDbContext))]
[Migration("20251102220422_InitialCreate")]
partial class InitialCreate
[Migration("20251103000604_FixValueObjectForeignKeys")]
partial class FixValueObjectForeignKeys
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@@ -55,9 +55,6 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
b.Property<Guid>("ProjectId")
.HasColumnType("uuid");
b.Property<Guid?>("ProjectId1")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(50)
@@ -72,8 +69,6 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
b.HasIndex("ProjectId");
b.HasIndex("ProjectId1");
b.ToTable("Epics", "project_management");
});
@@ -232,14 +227,10 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Epic", b =>
{
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", null)
.WithMany()
.WithMany("Epics")
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", null)
.WithMany("Epics")
.HasForeignKey("ProjectId1");
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", b =>
@@ -273,7 +264,7 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Story", b =>
{
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Epic", null)
.WithMany()
.WithMany("Stories")
.HasForeignKey("EpicId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
@@ -282,16 +273,26 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.WorkTask", b =>
{
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Story", null)
.WithMany()
.WithMany("Tasks")
.HasForeignKey("StoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Epic", b =>
{
b.Navigation("Stories");
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", b =>
{
b.Navigation("Epics");
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Story", b =>
{
b.Navigation("Tasks");
});
#pragma warning restore 612, 618
}
}

View File

@@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
public partial class FixValueObjectForeignKeys : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@@ -46,8 +46,7 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
Priority = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
CreatedBy = table.Column<Guid>(type: "uuid", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
ProjectId1 = table.Column<Guid>(type: "uuid", nullable: true)
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
@@ -59,12 +58,6 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
principalTable: "Projects",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Epics_Projects_ProjectId1",
column: x => x.ProjectId1,
principalSchema: "project_management",
principalTable: "Projects",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
@@ -139,12 +132,6 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
table: "Epics",
column: "ProjectId");
migrationBuilder.CreateIndex(
name: "IX_Epics_ProjectId1",
schema: "project_management",
table: "Epics",
column: "ProjectId1");
migrationBuilder.CreateIndex(
name: "IX_Projects_CreatedAt",
schema: "project_management",

View File

@@ -52,9 +52,6 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
b.Property<Guid>("ProjectId")
.HasColumnType("uuid");
b.Property<Guid?>("ProjectId1")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(50)
@@ -69,8 +66,6 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
b.HasIndex("ProjectId");
b.HasIndex("ProjectId1");
b.ToTable("Epics", "project_management");
});
@@ -229,14 +224,10 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Epic", b =>
{
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", null)
.WithMany()
.WithMany("Epics")
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", null)
.WithMany("Epics")
.HasForeignKey("ProjectId1");
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", b =>
@@ -270,7 +261,7 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Story", b =>
{
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Epic", null)
.WithMany()
.WithMany("Stories")
.HasForeignKey("EpicId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
@@ -279,16 +270,26 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Migrations
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.WorkTask", b =>
{
b.HasOne("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Story", null)
.WithMany()
.WithMany("Tasks")
.HasForeignKey("StoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Epic", b =>
{
b.Navigation("Stories");
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Project", b =>
{
b.Navigation("Epics");
});
modelBuilder.Entity("ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate.Story", b =>
{
b.Navigation("Tasks");
});
#pragma warning restore 612, 618
}
}

View File

@@ -70,13 +70,11 @@ public class EpicConfiguration : IEntityTypeConfiguration<Epic>
builder.Property(e => e.UpdatedAt);
// Ignore navigation properties (DDD pattern - access through aggregate)
builder.Ignore(e => e.Stories);
// Foreign key relationship to Project
builder.HasOne<Project>()
.WithMany()
.HasForeignKey(e => e.ProjectId)
// Configure Stories collection (owned by Epic in the aggregate)
// Use string-based FK name because EpicId is a value object with conversion configured in StoryConfiguration
builder.HasMany<Story>("Stories")
.WithOne()
.HasForeignKey("EpicId")
.OnDelete(DeleteBehavior.Cascade);
// Indexes

View File

@@ -67,7 +67,12 @@ public class ProjectConfiguration : IEntityTypeConfiguration<Project>
builder.Property(p => p.UpdatedAt);
// Relationships - Epics collection (owned by aggregate)
// Note: We don't expose this as navigation property in DDD, epics are accessed through repository
// Configure the one-to-many relationship with Epic
// Use string-based FK name because ProjectId is a value object with conversion configured in EpicConfiguration
builder.HasMany<Epic>("Epics")
.WithOne()
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Cascade);
// Indexes for performance
builder.HasIndex(p => p.CreatedAt);

View File

@@ -80,13 +80,11 @@ public class StoryConfiguration : IEntityTypeConfiguration<Story>
builder.Property(s => s.UpdatedAt);
// Ignore navigation properties (DDD pattern - access through aggregate)
builder.Ignore(s => s.Tasks);
// Foreign key relationship to Epic
builder.HasOne<Epic>()
.WithMany()
.HasForeignKey(s => s.EpicId)
// Configure Tasks collection (owned by Story in the aggregate)
// Use string-based FK name because StoryId is a value object with conversion configured in WorkTaskConfiguration
builder.HasMany<WorkTask>("Tasks")
.WithOne()
.HasForeignKey("StoryId")
.OnDelete(DeleteBehavior.Cascade);
// Indexes

View File

@@ -80,12 +80,6 @@ public class WorkTaskConfiguration : IEntityTypeConfiguration<WorkTask>
builder.Property(t => t.UpdatedAt);
// Foreign key relationship to Story
builder.HasOne<Story>()
.WithMany()
.HasForeignKey(t => t.StoryId)
.OnDelete(DeleteBehavior.Cascade);
// Indexes
builder.HasIndex(t => t.StoryId);
builder.HasIndex(t => t.AssigneeId);

View File

@@ -56,7 +56,21 @@ public abstract class Enumeration : IComparable
public static T FromDisplayName<T>(string displayName) where T : Enumeration
{
var matchingItem = Parse<T, string>(displayName, "display name", item => item.Name == displayName);
// First try exact match
var matchingItem = GetAll<T>().FirstOrDefault(item => item.Name == displayName);
// If not found, try removing spaces from both the input and the enumeration names
// This allows "InProgress" to match "In Progress", "ToDo" to match "To Do", etc.
if (matchingItem == null)
{
var normalizedInput = displayName.Replace(" ", "");
matchingItem = GetAll<T>().FirstOrDefault(item =>
item.Name.Replace(" ", "").Equals(normalizedInput, StringComparison.OrdinalIgnoreCase));
}
if (matchingItem == null)
throw new InvalidOperationException($"'{displayName}' is not a valid display name in {typeof(T)}");
return matchingItem;
}

View File

@@ -0,0 +1,35 @@
# Test script to verify no EF Core warnings
Write-Host "Starting API to check for EF Core warnings..." -ForegroundColor Cyan
$apiProcess = Start-Process -FilePath "dotnet" `
-ArgumentList "run --project C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api\src\ColaFlow.API\ColaFlow.API.csproj" `
-WorkingDirectory "C:\Users\yaoji\git\ColaCoder\product-master\colaflow-api" `
-RedirectStandardOutput "api-output.log" `
-RedirectStandardError "api-errors.log" `
-PassThru `
-NoNewWindow
Write-Host "Waiting 15 seconds for API to start..." -ForegroundColor Yellow
Start-Sleep -Seconds 15
# Check for warnings
$warnings = Select-String -Path "api-errors.log" -Pattern "(ProjectId1|EpicId1|StoryId1|shadow state.*conflicting)" -Context 1,1
if ($warnings) {
Write-Host "`nERROR: EF Core warnings found!" -ForegroundColor Red
$warnings | ForEach-Object { Write-Host $_.Line -ForegroundColor Red }
$exitCode = 1
} else {
Write-Host "`nSUCCESS: No EF Core warnings found!" -ForegroundColor Green
$exitCode = 0
}
# Stop API
Stop-Process -Id $apiProcess.Id -Force
Write-Host "`nAPI stopped." -ForegroundColor Cyan
# Show last 20 lines of logs
Write-Host "`nLast 20 lines of error log:" -ForegroundColor Yellow
Get-Content "api-errors.log" -Tail 20
exit $exitCode

View File

@@ -22,6 +22,8 @@
<ItemGroup>
<ProjectReference Include="..\..\src\ColaFlow.Application\ColaFlow.Application.csproj" />
<ProjectReference Include="..\..\src\Modules\ProjectManagement\ColaFlow.Modules.ProjectManagement.Application\ColaFlow.Modules.ProjectManagement.Application.csproj" />
<ProjectReference Include="..\..\src\Modules\ProjectManagement\ColaFlow.Modules.ProjectManagement.Domain\ColaFlow.Modules.ProjectManagement.Domain.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,111 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.AssignStory;
public class AssignStoryCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly AssignStoryCommandHandler _handler;
public AssignStoryCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new AssignStoryCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Assign_Story_Successfully()
{
// Arrange
var userId = UserId.Create();
var assigneeId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Description", TaskPriority.Medium, userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(story.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new AssignStoryCommand
{
StoryId = story.Id.Value,
AssigneeId = assigneeId.Value
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.AssigneeId.Should().Be(assigneeId.Value);
story.AssigneeId.Should().Be(assigneeId);
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Fail_When_Story_Not_Found()
{
// Arrange
var storyId = StoryId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new AssignStoryCommand
{
StoryId = storyId.Value,
AssigneeId = Guid.NewGuid()
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Story*");
}
[Fact]
public async Task Should_Reassign_Story_To_Different_User()
{
// Arrange
var userId = UserId.Create();
var firstAssignee = UserId.Create();
var secondAssignee = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Description", TaskPriority.Medium, userId);
// First assign
story.AssignTo(firstAssignee);
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(story.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new AssignStoryCommand
{
StoryId = story.Id.Value,
AssigneeId = secondAssignee.Value
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.AssigneeId.Should().Be(secondAssignee.Value);
story.AssigneeId.Should().Be(secondAssignee);
}
}

View File

@@ -0,0 +1,119 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.CreateStory;
public class CreateStoryCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly CreateStoryCommandHandler _handler;
public CreateStoryCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new CreateStoryCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Create_Story_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var epicId = epic.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithEpicAsync(epicId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new CreateStoryCommand
{
EpicId = epicId.Value,
Title = "New Story",
Description = "Story Description",
Priority = "High",
EstimatedHours = 8,
AssigneeId = userId.Value,
CreatedBy = userId.Value
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Title.Should().Be("New Story");
result.Description.Should().Be("Story Description");
result.EpicId.Should().Be(epicId.Value);
result.Status.Should().Be("To Do");
result.Priority.Should().Be("High");
result.EstimatedHours.Should().Be(8);
result.AssigneeId.Should().Be(userId.Value);
epic.Stories.Should().ContainSingle();
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Fail_When_Epic_Not_Found()
{
// Arrange
var epicId = EpicId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithEpicAsync(epicId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new CreateStoryCommand
{
EpicId = epicId.Value,
Title = "New Story",
Description = "Description",
Priority = "Medium",
CreatedBy = Guid.NewGuid()
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Epic*");
}
[Fact]
public async Task Should_Set_Default_Status_To_ToDo()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithEpicAsync(epic.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new CreateStoryCommand
{
EpicId = epic.Id.Value,
Title = "New Story",
Description = "Description",
Priority = "Low",
CreatedBy = userId.Value
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Status.Should().Be("To Do");
}
}

View File

@@ -0,0 +1,121 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.CreateTask;
public class CreateTaskCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly CreateTaskCommandHandler _handler;
public CreateTaskCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new CreateTaskCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Create_Task_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var storyId = story.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new CreateTaskCommand
{
StoryId = storyId.Value,
Title = "New Task",
Description = "Task Description",
Priority = "High",
EstimatedHours = 4,
AssigneeId = userId.Value,
CreatedBy = userId.Value
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Title.Should().Be("New Task");
result.Description.Should().Be("Task Description");
result.StoryId.Should().Be(storyId.Value);
result.Status.Should().Be("To Do");
result.Priority.Should().Be("High");
result.EstimatedHours.Should().Be(4);
result.AssigneeId.Should().Be(userId.Value);
story.Tasks.Should().ContainSingle();
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Fail_When_Story_Not_Found()
{
// Arrange
var storyId = StoryId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new CreateTaskCommand
{
StoryId = storyId.Value,
Title = "New Task",
Description = "Description",
Priority = "Medium",
CreatedBy = Guid.NewGuid()
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Story*");
}
[Fact]
public async Task Should_Set_Default_Status_To_ToDo()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(story.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new CreateTaskCommand
{
StoryId = story.Id.Value,
Title = "New Task",
Description = "Description",
Priority = "Low",
CreatedBy = userId.Value
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Status.Should().Be("To Do");
}
}

View File

@@ -0,0 +1,93 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.DeleteStory;
public class DeleteStoryCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly DeleteStoryCommandHandler _handler;
public DeleteStoryCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new DeleteStoryCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Delete_Story_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Story to Delete", "Description", TaskPriority.Medium, userId);
var storyId = story.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new DeleteStoryCommand { StoryId = storyId.Value };
// Act
await _handler.Handle(command, CancellationToken.None);
// Assert
epic.Stories.Should().BeEmpty();
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Fail_When_Story_Not_Found()
{
// Arrange
var storyId = StoryId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new DeleteStoryCommand { StoryId = storyId.Value };
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Story*");
}
[Fact]
public async Task Should_Fail_When_Story_Has_Tasks()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Story with Tasks", "Description", TaskPriority.Medium, userId);
// Add a task to the story
story.CreateTask("Task 1", "Task Description", TaskPriority.High, userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(story.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new DeleteStoryCommand { StoryId = story.Id.Value };
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<DomainException>()
.WithMessage("*cannot delete*story*tasks*");
}
}

View File

@@ -0,0 +1,68 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.DeleteTask;
public class DeleteTaskCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly DeleteTaskCommandHandler _handler;
public DeleteTaskCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new DeleteTaskCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Delete_Task_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Task to Delete", "Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new DeleteTaskCommand { TaskId = taskId.Value };
// Act
await _handler.Handle(command, CancellationToken.None);
// Assert
story.Tasks.Should().BeEmpty();
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Fail_When_Task_Not_Found()
{
// Arrange
var taskId = TaskId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new DeleteTaskCommand { TaskId = taskId.Value };
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Task*");
}
}

View File

@@ -0,0 +1,120 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.UpdateStory;
public class UpdateStoryCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly UpdateStoryCommandHandler _handler;
public UpdateStoryCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new UpdateStoryCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Update_Story_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Original Title", "Original Description", TaskPriority.Low, userId);
var storyId = story.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateStoryCommand
{
StoryId = storyId.Value,
Title = "Updated Title",
Description = "Updated Description",
Status = "In Progress",
Priority = "High",
EstimatedHours = 16
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Title.Should().Be("Updated Title");
result.Description.Should().Be("Updated Description");
result.Status.Should().Be("In Progress");
result.Priority.Should().Be("High");
result.EstimatedHours.Should().Be(16);
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Fail_When_Story_Not_Found()
{
// Arrange
var storyId = StoryId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new UpdateStoryCommand
{
StoryId = storyId.Value,
Title = "Updated Title",
Description = "Updated Description"
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Story*");
}
[Fact]
public async Task Should_Update_All_Fields_Correctly()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Original", "Original", TaskPriority.Low, userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(story.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateStoryCommand
{
StoryId = story.Id.Value,
Title = "New Title",
Description = "New Description",
Status = "Done",
Priority = "Urgent",
EstimatedHours = 24
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
story.Title.Should().Be("New Title");
story.Description.Should().Be("New Description");
story.Status.Should().Be(WorkItemStatus.Done);
story.Priority.Should().Be(TaskPriority.Urgent);
story.EstimatedHours.Should().Be(24);
}
}

View File

@@ -0,0 +1,331 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Commands.UpdateTaskStatus;
/// <summary>
/// Tests for UpdateTaskStatusCommandHandler
/// </summary>
public class UpdateTaskStatusCommandHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly Mock<IUnitOfWork> _unitOfWorkMock;
private readonly UpdateTaskStatusCommandHandler _handler;
public UpdateTaskStatusCommandHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_unitOfWorkMock = new Mock<IUnitOfWork>();
_handler = new UpdateTaskStatusCommandHandler(_projectRepositoryMock.Object, _unitOfWorkMock.Object);
}
[Fact]
public async Task Should_Update_Task_Status_To_InProgress_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "In Progress" // Display name with space
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Id.Should().Be(taskId.Value);
result.Status.Should().Be("In Progress");
task.Status.Should().Be(WorkItemStatus.InProgress);
_projectRepositoryMock.Verify(x => x.Update(project), Times.Once);
_unitOfWorkMock.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Should_Update_Task_Status_To_InProgress_With_CodeName_Successfully()
{
// Arrange - This tests the bug fix for accepting "InProgress" (without space)
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "InProgress" // Code name without space (this was causing the bug)
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Id.Should().Be(taskId.Value);
result.Status.Should().Be("In Progress");
task.Status.Should().Be(WorkItemStatus.InProgress);
}
[Fact]
public async Task Should_Update_Task_Status_To_Done_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "Done"
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Status.Should().Be("Done");
task.Status.Should().Be(WorkItemStatus.Done);
}
[Fact]
public async Task Should_Update_Task_Status_To_Blocked_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "Blocked"
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Status.Should().Be("Blocked");
task.Status.Should().Be(WorkItemStatus.Blocked);
}
[Fact]
public async Task Should_Update_Task_Status_To_InReview_Successfully()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "In Review"
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Status.Should().Be("In Review");
task.Status.Should().Be(WorkItemStatus.InReview);
}
[Fact]
public async Task Should_Throw_NotFoundException_When_Task_Not_Found()
{
// Arrange
var taskId = TaskId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "In Progress"
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Task*");
}
[Fact]
public async Task Should_Throw_Exception_When_Moving_Done_To_ToDo()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
// First set task to Done
task.UpdateStatus(WorkItemStatus.Done);
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "To Do"
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<DomainException>()
.WithMessage("*Cannot move a completed task back to ToDo*");
}
[Fact]
public async Task Should_Allow_Blocked_To_Any_Status()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
// Set task to Blocked
task.UpdateStatus(WorkItemStatus.Blocked);
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "In Progress"
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Status.Should().Be("In Progress");
task.Status.Should().Be(WorkItemStatus.InProgress);
}
[Fact]
public async Task Should_Allow_Any_Status_To_Blocked()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
// Task starts as ToDo
task.Status.Should().Be(WorkItemStatus.ToDo);
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "Blocked"
};
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Status.Should().Be("Blocked");
task.Status.Should().Be(WorkItemStatus.Blocked);
}
[Fact]
public async Task Should_Throw_Exception_For_Invalid_Status()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Test Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.Medium, userId);
var taskId = task.Id;
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var command = new UpdateTaskStatusCommand
{
TaskId = taskId.Value,
NewStatus = "InvalidStatus"
};
// Act
Func<Task> act = async () => await _handler.Handle(command, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<InvalidOperationException>()
.WithMessage("*InvalidStatus*");
}
}

View File

@@ -0,0 +1,71 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoryById;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Queries.GetStoryById;
public class GetStoryByIdQueryHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly GetStoryByIdQueryHandler _handler;
public GetStoryByIdQueryHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_handler = new GetStoryByIdQueryHandler(_projectRepositoryMock.Object);
}
[Fact]
public async Task Should_Return_Story_With_Tasks()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.High, userId);
var task1 = story.CreateTask("Task 1", "Description 1", TaskPriority.Medium, userId);
var task2 = story.CreateTask("Task 2", "Description 2", TaskPriority.Low, userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(story.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var query = new GetStoryByIdQuery(story.Id.Value);
// Act
var result = await _handler.Handle(query, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Id.Should().Be(story.Id.Value);
result.Title.Should().Be("Test Story");
result.Description.Should().Be("Story Description");
result.Priority.Should().Be("High");
result.Tasks.Should().HaveCount(2);
result.Tasks.Should().Contain(t => t.Id == task1.Id.Value);
result.Tasks.Should().Contain(t => t.Id == task2.Id.Value);
}
[Fact]
public async Task Should_Fail_When_Story_Not_Found()
{
// Arrange
var storyId = StoryId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithStoryAsync(storyId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var query = new GetStoryByIdQuery(storyId.Value);
// Act
Func<Task> act = async () => await _handler.Handle(query, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Story*");
}
}

View File

@@ -0,0 +1,69 @@
using FluentAssertions;
using Moq;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Modules.ProjectManagement.Domain.Exceptions;
namespace ColaFlow.Application.Tests.Queries.GetTaskById;
public class GetTaskByIdQueryHandlerTests
{
private readonly Mock<IProjectRepository> _projectRepositoryMock;
private readonly GetTaskByIdQueryHandler _handler;
public GetTaskByIdQueryHandlerTests()
{
_projectRepositoryMock = new Mock<IProjectRepository>();
_handler = new GetTaskByIdQueryHandler(_projectRepositoryMock.Object);
}
[Fact]
public async Task Should_Return_Task_Details()
{
// Arrange
var userId = UserId.Create();
var project = Project.Create("Test Project", "Description", "TST", userId);
var epic = project.CreateEpic("Test Epic", "Epic Description", userId);
var story = epic.CreateStory("Test Story", "Story Description", TaskPriority.Medium, userId);
var task = story.CreateTask("Test Task", "Task Description", TaskPriority.High, userId);
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(task.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(project);
var query = new GetTaskByIdQuery(task.Id.Value);
// Act
var result = await _handler.Handle(query, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Id.Should().Be(task.Id.Value);
result.Title.Should().Be("Test Task");
result.Description.Should().Be("Task Description");
result.StoryId.Should().Be(story.Id.Value);
result.Status.Should().Be("To Do");
result.Priority.Should().Be("High");
}
[Fact]
public async Task Should_Fail_When_Task_Not_Found()
{
// Arrange
var taskId = TaskId.Create();
_projectRepositoryMock
.Setup(x => x.GetProjectWithTaskAsync(taskId, It.IsAny<CancellationToken>()))
.ReturnsAsync((Project?)null);
var query = new GetTaskByIdQuery(taskId.Value);
// Act
Func<Task> act = async () => await _handler.Handle(query, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<NotFoundException>()
.WithMessage("*Task*");
}
}