using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Dashboard;
using Khaemhat.Application.Files;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Search;
using Khaemhat.Application.Seeding;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Files;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.PostgreSql;
using Khaemhat.Data.Sqlite;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Fiscal.Italy;
using Khaemhat.Infrastructure.Caching;
using Khaemhat.Infrastructure.Files;
using Khaemhat.Infrastructure.Http;
using Khaemhat.Infrastructure.Licensing;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Help;
using Khaemhat.Web.Security;
using Khaemhat.Web.Shell;
namespace Khaemhat.Web.Hosting;
///
/// The composition of the instance (SPEC §3): data access on the configured databases, security, licences, log and
/// the start sequence. Services are singletons: they hold no per-request state and open a unit of work per call.
///
internal static class KhaemhatServices
{
/// The culture of the interface and of number and date formats (SPEC §10.8).
internal static readonly CultureInfo ItalianCulture = CultureInfo.GetCultureInfo("it-IT");
/// Registers every service of the instance.
/// The container.
/// The validated variables.
/// The database log queue, already plugged into the logging pipeline.
/// The container.
public static IServiceCollection AddKhaemhat(this IServiceCollection services, KhaemhatOptions options, DbLogSink logSink)
{
var dataAssembly = typeof(CompanyRegistry).Assembly;
services.AddSingleton(options);
services.AddSingleton(_ => new WikiLibrary());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(logSink);
services.AddSingleton(TimeProvider.System);
services.AddSingleton();
services.AddHttpContextAccessor();
services.AddSingleton();
// Secrets and data access.
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
services.AddSingleton(sp =>
{
var slow = sp.GetRequiredService().CreateLogger("Khaemhat.Performance.SlowQueries");
var user = sp.GetRequiredService();
return new DataAccessContext(sp.GetRequiredService(), user.Get)
{
SlowQueryObserver = query =>
{
using var section = slow.BeginScope(LogSections.Scope(LogSection.Performance));
slow.LogWarning(
"Slow query on {Database}: {Milliseconds} ms. {Sql}",
query.Database, (long)query.Duration.TotalMilliseconds, query.Sql.Length > 2000 ? query.Sql[..2000] : query.Sql);
},
};
});
services.AddSingleton(sp => sp.GetRequiredService().Resolve(options.SystemDatabase));
services.AddSingleton(sp => new CompanyRegistry(
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService()));
services.AddSingleton(sp => new DatabaseLocator(sp.GetRequiredService(), sp.GetRequiredService()));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(new InstanceDatabases(
options.SystemDatabase, options.CompanyServer, MigrationCatalog.ForSystem(dataAssembly), MigrationCatalog.ForCompany(dataAssembly)));
// Cache: in memory, or on Redis when KHAEMHAT_REDIS is set (falling back to memory while Redis is down).
if (options.Redis is { } redis)
{
services.AddSingleton(new RedisClient(RedisEndpoint.Parse(redis)));
services.AddSingleton(sp => new RedisCacheProvider(
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>()));
}
else
{
services.AddSingleton(sp => new MemoryCacheProvider(sp.GetRequiredService()));
}
// Security.
services.AddSingleton(new SecurityPolicyOptions());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(ModuleRegistry.Default);
services.AddSingleton(LicenseVerifier.Product);
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// Country fiscal packs (ADR 0007, ADR 0025): the only place that names a concrete pack. The application finds
// the pack of a company through FiscalPackCatalog and company_profile.country.
services.AddSingleton();
services.AddSingleton(sp => new FiscalPackCatalog(sp.GetServices()));
// Company tables, profile and fiscal years (#38, #39), base data (#45), checks against European services (#40).
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// The ledger (ADR 0036, ADR 0037): the documents post through LedgerPoster inside the transaction of the engine.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// The schedule and the treasury (ADR 0038): collections, remittances, reconciliation, reminders, cash flow.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>));
// Guided import and export (ADR 0031): the entities in the order of the screen.
services.AddSingleton(sp => ActivatorUtilities.CreateInstance(
sp, Khaemhat.Core.Parties.PartyKind.Customer));
services.AddSingleton(sp => ActivatorUtilities.CreateInstance(
sp, Khaemhat.Core.Parties.PartyKind.Supplier));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(30));
services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(20));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// Companies and start.
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddScoped();
services.AddSingleton(sp => new StartupOrchestrator(
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService(),
logSink, sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>()));
services.AddHostedService();
// History of the records and scheduled tasks.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddHostedService();
// Interface (SPEC §10): texts, preferences and the per-circuit state of the shell.
services.AddSingleton(JsonTextProvider.FromAssembly(typeof(KhaemhatServices).Assembly, ItalianCulture));
services.AddSingleton();
services.AddSingleton();
// Dashboard (SPEC §10.3): the sources of the lists join from the modules that feed them.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// Files and attachments (#34): store on the data volume, antivirus hook, attachments, generators, trash job.
services.AddSingleton(FileStoreOptions.ForDataDirectory(options.DataDir));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// Mail (#52): the SMTP client written in house, the queue that sends in the background, documents by e-mail.
services.AddSingleton(new Khaemhat.Infrastructure.Mail.SmtpSettings(
options.SmtpHost, options.SmtpPortNumber, options.SmtpUser, options.SmtpPassword, options.SmtpFrom,
options.SmtpSecurityMode switch
{
SmtpSecurity.Ssl => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.Ssl,
SmtpSecurity.None => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.None,
_ => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.StartTls,
}));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddHostedService(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
return services;
}
}
/// The user name written in the audit columns: the signed-in user of the current request, else system.
/// The current request.
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
{
/// The name.
/// The user name, or outside requests.
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
}