feat: company table screens, profile and fiscal years, seed command (#38, #39, #45)

Gives the company tables of the previous commit their screens, so a company
can be configured from the browser, and makes the base data runnable outside
the web server.

- one generic editor for the 26 coded tables (/tabelle/<slug>), described in
  TableScreens: grid with active/disabled filter, detail with errors and
  warnings, disable instead of delete, CSV export and all-or-nothing import,
  "update from base tables"; index page and menu entries
- company profile in tabs with the fiscal pack checks, fiscal years with
  month lock/unlock, exchange rates with manual rates
- PaymentTermService: installments saved together, percentages must sum to 100
- a new profile proposes the registered company name instead of its code
- seed verb in Khaemhat.Web and scripts/seed.sh --base [--company CODE],
  shipped in the image under /app/scripts
- ADR 0026 (base data only adds missing codes; ISTAT and ABI/CAB lists come
  as separate datasets), wiki, CHANGELOG, STATUS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 23:15:09 +01:00
1 parent 34e196424f
commit 9bcf8c1082
33 files changed
+3272 -43

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
using Khaemhat.Core.Tables;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Web.Tables;
/// <summary>A group of fields of a tab of the company profile.</summary>
/// <param name="Key">The text key of the title, under <c>CompanyTables.Profile.Groups</c>.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Fields">The fields.</param>
public sealed record ProfileGroup(string Key, string Icon, IReadOnlyList<TableField> Fields);
/// <summary>A tab of the company profile.</summary>
/// <param name="Id">The id in the address (<c>?scheda=fiscale</c>).</param>
/// <param name="Icon">The icon.</param>
/// <param name="Groups">The groups.</param>
public sealed record ProfileTab(string Id, string Icon, IReadOnlyList<ProfileGroup> Groups);
/// <summary>The tabs of the company profile (SPEC §11.1, mockup 075).</summary>
public static class ProfileLayout
{
/// <summary>The tabs, in order.</summary>
public static IReadOnlyList<ProfileTab> Tabs { get; } =
[
new("societa", "building",
[
new("Company", "building",
[
new(nameof(CompanyProfile.LegalName)) { Required = true, Span = 12, MaxLength = 200 },
new(nameof(CompanyProfile.FiscalName)) { Span = 12, MaxLength = 200 },
new(nameof(CompanyProfile.ReaOffice), TableFieldKind.Code) { MaxLength = 2, Span = 3 },
new(nameof(CompanyProfile.ReaNumber), TableFieldKind.Code) { MaxLength = 20, Span = 3 },
new(nameof(CompanyProfile.ShareCapital), TableFieldKind.Number) { Decimals = 2, Min = 0, Span = 6 },
new(nameof(CompanyProfile.Shareholders), TableFieldKind.Choice) { Values = ["SU", "SM"] },
new(nameof(CompanyProfile.LiquidationStatus), TableFieldKind.Choice) { Values = ["LN", "LS"] },
]),
new("Address", "pin",
[
new(nameof(CompanyProfile.Address)) { Span = 9 },
new(nameof(CompanyProfile.StreetNumber)) { Span = 3, MaxLength = 10 },
new(nameof(CompanyProfile.PostalCode), TableFieldKind.Code) { Span = 3, MaxLength = 10 },
new(nameof(CompanyProfile.City)) { Span = 6 },
new(nameof(CompanyProfile.ProvinceCode), TableFieldKind.Code) { Span = 3, MaxLength = 2 },
new(nameof(CompanyProfile.AddressCountry), TableFieldKind.Lookup) { Lookup = typeof(Country), ByCode = true },
new(nameof(CompanyProfile.Phone)),
new(nameof(CompanyProfile.Email)),
new(nameof(CompanyProfile.Pec)),
new(nameof(CompanyProfile.Website)) { Span = 12 },
]),
]),
new("fiscale", "file-check",
[
new("Tax", "file-check",
[
new(nameof(CompanyProfile.Country), TableFieldKind.Lookup) { Lookup = typeof(Country), ByCode = true, Required = true },
new(nameof(CompanyProfile.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, Required = true },
new(nameof(CompanyProfile.VatNumber), TableFieldKind.Code) { MaxLength = 30 },
new(nameof(CompanyProfile.TaxCode), TableFieldKind.Code) { MaxLength = 16 },
new(nameof(CompanyProfile.TaxRegime), TableFieldKind.CodeList) { CodeList = TaxRegimes, Required = true, Span = 12 },
new(nameof(CompanyProfile.RecipientCode), TableFieldKind.Code) { MaxLength = 7 },
]),
]),
new("banche", "coins",
[
new("Bank", "coins",
[
new(nameof(CompanyProfile.DefaultBankAccountId), TableFieldKind.Lookup) { Lookup = typeof(BankAccount), Span = 12 },
]),
]),
new("stampa", "printer",
[
new("Print", "printer",
[
new(nameof(CompanyProfile.FooterNotes)) { Span = 12, Rows = 4, MaxLength = 1000 },
]),
]),
new("esercizi", "calendar",
[
new("Vat", "calendar",
[
new(nameof(CompanyProfile.FiscalYearStartMonth), TableFieldKind.Number) { Min = 1, Max = 12, Required = true, Span = 4 },
new(nameof(CompanyProfile.VatPeriodicity), TableFieldKind.Choice) { Span = 4 },
new(nameof(CompanyProfile.ProRataPercent), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, Span = 4 },
new(nameof(CompanyProfile.CashVat), TableFieldKind.Bool) { Span = 12 },
]),
]),
new("trasmittente", "send",
[
new("Transmitter", "send",
[
new(nameof(CompanyProfile.TransmitterCountry), TableFieldKind.Code) { MaxLength = 2, Span = 3 },
new(nameof(CompanyProfile.TransmitterId), TableFieldKind.Code) { MaxLength = 28, Span = 9 },
]),
new("Intermediary", "users",
[
new(nameof(CompanyProfile.IntermediaryName)) { Span = 8 },
new(nameof(CompanyProfile.IntermediaryTaxCode), TableFieldKind.Code) { MaxLength = 16, Span = 4 },
]),
]),
];
/// <summary>Every field, in order.</summary>
public static IEnumerable<TableField> Fields => Tabs.SelectMany(t => t.Groups).SelectMany(g => g.Fields);
/// <summary>The tab of a field, to show the one with an error.</summary>
/// <param name="property">The property.</param>
/// <returns>The tab, or <see langword="null"/>.</returns>
public static ProfileTab? TabOf(string? property) =>
Tabs.FirstOrDefault(t => t.Groups.Any(g => g.Fields.Any(f => f.Property == property)));
private static CodeList? TaxRegimes(IFiscalPack pack) => pack.GetFeature<IEInvoiceFormat>()?.TaxRegimes;
}
+98
View File
@@ -0,0 +1,98 @@
using System.Globalization;
using System.Reflection;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Entities;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Tables;
/// <summary>The choices of the fields of a page: rows of other tables, lists of the fiscal pack, enumerations, fixed values.</summary>
public sealed class TableOptions
{
private readonly Dictionary<string, IReadOnlyList<KhOption<string>>> _lookups = new(StringComparer.Ordinal);
/// <summary>The fiscal pack of the company.</summary>
public IFiscalPack? Pack { get; private set; }
/// <summary>Reads the pack of the company and the rows every lookup field points to.</summary>
/// <param name="tables">The tables.</param>
/// <param name="fiscal">The fiscal context.</param>
/// <param name="fields">The fields.</param>
/// <param name="actor">Who reads.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task LoadAsync(TableService tables, CompanyFiscalContext fiscal, IEnumerable<TableField> fields, Actor actor, string company,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(fields);
Pack = await fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
foreach (var field in fields.Where(f => f is { Kind: TableFieldKind.Lookup, Lookup: not null }))
{
var choices = await TableValues.LookupAsync(tables, field.Lookup!, field.ByCode, actor, company, cancellationToken).ConfigureAwait(false);
_lookups[field.Property] = [.. choices.Select(c => new KhOption<string>(c.Value, c.Text))];
}
}
/// <summary>The choices of a field for a row.</summary>
/// <param name="field">The field.</param>
/// <param name="property">Its property.</param>
/// <param name="row">The row, to keep an obsolete code or leave out the row itself.</param>
/// <param name="texts">The texts.</param>
/// <returns>The choices.</returns>
public IReadOnlyList<KhOption<string>> For(TableField field, PropertyInfo property, object? row, ITexts texts)
{
ArgumentNullException.ThrowIfNull(field);
ArgumentNullException.ThrowIfNull(property);
ArgumentNullException.ThrowIfNull(texts);
var current = row is null ? null : TableValues.GetText(row, property);
switch (field.Kind)
{
case TableFieldKind.Choice when field.Values is { } values:
return [.. values.Select(v => new KhOption<string>(v, texts[ValueKey(field, v)]))];
case TableFieldKind.Choice:
return [.. TableValues.EnumChoices(property, v => texts[TableScreens.EnumKey(v)]).Select(c => new KhOption<string>(c.Value, c.Text))];
case TableFieldKind.CodeList:
var list = Pack is null ? null : field.CodeList?.Invoke(Pack);
if (list is null)
{
return current is null ? [] : [new(current, current)];
}
return [.. list.Entries.Where(e => !e.Obsolete || e.Code == current).Select(e => new KhOption<string>(e.Code, e.Code + " · " + e.Description))];
default:
var options = _lookups.GetValueOrDefault(field.Property) ?? [];
// A self reference never points to the row itself.
return field.Lookup == row?.GetType() && row is Entity<long> { Id: > 0 } entity
? [.. options.Where(o => o.Value != entity.Id.ToString(CultureInfo.InvariantCulture))]
: options;
}
}
/// <summary>The code shown in the grid for the value of a lookup.</summary>
/// <param name="field">The field.</param>
/// <param name="value">The stored value.</param>
/// <returns>The code.</returns>
public string? CodeOf(TableField field, string? value)
{
ArgumentNullException.ThrowIfNull(field);
return value is null ? null : _lookups.GetValueOrDefault(field.Property)?.FirstOrDefault(o => o.Value == value)?.Text.Split(" · ")[0] ?? value;
}
/// <summary>The text key of a fixed value: <c>CompanyTables.Values.&lt;Property&gt;.&lt;Value&gt;</c>.</summary>
/// <param name="field">The field.</param>
/// <param name="value">The value.</param>
/// <returns>The key.</returns>
public static string ValueKey(TableField field, string value)
{
ArgumentNullException.ThrowIfNull(field);
return "CompanyTables.Values." + field.Property + "." + value;
}
}
+359
View File
@@ -0,0 +1,359 @@
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Web.Tables;
/// <summary>How a field of a company table is edited.</summary>
public enum TableFieldKind
{
/// <summary>Free text.</summary>
Text = 0,
/// <summary>A short code in monospace, upper case.</summary>
Code = 1,
/// <summary>A number (decimal or integer property).</summary>
Number = 2,
/// <summary>A yes/no flag.</summary>
Bool = 3,
/// <summary>A date.</summary>
Date = 4,
/// <summary>A value of an enumeration.</summary>
Choice = 5,
/// <summary>A row of another company table, by id or by code.</summary>
Lookup = 6,
/// <summary>A code of a list of the fiscal pack (payment methods of the e-invoice, VAT natures).</summary>
CodeList = 7,
}
/// <summary>A field of the detail panel of a company table (mockup 076).</summary>
/// <param name="Property">The property of the entity; its label is <c>CompanyTables.Fields.&lt;Property&gt;</c>.</param>
/// <param name="Kind">How it is edited.</param>
public sealed record TableField(string Property, TableFieldKind Kind = TableFieldKind.Text)
{
/// <summary>The columns of the form it takes, out of 12.</summary>
public int Span { get; init; } = 6;
/// <summary>The decimals of a number.</summary>
public int Decimals { get; init; }
/// <summary>The smallest number.</summary>
public decimal? Min { get; init; }
/// <summary>The largest number.</summary>
public decimal? Max { get; init; }
/// <summary>The longest text.</summary>
public int? MaxLength { get; init; }
/// <summary>Whether the field must be filled.</summary>
public bool Required { get; init; }
/// <summary>The table a lookup points to.</summary>
public Type? Lookup { get; init; }
/// <summary>Whether a lookup stores the code (a string property) instead of the id.</summary>
public bool ByCode { get; init; }
/// <summary>The list of the fiscal pack a <see cref="TableFieldKind.CodeList"/> field takes its codes from.</summary>
public Func<IFiscalPack, CodeList?>? CodeList { get; init; }
/// <summary>Whether the field is also a column of the grid.</summary>
public bool InGrid { get; init; }
/// <summary>The width of the grid column.</summary>
public string? Width { get; init; }
/// <summary>Whether the value is computed and only shown.</summary>
public bool ReadOnly { get; init; }
/// <summary>The fixed values of a <see cref="TableFieldKind.Choice"/> on a text property; their texts are <c>CompanyTables.Values.&lt;Property&gt;.&lt;Value&gt;</c>.</summary>
public IReadOnlyList<string>? Values { get; init; }
/// <summary>The rows of a multi-line text.</summary>
public int Rows { get; init; }
/// <summary>The text key of the label.</summary>
public string LabelKey => "CompanyTables.Fields." + Property;
}
/// <summary>A company table as the interface shows it: address, icon, group and fields.</summary>
/// <param name="Slug">The last part of the address, such as <c>codici-iva</c>.</param>
/// <param name="Key">The key of the <see cref="TableDefinition"/>, such as <c>tax-codes</c>.</param>
/// <param name="Entity">The entity.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Group">The group of the index page.</param>
public sealed record TableScreen(string Slug, string Key, Type Entity, string Icon, TableGroup Group)
{
/// <summary>The fields after code and description, in order.</summary>
public IReadOnlyList<TableField> Fields { get; init; } = [];
/// <summary>The address.</summary>
public string Href => TableScreens.BasePath + "/" + Slug;
/// <summary>The text key of the title.</summary>
public string TitleKey => "CompanyTables.Screens." + Key + ".Title";
/// <summary>The text key of the one-line description.</summary>
public string HintKey => "CompanyTables.Screens." + Key + ".Hint";
}
/// <summary>The groups of the index page of the company tables.</summary>
public enum TableGroup
{
/// <summary>VAT, payments, banks, currencies.</summary>
Fiscal = 0,
/// <summary>Documents, numbering, price lists, discounts.</summary>
Sales = 1,
/// <summary>Warehouses, reasons, units, transport.</summary>
Logistics = 2,
/// <summary>Countries, provinces, municipalities.</summary>
Geography = 3,
/// <summary>Categories, salespeople, cost centres, jobs.</summary>
Classification = 4,
}
/// <summary>
/// The company tables of SPEC §11.1 with the fields of their detail panel. The page <c>/tabelle/{slug}</c> is generic
/// (<c>KhTableEditor</c>); the company profile, the fiscal years and the exchange rates have pages of their own.
/// </summary>
public static class TableScreens
{
/// <summary>The address of the area.</summary>
public const string BasePath = "/tabelle";
/// <summary>Every screen, in the order of the index page.</summary>
public static IReadOnlyList<TableScreen> All { get; } =
[
new("codici-iva", "tax-codes", typeof(TaxCode), "euro", TableGroup.Fiscal)
{
Fields =
[
new(nameof(TaxCode.Rate), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, InGrid = true, Width = "80px", Span = 3 },
new(nameof(TaxCode.Nature), TableFieldKind.CodeList) { CodeList = p => p.TaxCodes.Natures, InGrid = true, Width = "90px", Span = 3 },
new(nameof(TaxCode.Kind), TableFieldKind.Choice) { ReadOnly = true, InGrid = true, Width = "150px", Span = 3 },
new(nameof(TaxCode.Exigibility), TableFieldKind.Choice) { Span = 3 },
new(nameof(TaxCode.NonDeductiblePercent), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, Span = 3 },
new(nameof(TaxCode.ValidFrom), TableFieldKind.Date) { Span = 3 },
new(nameof(TaxCode.ValidTo), TableFieldKind.Date) { Span = 3 },
new(nameof(TaxCode.LegalReference)) { Span = 12, InGrid = true },
new(nameof(TaxCode.SalesAccountCode), TableFieldKind.Code),
new(nameof(TaxCode.PurchaseAccountCode), TableFieldKind.Code),
],
},
new("modalita-pagamento", "payment-methods", typeof(PaymentMethod), "coins", TableGroup.Fiscal)
{
Fields =
[
new(nameof(PaymentMethod.EInvoiceCode), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.PaymentMethods), Required = true, InGrid = true, Width = "90px" },
new(nameof(PaymentMethod.NeedsBank), TableFieldKind.Bool) { InGrid = true, Width = "90px" },
],
},
new("pagamenti", "payment-terms", typeof(PaymentTerm), "calendar", TableGroup.Fiscal)
{
Fields =
[
new(nameof(PaymentTerm.PaymentMethodId), TableFieldKind.Lookup) { Lookup = typeof(PaymentMethod), InGrid = true, Width = "160px" },
new(nameof(PaymentTerm.Condition), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.PaymentConditions), Required = true, InGrid = true, Width = "90px" },
new(nameof(PaymentTerm.VatOnFirstInstallment), TableFieldKind.Bool) { Span = 12 },
],
},
new("banche", "bank-accounts", typeof(BankAccount), "building", TableGroup.Fiscal)
{
Fields =
[
new(nameof(BankAccount.BankName)) { Span = 12, InGrid = true },
new(nameof(BankAccount.Iban), TableFieldKind.Code) { Span = 8, MaxLength = 34, InGrid = true, Width = "260px" },
new(nameof(BankAccount.Bic), TableFieldKind.Code) { Span = 4, MaxLength = 11 },
new(nameof(BankAccount.SiaCode), TableFieldKind.Code) { Span = 4, MaxLength = 5 },
new(nameof(BankAccount.CucCode), TableFieldKind.Code) { Span = 4, MaxLength = 8 },
new(nameof(BankAccount.AccountCode), TableFieldKind.Code) { Span = 4 },
new(nameof(BankAccount.IsDefault), TableFieldKind.Bool) { Span = 12, InGrid = true, Width = "90px" },
],
},
new("valute", "currencies", typeof(Currency), "euro", TableGroup.Fiscal)
{
Fields =
[
new(nameof(Currency.Symbol)) { MaxLength = 5, InGrid = true, Width = "80px", Span = 3 },
new(nameof(Currency.Decimals), TableFieldKind.Number) { Min = 0, Max = 4, InGrid = true, Width = "80px", Span = 3 },
],
},
new("tipi-documento", "document-types", typeof(DocumentType), "file", TableGroup.Sales)
{
Fields =
[
new(nameof(DocumentType.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px" },
new(nameof(DocumentType.NumeratorId), TableFieldKind.Lookup) { Lookup = typeof(DocumentNumerator), InGrid = true, Width = "120px" },
new(nameof(DocumentType.InventoryReasonId), TableFieldKind.Lookup) { Lookup = typeof(InventoryReason) },
new(nameof(DocumentType.EInvoiceType), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.DocumentTypes), InGrid = true, Width = "90px" },
new(nameof(DocumentType.VatRegisterCode), TableFieldKind.Code) { Span = 4 },
new(nameof(DocumentType.JournalTemplateCode), TableFieldKind.Code) { Span = 4 },
new(nameof(DocumentType.PrintTemplate), TableFieldKind.Code) { Span = 4 },
],
},
new("numeratori", "numerators", typeof(DocumentNumerator), "list", TableGroup.Sales)
{
Fields =
[
new(nameof(DocumentNumerator.Year), TableFieldKind.Number) { Min = 2000, Max = 2100, Required = true, InGrid = true, Width = "70px", Span = 3 },
new(nameof(DocumentNumerator.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px", Span = 5 },
new(nameof(DocumentNumerator.Section), TableFieldKind.Code) { MaxLength = 10, InGrid = true, Width = "80px", Span = 4 },
new(nameof(DocumentNumerator.Prefix), TableFieldKind.Code) { MaxLength = 10, Span = 4 },
new(nameof(DocumentNumerator.Format)) { Required = true, Span = 8, InGrid = true, Width = "180px" },
new(nameof(DocumentNumerator.LastNumber), TableFieldKind.Number) { Min = 0, InGrid = true, Width = "100px", Span = 4 },
new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 8 },
],
},
new("listini", "price-lists", typeof(PriceList), "tag", TableGroup.Sales)
{
Fields =
[
new(nameof(PriceList.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, Required = true, InGrid = true, Width = "80px", Span = 4 },
new(nameof(PriceList.VatIncluded), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 8 },
new(nameof(PriceList.ValidFrom), TableFieldKind.Date),
new(nameof(PriceList.ValidTo), TableFieldKind.Date),
new(nameof(PriceList.BasePriceListId), TableFieldKind.Lookup) { Lookup = typeof(PriceList) },
new(nameof(PriceList.MarkupPercent), TableFieldKind.Number) { Decimals = 2, Span = 3 },
new(nameof(PriceList.RoundingStep), TableFieldKind.Number) { Decimals = 4, Min = 0, Span = 3 },
],
},
new("sconti", "discount-policies", typeof(DiscountPolicy), "tag", TableGroup.Sales)
{
Fields = [new(nameof(DiscountPolicy.Formula), TableFieldKind.Code) { Required = true, InGrid = true, Width = "140px" }],
},
new("agenti", "salespeople", typeof(Salesperson), "user", TableGroup.Sales)
{
Fields =
[
new(nameof(Salesperson.Email)) { InGrid = true },
new(nameof(Salesperson.Phone)),
new(nameof(Salesperson.CommissionPercent), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, InGrid = true, Width = "90px" },
new(nameof(Salesperson.Enasarco), TableFieldKind.Bool),
],
},
new("depositi", "warehouses", typeof(Warehouse), "box", TableGroup.Logistics)
{
Fields =
[
new(nameof(Warehouse.Address)) { Span = 12 },
new(nameof(Warehouse.City)) { Span = 8, InGrid = true },
new(nameof(Warehouse.ProvinceCode), TableFieldKind.Code) { MaxLength = 2, Span = 4, InGrid = true, Width = "60px" },
new(nameof(Warehouse.IsDefault), TableFieldKind.Bool) { Span = 12, InGrid = true, Width = "90px" },
],
},
new("causali-magazzino", "inventory-reasons", typeof(InventoryReason), "activity", TableGroup.Logistics)
{
Fields =
[
new(nameof(InventoryReason.Effect), TableFieldKind.Choice) { InGrid = true, Width = "110px", Span = 4 },
new(nameof(InventoryReason.AffectsValue), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 4 },
new(nameof(InventoryReason.IsTransfer), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 4 },
],
},
new("unita-di-misura", "units", typeof(UnitOfMeasure), "grid", TableGroup.Logistics)
{
Fields =
[
new(nameof(UnitOfMeasure.Decimals), TableFieldKind.Number) { Min = 0, Max = 6, InGrid = true, Width = "80px", Span = 3 },
new(nameof(UnitOfMeasure.EInvoiceCode), TableFieldKind.Code) { MaxLength = 10, InGrid = true, Width = "100px", Span = 3 },
],
},
new("vettori", "carriers", typeof(Carrier), "truck", TableGroup.Logistics)
{
Fields =
[
new(nameof(Carrier.VatNumber), TableFieldKind.Code) { InGrid = true, Width = "130px" },
new(nameof(Carrier.RegisterNumber), TableFieldKind.Code),
new(nameof(Carrier.Address)) { Span = 12 },
new(nameof(Carrier.City)) { InGrid = true },
new(nameof(Carrier.Phone)),
new(nameof(Carrier.Email)) { Span = 12 },
],
},
new("porto", "shipping-terms", typeof(ShippingTerm), "truck", TableGroup.Logistics),
new("trasporto-a-cura", "transport-means", typeof(TransportMean), "truck", TableGroup.Logistics),
new("causali-trasporto", "transport-reasons", typeof(TransportReason), "truck", TableGroup.Logistics),
new("aspetto-beni", "goods-appearances", typeof(GoodsAppearance), "box", TableGroup.Logistics),
new("rese", "delivery-terms", typeof(DeliveryTerm), "globe", TableGroup.Logistics),
new("nazioni", "countries", typeof(Country), "globe", TableGroup.Geography)
{
Fields =
[
new(nameof(Country.Iso3), TableFieldKind.Code) { MaxLength = 3, InGrid = true, Width = "70px", Span = 3 },
new(nameof(Country.VatPrefix), TableFieldKind.Code) { MaxLength = 2, InGrid = true, Width = "80px", Span = 3 },
new(nameof(Country.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, InGrid = true, Width = "80px", Span = 3 },
new(nameof(Country.EuMember), TableFieldKind.Bool) { InGrid = true, Width = "70px", Span = 3 },
],
},
new("province", "provinces", typeof(Province), "pin", TableGroup.Geography)
{
Fields = [new(nameof(Province.Region)) { InGrid = true }],
},
new("comuni", "municipalities", typeof(Municipality), "pin", TableGroup.Geography)
{
Fields =
[
new(nameof(Municipality.ProvinceCode), TableFieldKind.Code) { MaxLength = 2, Required = true, InGrid = true, Width = "60px", Span = 3 },
new(nameof(Municipality.IstatCode), TableFieldKind.Code) { MaxLength = 6, InGrid = true, Width = "90px", Span = 3 },
new(nameof(Municipality.Region)) { InGrid = true },
new(nameof(Municipality.PostalCodes)) { Span = 12, InGrid = true, Width = "160px" },
],
},
new("categorie-articoli", "item-categories", typeof(ItemCategory), "layers", TableGroup.Classification)
{
Fields =
[
new(nameof(ItemCategory.ParentId), TableFieldKind.Lookup) { Lookup = typeof(ItemCategory), InGrid = true, Width = "140px" },
new(nameof(ItemCategory.Level), TableFieldKind.Number) { ReadOnly = true, InGrid = true, Width = "70px", Span = 3 },
],
},
new("categorie-soggetti", "party-categories", typeof(PartyCategory), "users", TableGroup.Classification),
new("centri-di-costo", "cost-centers", typeof(CostCenter), "target", TableGroup.Classification)
{
Fields = [new(nameof(CostCenter.ParentId), TableFieldKind.Lookup) { Lookup = typeof(CostCenter), InGrid = true, Width = "140px" }],
},
new("commesse", "jobs", typeof(Job), "folder", TableGroup.Classification)
{
Fields =
[
new(nameof(Job.Status), TableFieldKind.Choice) { InGrid = true, Width = "110px", Span = 4 },
new(nameof(Job.StartDate), TableFieldKind.Date) { InGrid = true, Width = "100px", Span = 4 },
new(nameof(Job.EndDate), TableFieldKind.Date) { Span = 4 },
],
},
];
/// <summary>The screen of an address.</summary>
/// <param name="slug">The last part of the address.</param>
/// <returns>The screen, or <see langword="null"/>.</returns>
public static TableScreen? Find(string? slug) =>
All.FirstOrDefault(s => string.Equals(s.Slug, slug, StringComparison.OrdinalIgnoreCase));
/// <summary>The screen of an entity.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The screen, or <see langword="null"/>.</returns>
public static TableScreen? Of(Type entity) => All.FirstOrDefault(s => s.Entity == entity);
/// <summary>The text key of a value of an enumeration: <c>CompanyTables.Enums.&lt;Type&gt;.&lt;Value&gt;</c>.</summary>
/// <param name="value">The value.</param>
/// <returns>The key.</returns>
public static string EnumKey(Enum value)
{
ArgumentNullException.ThrowIfNull(value);
return "CompanyTables.Enums." + value.GetType().Name + "." + value;
}
private static Func<IFiscalPack, CodeList?> EInvoice(Func<IEInvoiceFormat, CodeList> list) =>
pack => pack.GetFeature<IEInvoiceFormat>() is { } format ? list(format) : null;
}
+143
View File
@@ -0,0 +1,143 @@
using System.Globalization;
using System.Reflection;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
namespace Khaemhat.Web.Tables;
/// <summary>A choice of a lookup or code list: the stored value and the text shown.</summary>
/// <param name="Value">The value: the id or the code, as text.</param>
/// <param name="Text">The text, such as <c>BB30 · Bonifico 30 gg</c>.</param>
public sealed record TableChoice(string Value, string Text);
/// <summary>Reads and writes the fields of a company table row by name, converting between the editors and the properties.</summary>
public static class TableValues
{
/// <summary>The property of a field.</summary>
/// <param name="entity">The entity.</param>
/// <param name="field">The field.</param>
/// <returns>The property.</returns>
public static PropertyInfo PropertyOf(Type entity, TableField field)
{
ArgumentNullException.ThrowIfNull(entity);
ArgumentNullException.ThrowIfNull(field);
return entity.GetProperty(field.Property, BindingFlags.Public | BindingFlags.Instance)
?? throw new InvalidOperationException($"{entity.Name} has no property {field.Property}.");
}
/// <summary>The value as text (codes, lookups, choices).</summary>
/// <param name="row">The row.</param>
/// <param name="property">The property.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public static string? GetText(object row, PropertyInfo property) => property.GetValue(row) switch
{
null => null,
string text => text,
long id => id.ToString(CultureInfo.InvariantCulture),
Enum value => value.ToString(),
IFormattable value => value.ToString(null, CultureInfo.InvariantCulture),
var value => value.ToString(),
};
/// <summary>Writes a text into a string, id or enumeration property; an empty text clears what can be cleared.</summary>
/// <param name="row">The row.</param>
/// <param name="property">The property.</param>
/// <param name="text">The text.</param>
public static void SetText(object row, PropertyInfo property, string? text)
{
ArgumentNullException.ThrowIfNull(property);
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var empty = string.IsNullOrWhiteSpace(text);
object? value;
if (type == typeof(string))
{
value = empty ? (IsNullable(property) ? null : string.Empty) : text!.Trim();
}
else if (empty)
{
value = Nullable.GetUnderlyingType(property.PropertyType) is null ? Activator.CreateInstance(type) : null;
}
else if (type.IsEnum)
{
value = Enum.Parse(type, text!, ignoreCase: true);
}
else
{
value = Convert.ChangeType(text, type, CultureInfo.InvariantCulture);
}
property.SetValue(row, value);
}
/// <summary>The value of a number property.</summary>
/// <param name="row">The row.</param>
/// <param name="property">The property.</param>
/// <returns>The number, or <see langword="null"/>.</returns>
public static decimal? GetNumber(object row, PropertyInfo property) =>
property.GetValue(row) is { } value ? Convert.ToDecimal(value, CultureInfo.InvariantCulture) : null;
/// <summary>Writes a number into a decimal, integer or long property; an empty value is zero unless it may be empty.</summary>
/// <param name="row">The row.</param>
/// <param name="property">The property.</param>
/// <param name="number">The number.</param>
public static void SetNumber(object row, PropertyInfo property, decimal? number)
{
ArgumentNullException.ThrowIfNull(property);
var nullable = Nullable.GetUnderlyingType(property.PropertyType);
var type = nullable ?? property.PropertyType;
if (number is null)
{
property.SetValue(row, nullable is null ? Activator.CreateInstance(type) : null);
return;
}
var value = type == typeof(decimal) ? number.Value : Math.Round(number.Value, MidpointRounding.AwayFromZero);
property.SetValue(row, Convert.ChangeType(value, type, CultureInfo.InvariantCulture));
}
/// <summary>The choices of an enumeration, with their texts.</summary>
/// <param name="property">The property.</param>
/// <param name="text">The text of a value.</param>
/// <returns>The choices.</returns>
public static IReadOnlyList<TableChoice> EnumChoices(PropertyInfo property, Func<Enum, string> text)
{
ArgumentNullException.ThrowIfNull(property);
ArgumentNullException.ThrowIfNull(text);
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
return [.. Enum.GetValues(type).Cast<Enum>().Select(v => new TableChoice(v.ToString(), text(v)))];
}
/// <summary>Reads the rows of a coded table, whatever its type, as choices.</summary>
/// <param name="tables">The service.</param>
/// <param name="entity">The table.</param>
/// <param name="byCode">Whether the value is the code instead of the id.</param>
/// <param name="actor">Who asks.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The choices, enabled rows only.</returns>
public static async Task<IReadOnlyList<TableChoice>> LookupAsync(TableService tables, Type entity, bool byCode, Actor actor, string company,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(tables);
ArgumentNullException.ThrowIfNull(entity);
var method = typeof(TableService).GetMethod(nameof(TableService.ActiveAsync))!.MakeGenericMethod(entity);
var task = (Task)method.Invoke(tables, [actor, company, cancellationToken])!;
await task.ConfigureAwait(false);
var rows = (IEnumerable<ICodedRecord>)task.GetType().GetProperty(nameof(Task<object>.Result))!.GetValue(task)!;
return [.. rows.Select(r => new TableChoice(byCode ? r.Code : r.Id.ToString(CultureInfo.InvariantCulture), r.Code + " · " + r.Description))];
}
/// <summary>Splits the errors of a refused save (<c>Field:code</c>) into field and code.</summary>
/// <param name="error">The error.</param>
/// <returns>The field (or <see langword="null"/>) and the code.</returns>
public static (string? Field, string Code) SplitError(string error)
{
ArgumentNullException.ThrowIfNull(error);
var colon = error.IndexOf(':', StringComparison.Ordinal);
return colon > 0 ? (error[..colon], error[(colon + 1)..]) : (null, error);
}
private static bool IsNullable(PropertyInfo property) =>
new NullabilityInfoContext().Create(property).WriteState == NullabilityState.Nullable;
}