using Khaemhat.Application.Audit;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Migrations;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Instance;
/// Where the databases of the instance are and which migrations they get.
/// The system database (KHAEMHAT_SYSTEM_DB).
/// Where new company databases are created (KHAEMHAT_DB_SERVER, or next to the system one).
/// The migrations of the system database.
/// The migrations of every company database.
public sealed record InstanceDatabases(DatabaseUrl System, DatabaseUrl CompanyServer, MigrationCatalog SystemMigrations, MigrationCatalog CompanyMigrations);
/// A company to create.
/// The code (database khaemhat_<code>).
/// The company name.
/// Whether it becomes the default company.
/// Notes for administrators.
/// Whether to load the demo data.
public sealed record NewCompany(string Code, string Name, bool IsDefault = false, string? Notes = null, bool SeedDemo = false);
///
/// Fills a new or migrated company database. Modules register their own: base data at creation (plan of accounts, VAT
/// codes) and demo data when asked (SPEC §5.5). Seeders must be idempotent: they run again at every start.
///
public interface ICompanySeeder
{
/// The order among seeders (lower first).
int Order { get; }
/// Fills the database.
/// The company.
/// What to load.
/// Cancellation.
/// A task.
Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default);
}
/// What a seeder is asked to load.
/// Whether the database was just created.
/// Whether the base data is wanted (KHAEMHAT_SEED_BASE).
/// Whether the demo data is wanted.
public sealed record CompanySeedContext(bool IsNew, bool Base, bool Demo);
/// The predefined roles of SPEC §7.2, kept equal to their templates in every company.
/// The role service.
public sealed class PredefinedRolesSeeder(RoleService roles) : ICompanySeeder
{
///
public int Order => 0;
///
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) =>
roles.SyncPredefinedRolesAsync(companyCode, cancellationToken);
}
///
/// Creates, attaches and migrates company databases (SPEC §5.4, §12.1; mockup 080). Creating a company is an
/// instance administration task: super user or administrators. The number of companies is limited by the licence
/// (module MULTI).
///
public sealed class CompanyService
{
private readonly ICompanyRegistry _registry;
private readonly DbProviderCatalog _providers;
private readonly MigrationRunner _migrations;
private readonly InstanceDatabases _databases;
private readonly ILicenseGate _licenses;
private readonly SessionStore _sessions;
private readonly ISecurityAuditLog _audit;
private readonly IReadOnlyList _seeders;
private readonly ILogger _logger;
/// Creates the service.
/// The company registry.
/// The database providers.
/// Applies migrations.
/// Where databases are.
/// The licence in force.
/// The sessions (revoked when a company goes into maintenance).
/// The security audit.
/// The seeders of the modules.
/// The log.
public CompanyService(
ICompanyRegistry registry, DbProviderCatalog providers, MigrationRunner migrations, InstanceDatabases databases, ILicenseGate licenses,
SessionStore sessions, ISecurityAuditLog audit, IEnumerable seeders, ILogger logger)
{
ArgumentNullException.ThrowIfNull(registry);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(migrations);
ArgumentNullException.ThrowIfNull(databases);
ArgumentNullException.ThrowIfNull(licenses);
ArgumentNullException.ThrowIfNull(sessions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(seeders);
ArgumentNullException.ThrowIfNull(logger);
_registry = registry;
_providers = providers;
_migrations = migrations;
_databases = databases;
_licenses = licenses;
_sessions = sessions;
_audit = audit;
_seeders = [.. seeders.OrderBy(s => s.Order)];
_logger = logger;
}
/// The companies of the instance.
/// Cancellation.
/// The companies by code.
public Task> ListAsync(CancellationToken cancellationToken = default) => _registry.ListAsync(cancellationToken);
///
/// Creates a company: a new database khaemhat_<code> on the company server, registered, migrated and
/// filled by the seeders.
///
/// Who acts: an instance account.
/// The company.
/// Cancellation.
/// The registered company.
/// The actor is not an instance account, or the licence allows no more companies.
public async Task CreateAsync(Actor actor, NewCompany company, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(company);
RequireInstanceAdministrator(actor);
var code = Validate(company.Code, company.Name);
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
var target = _providers.Resolve(url);
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException([$"Il database {url.DatabaseName} esiste già: usa «Collega database esistente»."]);
}
await target.Provider.EnsureDatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false);
var registered = await _registry.RegisterAsync(new CompanyRegistration(code, company.Name, url, company.IsDefault, company.Notes), cancellationToken)
.ConfigureAwait(false);
await PrepareAsync(registered, new CompanySeedContext(IsNew: true, Base: true, Demo: company.SeedDemo), cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("company.created", actor.UserName, Target: code), cancellationToken).ConfigureAwait(false);
return registered;
}
///
/// Attaches an existing company database (restored from a backup or moved from another instance) and migrates it.
///
/// Who acts: an instance account.
/// The company code.
/// The company name.
/// Where the database is.
/// Cancellation.
/// The registered company.
public async Task AttachAsync(Actor actor, string code, string name, DatabaseUrl database, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(database);
RequireInstanceAdministrator(actor);
var normalized = Validate(code, name);
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
var target = _providers.Resolve(database);
if (!await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException(["Il database indicato non esiste o non è raggiungibile."]);
}
var registered = await _registry.RegisterAsync(new CompanyRegistration(normalized, name, database), cancellationToken).ConfigureAwait(false);
await PrepareAsync(registered, new CompanySeedContext(IsNew: false, Base: false, Demo: false), cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("company.attached", actor.UserName, Target: normalized), cancellationToken).ConfigureAwait(false);
return registered;
}
///
/// Changes the state of a company. Maintenance and disabling sign out its users at once; instance accounts can still
/// open a company in maintenance.
///
/// Who acts: an instance account.
/// The company.
/// The new state.
/// Cancellation.
/// A task.
public async Task SetStatusAsync(Actor actor, string code, CompanyStatus status, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireInstanceAdministrator(actor);
await _registry.SetStatusAsync(code, status, cancellationToken).ConfigureAwait(false);
if (status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
var revoked = await _sessions.RevokeCompanyAsync(code, "company-" + status.ToString().ToLowerInvariant(), cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Company {Company} is now {Status}: {Count} sessions closed.", code, status, revoked);
}
await _audit.WriteAsync(
new SecurityEvent("company.status", actor.UserName, Target: CompanyCodes.Normalize(code), Details: status.ToString()), cancellationToken).ConfigureAwait(false);
}
///
/// Migrates every company that is not disabled and runs the seeders again (at each start). A company whose
/// migration fails is put in maintenance and logged; the others go on.
///
/// Whether demo data is wanted (KHAEMHAT_SEED_DEMO).
/// Cancellation.
/// The companies that failed.
public async Task> PrepareAllAsync(bool seedDemo, CancellationToken cancellationToken = default)
{
var failed = new List();
foreach (var company in await _registry.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status == CompanyStatus.Disabled)
{
continue;
}
try
{
await PrepareAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: seedDemo), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed.Add(company.Code);
using (_logger.BeginScope(LogSections.Scope(LogSection.Migrations)))
{
_logger.LogError(ex, "Company {Company} could not be migrated: it is put in maintenance.", company.Code);
}
await _registry.SetStatusAsync(company.Code, CompanyStatus.Maintenance, cancellationToken).ConfigureAwait(false);
}
}
return failed;
}
private async Task PrepareAsync(Company company, CompanySeedContext context, CancellationToken cancellationToken)
{
var target = await _registry.ResolveAsync(company.Code, cancellationToken).ConfigureAwait(false);
var report = await _migrations.RunAsync(target, _databases.CompanyMigrations, cancellationToken).ConfigureAwait(false);
LogMigrations(_logger, report, company.Code);
foreach (var seeder in _seeders)
{
await seeder.SeedAsync(company.Code, context, cancellationToken).ConfigureAwait(false);
}
}
/// Writes a migration report in the section Migrazioni.
/// The log.
/// The report.
/// The company, or for the system database.
public static void LogMigrations(ILogger logger, MigrationReport report, string? companyCode)
{
ArgumentNullException.ThrowIfNull(logger);
ArgumentNullException.ThrowIfNull(report);
using var section = logger.BeginScope(LogSections.Scope(LogSection.Migrations));
using var company = logger.BeginScope(new Dictionary { [LogSections.CompanyKey] = companyCode });
foreach (var (migration, duration) in report.Applied)
{
logger.LogInformation("Migration {Migration} applied to {Database} in {Milliseconds} ms.", migration.ToString(), report.Database, (long)duration.TotalMilliseconds);
}
foreach (var warning in report.Warnings)
{
logger.LogWarning("Database {Database}: {Warning}", report.Database, warning);
}
if (report.Applied.Count == 0)
{
logger.LogDebug("Database {Database} is up to date ({Count} migrations).", report.Database, report.AlreadyApplied);
}
}
private static string Validate(string code, string name)
{
var errors = new List();
if (!CompanyCodes.IsValid((code ?? string.Empty).Trim().ToUpperInvariant()))
{
errors.Add("Il codice azienda deve avere da 1 a 20 caratteri tra lettere, cifre e trattino basso.");
}
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > 200)
{
errors.Add("La ragione sociale è obbligatoria (al massimo 200 caratteri).");
}
return errors.Count > 0 ? throw new ValidationFailedException(errors) : CompanyCodes.Normalize(code!);
}
private async Task RequireRoomAsync(CancellationToken cancellationToken)
{
var limit = _licenses.Current.MaxCompanies;
var count = (await _registry.ListAsync(cancellationToken).ConfigureAwait(false)).Count;
if (count >= limit)
{
throw new AccessDeniedException(
SecurityErrors.LicenseLimitReached,
limit <= 1
? "La licenza consente una sola azienda: per gestirne altre serve il modulo Multi-azienda (MULTI)."
: $"La licenza consente al massimo {limit} aziende.");
}
}
private static void RequireInstanceAdministrator(Actor actor)
{
if (!actor.IsInstanceAccount)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Solo gli account di istanza possono gestire le aziende.");
}
}
}