feat(api): validate account institution is connected and allow adding new account

This commit is contained in:
Stevan Freeborn
2026-02-13 12:33:37 -06:00
parent 9255bd2fc3
commit 14d8d4dd9e
3 changed files with 173 additions and 6 deletions
+16 -2
View File
@@ -1,3 +1,5 @@
using FiscalOS.Core.Accounts;
namespace FiscalOS.API.Accounts.Add;
internal static class Endpoint
@@ -19,6 +21,7 @@ internal static class Endpoint
var userId = httpContext.GetUserId();
var user = await appDbContext.Users
.Include(u => u.Institutions.Where(i => i.Metadata is PlaidMetadata && ((PlaidMetadata)i.Metadata).PlaidId == request.PlaidInstitutionId))
.Include(u => u.Accounts.Where(a => a.Metadata is PlaidAccountMetadata && ((PlaidAccountMetadata)a.Metadata).PlaidId == request.PlaidAccountId))
.ThenInclude(a => a.Metadata)
.SingleOrDefaultAsync(u => u.Id == userId, ct);
@@ -28,13 +31,24 @@ internal static class Endpoint
return Results.Unauthorized();
}
if (user.Institutions.Any() is false)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["PlaidInstitutionId"] = ["The PlaidInstitutionId field is invalid. No institution connected with the given PlaidInstitutionId was found for the user."],
});
}
if (user.Accounts.Any())
{
return Results.Conflict();
}
// TODO: This is new account
// so we should add to the database
var accountMetadata = PlaidAccountMetadata.From(request.PlaidAccountId, request.PlaidAccountName);
var account = Account.From(user.Institutions.First().Id, request.PlaidAccountName, accountMetadata);
user.AddAccount(account);
await appDbContext.SaveChangesAsync(ct);
return Results.Ok();
}