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; /// Endpoints for managing entries (saisies) within a month. [ApiController] [Produces("application/json")] public class EntriesController : ControllerBase { private readonly AppDbContext _db; private readonly CsvImportService _csvImportService; private readonly ExportService _exportService; private readonly ILogger _logger; public EntriesController( AppDbContext db, CsvImportService csvImportService, ExportService exportService, ILogger logger) { _db = db; _csvImportService = csvImportService; _exportService = exportService; _logger = logger; } // ── GET /api/months/{monthId}/entries ───────────────────────────────────── /// Returns all entries for a month, sorted by date then creation time. [HttpGet("api/months/{monthId:guid}/entries")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task 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 ──────────────────────────────────── /// Creates a new entry in a month. [HttpPost("api/months/{monthId:guid}/entries")] [ProducesResponseType(typeof(EntryDto), StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task 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(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} ───────────────────────────────────────────────── /// Updates an existing entry. [HttpPut("api/entries/{id:guid}")] [ProducesResponseType(typeof(EntryDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task 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(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} ────────────────────────────────────────────── /// Deletes an entry. [HttpDelete("api/entries/{id:guid}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task 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 ───────────────────────────────── /// Bulk-imports entries from a CSV file upload. [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 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 ──────────────────────────────── /// Exports all entries for a month as an Excel .xlsx file. [HttpGet("api/months/{monthId:guid}/export-excel")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task 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); } }