Initial commit

This commit is contained in:
Kevin Harlay
2026-09-07 13:33:22 +02:00
commit ebfaf6f5ec
295 changed files with 8786 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
using ExpenseTracker.Api.Data;
using ExpenseTracker.Api.DTOs;
using ExpenseTracker.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ExpenseTracker.Api.Controllers;
/// <summary>Endpoints for managing expense categories.</summary>
[ApiController]
[Route("api/categories")]
[Produces("application/json")]
public class CategoriesController : ControllerBase
{
private readonly AppDbContext _db;
private readonly ILogger<CategoriesController> _logger;
public CategoriesController(AppDbContext db, ILogger<CategoriesController> logger)
{
_db = db;
_logger = logger;
}
// ── GET /api/categories ───────────────────────────────────────────────────
/// <summary>Returns all categories sorted by name ascending.</summary>
[HttpGet]
[ProducesResponseType(typeof(List<CategoryDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAll()
{
var categories = await _db.Categories
.OrderBy(c => c.Name)
.Select(c => new CategoryDto(c.Id, c.Name, c.Color))
.ToListAsync();
return Ok(categories);
}
// ── POST /api/categories ──────────────────────────────────────────────────
/// <summary>Creates a new category.</summary>
[HttpPost]
[ProducesResponseType(typeof(CategoryDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateCategoryDto dto)
{
// FluentValidation auto-validation handles 400 before we get here.
var category = new Category
{
Id = Guid.NewGuid(),
Name = dto.Name,
Color = dto.Color
};
_db.Categories.Add(category);
await _db.SaveChangesAsync();
_logger.LogInformation("Category '{Name}' created with id {Id}.", category.Name, category.Id);
var result = new CategoryDto(category.Id, category.Name, category.Color);
return CreatedAtAction(nameof(GetAll), null, result);
}
// ── DELETE /api/categories/{id} ───────────────────────────────────────────
/// <summary>Deletes a category. Returns 409 Conflict if entries reference it.</summary>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Delete(Guid id)
{
var category = await _db.Categories.FindAsync(id);
if (category is null)
{
_logger.LogWarning("Delete category: id {Id} not found.", id);
return NotFound(new { error = "Category not found." });
}
bool hasEntries = await _db.Entries.AnyAsync(e => e.CategoryId == id);
if (hasEntries)
{
_logger.LogWarning("Delete category {Id} refused: entries still reference it.", id);
return Conflict(new { error = "This category is referenced by one or more entries and cannot be deleted." });
}
_db.Categories.Remove(category);
await _db.SaveChangesAsync();
_logger.LogInformation("Category {Id} deleted.", id);
return NoContent();
}
}
+273
View File
@@ -0,0 +1,273 @@
using ExpenseTracker.Api.Data;
using ExpenseTracker.Api.DTOs;
using ExpenseTracker.Api.Models;
using ExpenseTracker.Api.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ExpenseTracker.Api.Controllers;
/// <summary>Endpoints for managing entries (saisies) within a month.</summary>
[ApiController]
[Produces("application/json")]
public class EntriesController : ControllerBase
{
private readonly AppDbContext _db;
private readonly CsvImportService _csvImportService;
private readonly ExportService _exportService;
private readonly ILogger<EntriesController> _logger;
public EntriesController(
AppDbContext db,
CsvImportService csvImportService,
ExportService exportService,
ILogger<EntriesController> logger)
{
_db = db;
_csvImportService = csvImportService;
_exportService = exportService;
_logger = logger;
}
// ── GET /api/months/{monthId}/entries ─────────────────────────────────────
/// <summary>Returns all entries for a month, sorted by date then creation time.</summary>
[HttpGet("api/months/{monthId:guid}/entries")]
[ProducesResponseType(typeof(List<EntryDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetAll(Guid monthId)
{
bool monthExists = await _db.Months.AnyAsync(m => m.Id == monthId);
if (!monthExists)
{
_logger.LogWarning("GetAll entries: month {MonthId} not found.", monthId);
return NotFound(new { error = "Month not found." });
}
var entries = await _db.Entries
.AsNoTracking()
.Include(e => e.Category)
.Where(e => e.MonthId == monthId)
.OrderBy(e => e.EntryDate)
.ThenBy(e => e.CreatedAt)
.Select(e => new EntryDto(
e.Id,
e.MonthId,
e.Type.ToString(),
e.Amount,
e.Label,
e.CategoryId,
e.Category != null ? e.Category.Name : null,
e.EntryDate,
e.CreatedAt))
.ToListAsync();
return Ok(entries);
}
// ── POST /api/months/{monthId}/entries ────────────────────────────────────
/// <summary>Creates a new entry in a month.</summary>
[HttpPost("api/months/{monthId:guid}/entries")]
[ProducesResponseType(typeof(EntryDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Create(Guid monthId, [FromBody] CreateEntryDto dto)
{
// FluentValidation auto-validation handles 400 before we get here.
bool monthExists = await _db.Months.AnyAsync(m => m.Id == monthId);
if (!monthExists)
{
_logger.LogWarning("Create entry: month {MonthId} not found.", monthId);
return NotFound(new { error = "Month not found." });
}
if (!Enum.TryParse<EntryType>(dto.Type, out var entryType))
{
return BadRequest(new { error = "Invalid entry type." });
}
if (entryType == EntryType.EXPENSE && dto.CategoryId.HasValue)
{
bool categoryExists = await _db.Categories.AnyAsync(c => c.Id == dto.CategoryId.Value);
if (!categoryExists)
{
return BadRequest(new { error = "Category not found." });
}
}
var entry = new Entry
{
Id = Guid.NewGuid(),
MonthId = monthId,
Type = entryType,
Amount = dto.Amount,
Label = dto.Label,
CategoryId = dto.CategoryId,
EntryDate = dto.EntryDate,
CreatedAt = DateTime.UtcNow
};
_db.Entries.Add(entry);
await _db.SaveChangesAsync();
_logger.LogInformation("Entry {Id} created in month {MonthId}.", entry.Id, monthId);
// Reload with category name
var categoryName = entry.CategoryId.HasValue
? (await _db.Categories.FindAsync(entry.CategoryId.Value))?.Name
: null;
var result = new EntryDto(
entry.Id,
entry.MonthId,
entry.Type.ToString(),
entry.Amount,
entry.Label,
entry.CategoryId,
categoryName,
entry.EntryDate,
entry.CreatedAt);
return CreatedAtAction(nameof(GetAll), new { monthId }, result);
}
// ── PUT /api/entries/{id} ─────────────────────────────────────────────────
/// <summary>Updates an existing entry.</summary>
[HttpPut("api/entries/{id:guid}")]
[ProducesResponseType(typeof(EntryDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateEntryDto dto)
{
// FluentValidation auto-validation handles 400 before we get here.
var entry = await _db.Entries.FindAsync(id);
if (entry is null)
{
_logger.LogWarning("Update entry: entry {Id} not found.", id);
return NotFound(new { error = "Entry not found." });
}
if (!Enum.TryParse<EntryType>(dto.Type, out var entryType))
{
return BadRequest(new { error = "Invalid entry type." });
}
if (entryType == EntryType.EXPENSE && dto.CategoryId.HasValue)
{
bool categoryExists = await _db.Categories.AnyAsync(c => c.Id == dto.CategoryId.Value);
if (!categoryExists)
{
return BadRequest(new { error = "Category not found." });
}
}
entry.Type = entryType;
entry.Amount = dto.Amount;
entry.Label = dto.Label;
entry.CategoryId = dto.CategoryId;
entry.EntryDate = dto.EntryDate;
await _db.SaveChangesAsync();
_logger.LogInformation("Entry {Id} updated.", id);
var categoryName = entry.CategoryId.HasValue
? (await _db.Categories.FindAsync(entry.CategoryId.Value))?.Name
: null;
var result = new EntryDto(
entry.Id,
entry.MonthId,
entry.Type.ToString(),
entry.Amount,
entry.Label,
entry.CategoryId,
categoryName,
entry.EntryDate,
entry.CreatedAt);
return Ok(result);
}
// ── DELETE /api/entries/{id} ──────────────────────────────────────────────
/// <summary>Deletes an entry.</summary>
[HttpDelete("api/entries/{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id)
{
var entry = await _db.Entries.FindAsync(id);
if (entry is null)
{
_logger.LogWarning("Delete entry: entry {Id} not found.", id);
return NotFound(new { error = "Entry not found." });
}
_db.Entries.Remove(entry);
await _db.SaveChangesAsync();
_logger.LogInformation("Entry {Id} deleted.", id);
return NoContent();
}
// ── POST /api/months/{monthId}/import-csv ─────────────────────────────────
/// <summary>Bulk-imports entries from a CSV file upload.</summary>
[HttpPost("api/months/{monthId:guid}/import-csv")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(ImportResultDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> ImportCsv(Guid monthId, IFormFile? file)
{
bool monthExists = await _db.Months.AnyAsync(m => m.Id == monthId);
if (!monthExists)
{
_logger.LogWarning("ImportCsv: month {MonthId} not found.", monthId);
return NotFound(new { error = "Month not found." });
}
if (file is null || file.Length == 0)
{
return BadRequest(new { error = "No file provided." });
}
using var stream = file.OpenReadStream();
var result = await _csvImportService.ImportAsync(monthId, stream, _db);
return Ok(result);
}
// ── GET /api/months/{monthId}/export-excel ────────────────────────────────
/// <summary>Exports all entries for a month as an Excel .xlsx file.</summary>
[HttpGet("api/months/{monthId:guid}/export-excel")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> ExportExcel(Guid monthId)
{
var month = await _db.Months
.AsNoTracking()
.FirstOrDefaultAsync(m => m.Id == monthId);
if (month is null)
{
_logger.LogWarning("ExportExcel: month {MonthId} not found.", monthId);
return NotFound(new { error = "Month not found." });
}
var bytes = await _exportService.ExportMonthAsync(monthId, _db);
var fileName = ExportService.GetFileName(month.MonthNumber, month.Year);
return File(
bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
fileName);
}
}
+130
View File
@@ -0,0 +1,130 @@
using ExpenseTracker.Api.Data;
using ExpenseTracker.Api.DTOs;
using ExpenseTracker.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ExpenseTracker.Api.Controllers;
/// <summary>Endpoints for managing budget months.</summary>
[ApiController]
[Route("api/months")]
[Produces("application/json")]
public class MonthsController : ControllerBase
{
private readonly AppDbContext _db;
private readonly ILogger<MonthsController> _logger;
public MonthsController(AppDbContext db, ILogger<MonthsController> logger)
{
_db = db;
_logger = logger;
}
// ── GET /api/months ───────────────────────────────────────────────────────
/// <summary>Returns all months sorted by year then month number, descending.</summary>
[HttpGet]
[ProducesResponseType(typeof(List<MonthDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAll()
{
var months = await _db.Months
.OrderByDescending(m => m.Year)
.ThenByDescending(m => m.MonthNumber)
.Select(m => new MonthDto(m.Id, m.Year, m.MonthNumber, m.DefaultSalary, m.CreatedAt))
.ToListAsync();
return Ok(months);
}
// ── POST /api/months ──────────────────────────────────────────────────────
/// <summary>Creates a new month. Automatically inserts an INCOME entry for the salary if &gt; 0.</summary>
[HttpPost]
[ProducesResponseType(typeof(MonthDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Create([FromBody] CreateMonthDto dto)
{
// FluentValidation auto-validation handles 400 before we get here.
bool exists = await _db.Months
.AnyAsync(m => m.Year == dto.Year && m.MonthNumber == dto.Month);
if (exists)
{
_logger.LogWarning("Conflict: month {Year}-{Month} already exists.", dto.Year, dto.Month);
return Conflict(new { error = "A month with this year and month number already exists." });
}
var month = new Month
{
Id = Guid.NewGuid(),
Year = dto.Year,
MonthNumber = dto.Month,
DefaultSalary = dto.DefaultSalary,
CreatedAt = DateTime.UtcNow
};
_db.Months.Add(month);
if (dto.DefaultSalary > 0)
{
var income = new Entry
{
Id = Guid.NewGuid(),
MonthId = month.Id,
Type = EntryType.INCOME,
Amount = dto.DefaultSalary,
Label = "Salaire",
CategoryId = null,
EntryDate = new DateOnly(dto.Year, dto.Month, 1),
CreatedAt = DateTime.UtcNow
};
_db.Entries.Add(income);
}
await _db.SaveChangesAsync();
_logger.LogInformation("Month {Year}-{Month} created with id {Id}.", month.Year, month.MonthNumber, month.Id);
var result = new MonthDto(month.Id, month.Year, month.MonthNumber, month.DefaultSalary, month.CreatedAt);
return CreatedAtAction(nameof(GetSummary), new { id = month.Id }, result);
}
// ── GET /api/months/{id}/summary ──────────────────────────────────────────
/// <summary>Returns the balance summary for a given month.</summary>
[HttpGet("{id:guid}/summary")]
[ProducesResponseType(typeof(MonthSummaryDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetSummary(Guid id)
{
var month = await _db.Months.FindAsync(id);
if (month is null)
{
_logger.LogWarning("GetSummary: month {Id} not found.", id);
return NotFound(new { error = "Month not found." });
}
var entries = await _db.Entries
.Where(e => e.MonthId == id)
.ToListAsync();
decimal totalIncome = entries.Where(e => e.Type == EntryType.INCOME).Sum(e => e.Amount);
decimal totalExpense = entries.Where(e => e.Type == EntryType.EXPENSE).Sum(e => e.Amount);
decimal balance = totalIncome - totalExpense;
var summary = new MonthSummaryDto(
MonthId: month.Id,
Year: month.Year,
MonthNumber: month.MonthNumber,
TotalIncome: totalIncome,
TotalExpense: totalExpense,
Balance: balance);
return Ok(summary);
}
}
+65
View File
@@ -0,0 +1,65 @@
using ExpenseTracker.Api.Data;
using ExpenseTracker.Api.DTOs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ExpenseTracker.Api.Controllers;
/// <summary>Endpoints for managing global application settings.</summary>
[ApiController]
[Route("api/settings")]
[Produces("application/json")]
public class SettingsController : ControllerBase
{
private readonly AppDbContext _db;
private readonly ILogger<SettingsController> _logger;
public SettingsController(AppDbContext db, ILogger<SettingsController> logger)
{
_db = db;
_logger = logger;
}
// ── GET /api/settings ─────────────────────────────────────────────────────
/// <summary>Returns all application settings.</summary>
[HttpGet]
[ProducesResponseType(typeof(List<SettingsDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAll()
{
var settings = await _db.AppSettings
.OrderBy(s => s.Key)
.Select(s => new SettingsDto(s.Key, s.Value))
.ToListAsync();
return Ok(settings);
}
// ── PUT /api/settings/default-salary ──────────────────────────────────────
/// <summary>Updates the default salary setting.</summary>
[HttpPut("default-salary")]
[ProducesResponseType(typeof(SettingsDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateDefaultSalary([FromBody] UpdateDefaultSalaryDto dto)
{
// FluentValidation auto-validation handles 400 before we get here.
var setting = await _db.AppSettings
.FirstOrDefaultAsync(s => s.Key == "default_salary");
if (setting is null)
{
_logger.LogWarning("UpdateDefaultSalary: key 'default_salary' not found in app_settings.");
return NotFound(new { error = "Setting 'default_salary' not found." });
}
setting.Value = dto.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
await _db.SaveChangesAsync();
_logger.LogInformation("Setting 'default_salary' updated to {Value}.", setting.Value);
return Ok(new SettingsDto(setting.Key, setting.Value));
}
}