using Khaemhat.Application.Security; using Khaemhat.Core.Instance; using Khaemhat.Data; using Khaemhat.Data.Querying; namespace Khaemhat.Application.Instance; /// /// Reads and writes the preferences of a company as a whole (company_settings, SPEC ยง11.12): the default /// dashboard of each role today, the company options of the later modules tomorrow. Reading is open to the company /// code (the callers check what they show); writing needs company.settings.write. /// /// Opens the databases. /// Checks the permission to write. public sealed class CompanySettingsService(IUnitOfWorkFactory factory, PermissionService permissions) { /// The permission to change the settings. public const string WritePermission = "company.settings.write"; /// The longest value accepted (layouts are JSON). public const int MaxValueLength = 64 * 1024; /// Reads the settings of a company, all or those whose key starts with a prefix. /// The company. /// The start of the keys, or for all. /// Cancellation. /// The values by key. public async Task> GetAllAsync(string companyCode, string? prefix = null, CancellationToken cancellationToken = default) { ArgumentException.ThrowIfNullOrWhiteSpace(companyCode); await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); var rows = await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false); return rows.Where(r => prefix is null || r.Key.StartsWith(prefix, StringComparison.Ordinal)) .ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal); } /// Reads one setting. /// The company. /// The key. /// Cancellation. /// The value, or . public async Task GetAsync(string companyCode, string key, CancellationToken cancellationToken = default) { ArgumentException.ThrowIfNullOrWhiteSpace(key); var all = await GetAllAsync(companyCode, key, cancellationToken).ConfigureAwait(false); return all.TryGetValue(key, out var value) ? value : null; } /// Writes one setting; removes it. /// Who writes: needs in that company. /// The company. /// The key. /// The value. /// Cancellation. /// A task. public Task SetAsync(Actor actor, string companyCode, string key, string? value, CancellationToken cancellationToken = default) => SetManyAsync(actor, companyCode, new Dictionary(StringComparer.Ordinal) { [key] = value }, cancellationToken); /// Writes several settings in one transaction; values remove the key. /// Who writes: needs in that company. /// The company. /// The values by key. /// Cancellation. /// A task. /// The actor may not change this company's settings. public async Task SetManyAsync(Actor actor, string companyCode, IReadOnlyDictionary values, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(actor); ArgumentException.ThrowIfNullOrWhiteSpace(companyCode); ArgumentNullException.ThrowIfNull(values); if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, companyCode, StringComparison.OrdinalIgnoreCase)) { throw new AccessDeniedException("Settings of another company."); } await permissions.DemandAsync(actor, WritePermission, cancellationToken).ConfigureAwait(false); foreach (var (key, value) in values) { if (string.IsNullOrWhiteSpace(key) || key.Length > 200) { throw new ValidationFailedException("settings.key_invalid"); } if (value is { Length: > MaxValueLength }) { throw new ValidationFailedException("settings.value_too_long"); } } if (values.Count == 0) { return; } await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); await unitOfWork.InTransactionAsync(ct => WriteAsync(unitOfWork, values, ct), cancellationToken).ConfigureAwait(false); } private static async Task> ListAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken) => (await unitOfWork.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; private static async Task WriteAsync(IUnitOfWork unitOfWork, IReadOnlyDictionary values, CancellationToken cancellationToken) { var repository = unitOfWork.Repository(); var existing = (await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal); foreach (var (key, value) in values) { if (existing.TryGetValue(key, out var row)) { if (value is null) { await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false); } else if (!string.Equals(row.Value, value, StringComparison.Ordinal)) { row.Value = value; await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); } } else if (value is not null) { await repository.InsertAsync(new CompanySetting { Key = key, Value = value }, cancellationToken).ConfigureAwait(false); } } } }