Files
Khaemhat/src/Khaemhat.Web/Hosting/SeedCommand.cs
T
Alby96andClaude Opus 5.5 ced689b297 feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60)
Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the
movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP)
become draft purchase invoices with supplier, items and tax codes matched, the file attached
and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase
invoices show price differences against the order and the self-invoice still to issue,
with a pending list on the self-invoice screen. The opening stock import now writes an
opening movement. The demo company gets purchases, an opening stock, a pending
self-invoice and a stock take being counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:01:32 +01:00

157 lines
7.0 KiB
C#

using System.Globalization;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Seeding;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Infrastructure.Logging;
namespace Khaemhat.Web.Hosting;
/// <summary>What <c>seed</c> was asked to do.</summary>
/// <param name="Demo">Add the demo data too, after the base data, to the tables still empty.</param>
/// <param name="Scale">How many times the demo catalogues are repeated.</param>
/// <param name="Company">The company, or <see langword="null"/> for every active one.</param>
public sealed record SeedOptions(bool Demo, int Scale, string? Company);
/// <summary>
/// The command line of <c>scripts/seed.sh</c> (SPEC §4, §14): <c>seed --base|--demo [--scale N] [--company CODE]</c>
/// runs the start sequence without serving anything (migrations, first company), then adds the missing base data, and
/// with <c>--demo</c> the demo data, to one company or to every active one, and prints what it added. Rows already there
/// are never changed (ADR 0026); each demo seeder fills only its tables still empty.
/// </summary>
public static class SeedCommand
{
/// <summary>The first argument that selects the command.</summary>
public const string Verb = "seed";
/// <summary>Exit code of a wrong command line.</summary>
public const int UsageError = 64;
/// <summary>The largest <c>--scale</c>.</summary>
public const int MaxScale = 100;
/// <summary>Whether the arguments ask for this command.</summary>
/// <param name="args">The arguments.</param>
/// <returns><see langword="true"/> for <c>seed ...</c>.</returns>
public static bool Matches(string[] args) => args is [Verb, ..];
/// <summary>Reads the options after the verb.</summary>
/// <param name="args">The arguments, verb included.</param>
/// <param name="options">What to do, when the line is valid.</param>
/// <param name="error">The problem, or <see langword="null"/>.</param>
/// <returns><see langword="true"/> when the line is valid.</returns>
public static bool TryParse(string[] args, out SeedOptions? options, out string? error)
{
ArgumentNullException.ThrowIfNull(args);
options = null;
error = null;
var wantsBase = false;
var wantsDemo = false;
int? scale = null;
string? company = null;
for (var i = 1; i < args.Length; i++)
{
switch (args[i])
{
case "--base":
wantsBase = true;
break;
case "--demo":
wantsDemo = true;
break;
case "--scale" when i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n is >= 1 and <= MaxScale:
scale = n;
i++;
break;
case "--company" when i + 1 < args.Length && CompanyCodes.IsValid(CompanyCodes.Normalize(args[i + 1])):
company = CompanyCodes.Normalize(args[++i]);
break;
default:
error = "Argomento non valido: " + args[i];
return false;
}
}
if (!wantsBase && !wantsDemo)
{
error = "Uso: seed --base | --demo [--scale N] [--company CODICE]";
return false;
}
if (scale is not null && !wantsDemo)
{
error = "--scale vale solo con --demo.";
return false;
}
options = new SeedOptions(wantsDemo, scale ?? 1, company);
return true;
}
/// <summary>Runs the command.</summary>
/// <param name="args">The arguments, verb included.</param>
/// <returns>The exit code: 0 done, 1 failed, 64 wrong command line.</returns>
public static async Task<int> RunAsync(string[] args)
{
if (!TryParse(args, out var options, out var error) || options is null)
{
await Console.Error.WriteLineAsync(error).ConfigureAwait(false);
return UsageError;
}
// The configuration comes from the KHAEMHAT_* variables, as for the service; no web server is started.
var app = KhaemhatApp.Build([]);
await using (app.ConfigureAwait(false))
{
var services = app.Services;
try
{
await services.GetRequiredService<StartupOrchestrator>().RunAsync().ConfigureAwait(false);
var registry = services.GetRequiredService<ICompanyRegistry>();
var company = options.Company;
IReadOnlyList<string> codes = company is null
? [.. (await registry.ListAsync().ConfigureAwait(false)).Where(c => c.Status == CompanyStatus.Active).Select(c => c.Code)]
: await registry.FindAsync(company).ConfigureAwait(false) is { } found ? [found.Code] : [];
if (codes.Count == 0)
{
await Console.Error.WriteLineAsync(company is null ? "Nessuna azienda attiva." : "Azienda sconosciuta: " + company).ConfigureAwait(false);
return 1;
}
var runner = services.GetRequiredService<SeedRunner>();
foreach (var code in codes)
{
// The demo data need the base tables: --demo runs the base seeders first.
var report = await runner.RunAsync(code, SeedKind.Base).ConfigureAwait(false);
Print(code, "dati di base " + report.DataVersion, report);
if (options.Demo)
{
Print(code, "dati dimostrativi, scala " + options.Scale.ToString(CultureInfo.InvariantCulture),
await runner.RunAsync(code, SeedKind.Demo, options.Scale).ConfigureAwait(false));
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
return 0;
}
finally
{
await services.GetRequiredService<DbLogSink>().DisposeAsync().ConfigureAwait(false);
}
}
}
private static void Print(string company, string what, SeedReport report)
{
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{company}: {what}, {report.Total} righe aggiunte."));
foreach (var (table, count) in report.Added.Where(a => a.Value > 0).OrderBy(a => a.Key, StringComparer.Ordinal))
{
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}"));
}
}
}