feat: parties with radar, record, checks, VIES and demo data (#41)

Customers, suppliers, prospects and leads live in one parties archive
with a kind and a subject type (ADR 0029). A customer that also supplies
carries is_also_supplier, so it shows in both radars with one code.

- Three radars (/anagrafiche/clienti, /fornitori, /contatti) with search,
  quick filters and bulk disable/enable; the record has eight tabs
  (main data, addresses, contacts, terms, fiscal and SDI, banks, notes and
  attachments, history) on the MasterDataPage base.
- PartyService saves the whole record in one transaction, checks it with
  the fiscal pack (VAT number, tax code, recipient code, country), treats
  a duplicate VAT number or a consumer without tax code as warnings, fills
  the default recipient code, runs VIES after commit for EU companies, and
  converts prospects/leads (new customer code, old one kept as
  previous_code) and suppliers (become customers that also supply).
- Delete falls back to disable when the party is referenced.
- DemoPartiesSeeder adds 3 salespeople and 21 parties with fictitious but
  formally valid identifiers; SeedAsync now runs demo seeders when asked.
- Test host accepts service overrides so VIES can be stubbed.

Docs: ADR 0029, wiki Anagrafiche and demo data pages, regenerated data
model, CHANGELOG and STATUS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 10:06:33 +01:00
1 parent a9eda510f2
commit 3401271483
28 files changed
+4600 -85

No files matched your search

@@ -0,0 +1,979 @@
using System.Data.Common;
using Khaemhat.Application.Audit;
using Khaemhat.Core.Instance;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Validation;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Http;
namespace Khaemhat.Application.Parties;
/// <summary>A party with every detail: what the record page shows and saves in one go.</summary>
public sealed class PartyRecord
{
/// <summary>The party.</summary>
public Party Party { get; set; } = new();
/// <summary>The sales terms (customers).</summary>
public PartySalesTerms Sales { get; set; } = new();
/// <summary>The purchase terms (suppliers).</summary>
public PartyPurchaseTerms Purchase { get; set; } = new();
/// <summary>The fiscal data.</summary>
public PartyFiscal Fiscal { get; set; } = new();
/// <summary>The other addresses.</summary>
public List<PartyAddress> Addresses { get; set; } = [];
/// <summary>The contact people.</summary>
public List<PartyContact> Contacts { get; set; } = [];
/// <summary>The bank accounts.</summary>
public List<PartyBankAccount> BankAccounts { get; set; } = [];
}
/// <summary>Which parties a radar shows (menu <i>Anagrafiche</i>).</summary>
public enum PartyArchive
{
/// <summary>Customers (also those that are suppliers).</summary>
Customers = 0,
/// <summary>Suppliers (also customers that are suppliers).</summary>
Suppliers = 1,
/// <summary>Prospects and leads.</summary>
Contacts = 2,
}
/// <summary>A row of the radar of the parties (mockup 012).</summary>
/// <param name="Id">The id.</param>
/// <param name="Code">The code.</param>
/// <param name="Name">The name.</param>
/// <param name="Kind">What the party is.</param>
/// <param name="IsAlsoSupplier">A customer that is also a supplier.</param>
/// <param name="SubjectType">The kind of subject.</param>
/// <param name="VatNumber">The VAT number.</param>
/// <param name="TaxCode">The tax code.</param>
/// <param name="City">The city.</param>
/// <param name="Province">The province.</param>
/// <param name="CountryCode">The country.</param>
/// <param name="SalespersonId">The salesperson.</param>
/// <param name="CategoryId">The category.</param>
/// <param name="Disabled">Disabled.</param>
public sealed record PartyRow(
long Id, string Code, string Name, PartyKind Kind, bool IsAlsoSupplier, SubjectType SubjectType, string? VatNumber, string? TaxCode, string? City,
string? Province, string CountryCode, long? SalespersonId, long? CategoryId, bool Disabled)
{
/// <summary>The terms of the row, filled for the page shown.</summary>
public PartyRowTerms? Terms { get; init; }
/// <summary>VAT number or, without one, tax code (column <i>P.IVA / C.F.</i>).</summary>
public string? Identifier => VatNumber ?? TaxCode;
}
/// <summary>The terms shown on a radar row.</summary>
/// <param name="PaymentTermId">The payment terms.</param>
/// <param name="PriceListId">The price list.</param>
/// <param name="Blocked">Orders blocked.</param>
/// <param name="SplitPayment">Split payment.</param>
public sealed record PartyRowTerms(long? PaymentTermId, long? PriceListId, bool Blocked, bool SplitPayment);
/// <summary>What deleting a party did.</summary>
public enum PartyDeleteOutcome
{
/// <summary>The party is gone.</summary>
Deleted = 0,
/// <summary>The party is used by documents: it was disabled instead.</summary>
Disabled = 1,
}
/// <summary>
/// The parties (SPEC §11.2, issue #41, ADR 0029): radar, read and save of a party with its details in one transaction,
/// automatic codes by kind, the checks of the fiscal pack, the VIES check of EU numbers, conversion of leads and prospects
/// into customers, delete or disable.
/// </summary>
/// <remarks>Permissions <c>parties.party.read</c>, <c>write</c>, <c>delete</c>.</remarks>
public sealed class PartyService
{
/// <summary>Permission to see the parties.</summary>
public const string ReadPermission = "parties.party.read";
/// <summary>Permission to create and change the parties.</summary>
public const string WritePermission = "parties.party.write";
/// <summary>Permission to delete the parties.</summary>
public const string DeletePermission = "parties.party.delete";
/// <summary>Error: the name is missing.</summary>
public const string NameRequired = "parties.name.required";
/// <summary>Error: the VAT number is required for this kind of subject.</summary>
public const string VatNumberRequired = "parties.vat-number.required";
/// <summary>Error: a public administration needs a VAT number or a tax code.</summary>
public const string IdentifierRequired = "parties.identifier.required";
/// <summary>Error: the tax code is not valid.</summary>
public const string TaxCodeInvalid = "parties.tax-code.invalid";
/// <summary>Warning: a private customer without tax code.</summary>
public const string TaxCodeMissing = "parties.tax-code.missing";
/// <summary>Error: another party has the code.</summary>
public const string CodeDuplicate = "parties.code.duplicate";
/// <summary>Error: the country is not in the table of the countries.</summary>
public const string CountryUnknown = "parties.country.unknown";
/// <summary>Error: an EU subject needs a member state other than the company's.</summary>
public const string CountryNotEu = "parties.country.not-eu";
/// <summary>Error: a domestic subject needs the company's country.</summary>
public const string CountryNotDomestic = "parties.country.not-domestic";
/// <summary>Warning: another party has the same VAT number.</summary>
public const string VatNumberDuplicate = "parties.vat-number.duplicate";
/// <summary>Error: a declaration of intent needs number and ceiling.</summary>
public const string IntentIncomplete = "parties.intent.incomplete";
/// <summary>Error: the exigibility is not I, D or S.</summary>
public const string ExigibilityInvalid = "parties.exigibility.invalid";
/// <summary>Error: the day of the month is not 1-31.</summary>
public const string DayRange = "parties.day.range";
/// <summary>Error: a value cannot be negative.</summary>
public const string NotNegative = "parties.value.negative";
/// <summary>Error: an address or contact without name, a bank account without IBAN.</summary>
public const string DetailRequired = "parties.detail.required";
/// <summary>Error: the party is not a lead or prospect, nor a supplier (conversion).</summary>
public const string AlreadyCustomer = "parties.convert.already-customer";
/// <summary>Error: the party changed or was deleted meanwhile.</summary>
public const string NotFound = "parties.not-found";
/// <summary>The entity name of the attachments and the history.</summary>
public const string Entity = "parties.party";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly CompanyFiscalContext _fiscal;
private readonly CodeRuleService _codes;
private readonly AutoFillService _autoFill;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks permissions.</param>
/// <param name="audit">Writes the history.</param>
/// <param name="fiscal">The fiscal pack of each company.</param>
/// <param name="codes">The automatic codes.</param>
/// <param name="autoFill">The automatic filling options and the VIES check.</param>
/// <param name="clock">The clock.</param>
public PartyService(
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, CodeRuleService codes, AutoFillService autoFill,
TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(codes);
ArgumentNullException.ThrowIfNull(autoFill);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_audit = audit;
_fiscal = fiscal;
_codes = codes;
_autoFill = autoFill;
_clock = clock;
}
/// <summary>The fields of the radar: search on code, name, VAT number, tax code and city.</summary>
public static ListFields<Party> Fields { get; } = new ListFields<Party>()
.Add("code", p => p.Code, searchable: true)
.Add("name", p => p.Name, searchable: true)
.Add("vatNumber", p => p.VatNumber, searchable: true)
.Add("taxCode", p => p.TaxCode, searchable: true)
.Add("city", p => p.City, searchable: true)
.Add("province", p => p.Province)
.Add("country", p => p.CountryCode)
.Add("subjectType", p => p.SubjectType)
.Add("kind", p => p.Kind)
.Add("salesperson", p => p.SalespersonId)
.Add("category", p => p.CategoryId)
.Add("disabled", p => p.Disabled)
.OrderByDefault(new ListSort("name"));
/// <summary>The code archive of a kind of party (ADR 0027).</summary>
/// <param name="kind">The kind.</param>
/// <returns>The key of <see cref="CodeRuleService.Definitions"/>.</returns>
public static string CodeRuleOf(PartyKind kind) => kind switch
{
PartyKind.Customer => "customers",
PartyKind.Supplier => "suppliers",
_ => "leads",
};
/// <summary>The kind of e-invoice recipient of a subject.</summary>
/// <param name="subject">The kind of subject.</param>
/// <returns>The recipient kind.</returns>
public static RecipientKind RecipientOf(SubjectType subject) => subject switch
{
SubjectType.PublicAdministration => RecipientKind.PublicAdministration,
SubjectType.Person => RecipientKind.Consumer,
SubjectType.EuCompany or SubjectType.NonEuCompany => RecipientKind.Foreign,
_ => RecipientKind.Business,
};
/// <summary>A page of the radar.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="archive">Customers, suppliers or contacts.</param>
/// <param name="query">Search, filters, ordering and page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page, with the terms of its rows.</returns>
public async Task<ListPage<PartyRow>> ListAsync(Actor actor, string companyCode, PartyArchive archive, ListQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var select = archive switch
{
PartyArchive.Customers => Query.For<Party>().Where(p => p.Kind == PartyKind.Customer),
PartyArchive.Suppliers => Query.For<Party>().Where(p => p.Kind == PartyKind.Supplier || (p.Kind == PartyKind.Customer && p.IsAlsoSupplier)),
_ => Query.For<Party>().Where(p => p.Kind == PartyKind.Prospect || p.Kind == PartyKind.Lead),
};
var page = await uow.Repository<Party, long>().ListAsync(Fields.Apply(select, query), cancellationToken).ConfigureAwait(false);
var ids = page.Items.Select(p => p.Id).ToList();
var sales = ids.Count == 0
? []
: (await uow.Repository<PartySalesTerms, long>().ListAsync(Query.For<PartySalesTerms>().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items;
var purchase = ids.Count == 0
? []
: (await uow.Repository<PartyPurchaseTerms, long>().ListAsync(Query.For<PartyPurchaseTerms>().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items;
var fiscal = ids.Count == 0
? []
: (await uow.Repository<PartyFiscal, long>().ListAsync(Query.For<PartyFiscal>().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items;
var salesBy = sales.ToDictionary(s => s.PartyId);
var purchaseBy = purchase.ToDictionary(s => s.PartyId);
var fiscalBy = fiscal.ToDictionary(s => s.PartyId);
IReadOnlyList<PartyRow> rows =
[
.. page.Items.Select(p => RowOf(p) with
{
Terms = new PartyRowTerms(
archive == PartyArchive.Suppliers ? purchaseBy.GetValueOrDefault(p.Id)?.PaymentTermId : salesBy.GetValueOrDefault(p.Id)?.PaymentTermId,
salesBy.GetValueOrDefault(p.Id)?.PriceListId,
salesBy.GetValueOrDefault(p.Id)?.Blocked ?? false,
fiscalBy.GetValueOrDefault(p.Id)?.SplitPayment ?? false),
}),
];
return new ListPage<PartyRow>(rows, page.TotalCount, new Dictionary<string, decimal>());
}
/// <summary>Parties for a hotlink: active ones whose code or name starts with or contains the text.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="archive">Customers, suppliers or contacts.</param>
/// <param name="text">The text typed.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Up to 20 rows.</returns>
public async Task<IReadOnlyList<PartyRow>> SearchAsync(Actor actor, string companyCode, PartyArchive archive, string? text, CancellationToken cancellationToken = default)
{
var page = await ListAsync(
actor, companyCode, archive,
new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 },
cancellationToken).ConfigureAwait(false);
return page.Items;
}
/// <summary>A party with every detail.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record, or <see langword="null"/>.</returns>
public async Task<PartyRecord?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
/// <summary>A new party of a kind, with the values proposed by the company (country, currency, defaults).</summary>
/// <param name="actor">Who creates it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="kind">The kind.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record, not saved.</returns>
public async Task<PartyRecord> NewAsync(Actor actor, string companyCode, PartyKind kind, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
return new PartyRecord
{
Party = new Party { Kind = kind, CountryCode = pack.CountryCode, Since = kind is PartyKind.Customer or PartyKind.Supplier ? today : null },
};
}
/// <summary>Checks a record without saving it: normalizes it in place and returns errors and warnings.</summary>
/// <param name="actor">Who checks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The problems, with fields such as <c>VatNumber</c>, <c>Fiscal.RecipientCode</c> or <c>Addresses.0.Name</c>.</returns>
public async Task<IReadOnlyList<TableProblem>> ValidateAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Saves a party with its details: inserts it when its id is 0 (assigning the code when empty), updates it otherwise.
/// An EU VAT number that is new or changed is checked on VIES when the option is on; the outcome is saved.
/// </summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The saved record, read back.</returns>
/// <exception cref="ValidationFailedException">A rule failed; errors are <c>Field:code</c>.</exception>
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the party meanwhile.</exception>
public async Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var party = record.Party;
long id;
PartyRecord? before;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
before = party.Id == 0 ? null : await LoadAsync(uow, party.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]);
var problems = (await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
var codeChanged = before is null || !string.Equals(before.Party.Code, party.Code, StringComparison.Ordinal);
var rule = await _codes.RuleAsync(company, CodeRuleOf(party.Kind), cancellationToken).ConfigureAwait(false);
if (party.Code.Length > 0 && codeChanged && CodeRuleService.CheckManual(rule, party.Code) is { } manual)
{
problems.Add(nameof(Party.Code) + ":" + manual);
}
if (problems.Count > 0)
{
throw new ValidationFailedException(problems);
}
if (party.Code.Length == 0)
{
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
}
id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (party.SubjectType == SubjectType.EuCompany && party.VatNumber is { Length: > 0 }
&& (before is null || before.Party.VatNumber != party.VatNumber || before.Party.CountryCode != party.CountryCode || before.Party.VatCheck == VatCheckStatus.None)
&& await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false))
{
await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await LoadAsync(read, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
}
/// <summary>Checks the VAT number of an EU party on VIES now (action <i>VIES</i>) and saves the outcome.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The answer of VIES, or <see langword="null"/> when the party has no VAT number of a member state.</returns>
public async Task<ViesResult?> CheckVatAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
return await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Turns a lead or prospect into a customer with a customer code (the old code stays in
/// <see cref="Party.PreviousCode"/>), or makes a supplier also a customer (it keeps its code).
/// </summary>
/// <param name="actor">Who converts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The party.</returns>
public async Task<PartyRecord> ConvertToCustomerAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<Party, long>();
var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
var before = Clone(party);
switch (party.Kind)
{
case PartyKind.Customer:
throw new ValidationFailedException(["Kind:" + AlreadyCustomer]);
case PartyKind.Supplier:
party.Kind = PartyKind.Customer;
party.IsAlsoSupplier = true;
break;
default:
var rule = await _codes.RuleAsync(company, CodeRuleOf(PartyKind.Customer), cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
party.PreviousCode = party.Code;
party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
party.Kind = PartyKind.Customer;
party.Since ??= today;
break;
}
await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
}
/// <summary>Disables or enables parties (radar action <i>Disabilita</i>).</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The parties.</param>
/// <param name="disabled">Disable or enable.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The parties changed.</returns>
public async Task<int> SetDisabledAsync(Actor actor, string companyCode, IEnumerable<long> ids, bool disabled, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<Party, long>();
var changed = 0;
foreach (var id in ids.Distinct())
{
if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } party && party.Disabled != disabled)
{
var before = Clone(party);
party.Disabled = disabled;
await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false);
changed++;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return changed;
}
/// <summary>Deletes a party never used, or disables it when documents refer to it.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened.</returns>
public async Task<PartyDeleteOutcome> DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var before = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
// The details go with the party (cascade); the documents of later milestones refuse the delete.
await uow.Repository<Party, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, before.Party, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return PartyDeleteOutcome.Deleted;
}
catch (DbException)
{
await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
return PartyDeleteOutcome.Disabled;
}
}
/// <summary>The history of a party, newest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The changes of the party and of its details.</returns>
public async Task<IReadOnlyList<AuditEntry>> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
var entries = new List<AuditEntry>();
foreach (var entity in new[] { nameof(Party), nameof(PartySalesTerms), nameof(PartyPurchaseTerms), nameof(PartyFiscal) })
{
entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false));
}
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
}
private static PartyRow RowOf(Party p) =>
new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled);
private static async Task<bool> TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.Code == code), cancellationToken).ConfigureAwait(false) > 0;
private static async Task<PartyRecord?> LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<Party, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } party)
{
return null;
}
return new PartyRecord
{
Party = party,
Sales = await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false)
?? new PartySalesTerms { PartyId = id },
Purchase = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(Query.For<PartyPurchaseTerms>().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false)
?? new PartyPurchaseTerms { PartyId = id },
Fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false)
?? new PartyFiscal { PartyId = id },
Addresses = [.. (await uow.Repository<PartyAddress, long>().ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
Contacts = [.. (await uow.Repository<PartyContact, long>().ListAsync(Query.For<PartyContact>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
BankAccounts = [.. (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
};
}
private async Task<long> WriteAsync(IUnitOfWork uow, PartyRecord record, PartyRecord? before, string userName, CancellationToken cancellationToken)
{
var party = record.Party;
var parties = uow.Repository<Party, long>();
if (before is null)
{
party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<Party>(uow, AuditAction.Insert, party.Id, null, party, userName, cancellationToken).ConfigureAwait(false);
}
else
{
await parties.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, party.Id, before.Party, party, userName, cancellationToken).ConfigureAwait(false);
}
var id = party.Id;
await UpsertAsync(uow, record.Sales, before?.Sales, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false);
await UpsertAsync(uow, record.Purchase, before?.Purchase, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false);
await UpsertAsync(uow, record.Fiscal, before?.Fiscal, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
return id;
}
// The one-to-one details: inserted the first time, then updated; the history is kept under the id of the party.
private async Task UpsertAsync<T>(IUnitOfWork uow, T row, T? before, long partyId, string userName, Action<T> link, CancellationToken cancellationToken)
where T : Core.Entities.Entity<long>, new()
{
link(row);
var repository = uow.Repository<T, long>();
if (before is null || before.Id == 0)
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
return;
}
row.Id = before.Id;
row.RowVersion = before.RowVersion;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, partyId, before, row, userName, cancellationToken).ConfigureAwait(false);
}
// The lists: rows removed are deleted, rows kept are updated, new rows inserted.
private static async Task ReplaceAsync<T>(IUnitOfWork uow, List<T> rows, List<T> before, Action<T> link, CancellationToken cancellationToken)
where T : Core.Entities.Entity<long>, new()
{
var repository = uow.Repository<T, long>();
var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet();
foreach (var old in before.Where(b => !kept.Contains(b.Id)))
{
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
var versions = before.ToDictionary(b => b.Id, b => b.RowVersion);
foreach (var row in rows)
{
link(row);
if (row.Id != 0 && versions.TryGetValue(row.Id, out var version))
{
row.RowVersion = version;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
}
else
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
}
}
}
private async Task<ViesResult?> CheckVatCoreAsync(string company, long id, string userName, CancellationToken cancellationToken)
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<Party, long>();
var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
if (party.VatNumber is not { Length: > 0 } number || ViesClient.MemberStateCode(party.CountryCode) is not { } state)
{
return null;
}
var result = await _autoFill.CheckVatAsync(state, number, cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
var before = Clone(party);
party.VatCheck = result.Status switch
{
ViesStatus.Valid => VatCheckStatus.Valid,
ViesStatus.Invalid or ViesStatus.InvalidInput => VatCheckStatus.Invalid,
_ => VatCheckStatus.Unavailable,
};
party.VatCheckedAt = result.CheckedAt.UtcDateTime;
await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, userName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return result;
}
private static async Task<IReadOnlyList<TableProblem>> CheckAsync(IUnitOfWork uow, IFiscalPack pack, PartyRecord record, CancellationToken cancellationToken)
{
var problems = new List<TableProblem>();
var party = record.Party;
var trading = party.Kind is PartyKind.Customer or PartyKind.Supplier;
Normalize(party);
if (party.SubjectType == SubjectType.Person && party.Name.Length == 0 && (party.LastName is not null || party.FirstName is not null))
{
party.Name = string.Join(' ', new[] { party.LastName, party.FirstName }.Where(n => n is not null));
}
if (party.Name.Length == 0)
{
problems.Add(new(nameof(Party.Name), NameRequired));
}
if (party.Code.Length > 0)
{
var code = party.Code;
var id = party.Id;
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.Code == code && p.Id != id), cancellationToken).ConfigureAwait(false) > 0)
{
problems.Add(new(nameof(Party.Code), CodeDuplicate));
}
}
// Country: the domestic subjects live in the company's country, the EU ones in another member state.
var countryCode = party.CountryCode;
var country = await uow.Repository<Country, long>().FindAsync(Query.For<Country>().Where(c => c.Code == countryCode), cancellationToken).ConfigureAwait(false);
var domestic = party.CountryCode == pack.CountryCode;
if (country is null)
{
problems.Add(new(nameof(Party.CountryCode), CountryUnknown));
}
else if (party.SubjectType == SubjectType.EuCompany && (!country.EuMember || domestic))
{
problems.Add(new(nameof(Party.CountryCode), CountryNotEu));
}
else if (party.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate && !domestic)
{
problems.Add(new(nameof(Party.CountryCode), CountryNotDomestic));
}
var rules = pack.GetFeature<ITaxIdentifierRules>();
if (party.VatNumber is not null)
{
if (domestic && rules is not null)
{
party.VatNumber = rules.NormalizeVatNumber(party.VatNumber);
if (!rules.IsValidVatNumber(party.VatNumber))
{
problems.Add(new(nameof(Party.VatNumber), TableCatalog.VatNumberInvalid));
}
}
else if ((country?.VatPrefix ?? country?.Code) is { } prefix && party.VatNumber.StartsWith(prefix, StringComparison.Ordinal))
{
party.VatNumber = party.VatNumber[prefix.Length..];
}
var vat = party.VatNumber;
var self = party.Id;
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.VatNumber == vat && p.CountryCode == countryCode && p.Id != self), cancellationToken).ConfigureAwait(false) > 0)
{
problems.Add(new(nameof(Party.VatNumber), VatNumberDuplicate, IsWarning: true));
}
}
else if (trading && party.SubjectType is SubjectType.Company or SubjectType.FlatRate or SubjectType.EuCompany)
{
problems.Add(new(nameof(Party.VatNumber), VatNumberRequired));
}
if (party.TaxCode is not null && domestic && rules is not null && !rules.IsValidTaxCode(party.TaxCode))
{
problems.Add(new(nameof(Party.TaxCode), TaxCodeInvalid));
}
if (trading && party.SubjectType == SubjectType.PublicAdministration && party.VatNumber is null && party.TaxCode is null)
{
problems.Add(new(nameof(Party.TaxCode), IdentifierRequired));
}
if (party.Kind == PartyKind.Customer && party.SubjectType == SubjectType.Person && party.TaxCode is null)
{
problems.Add(new(nameof(Party.TaxCode), TaxCodeMissing, IsWarning: true));
}
Email(party.Email, nameof(Party.Email), problems);
Email(party.Pec, nameof(Party.Pec), problems);
CheckFiscal(record.Fiscal, party, rules, problems);
CheckTerms(record, problems);
CheckDetails(record, pack, problems);
return problems;
}
private static void Normalize(Party party)
{
party.Code = party.Code.Trim().ToUpperInvariant();
party.Name = party.Name.Trim();
party.FirstName = Clean(party.FirstName);
party.LastName = Clean(party.LastName);
party.FiscalName = Clean(party.FiscalName);
party.VatNumber = Clean(party.VatNumber)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
party.TaxCode = Clean(party.TaxCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
party.Province = Clean(party.Province)?.ToUpperInvariant();
party.CountryCode = (Clean(party.CountryCode) ?? string.Empty).ToUpperInvariant();
party.CurrencyCode = (Clean(party.CurrencyCode) ?? "EUR").ToUpperInvariant();
party.Language = (Clean(party.Language) ?? "it").ToLowerInvariant();
party.Email = Clean(party.Email);
party.Pec = Clean(party.Pec);
party.PostalCode = Clean(party.PostalCode);
party.City = Clean(party.City);
party.Address = Clean(party.Address);
}
private static void CheckFiscal(PartyFiscal fiscal, Party party, ITaxIdentifierRules? rules, List<TableProblem> problems)
{
fiscal.RecipientCode = Clean(fiscal.RecipientCode)?.ToUpperInvariant();
fiscal.RecipientPec = Clean(fiscal.RecipientPec);
fiscal.Exigibility = Clean(fiscal.Exigibility)?.ToUpperInvariant();
var recipient = RecipientOf(party.SubjectType);
if (party.Kind is PartyKind.Customer && rules is not null)
{
// Consumers and foreign customers get the code of the e-invoice format; a business with only a PEC gets 0000000.
if (fiscal.RecipientCode is null && (recipient is RecipientKind.Consumer or RecipientKind.Foreign || fiscal.RecipientPec is not null))
{
fiscal.RecipientCode = rules.DefaultRecipientCode(recipient);
}
problems.AddRange(rules.CheckRecipientCode(fiscal.RecipientCode, recipient)
.Select(p => new TableProblem("Fiscal." + p.Field, p.Code, p.Severity == FiscalProblemSeverity.Warning)));
}
Email(fiscal.RecipientPec, "Fiscal." + nameof(PartyFiscal.RecipientPec), problems);
if (fiscal.SplitPayment)
{
fiscal.Exigibility = "S";
}
if (fiscal.Exigibility is not (null or "I" or "D" or "S"))
{
problems.Add(new("Fiscal." + nameof(PartyFiscal.Exigibility), ExigibilityInvalid));
}
Percent(fiscal.WithholdingRate, "Fiscal." + nameof(PartyFiscal.WithholdingRate), problems);
Percent(fiscal.PensionFundRate, "Fiscal." + nameof(PartyFiscal.PensionFundRate), problems);
if (fiscal.IntentActive)
{
fiscal.IntentNumber = Clean(fiscal.IntentNumber);
if (fiscal.IntentNumber is null)
{
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentNumber), IntentIncomplete));
}
if (fiscal.IntentCeiling is null)
{
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), IntentIncomplete));
}
}
if (fiscal.IntentCeiling < 0)
{
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), NotNegative));
}
if (fiscal.IntentFrom is { } from && fiscal.IntentTo is { } to && to < from)
{
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentTo), TableCatalog.ValidityOrder));
}
}
private static void CheckTerms(PartyRecord record, List<TableProblem> problems)
{
var sales = record.Sales;
Percent(sales.Discount1, "Sales." + nameof(PartySalesTerms.Discount1), problems);
Percent(sales.Discount2, "Sales." + nameof(PartySalesTerms.Discount2), problems);
if (sales.CreditLimit < 0)
{
problems.Add(new("Sales." + nameof(PartySalesTerms.CreditLimit), NotNegative));
}
if (sales.InvoiceDay is < 1 or > 31)
{
problems.Add(new("Sales." + nameof(PartySalesTerms.InvoiceDay), DayRange));
}
sales.DocumentsEmail = Clean(sales.DocumentsEmail);
Email(sales.DocumentsEmail, "Sales." + nameof(PartySalesTerms.DocumentsEmail), problems);
var purchase = record.Purchase;
Percent(purchase.Discount, "Purchase." + nameof(PartyPurchaseTerms.Discount), problems);
if (purchase.LeadTimeDays < 0)
{
problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.LeadTimeDays), NotNegative));
}
if (purchase.MinimumOrder < 0)
{
problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.MinimumOrder), NotNegative));
}
purchase.OrdersEmail = Clean(purchase.OrdersEmail);
Email(purchase.OrdersEmail, "Purchase." + nameof(PartyPurchaseTerms.OrdersEmail), problems);
}
private static void CheckDetails(PartyRecord record, IFiscalPack pack, List<TableProblem> problems)
{
for (var i = 0; i < record.Addresses.Count; i++)
{
var address = record.Addresses[i];
address.Name = address.Name.Trim();
address.CountryCode = (Clean(address.CountryCode) ?? pack.CountryCode).ToUpperInvariant();
address.Province = Clean(address.Province)?.ToUpperInvariant();
if (address.Name.Length == 0)
{
problems.Add(new($"Addresses.{i}.{nameof(PartyAddress.Name)}", DetailRequired));
}
}
for (var i = 0; i < record.Contacts.Count; i++)
{
var contact = record.Contacts[i];
contact.Name = contact.Name.Trim();
contact.Email = Clean(contact.Email);
if (contact.Name.Length == 0)
{
problems.Add(new($"Contacts.{i}.{nameof(PartyContact.Name)}", DetailRequired));
}
Email(contact.Email, $"Contacts.{i}.{nameof(PartyContact.Email)}", problems);
}
var directory = pack.GetFeature<IBankDirectory>();
for (var i = 0; i < record.BankAccounts.Count; i++)
{
var account = record.BankAccounts[i];
account.Iban = IbanValidator.Normalize(account.Iban);
account.Bic = Clean(account.Bic)?.ToUpperInvariant();
if (account.Iban.Length == 0)
{
problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", DetailRequired));
continue;
}
if (!IbanValidator.IsValid(account.Iban))
{
problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", TableCatalog.IbanInvalid));
continue;
}
if (directory?.ReadIban(account.Iban) is { } bank)
{
account.BankCode = bank.BankCode;
account.BranchCode = bank.BranchCode;
account.BankName ??= bank.Name;
account.Bic ??= bank.Bic;
}
}
// One default per list: the first one marked wins.
OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v);
OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v);
foreach (var kind in record.Addresses.Select(a => a.Kind).Distinct().ToList())
{
OneDefault([.. record.Addresses.Where(a => a.Kind == kind)], a => a.IsDefault, (a, v) => a.IsDefault = v);
}
}
private static void OneDefault<T>(List<T> rows, Func<T, bool> get, Action<T, bool> set)
{
var found = false;
foreach (var row in rows)
{
if (get(row))
{
if (found)
{
set(row, false);
}
found = true;
}
}
}
private static void Email(string? value, string field, List<TableProblem> problems)
{
if (value is not null && !EmailValidator.IsValid(value))
{
problems.Add(new(field, TableCatalog.EmailInvalid));
}
}
private static void Percent(decimal? value, string field, List<TableProblem> problems)
{
if (value is < 0 or > 100)
{
problems.Add(new(field, TableCatalog.PercentRange));
}
}
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static Party Clone(Party party)
{
var copy = new Party();
foreach (var property in typeof(Party).GetProperties().Where(p => p.CanRead && p.CanWrite))
{
property.SetValue(copy, property.GetValue(party));
}
return copy;
}
}
@@ -0,0 +1,293 @@
using Khaemhat.Application.Modules;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The parties of the demo company (SPEC §14, issue #41): customers of every kind of subject (companies, public
/// administration with split payment, private persons, EU and non-EU companies, flat rate, a declaration of intent, a
/// customer blocked over its credit, one that is also a supplier, one disabled), suppliers (a professional with
/// withholding, an ENASARCO agent, an EU supplier), prospects and leads, and three salespeople. Every name, number and
/// bank account is fictitious: the VAT numbers have a valid check digit, the IBANs a valid check, the ABI codes belong
/// to no bank. Runs only on a company without parties; the rows are marked as demo.
/// </summary>
/// <param name="codes">The automatic code rules.</param>
public sealed class DemoPartiesSeeder(CodeRuleService codes) : ISeeder
{
/// <summary>The fictitious VAT numbers, valid for the Italian check digit (tests check them with the pack).</summary>
public static readonly IReadOnlyList<string> VatNumbers =
[
"04123456784", "05234567898", "06345678905", "07456789010", "08567890127", "09678901233", "10789012340", "11890123455",
"12901234562", "13012345677", "14123456700", "15234567814", "16345678920", "17456789035",
];
/// <summary>The fictitious tax code of the public administration (numeric, valid check digit).</summary>
public const string AdministrationTaxCode = "80012345676";
/// <summary>The fictitious IBANs, with a valid check and ABI codes of no bank.</summary>
public static readonly IReadOnlyList<string> Ibans = ["IT53X0123410100000012345678", "IT21X0567822000000000987654", "IT11X0987645600000101234567"];
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public SeedKind Kind => SeedKind.Demo;
/// <inheritdoc />
public int Order => 10;
/// <inheritdoc />
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var uow = context.UnitOfWork;
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
var rules = new Dictionary<PartyKind, CodeRule>();
foreach (var kind in Enum.GetValues<PartyKind>())
{
rules[kind] = await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false);
}
var salespeople = await context.EnsureAsync(
"salespeople",
[
new Salesperson { Code = "VERDI", Description = "Marco Verdi", Email = "m.verdi@demo.example", CommissionPercent = 5m, Enasarco = true },
new Salesperson { Code = "NERI", Description = "Laura Neri", Email = "l.neri@demo.example", CommissionPercent = 4m, Enasarco = true },
new Salesperson { Code = "BIANCO", Description = "Paolo Bianco", Email = "p.bianco@demo.example", CommissionPercent = 3m },
],
cancellationToken).ConfigureAwait(false);
var terms = (await uow.Repository<PaymentTerm, long>().ListAsync(Query.For<PaymentTerm>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(t => t.Code, t => t.Id, StringComparer.OrdinalIgnoreCase);
var priceList = (await uow.Repository<PriceList, long>().FindAsync(Query.For<PriceList>().Where(p => p.Code == "BASE"), cancellationToken).ConfigureAwait(false))?.Id;
long? Term(string code) => terms.TryGetValue(code, out var id) ? id : null;
long? Agent(string code) => salespeople.TryGetValue(code, out var s) ? s.Id : null;
var identifiers = context.Pack.GetFeature<ITaxIdentifierRules>();
var year = context.Today.Year;
var seeds = new List<PartyRecord>
{
Customer("Rossi Impianti S.r.l.", SubjectType.Company, VatNumbers[0], "Via Nizza", "120", "10126", "Torino", "TO", Term("RB60FM"), Agent("VERDI"), r =>
{
r.Fiscal.RecipientCode = "M5UXCR1";
r.Party.Phone = "011 5550101";
r.Party.Email = "amministrazione@rossi-impianti.example";
r.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Titolare", Mobile = "333 5550101", Email = "mario@rossi-impianti.example", IsDefault = true });
r.Contacts.Add(new PartyContact { Name = "Anna Ferri", Role = "Amministrazione", Phone = "011 5550102", Email = "amministrazione@rossi-impianti.example" });
r.Addresses.Add(new PartyAddress { Kind = PartyAddressKind.Site, Name = "Cantiere Lingotto", Address = "Via Ventimiglia", StreetNumber = "88", PostalCode = "10126", City = "Torino", Province = "TO", IsDefault = true });
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[0], BankCode = "01234", BranchCode = "10100", IsDefault = true });
r.Sales.Discount1 = 5m;
r.Sales.CreditLimit = 30000m;
r.Sales.SendDocuments = DocumentDelivery.Email;
r.Sales.DocumentsEmail = "amministrazione@rossi-impianti.example";
}),
Customer("Bianchi & Figli S.n.c.", SubjectType.Company, VatNumbers[1], "Corso Langhe", "5", "12051", "Alba", "CN", Term("RB3060FM"), Agent("VERDI"), r =>
{
r.Fiscal.RecipientCode = "0000000";
r.Fiscal.RecipientPec = "bianchiefigli@pec.demo.example";
r.Party.Pec = "bianchiefigli@pec.demo.example";
}),
Customer("Comune di Valdora", SubjectType.PublicAdministration, null, "Piazza del Municipio", "1", "12060", "Valdora", "CN", Term("BB30"), null, r =>
{
r.Party.TaxCode = AdministrationTaxCode;
r.Fiscal.RecipientCode = "UFX9K2";
r.Fiscal.SplitPayment = true;
r.Fiscal.Exigibility = "S";
r.Fiscal.AdministrationReference = "SETT-TECNICO";
}),
Customer("Ferramenta Gallo", SubjectType.Company, VatNumbers[2], "Corso Alfieri", "210", "14100", "Asti", "AT", Term("RD"), Agent("NERI"), r =>
{
r.Fiscal.RecipientCode = "KRRH6B9";
r.Sales.CreditLimit = 5000m;
r.Sales.Blocked = true;
r.Party.Notes = "Ordini bloccati: fido superato, rientro concordato entro fine mese.";
}),
Customer("Bergwerk Bau GmbH", SubjectType.EuCompany, "U12345678", "Museumstrasse", "12", "6020", "Innsbruck", null, Term("BB30"), Agent("NERI"), r =>
{
r.Party.CountryCode = "AT";
r.Party.Language = "de";
r.Fiscal.RecipientCode = "XXXXXXX";
}),
Customer("Esposito Mario", SubjectType.Person, null, "Via Po", "18", "10124", "Torino", "TO", Term("RD"), null, r =>
{
r.Party.LastName = "Esposito";
r.Party.FirstName = "Mario";
r.Party.TaxCode = Personal(identifiers, "Esposito", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219");
r.Party.Email = "mario.esposito@posta.example";
r.Fiscal.RecipientCode = "0000000";
r.Party.PrivacyAccepted = true;
}),
Customer("Idrotermica Piemonte S.r.l.", SubjectType.Company, VatNumbers[3], "Via Roma", "44", "12100", "Cuneo", "CN", Term("RB3060FM"), Agent("VERDI"), r =>
{
r.Fiscal.RecipientCode = "T04ZHR3";
r.Fiscal.IntentActive = true;
r.Fiscal.IntentNumber = "14/" + year;
r.Fiscal.IntentDate = new DateOnly(year, 1, 15);
r.Fiscal.IntentProtocol = "26011512345678901-000001";
r.Fiscal.IntentCeiling = 150000m;
r.Fiscal.IntentFrom = new DateOnly(year, 1, 1);
r.Fiscal.IntentTo = new DateOnly(year, 12, 31);
}),
Customer("Nordic Pipes AS", SubjectType.NonEuCompany, "987654321", "Storgata", "7", "0155", "Oslo", null, Term("RD"), Agent("NERI"), r =>
{
r.Party.CountryCode = "NO";
r.Party.Language = "en";
r.Fiscal.RecipientCode = "XXXXXXX";
}),
Customer("Studio Tecnico Ing. Ferrero", SubjectType.FlatRate, VatNumbers[4], "Via Vittorio Emanuele", "3", "12051", "Alba", "CN", Term("BB30"), null, r =>
{
r.Fiscal.RecipientCode = "USAL8PV";
r.Fiscal.StampDutyCharged = true;
}),
Customer("Edilizia Moderna S.p.A.", SubjectType.Company, VatNumbers[5], "Viale Monza", "250", "20126", "Milano", "MI", Term("RB3060FM"), Agent("BIANCO"), r =>
{
r.Party.IsAlsoSupplier = true;
r.Fiscal.RecipientCode = "W7YVJK9";
r.Purchase.PaymentTermId = Term("BB30FM");
r.Sales.Discount1 = 10m;
r.Sales.Discount2 = 3m;
}),
Customer("Termoidraulica Sacco", SubjectType.Company, VatNumbers[6], "Via Cavour", "9", "12042", "Bra", "CN", Term("RD"), Agent("NERI"), r =>
{
r.Fiscal.RecipientCode = "SUBM70N";
r.Party.Disabled = true;
r.Party.Notes = "Attività cessata.";
}),
Customer("Hotel Belvedere S.r.l.", SubjectType.Company, VatNumbers[7], "Passeggiata Cadorna", "15", "17021", "Alassio", "SV", Term("BB30FM"), Agent("BIANCO"), r =>
{
r.Fiscal.RecipientCode = "5RUO82D";
r.Contacts.Add(new PartyContact { Name = "Giulia Marino", Role = "Direzione", Phone = "0182 555010", IsDefault = true });
}),
Supplier("Metalli Nord S.p.A.", VatNumbers[8], "Via Industriale", "40", "25125", "Brescia", "BS", Term("RB60FM"), r =>
{
r.Purchase.LeadTimeDays = 10;
r.Purchase.MinimumOrder = 500m;
r.Purchase.OrdersEmail = "ordini@metalli-nord.example";
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[1], BankCode = "05678", BranchCode = "22000", IsDefault = true });
}),
Supplier("Plastica Sud S.r.l.", VatNumbers[9], "Via Appia", "301", "81100", "Caserta", "CE", Term("BB30FM"), r => r.Purchase.LeadTimeDays = 15),
Supplier("Studio Rag. Neri Paola", VatNumbers[10], "Via Vittorio Veneto", "21", "12100", "Cuneo", "CN", Term("RD"), r =>
{
r.Fiscal.Withholding = true;
r.Fiscal.WithholdingRate = 20m;
r.Fiscal.WithholdingReason = "A";
r.Fiscal.PensionFund = "TC04";
r.Fiscal.PensionFundRate = 4m;
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[2], BankCode = "09876", BranchCode = "45600", IsDefault = true });
}),
Supplier("Agenzia Commerciale Bruno", VatNumbers[11], "Corso Francia", "77", "10138", "Torino", "TO", Term("BB30FM"), r =>
{
r.Fiscal.Withholding = true;
r.Fiscal.WithholdingRate = 23m;
r.Fiscal.WithholdingReason = "R";
r.Fiscal.Enasarco = true;
}),
Supplier("Elektro Werke Süd GmbH", "123456789", "Industriestrasse", "5", "80331", "München", null, Term("BB30"), r =>
{
r.Party.SubjectType = SubjectType.EuCompany;
r.Party.CountryCode = "DE";
r.Party.Language = "de";
}),
Contact(PartyKind.Prospect, "Caseificio Valle Stura S.r.l.", VatNumbers[12], "12014", "Demonte", "CN", Agent("VERDI")),
Contact(PartyKind.Prospect, "Agriturismo Le Vigne", VatNumbers[13], "12060", "Barolo", "CN", Agent("BIANCO")),
Contact(PartyKind.Lead, "Fontana Marco (fiera di Bologna)", null, null, null, null, Agent("NERI")),
Contact(PartyKind.Lead, "Cantina Sociale del Roero", null, "12043", "Canale", "CN", null),
};
foreach (var record in seeds)
{
record.Sales.PriceListId ??= record.Party.IsCustomer ? priceList : null;
await InsertAsync(uow, record, rules[record.Party.Kind], context.Today, cancellationToken).ConfigureAwait(false);
context.Count("parties");
}
}
private static PartyRecord Customer(string name, SubjectType subject, string? vat, string address, string number, string postalCode, string city, string? province,
long? paymentTermId, long? salespersonId, Action<PartyRecord> more)
{
var record = New(PartyKind.Customer, name, subject, vat, postalCode, city, province, salespersonId);
record.Party.Address = address;
record.Party.StreetNumber = number;
record.Sales.PaymentTermId = paymentTermId;
more(record);
return record;
}
private static PartyRecord Supplier(string name, string vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId,
Action<PartyRecord> more)
{
var record = New(PartyKind.Supplier, name, SubjectType.Company, vat, postalCode, city, province, null);
record.Party.Address = address;
record.Party.StreetNumber = number;
record.Purchase.PaymentTermId = paymentTermId;
more(record);
return record;
}
private static PartyRecord Contact(PartyKind kind, string name, string? vat, string? postalCode, string? city, string? province, long? salespersonId) =>
New(kind, name, SubjectType.Company, vat, postalCode, city, province, salespersonId);
private static PartyRecord New(PartyKind kind, string name, SubjectType subject, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => new()
{
Party = new Party
{
Kind = kind, Name = name, SubjectType = subject, VatNumber = vat, PostalCode = postalCode, City = city, Province = province, SalespersonId = salespersonId,
CategoryId = null, PrivacyAccepted = kind is PartyKind.Customer or PartyKind.Supplier, IsDemo = true,
},
};
private static string? Personal(ITaxIdentifierRules? rules, string surname, string name, DateOnly birth, PersonSex sex, string place) =>
rules?.ComputePersonalTaxCode(new PersonalTaxCodeData(surname, name, birth, sex, place));
private static async Task InsertAsync(IUnitOfWork uow, PartyRecord record, CodeRule rule, DateOnly today, CancellationToken cancellationToken)
{
var parties = uow.Repository<Party, long>();
var party = record.Party;
party.Code = await CodeRuleService.AssignAsync(
uow, rule, today, null,
async (code, ct) => await parties.CountAsync(Query.For<Party>().Where(p => p.Code == code), ct).ConfigureAwait(false) > 0,
cancellationToken).ConfigureAwait(false);
party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false);
if (party.IsCustomer)
{
record.Sales.PartyId = party.Id;
await uow.Repository<PartySalesTerms, long>().InsertAsync(record.Sales, cancellationToken).ConfigureAwait(false);
}
if (party.IsSupplier)
{
record.Purchase.PartyId = party.Id;
await uow.Repository<PartyPurchaseTerms, long>().InsertAsync(record.Purchase, cancellationToken).ConfigureAwait(false);
}
record.Fiscal.PartyId = party.Id;
await uow.Repository<PartyFiscal, long>().InsertAsync(record.Fiscal, cancellationToken).ConfigureAwait(false);
foreach (var address in record.Addresses)
{
address.PartyId = party.Id;
address.CountryCode = address.CountryCode.Length == 0 ? party.CountryCode : address.CountryCode;
await uow.Repository<PartyAddress, long>().InsertAsync(address, cancellationToken).ConfigureAwait(false);
}
foreach (var contact in record.Contacts)
{
contact.PartyId = party.Id;
await uow.Repository<PartyContact, long>().InsertAsync(contact, cancellationToken).ConfigureAwait(false);
}
foreach (var account in record.BankAccounts)
{
account.PartyId = party.Id;
await uow.Repository<PartyBankAccount, long>().InsertAsync(account, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -207,6 +207,12 @@ public sealed partial class SeedRunner : ICompanySeeder
{
await RunAsync(companyCode, SeedKind.Base, cancellationToken).ConfigureAwait(false);
}
// The demo seeders fill only a company without data of their own (each checks its tables).
if (context.Demo)
{
await RunAsync(companyCode, SeedKind.Demo, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>The button <i>Aggiorna tabelle di base</i>: runs the base seeders for a company.</summary>