Implement owned Profile schema and atomic authorized lifecycle

This commit is contained in:
Steffen committed 2026-10-14 11:37:12 +02:00
1 parent 523cfbf42e
commit bfe6ebf5af
24 files changed
+3056 -3

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
+12
View File
@@ -0,0 +1,12 @@
namespace HealthApp.Profile.Domain;
internal sealed class Patient
{
public string? AccountId { get; set; }
public Guid PatientId { get; set; }
public string Name { get; set; } = "";
public DateOnly DateOfBirth { get; set; }
public string? ContactInfo { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,7 @@
CREATE SCHEMA IF NOT EXISTS profile;
CREATE TABLE IF NOT EXISTS profile.schema_version(version integer PRIMARY KEY);
CREATE TABLE IF NOT EXISTS profile.patient (
patient_id uuid PRIMARY KEY, account_id text NOT NULL, name varchar NOT NULL,
date_of_birth date NOT NULL,contact_info varchar,created_at timestamp without time zone NOT NULL,updated_at timestamp without time zone NOT NULL);
CREATE UNIQUE INDEX IF NOT EXISTS "IX_patient_account_id" ON profile.patient(account_id);
INSERT INTO profile.schema_version VALUES(1) ON CONFLICT DO NOTHING;
@@ -0,0 +1,24 @@
using Microsoft.EntityFrameworkCore;
using HealthApp.Profile.Domain;
namespace HealthApp.Profile.Persistence;
internal sealed class PatientDbContext(DbContextOptions<PatientDbContext> options) : DbContext(options)
{
public DbSet<Patient> Patients => Set<Patient>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var patient = modelBuilder.Entity<Patient>();
patient.ToTable("patient", "profile");
patient.HasKey(p => p.PatientId);
patient.Property(p => p.AccountId).HasColumnName("account_id").IsRequired();
patient.HasIndex(p => p.AccountId).IsUnique();
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
patient.Property(p => p.ContactInfo).HasColumnName("contact_info").HasColumnType("character varying");
patient.Property(p => p.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
patient.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
}
}
+4
View File
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj" /></ItemGroup>
</Project>
+40
View File
@@ -0,0 +1,40 @@
using System.ComponentModel.DataAnnotations;
using HealthApp.Contracts;
using HealthApp.Infrastructure;
using HealthApp.Profile.Domain;
using HealthApp.Profile.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
namespace HealthApp.Profile;
internal sealed class ProfileFacade(PatientDbContext db,RequestTransaction tx) : ProfileQueries,ProfileCommands
{
public async Task<Guid?> ResolveAccountAsync(string id,CancellationToken ct)
{await tx.EnlistAsync(db,ct);return await db.Patients.AsNoTracking().Where(p=>p.AccountId==id).Select(p=>(Guid?)p.PatientId).SingleOrDefaultAsync(ct);}
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct)
{await tx.EnlistAsync(db,ct);var p=await db.Patients.AsNoTracking().SingleOrDefaultAsync(p=>p.PatientId==scope.PatientId,ct);return p is null?null:Dto(p);}
public async Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest r,CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId);Validator.ValidateObject(r,new ValidationContext(r),true);
await tx.EnlistAsync(db,ct);if(await db.Patients.AnyAsync(p=>p.AccountId==trustedAccountId,ct))throw new ProfileAlreadyExistsException();
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
var p=new Patient{PatientId=Guid.NewGuid(),AccountId=trustedAccountId,Name=r.Name!,DateOfBirth=r.DateOfBirth!.Value,ContactInfo=r.ContactInfo,CreatedAt=now,UpdatedAt=now};db.Patients.Add(p);
try{await db.SaveChangesAsync(ct);}catch(DbUpdateException e) when(e.InnerException is PostgresException {SqlState:"23505",ConstraintName:"IX_patient_account_id"}){throw new ProfileAlreadyExistsException();}
return Dto(p);
}
public async Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest r,CancellationToken ct)
{
scope.RequireWrite();Validator.ValidateObject(r,new ValidationContext(r),true);await tx.EnlistAsync(db,ct);
var p=await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
if(p is null)return null;p.Name=r.Name!;p.ContactInfo=r.ContactInfo;p.UpdatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);await db.SaveChangesAsync(ct);return Dto(p);
}
private static PatientDto Dto(Patient p)=>new(p.PatientId,p.Name,p.DateOfBirth,p.ContactInfo);
}
public static class ProfileModule
{
public static IServiceCollection AddProfile(this IServiceCollection services)
{
services.AddScoped(sp=>new PatientDbContext(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
services.AddScoped<ProfileFacade>();services.AddScoped<ProfileQueries>(sp=>sp.GetRequiredService<ProfileFacade>());services.AddScoped<ProfileCommands>(sp=>sp.GetRequiredService<ProfileFacade>());return services;
}
}