Adds the company tables of SPEC 11.1 behind one generic service so that every table gets the same rules, history, cache and CSV import/export, plus the company profile, fiscal years with monthly lock and the base-data seeder. - 26 coded tables, exchange rates, company profile, fiscal years and periods: entities, maps and migrations 010-014 - TableService + TableCatalog: unique codes, per-table rules (VAT codes are checked by the fiscal pack), delete or disable when in use, single default, CSV export/import all-or-nothing, cache with cross-instance invalidation - CompanyProfileService (Italian identifiers through the pack), FiscalYearService with the date check used by every dated record - EcbRatesClient and the ECB rates system task; CsvReader - ISeeder/SeedRunner with the data version in company settings; base tables from the pack (IBaseTablesTemplate) and an embedded ISO country list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
222 lines
12 KiB
C#
222 lines
12 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
internal static class KhaemhatServices
|
|
{
|
|
/// <summary>The culture of the interface and of number and date formats (SPEC §10.8).</summary>
|
|
internal static readonly CultureInfo ItalianCulture = CultureInfo.GetCultureInfo("it-IT");
|
|
|
|
/// <summary>Registers every service of the instance.</summary>
|
|
/// <param name="services">The container.</param>
|
|
/// <param name="options">The validated variables.</param>
|
|
/// <param name="logSink">The database log queue, already plugged into the logging pipeline.</param>
|
|
/// <returns>The container.</returns>
|
|
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<ISearchProvider, HelpSearchProvider>();
|
|
services.AddSingleton<GlobalSearchService>();
|
|
services.AddSingleton(logSink);
|
|
services.AddSingleton(TimeProvider.System);
|
|
services.AddSingleton<BootstrapState>();
|
|
services.AddHttpContextAccessor();
|
|
services.AddSingleton<CurrentUserName>();
|
|
|
|
// Secrets and data access.
|
|
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
|
|
services.AddSingleton<SecretProtector>();
|
|
services.AddSingleton<ISecretProtector>(sp => sp.GetRequiredService<SecretProtector>());
|
|
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
|
|
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var slow = sp.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Performance.SlowQueries");
|
|
var user = sp.GetRequiredService<CurrentUserName>();
|
|
return new DataAccessContext(sp.GetRequiredService<TimeProvider>(), 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<DbProviderCatalog>().Resolve(options.SystemDatabase));
|
|
services.AddSingleton<ICompanyRegistry>(sp => new CompanyRegistry(
|
|
sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<ISecretProtector>(),
|
|
sp.GetRequiredService<MapRegistry>(), sp.GetRequiredService<DataAccessContext>()));
|
|
services.AddSingleton<IDatabaseLocator>(sp => new DatabaseLocator(sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<ICompanyRegistry>()));
|
|
services.AddSingleton<IUnitOfWorkFactory, UnitOfWorkFactory>();
|
|
services.AddSingleton<MigrationRunner>();
|
|
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<ICacheProvider>(sp => new RedisCacheProvider(
|
|
sp.GetRequiredService<RedisClient>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<RedisCacheProvider>>()));
|
|
}
|
|
else
|
|
{
|
|
services.AddSingleton<ICacheProvider>(sp => new MemoryCacheProvider(sp.GetRequiredService<TimeProvider>()));
|
|
}
|
|
|
|
// Security.
|
|
services.AddSingleton(new SecurityPolicyOptions());
|
|
services.AddSingleton<PasswordPolicy>();
|
|
services.AddSingleton<AccountSecurity>();
|
|
services.AddSingleton<ISecurityAuditLog, SecurityAuditLog>();
|
|
services.AddSingleton<SystemSettingsStore>();
|
|
services.AddSingleton(ModuleRegistry.Default);
|
|
services.AddSingleton(LicenseVerifier.Product);
|
|
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
|
|
services.AddSingleton<LicenseGate>();
|
|
services.AddSingleton<ILicenseGate>(sp => sp.GetRequiredService<LicenseGate>());
|
|
services.AddSingleton<ILicenseActivationService, OfflineActivationService>();
|
|
services.AddSingleton<PermissionService>();
|
|
services.AddSingleton<RoleService>();
|
|
services.AddSingleton<SystemUserService>();
|
|
services.AddSingleton<UserService>();
|
|
services.AddSingleton<SessionStore>();
|
|
services.AddSingleton<NotificationDispatcher>();
|
|
services.AddSingleton<SignInService>();
|
|
services.AddSingleton<ProfileService>();
|
|
|
|
// 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<IFiscalPack, ItalyFiscalPack>();
|
|
services.AddSingleton(sp => new FiscalPackCatalog(sp.GetServices<IFiscalPack>()));
|
|
|
|
// Company tables, profile and fiscal years (#38, #39), base data (#45), checks against European services (#40).
|
|
services.AddSingleton<CompanyFiscalContext>();
|
|
services.AddSingleton<TableCatalog>();
|
|
services.AddSingleton<TableService>();
|
|
services.AddSingleton<CompanyProfileService>();
|
|
services.AddSingleton<FiscalYearService>();
|
|
services.AddSingleton<ExchangeRateService>();
|
|
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
|
|
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
|
|
services.AddSingleton<IScheduledJob, EcbRatesJob>();
|
|
services.AddSingleton<ISeeder, BaseTablesSeeder>();
|
|
services.AddSingleton<SeedRunner>();
|
|
|
|
// Companies and start.
|
|
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
|
|
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
|
|
services.AddSingleton<CompanyService>();
|
|
services.AddSingleton<CompanyContextResolver>();
|
|
services.AddScoped<ICompanyContext, WebCompanyContext>();
|
|
services.AddSingleton(sp => new StartupOrchestrator(
|
|
sp.GetRequiredService<InstanceDatabases>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<MigrationRunner>(),
|
|
sp.GetRequiredService<SystemSettingsStore>(), sp.GetRequiredService<RoleService>(), sp.GetRequiredService<ILicenseGate>(),
|
|
sp.GetRequiredService<SystemUserService>(), sp.GetRequiredService<CompanyService>(), options, sp.GetRequiredService<IUnitOfWorkFactory>(),
|
|
logSink, sp.GetRequiredService<BootstrapState>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<StartupOrchestrator>>()));
|
|
services.AddHostedService<BootstrapService>();
|
|
|
|
// History of the records and scheduled tasks.
|
|
services.AddSingleton<AuditTrail>();
|
|
services.AddSingleton<AuditTrailService>();
|
|
services.AddSingleton<IScheduledJob, SessionCleanupJob>();
|
|
services.AddSingleton<IScheduledJob, LicenseCheckJob>();
|
|
services.AddSingleton<IScheduledJob, LogRetentionJob>();
|
|
services.AddSingleton<JobScheduler>();
|
|
services.AddHostedService<JobSchedulerService>();
|
|
|
|
// Interface (SPEC §10): texts, preferences and the per-circuit state of the shell.
|
|
services.AddSingleton<ITexts>(JsonTextProvider.FromAssembly(typeof(KhaemhatServices).Assembly, ItalianCulture));
|
|
services.AddSingleton<UserSettingsService>();
|
|
services.AddSingleton<CompanySettingsService>();
|
|
|
|
// Dashboard (SPEC §10.3): the sources of the lists join from the modules that feed them.
|
|
services.AddSingleton<DashboardService>();
|
|
services.AddSingleton<LicenseFeedSource>();
|
|
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<LicenseFeedSource>());
|
|
services.AddSingleton<IDeadlineSource>(sp => sp.GetRequiredService<LicenseFeedSource>());
|
|
services.AddSingleton<ITodoSource, NotificationTodoSource>();
|
|
services.AddSingleton<JobRunFeedSource>();
|
|
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<JobRunFeedSource>());
|
|
services.AddSingleton<IDoneSource>(sp => sp.GetRequiredService<JobRunFeedSource>());
|
|
services.AddSingleton<SystemStatusService>();
|
|
services.AddSingleton<TodoAggregator>();
|
|
services.AddSingleton<DoneAggregator>();
|
|
services.AddSingleton<DeadlineAggregator>();
|
|
services.AddScoped<ShellSession>();
|
|
services.AddScoped<ThemeService>();
|
|
services.AddScoped<TabService>();
|
|
services.AddScoped<KeyboardShortcutService>();
|
|
services.AddScoped<ToastService>();
|
|
services.AddScoped<DialogService>();
|
|
services.AddScoped<DrawerService>();
|
|
|
|
// Files and attachments (#34): store on the data volume, antivirus hook, attachments, generators, trash job.
|
|
services.AddSingleton(FileStoreOptions.ForDataDirectory(options.DataDir));
|
|
services.AddSingleton<IFileScanner, NoOpFileScanner>();
|
|
services.AddSingleton<IFileStore, VolumeFileStore>();
|
|
services.AddSingleton<AttachmentService>();
|
|
services.AddSingleton<IFileGenerator, DemoPdfGenerator>();
|
|
services.AddSingleton<IFileGenerator, DemoCsvGenerator>();
|
|
services.AddSingleton<IFileGenerator, DemoXlsxGenerator>();
|
|
services.AddSingleton<FileGeneratorRegistry>();
|
|
services.AddSingleton<FileGenerationService>();
|
|
services.AddSingleton<IScheduledJob, AttachmentTrashPurgeJob>();
|
|
return services;
|
|
}
|
|
}
|
|
|
|
/// <summary>The user name written in the audit columns: the signed-in user of the current request, else <c>system</c>.</summary>
|
|
/// <param name="accessor">The current request.</param>
|
|
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
|
|
{
|
|
/// <summary>The name.</summary>
|
|
/// <returns>The user name, or <see langword="null"/> outside requests.</returns>
|
|
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
|
|
}
|