using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
///
/// The sales of the demo company (SPEC ยง14, issue #53): the profile of the company, then a year of documents made the
/// way a user makes them, through the document engine: quotations sent, accepted, refused and expired; orders from
/// quotations and direct, delivered in full or in part; delivery notes still to invoice (for the deferred invoicing);
/// immediate and deferred invoices, a credit note, a pro forma and a few drafts. Dates fall between the first of
/// January and today, in order for each numerator. Runs only when the demo data are asked and the company has no sales
/// documents yet; every document is marked as demo.
///
/// The document engine.
/// The document editor (party terms, item prices).
/// The transformations between documents.
/// The company profiles.
/// The units of work.
/// The clock.
public sealed class DemoSalesSeeder(
DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, CompanyProfileService profiles, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// The fictitious VAT number of the demo company (valid check digit).
public const string CompanyVatNumber = "03579135793";
private static readonly Actor Seed = Actor.System;
private DocumentEngine Engine { get; } = engine;
private DocumentEditor Editor { get; } = editor;
private DocumentCopyService Copies { get; } = copies;
///
public int Order => 20;
///
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
await ProfileAsync(companyCode, cancellationToken).ConfigureAwait(false);
var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (data is null)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
await new Run(this, companyCode, data, today, cancellationToken).ExecuteAsync().ConfigureAwait(false);
}
// The letterhead of the demo company, when nobody wrote it yet.
private async Task ProfileAsync(string companyCode, CancellationToken cancellationToken)
{
var profile = await profiles.GetAsync(Seed, companyCode, cancellationToken).ConfigureAwait(false);
if (profile.Id != 0 || !string.IsNullOrEmpty(profile.VatNumber))
{
return;
}
profile.FiscalName = profile.LegalName;
profile.VatNumber = CompanyVatNumber;
profile.TaxCode = CompanyVatNumber;
profile.ReaOffice = "CN";
profile.ReaNumber = "123456";
profile.ShareCapital = 50000m;
profile.Shareholders = "SM";
profile.LiquidationStatus = "LN";
profile.Address = "Via dei Granai";
profile.StreetNumber = "57";
profile.PostalCode = "12100";
profile.City = "Cuneo";
profile.ProvinceCode = "CN";
profile.AddressCountry = "IT";
profile.Phone = "+39 0171 000000";
profile.Email = "info@demo.example";
profile.Pec = "demo@pec.demo.example";
profile.Website = "https://demo.example";
profile.FooterNotes = "Dati dimostrativi: nomi, numeri e conti sono fittizi.";
await profiles.SaveAsync(Seed, companyCode, profile, cancellationToken).ConfigureAwait(false);
}
// The parties and items the documents use; null when the company already has sales or lacks the demo masters.
private async Task ReadAsync(string companyCode, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0)
{
return null;
}
var parties = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
var items = (await uow.Repository- ().ListAsync(Query.For
- ().Where(i => i.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(i => i.Id).ToList();
var goods = items.Where(i => i.Kind == ItemKind.Goods).Select(i => i.Id).ToList();
var services = items.Where(i => i.Kind == ItemKind.Service).Select(i => i.Id).ToList();
string[] names = ["Rossi Impianti S.r.l.", "Bianchi & Figli S.n.c.", "Idrotermica Piemonte S.r.l.", "Edilizia Moderna S.p.A.", "Hotel Belvedere S.r.l.", "Esposito Mario"];
return goods.Count >= 12 && services.Count > 0 && names.All(parties.ContainsKey) ? new DemoData(parties, goods, services) : null;
}
private sealed record DemoData(IReadOnlyDictionary Parties, IReadOnlyList Goods, IReadOnlyList Services);
// One seeding, with its company and dates.
private sealed class Run(DemoSalesSeeder owner, string company, DemoData data, DateOnly today, CancellationToken cancellationToken)
{
private long Party(string name) => data.Parties[name];
// A date some months before today, kept between the first of January and today so that every document falls
// in the current year and the numbering stays in date order.
private DateOnly D(int monthsBack, int day)
{
var month = today.AddMonths(-monthsBack);
var date = new DateOnly(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
var first = new DateOnly(today.Year, 1, 1);
return date < first ? first : date > today ? today : date;
}
public async Task ExecuteAsync()
{
// Quotations (numerator PRE), in date order.
var q1 = await NewAsync("PRE", "Rossi Impianti S.r.l.", D(5, 10), [(0, 4m), (1, 10m), (2, 24m)], validDays: 30).ConfigureAwait(false);
var q2 = await NewAsync("PRE", "Hotel Belvedere S.r.l.", D(4, 3), [(3, 6m), (4, 6m)], validDays: 30).ConfigureAwait(false);
await NewAsync("PRE", "Edilizia Moderna S.p.A.", D(3, 1), [(5, 20m), (6, 40m)], validDays: 30).ConfigureAwait(false);
var q4 = await NewAsync("PRE", "Bianchi & Figli S.n.c.", D(2, 5), [(7, 12m), (8, 3m)], validDays: 60, service: 8m).ConfigureAwait(false);
await NewAsync("PRE", "Idrotermica Piemonte S.r.l.", D(0, 2), [(9, 2m), (10, 5m)], validDays: 30).ConfigureAwait(false);
await owner.Engine.CloseAsync(Seed, company, q2.Family, q2.Header.Id, cancellationToken).ConfigureAwait(false);
await NewAsync("PRE", "Esposito Mario", today, [(11, 1m)], validDays: 15, confirm: false).ConfigureAwait(false);
// Orders (numerator ORD): from the accepted quotations and direct.
var o1 = await ConfirmAsync(await CopyAsync(q1, "OC", D(5, 20)).ConfigureAwait(false)).ConfigureAwait(false);
var o3 = await NewAsync("OC", "Edilizia Moderna S.p.A.", D(3, 10), [(0, 10m), (2, 30m), (5, 50m)], reference: "ORD-EM-0412").ConfigureAwait(false);
var o2 = await ConfirmAsync(await CopyAsync(q4, "OC", D(2, 12)).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("OC", "Hotel Belvedere S.r.l.", D(1, 8), [(3, 4m), (4, 4m), (11, 2m)], reference: "Ristrutturazione bagni").ConfigureAwait(false);
// Delivery notes (numerator DDT): one per order, the second order in two goes; the last three stay to invoice.
var d1 = await ConfirmAsync(await CopyAsync(o1, "DDT", D(4, 2)).ConfigureAwait(false)).ConfigureAwait(false);
var d2 = await ConfirmAsync(await CopyAsync(o3, "DDT", D(3, 15), [o3.Lines[0].Id, o3.Lines[1].Id]).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(o2, "DDT", D(1, 5)).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(o3, "DDT", D(1, 12)).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("DDT", "Rossi Impianti S.r.l.", D(1, 20), [(6, 15m), (1, 6m)]).ConfigureAwait(false);
// Invoices and notes (numerator FAT, shared), in date order.
await NewAsync("FI", "Bianchi & Figli S.n.c.", D(5, 28), [(2, 12m), (9, 1m)], service: 4m).ConfigureAwait(false);
var f2 = await NewAsync("FI", "Hotel Belvedere S.r.l.", D(4, 10), [(3, 2m), (4, 2m), (10, 3m)]).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(d1, "FD", D(4, 30)).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(d2, "FD", D(3, 31)).ConfigureAwait(false)).ConfigureAwait(false);
var note = await CopyAsync(f2, "NC", D(2, 15), [f2.Lines[0].Id]).ConfigureAwait(false);
note.Lines[^1].Quantity = 1m;
note.Header.Notes = "Reso di un articolo difettoso.";
await ConfirmAsync(await owner.Engine.SaveAsync(Seed, company, note, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("FI", "Edilizia Moderna S.p.A.", D(1, 25), [(7, 30m), (8, 10m)], service: 16m).ConfigureAwait(false);
await NewAsync("FI", "Rossi Impianti S.r.l.", D(0, 5), [(0, 2m), (11, 1m)]).ConfigureAwait(false);
await NewAsync("FI", "Idrotermica Piemonte S.r.l.", today, [(5, 8m)], confirm: false).ConfigureAwait(false);
await NewAsync("PF", "Esposito Mario", today, [(9, 1m)], service: 3m).ConfigureAwait(false);
}
// A new document of the customer with goods (index in the demo goods, quantity) and optional hours of work.
private async Task NewAsync(
string type, string customer, DateOnly date, IReadOnlyList<(int Good, decimal Quantity)> lines, int? validDays = null, decimal? service = null,
string? reference = null, bool confirm = true)
{
var record = await owner.Engine.NewAsync(Seed, company, type, cancellationToken).ConfigureAwait(false);
record.Header.IsDemo = true;
record.Header.DocumentDate = date;
record.Header.ExternalReference = reference;
await owner.Editor.ApplyPartyAsync(Seed, company, record, Party(customer), cancellationToken).ConfigureAwait(false);
if (validDays is { } days)
{
record.Header.ValidUntil = date.AddDays(days);
}
foreach (var (good, quantity) in lines)
{
await AddAsync(record, data.Goods[good % data.Goods.Count], quantity).ConfigureAwait(false);
}
if (service is { } hours)
{
await AddAsync(record, data.Services[0], hours).ConfigureAwait(false);
}
record = await owner.Engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
return confirm ? await ConfirmAsync(record).ConfigureAwait(false) : record;
}
private async Task AddAsync(DocumentRecord record, long itemId, decimal quantity)
{
var line = DocumentStores.Of(record.Family).NewLine();
line.Quantity = quantity;
await owner.Editor.FillLineAsync(Seed, company, record, line, itemId, cancellationToken).ConfigureAwait(false);
record.Lines.Add(line);
}
private Task CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection? lines = null) =>
owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken);
private Task ConfirmAsync(DocumentRecord record) =>
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
}
}