mirror of
https://github.com/Sea-Haven-Industries/shoc-backend.git
synced 2026-09-30 11:53:12 +00:00
55 lines
1.6 KiB
C#
55 lines
1.6 KiB
C#
|
|
using Data.SeaHavenIndustries;
|
||
|
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
using SeaHaven.DataServices.Interfaces;
|
||
|
|
|
||
|
|
namespace SeaHaven.DataServices.Implementation;
|
||
|
|
|
||
|
|
public sealed class AccountOwnerDataService : IAccountOwnerDataService
|
||
|
|
{
|
||
|
|
private readonly ApplicationDbContext _context;
|
||
|
|
|
||
|
|
public AccountOwnerDataService(ApplicationDbContext context)
|
||
|
|
{
|
||
|
|
_context = context;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<bool> EnsureConfiguredOwnerAsync(
|
||
|
|
string? configuredUserId,
|
||
|
|
CancellationToken cancellationToken)
|
||
|
|
{
|
||
|
|
var ownerId = string.IsNullOrWhiteSpace(configuredUserId)
|
||
|
|
? null
|
||
|
|
: configuredUserId.Trim();
|
||
|
|
|
||
|
|
if (ownerId is not null)
|
||
|
|
{
|
||
|
|
var configuredUserExists = await _context.Users
|
||
|
|
.AsNoTracking()
|
||
|
|
.AnyAsync(user => user.Id == ownerId, cancellationToken);
|
||
|
|
|
||
|
|
if (!configuredUserExists)
|
||
|
|
throw new InvalidOperationException("The configured account owner user was not found.");
|
||
|
|
}
|
||
|
|
|
||
|
|
var ownerRows = await _context.Users
|
||
|
|
.Where(user => user.IsAccountOwner || (ownerId != null && user.Id == ownerId))
|
||
|
|
.ToListAsync(cancellationToken);
|
||
|
|
|
||
|
|
var changed = false;
|
||
|
|
foreach (var user in ownerRows)
|
||
|
|
{
|
||
|
|
var shouldBeOwner = ownerId is not null && user.Id == ownerId;
|
||
|
|
if (user.IsAccountOwner != shouldBeOwner)
|
||
|
|
{
|
||
|
|
user.IsAccountOwner = shouldBeOwner;
|
||
|
|
changed = true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (changed)
|
||
|
|
await _context.SaveChangesAsync(cancellationToken);
|
||
|
|
|
||
|
|
return changed;
|
||
|
|
}
|
||
|
|
}
|