feat: sales screens, deferred invoicing, printing and mail of documents (#49 #50 #51 #52)

Quotations, orders, delivery notes, invoices and credit notes get their radars and
one document screen (lines, header, transport, links, attachments) with the
transformations of the engine, so a quotation reaches the invoice without
retyping. The deferred invoicing groups the open delivery notes of a period by
customer, payment and destination into one invoice each.

Every document prints from one model: an HTML preview on screen and a PDF drawn
by the in-house writer, kept among the attachments as a new version. "Invia per
e-mail" proposes recipient, subject and text from the templates, attaches the
PDF and hands it to a background queue that talks SMTP itself (no external
library); the outcome goes to the log, section E-mail/PEC.

The demo company now has a year of sales in every state, made through the
engine, and run-dev.sh no longer writes to a stray B:\b folder under Git Bash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 17:20:25 +01:00
1 parent f12848865d
commit 826042f828
31 files changed
+5682 -16

No files matched your search

@@ -273,6 +273,12 @@ else
Value="@PartyScreens.Text(s.CompanyBankAccountId)" ValueChanged="v => Change(() => s.CompanyBankAccountId = PartyScreens.Id(v))" />
<KhNumberBox Label="@T["Parties.Fields.CreditLimit"]" Name="Sales.CreditLimit" Value="s.CreditLimit" ValueChanged="v => Change(() => s.CreditLimit = v)" Min="0" Span="3" />
<KhCheck Label="@T["Parties.Fields.Blocked"]" Name="Sales.Blocked" Value="s.Blocked" ValueChanged="v => Change(() => s.Blocked = v)" Span="3" />
<KhSelect TValue="string" Label="@T["Parties.Fields.ExcludedMonth1"]" Name="Sales.ExcludedMonth1" Options="MonthChoices" Empty="" Span="4"
Value="@s.ExcludedMonth1?.ToString(System.Globalization.CultureInfo.InvariantCulture)" ValueChanged="v => Change(() => s.ExcludedMonth1 = Month(v))" />
<KhSelect TValue="string" Label="@T["Parties.Fields.ExcludedMonth2"]" Name="Sales.ExcludedMonth2" Options="MonthChoices" Empty="" Span="4"
Value="@s.ExcludedMonth2?.ToString(System.Globalization.CultureInfo.InvariantCulture)" ValueChanged="v => Change(() => s.ExcludedMonth2 = Month(v))" />
<KhNumberBox Label="@T["Parties.Fields.ExcludedMonthsDay"]" Name="Sales.ExcludedMonthsDay" Value="s.ExcludedMonthsDay" ValueChanged="v => Change(() => s.ExcludedMonthsDay = (int?)v)"
Min="1" Max="31" Decimals="0" Span="4" Hint="@T["Parties.Hints.ExcludedMonths"]" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Parties.Groups.Delivery"]" Icon="truck">
<KhSelect TValue="string" Label="@T["Parties.Fields.CarrierId"]" Name="Sales.CarrierId" Options="_lookups.Carriers" Empty=""
@@ -874,6 +880,13 @@ else
private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse<PartyAddressKind>(value!));
// The months a customer excludes from the due dates (August, December...), named in the language of the screen.
private IReadOnlyList<KhOption<string>> MonthChoices =>
[.. Enumerable.Range(1, 12).Select(m => new KhOption<string>(m.ToString(System.Globalization.CultureInfo.InvariantCulture),
T.Culture.TextInfo.ToTitleCase(T.Culture.DateTimeFormat.GetMonthName(m))))];
private static int? Month(string? value) => int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var m) ? m : null;
private void SetDelivery(PartySalesTerms terms, string? value) => Change(() => terms.SendDocuments = Enum.Parse<DocumentDelivery>(value!));
private Task SetSubjectAsync(string? value)
@@ -0,0 +1,334 @@
@page "/vendite/fatturazione-differita"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Parties
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject DocumentEditor Editor
@inject DocumentEngine Engine
@inject DocumentCopyService Copies
@inject PartyService Parties
@inject ToastService Toasts
@inject TimeProvider Clock
@* The deferred invoicing (SPEC §11.3, mockup 030): the confirmed delivery notes not yet invoiced in a period, for one
customer or all; one deferred invoice (TD24) per customer, or per delivery note, with a reference line for each
delivery note; the invoices can be issued at once. *@
<KhPageTitle Text="@T["Sales.Deferred.Title"]" Icon="layers" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows("sales.invoice.write") || !Session.Permissions.Allows("sales.delivery.read"))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["Sales.Deferred.Procedure"]" Icon="layers">
<KhVSteps Items="Steps" Current="_step" Label="@T["Sales.Deferred.Procedure"]" />
<div class="kh-import-options">
<KhDateBox Label="@T["Sales.Deferred.From"]" Name="From" Value="_from" ValueChanged="v => Reset(() => _from = v)" Span="6" Disabled="_busy" />
<KhDateBox Label="@T["Sales.Deferred.To"]" Name="To" Value="_to" ValueChanged="v => Reset(() => _to = v)" Span="6" Required="true" Disabled="_busy" />
<KhHotlink TItem="PartyRow" Label="@T["Sales.Deferred.Customer"]" Name="PartyId" Value="_party" ValueChanged="v => Reset(() => _party = v)" Span="12"
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Hint="@T["Sales.Deferred.AllCustomers"]" Disabled="_busy" />
<KhDateBox Label="@T["Sales.Deferred.InvoiceDate"]" Name="InvoiceDate" Value="_invoiceDate" ValueChanged="v => _invoiceDate = v" Span="12" Required="true" Disabled="_busy" />
<KhSelect TValue="string" Label="@T["Sales.Deferred.Grouping"]" Name="Grouping" Options="GroupingChoices" Value="@(_perNote ? "note" : "party")"
ValueChanged="SetGrouping" Span="12" Disabled="_busy" />
<KhCheck Label="@T["Sales.Deferred.Issue"]" Name="Issue" Value="_issue" ValueChanged="v => _issue = v" Span="12" Disabled="_busy" />
<div class="c12 kh-endrow">
<button type="button" class="btn" disabled="@_busy" @onclick="SearchNotesAsync"><KhIcon Name="search" /> @T["Sales.Deferred.Search"]</button>
</div>
</div>
</KhPanel>
</div>
<div class="kh-import-main">
@if (_results.Count > 0)
{
<KhPanel Title="@T["Sales.Deferred.Results"]" Icon="check-circle">
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Deferred.Results"]">
<thead>
<tr>
<th scope="col">@T["Sales.Fields.PartyId"]</th>
<th scope="col">@T["Sales.Deferred.Invoice"]</th>
<th scope="col">@T["Sales.Radar.State"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
</tr>
</thead>
<tbody>
@foreach (var result in _results)
{
<tr>
<td>@result.PartyName</td>
@if (result.Record is { } record)
{
var state = SalesScreens.State(T, record.Header.Kind, record.Header.Status, null, Today);
<td class="code"><a href="@SalesScreens.RecordUrl(record.Header.Kind, record.Header.Id)">@(record.Header.DocumentNumber ?? T["Sales.DraftNumber"])</a></td>
<td><KhBadge Tone="state.Tone">@state.Text</KhBadge></td>
<td class="num">@T.Money(record.Header.TotalAmount)</td>
}
else
{
<td colspan="3" class="err"><KhIcon Name="alert-circle" /> @result.Error</td>
}
</tr>
}
</tbody>
</table>
</div>
<div class="kh-endrow kh-pad">
<a class="btn" href="vendite/fatture"><KhIcon Name="euro" /> @T["Sales.Sections.Invoices.Title"]</a>
<button type="button" class="btn" @onclick="Restart"><KhIcon Name="refresh" /> @T["Sales.Deferred.Again"]</button>
</div>
</KhPanel>
}
else
{
<KhPanel Title="@T["Sales.Deferred.Notes"]" Icon="truck">
<Actions>
<span class="muted sm">@T.Format("Sales.Deferred.Selected", _selected.Count, T.Money(SelectedTotal))</span>
<button type="button" class="btn primary" disabled="@(_selected.Count == 0 || _busy || _invoiceDate is null)" @onclick="GenerateAsync">
<KhIcon Name="send" /> @T["Sales.Deferred.Generate"]
</button>
</Actions>
<ChildContent>
@if (_notes is null)
{
<p class="muted kh-pad">@T["Sales.Deferred.Start"]</p>
}
else if (_notes.Count == 0)
{
<p class="muted kh-pad">@T["Sales.Deferred.None"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Deferred.Notes"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(_selected.Count == _notes.Count)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
<th scope="col">@T["Sales.Kinds.DeliveryNote"]</th>
<th scope="col">@T["Sales.Fields.DocumentDate"]</th>
<th scope="col">@T["Sales.Fields.PartyId"]</th>
<th scope="col" class="num">@T["Sales.Deferred.Lines"]</th>
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
<th scope="col">@T["Sales.Deferred.Invoice"]</th>
</tr>
</thead>
<tbody>
@foreach (var note in _notes)
{
var id = note.Row.Id;
<tr>
<td class="kh-check"><input type="checkbox" checked="@_selected.Contains(id)" aria-label="@note.Row.DocumentNumber" @onchange="e => Toggle(id, e.Value is true)" /></td>
<td class="code"><a href="@SalesScreens.RecordUrl(note.Row.Kind, id)">@note.Row.DocumentNumber</a></td>
<td>@T.Date(note.Row.Date)</td>
<td>@note.Row.PartyName</td>
<td class="num">@note.Lines.Count</td>
<td class="num">@T.Money(note.Row.Taxable)</td>
<td class="muted">@InvoiceLabel(note)</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
}
</div>
</div>
}
@code {
private readonly HashSet<long> _selected = [];
private readonly List<DeferredResult> _results = [];
private IReadOnlyList<OpenDocument>? _notes;
private PartyRow? _party;
private DateOnly? _from;
private DateOnly? _to;
private DateOnly? _invoiceDate;
private bool _perNote;
private bool _issue;
private bool _busy;
private bool _loaded;
private int _step;
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private IReadOnlyList<KhStep> Steps =>
[
new(T["Sales.Deferred.Steps.Period"], T["Sales.Deferred.Steps.PeriodDetail"]),
new(T["Sales.Deferred.Steps.Choose"], T["Sales.Deferred.Steps.ChooseDetail"]),
new(T["Sales.Deferred.Steps.Generate"], T["Sales.Deferred.Steps.GenerateDetail"]),
];
private IReadOnlyList<KhOption<string>> GroupingChoices =>
[new("party", T["Sales.Deferred.PerParty"]), new("note", T["Sales.Deferred.PerNote"])];
private decimal SelectedTotal => _notes?.Where(n => _selected.Contains(n.Row.Id)).Sum(n => n.Row.Taxable) ?? 0m;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
// The usual run: the delivery notes of last month, invoiced on its last day.
var firstOfMonth = new DateOnly(Today.Year, Today.Month, 1);
_from = firstOfMonth.AddMonths(-1);
_to = firstOfMonth.AddDays(-1);
_invoiceDate = _to;
_loaded = true;
}
private void Reset(Action change)
{
change();
_notes = null;
_selected.Clear();
_step = 0;
}
private async Task<IReadOnlyList<PartyRow>> SearchAsync(string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
: [];
private async Task SearchNotesAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (_to is null)
{
Toasts.Show(ToastKind.Error, T["Sales.Deferred.ToRequired"]);
return;
}
_busy = true;
try
{
_notes = await Editor.OpenAsync(actor, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], _party?.Id, _from, _to);
_selected.Clear();
_selected.UnionWith(_notes.Select(n => n.Row.Id));
_step = 1;
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"]);
}
finally
{
_busy = false;
}
}
private void Toggle(long id, bool on)
{
if (on)
{
_selected.Add(id);
}
else
{
_selected.Remove(id);
}
}
private void ToggleAll(ChangeEventArgs e)
{
_selected.Clear();
if (e.Value is true && _notes is not null)
{
_selected.UnionWith(_notes.Select(n => n.Row.Id));
}
}
// The invoices the run will make: one per customer (or per delivery note), in the order of the list.
private List<List<OpenDocument>> Groups() => _notes is null ? [] : _perNote
? [.. _notes.Where(n => _selected.Contains(n.Row.Id)).Select(n => new List<OpenDocument> { n })]
: [.. _notes.Where(n => _selected.Contains(n.Row.Id)).GroupBy(n => n.Row.PartyId).Select(g => g.ToList())];
private string? InvoiceLabel(OpenDocument note)
{
if (!_selected.Contains(note.Row.Id))
{
return null;
}
var groups = Groups();
var index = groups.FindIndex(g => g.Any(n => n.Row.Id == note.Row.Id));
return index < 0 ? null : T.Format("Sales.Deferred.InvoiceNumber", index + 1, groups[index].Count);
}
private async Task GenerateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _invoiceDate is not { } date)
{
return;
}
_busy = true;
_results.Clear();
try
{
foreach (var group in Groups())
{
var name = group[0].Row.PartyName ?? string.Empty;
try
{
var invoice = await Copies.MergeAsync(actor, company, DocumentFamily.SaleDocument, [.. group.Select(n => n.Row.Id)], "FD", date);
if (_issue)
{
invoice = await Engine.ConfirmAsync(actor, company, invoice.Family, invoice.Header.Id);
}
_results.Add(new(name, invoice, null));
}
catch (ValidationFailedException ex)
{
_results.Add(new(name, null, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))));
}
catch (InvalidDocumentActionException)
{
_results.Add(new(name, null, T[InvalidDocumentActionException.Code]));
}
}
_step = 2;
var made = _results.Count(r => r.Record is not null);
Toasts.Show(made == _results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("Sales.Deferred.Done", made, _results.Count));
}
finally
{
_busy = false;
}
}
private void SetGrouping(string? value) => _perNote = value == "note";
private void Restart()
{
_results.Clear();
Reset(() => { });
}
private sealed record DeferredResult(string PartyName, DocumentRecord? Record, string? Error);
}
@@ -0,0 +1,409 @@
@page "/vendite/{Segment}/nuovo"
@page "/vendite/{Segment}/{Id:long}"
@attribute [Authorize]
@inherits DocumentPage<DocumentRecord, DocumentLine>
@using Khaemhat.Application.Audit
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Items
@using Khaemhat.Application.Parties
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Tax
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Parties
@* The record of a sales document (SPEC §11.3, mockups 020-022 and 026-029): quotation, order, delivery note, invoice of
every kind, pro forma, credit and debit note. Righe first with the VAT summary, due dates and totals underneath, then
Testata, Trasporto for the documents that move goods, Totali, Scadenze, Note, Allegati, Collegamenti, Storico. The
totals are computed while typing with the code of the save; the actions follow the state machine of the engine. *@
<KhPageTitle Text="@PageTitle" Icon="@(_section?.Icon ?? "file")" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (_denied)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else if (Record is null || _section is null || _definition is null)
{
<div class="kh-message">
<KhIcon Name="alert" Class="lg" />
<h1>@T["Sales.NotFound"]</h1>
<a class="btn" href="@(_section is null ? SalesScreens.BasePath : SalesScreens.RadarUrl(_section))">@T["Sales.BackToList"]</a>
</div>
}
else
{
var h = Record.Header;
<KhRecordLayout Page="this">
<Heading>
<KhDocHead KindIcon="@_section.Icon" KindLabel="@_definition.Type.Description" Number="@(h.DocumentNumber ?? T["Sales.DraftNumber"])"
PartyName="@(_party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
TotalLabel="@T[ShowsNet ? "Sales.Totals.Net" : "Sales.Totals.Total"]" TotalValue="@T.Money(ShowsNet ? h.NetAmount : h.TotalAmount)" SubValues="HeadStats">
<Facts>
<span>@T["Sales.Fields.DocumentDate"] <b>@T.Date(h.DocumentDate)</b></span>
@if (h.Kind == DocumentKind.Quotation && h.ValidUntil is { } until)
{
<span>@T["Sales.Fields.ValidUntil"] <b>@T.Date(until)</b></span>
}
@if (h.DeliveryDate is { } delivery)
{
<span>@T["Sales.Fields.DeliveryDate"] <b>@T.Date(delivery)</b></span>
}
@if (h.Revision > 0)
{
<span>@T["Sales.Fields.Revision"] <b>@h.Revision</b></span>
}
@if (h.RelatedNumber is { } related)
{
<span>@T["Sales.Fields.Related"] <b>@related</b>@(h.RelatedDate is { } rd ? " · " + T.Date(rd) : null)</span>
}
</Facts>
<State>
@{ var state = SalesScreens.State(T, h.Kind, h.Status, h.ValidUntil, Today); }
<KhBadge Tone="state.Tone">@state.Text</KhBadge>
@if (h.IsDemo)
{
<KhBadge Tone="KhTone.Info">@T["Sales.Demo"]</KhBadge>
}
@if (IsModified)
{
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
}
</State>
<Chips>
@if (PartyScreens.Describe(_lookups.PaymentTerms, h.PaymentTermId) is { } payment)
{
<KhChip Icon="coins" Text="@T["Sales.Fields.PaymentTermId"]" Value="@payment" />
}
@if (PartyScreens.Describe(_lookups.PriceLists, h.PriceListId) is { } list)
{
<KhChip Icon="tag" Text="@T["Sales.Fields.PriceListId"]" Value="@list" />
}
@if (PartyScreens.Describe(_lookups.Salespeople, h.SalespersonId) is { } agent)
{
<KhChip Icon="user" Text="@T["Sales.Fields.SalespersonId"]" Value="@agent" />
}
@if (h.SplitPayment)
{
<KhChip Icon="shield" Text="@T["Sales.Fields.SplitPayment"]" Value="@T["Common.Yes"]" />
}
</Chips>
</KhDocHead>
</Heading>
<ChildContent>
@switch (ActiveTab)
{
case TabIds.Lines:
@if (h.PartyId is null && !IsReadOnly)
{
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
<button type="button" class="btn" @onclick="() => ShowTabAsync(TabIds.Header)">@T["Sales.Actions.ChooseParty"]</button></div>
}
<KhLinesGrid TLine="DocumentLine" @ref="_grid" Lines="Record.Lines" Columns="LineColumns" NewLine="NewLine" IsEmpty="IsEmptyLine"
IsDescriptive="l => l.Kind == DocumentLineKind.Description" NewDescriptive="NewDescriptionLine" DescriptionColumn="LineColumns[1]"
ReadOnly="IsReadOnly" OnChanged="LinesChangedAsync" Label="@T["Sales.Lines.Title"]" />
@if (Validation.Messages.Any(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true))
{
<ul class="kh-doc-errors">
@foreach (var message in Validation.Messages.Where(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true))
{
<li><KhIcon Name="alert-circle" /> @LineErrorText(message.Field!, message.Message)</li>
}
</ul>
}
<div class="kh-doc-panels">
<KhPanel Title="@T["Sales.Totals.Summary"]" Icon="euro" Tight="true">@TaxSummary</KhPanel>
<KhPanel Title="@T["Sales.Totals.Installments"]" Icon="calendar" Tight="true">@Installments</KhPanel>
<KhPanel Title="@T["Sales.Totals.Title"]" Icon="coins" Tight="true">@Totals</KhPanel>
</div>
break;
case TabIds.Header:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Document"]" Icon="file">
<KhTextBox Label="@T["Sales.Fields.DocumentTypeId"]" Name="DocumentTypeId" Value="@(_definition.Code + " · " + _definition.Type.Description)" ReadOnly="true" Span="6" />
<KhTextBox Label="@T["Sales.Fields.DocumentNumber"]" Name="DocumentNumber" Value="@(h.DocumentNumber ?? T["Sales.NumberOnConfirm"])" ReadOnly="true" Mono="true" Span="6" />
<KhDateBox Label="@T["Sales.Fields.DocumentDate"]" Name="DocumentDate" Value="h.DocumentDate" Required="true" Span="4" ReadOnly="@(h.Number is not null)"
ValueChanged="v => ChangeAsync(() => { if (v is { } d) { h.DocumentDate = d; h.Year = d.Year; } })" />
@if (h.Kind == DocumentKind.Quotation)
{
<KhDateBox Label="@T["Sales.Fields.ValidUntil"]" Name="ValidUntil" Value="h.ValidUntil" ValueChanged="v => Change(() => h.ValidUntil = v)" Span="4" />
}
@if (h.Kind is DocumentKind.Quotation or DocumentKind.SalesOrder or DocumentKind.DeliveryNote or DocumentKind.ProForma)
{
<KhDateBox Label="@T["Sales.Fields.DeliveryDate"]" Name="DeliveryDate" Value="h.DeliveryDate" ValueChanged="v => Change(() => h.DeliveryDate = v)" Span="4" />
}
<KhTextBox Label="@T["Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference" ValueChanged="v => Change(() => h.ExternalReference = v)"
Span="8" MaxLength="60" Hint="@T["Sales.Hints.ExternalReference"]" />
<KhDateBox Label="@T["Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate" ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" />
@if (IsNote)
{
<KhTextBox Label="@T["Sales.Fields.RelatedNumber"]" Name="RelatedNumber" Value="@h.RelatedNumber" ValueChanged="v => Change(() => h.RelatedNumber = v)"
Span="8" MaxLength="30" Mono="true" Hint="@T["Sales.Hints.Related"]" />
<KhDateBox Label="@T["Sales.Fields.RelatedDate"]" Name="RelatedDate" Value="h.RelatedDate" ValueChanged="v => Change(() => h.RelatedDate = v)" Span="4" />
}
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Party"]" Icon="users">
<KhHotlink TItem="PartyRow" Label="@T["Sales.Fields.PartyId"]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
Search="SearchPartiesAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenParty" ReadOnly="@(Record.Lines.Any(l => l.SourceLineId is not null))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_lookups.Currencies" Span="6"
Value="@h.CurrencyCode" ValueChanged="SetCurrency" />
@if (h.PartyId is not null)
{
<p class="muted sm c12"><KhIcon Name="info" /> @T["Sales.Hints.PartyDefaults"]</p>
}
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Conditions"]" Icon="coins">
<KhSelect TValue="string" Label="@T["Sales.Fields.PriceListId"]" Name="PriceListId" Options="_lookups.PriceLists" Empty="" Span="6"
Value="@PartyScreens.Text(h.PriceListId)" ValueChanged="v => Change(() => h.PriceListId = PartyScreens.Id(v))" />
<KhTextBox Label="@T["Sales.Fields.FooterDiscount"]" Name="FooterDiscount" Value="@h.FooterDiscount" ValueChanged="v => ChangeAsync(() => h.FooterDiscount = v)"
Span="3" Mono="true" MaxLength="30" Placeholder="10+5" />
<KhCheck Label="@T["Sales.Fields.PricesIncludeTax"]" Name="PricesIncludeTax" Value="h.PricesIncludeTax" ValueChanged="v => ChangeAsync(() => h.PricesIncludeTax = v)" Span="3" />
<KhSelect TValue="string" Label="@T["Sales.Fields.PaymentTermId"]" Name="PaymentTermId" Options="_lookups.PaymentTerms" Empty="" Span="6"
Value="@PartyScreens.Text(h.PaymentTermId)" ValueChanged="v => ChangeAsync(() => h.PaymentTermId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.PaymentMethodId"]" Name="PaymentMethodId" Options="_lookups.PaymentMethods" Empty="" Span="6"
Value="@PartyScreens.Text(h.PaymentMethodId)" ValueChanged="v => Change(() => h.PaymentMethodId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.BankAccountId"]" Name="BankAccountId" Options="_lookups.BankAccounts" Empty="" Span="12"
Value="@PartyScreens.Text(h.BankAccountId)" ValueChanged="v => Change(() => h.BankAccountId = PartyScreens.Id(v))" />
</KhFieldGroup>
@if (IsInvoice)
{
<KhFieldGroup Title="@T["Sales.Groups.Tax"]" Icon="shield">
<KhSelect TValue="string" Label="@T["Sales.Fields.Exigibility"]" Name="Exigibility" Options="ExigibilityChoices" Empty="" Span="6"
Value="@h.Exigibility?.ToString()" ValueChanged="SetExigibilityAsync" />
<KhCheck Label="@T["Sales.Fields.SplitPayment"]" Name="SplitPayment" Value="h.SplitPayment" ValueChanged="v => ChangeAsync(() => h.SplitPayment = v)" Span="3" />
<KhCheck Label="@T["Sales.Fields.StampDutyCharged"]" Name="StampDutyCharged" Value="h.StampDutyCharged" ValueChanged="v => ChangeAsync(() => h.StampDutyCharged = v)" Span="3" />
<KhTextBox Label="@T["Sales.Fields.Cig"]" Name="Cig" Value="@h.Cig" ValueChanged="v => Change(() => h.Cig = v)" Span="6" Mono="true" MaxLength="15" />
<KhTextBox Label="@T["Sales.Fields.Cup"]" Name="Cup" Value="@h.Cup" ValueChanged="v => Change(() => h.Cup = v)" Span="6" Mono="true" MaxLength="15" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Withholding"]" Icon="coins">
<KhNumberBox Label="@T["Sales.Fields.WithholdingRate"]" Name="WithholdingRate" Value="h.WithholdingRate" ValueChanged="v => ChangeAsync(() => h.WithholdingRate = v)" Min="0" Max="100" Span="3" />
<KhNumberBox Label="@T["Sales.Fields.WithholdingBasePercent"]" Name="WithholdingBasePercent" Value="h.WithholdingBasePercent"
ValueChanged="v => ChangeAsync(() => h.WithholdingBasePercent = v ?? 100m)" Min="0" Max="100" Span="3" />
<KhTextBox Label="@T["Sales.Fields.WithholdingType"]" Name="WithholdingType" Value="@h.WithholdingType" ValueChanged="v => Change(() => h.WithholdingType = v)" Span="3" Mono="true" MaxLength="4" Placeholder="RT01" />
<KhTextBox Label="@T["Sales.Fields.WithholdingReason"]" Name="WithholdingReason" Value="@h.WithholdingReason" ValueChanged="v => Change(() => h.WithholdingReason = v)" Span="3" Mono="true" MaxLength="2" Placeholder="A" />
<KhTextBox Label="@T["Sales.Fields.SocialSecurityFund"]" Name="SocialSecurityFund" Value="@h.SocialSecurityFund" ValueChanged="v => Change(() => h.SocialSecurityFund = v)" Span="3" Mono="true" MaxLength="4" Placeholder="TC22" />
<KhNumberBox Label="@T["Sales.Fields.SocialSecurityRate"]" Name="SocialSecurityRate" Value="h.SocialSecurityRate" ValueChanged="v => ChangeAsync(() => h.SocialSecurityRate = v)" Min="0" Max="100" Span="3" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SocialSecurityTaxCodeId"]" Name="SocialSecurityTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="3"
Value="@PartyScreens.Text(h.SocialSecurityTaxCodeId)" ValueChanged="v => ChangeAsync(() => h.SocialSecurityTaxCodeId = PartyScreens.Id(v))" />
<KhCheck Label="@T["Sales.Fields.SocialSecurityWithheld"]" Name="SocialSecurityWithheld" Value="h.SocialSecurityWithheld" ValueChanged="v => ChangeAsync(() => h.SocialSecurityWithheld = v)" Span="3" />
<KhNumberBox Label="@T["Sales.Fields.EnasarcoRate"]" Name="EnasarcoRate" Value="h.EnasarcoRate" ValueChanged="v => ChangeAsync(() => h.EnasarcoRate = v)" Min="0" Max="100" Span="3" />
<p class="muted sm c9">@T["Sales.Hints.Withholding"]</p>
</KhFieldGroup>
}
</KhForm>
break;
case SalesScreens.TransportTab:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Transport"]" Icon="truck">
<KhSelect TValue="string" Label="@T["Sales.Fields.TransportReasonId"]" Name="TransportReasonId" Options="_lookups.TransportReasons" Empty="" Span="6"
Value="@PartyScreens.Text(h.TransportReasonId)" ValueChanged="v => Change(() => h.TransportReasonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.TransportBy"]" Name="TransportBy" Options="TransportChoices" Empty="" Span="6"
Value="@h.TransportBy?.ToString()" ValueChanged="SetTransportBy" />
<KhSelect TValue="string" Label="@T["Sales.Fields.CarrierId"]" Name="CarrierId" Options="_lookups.Carriers" Empty="" Span="6"
Value="@PartyScreens.Text(h.CarrierId)" ValueChanged="v => Change(() => h.CarrierId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.ShippingTermId"]" Name="ShippingTermId" Options="_lookups.ShippingTerms" Empty="" Span="6"
Value="@PartyScreens.Text(h.ShippingTermId)" ValueChanged="v => Change(() => h.ShippingTermId = PartyScreens.Id(v))" />
<KhDateBox Label="@T["Sales.Fields.TransportStartDate"]" Name="TransportStart" Value="TransportDate" ValueChanged="SetTransportDate" Span="4" />
<KhTextBox Label="@T["Sales.Fields.TransportStartTime"]" Name="TransportStartTime" Type="time" Value="@TransportTime" ValueChanged="SetTransportTime" Span="2" />
<KhSelect TValue="string" Label="@T["Sales.Fields.WarehouseId"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
Value="@PartyScreens.Text(h.WarehouseId)" ValueChanged="v => Change(() => h.WarehouseId = PartyScreens.Id(v))" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Goods"]" Icon="box">
<KhSelect TValue="string" Label="@T["Sales.Fields.GoodsAppearanceId"]" Name="GoodsAppearanceId" Options="_lookups.GoodsAppearances" Empty="" Span="12"
Value="@PartyScreens.Text(h.GoodsAppearanceId)" ValueChanged="v => Change(() => h.GoodsAppearanceId = PartyScreens.Id(v))" />
<KhNumberBox Label="@T["Sales.Fields.Packages"]" Name="Packages" Value="h.Packages" ValueChanged="v => Change(() => h.Packages = (int?)v)" Min="0" Decimals="0" Span="4" />
<KhNumberBox Label="@T["Sales.Fields.GrossWeight"]" Name="GrossWeight" Value="h.GrossWeight" ValueChanged="v => Change(() => h.GrossWeight = v)" Min="0" Decimals="3" Span="4" />
<KhNumberBox Label="@T["Sales.Fields.NetWeight"]" Name="NetWeight" Value="h.NetWeight" ValueChanged="v => Change(() => h.NetWeight = v)" Min="0" Decimals="3" Span="4" />
<p class="muted sm c12">@T["Sales.Hints.Transport"]</p>
</KhFieldGroup>
</KhForm>
break;
case TabIds.Totals:
<div class="kh-doc-panels wide">
<KhPanel Title="@T["Sales.Totals.Summary"]" Icon="euro" Tight="true">@TaxSummary</KhPanel>
<KhPanel Title="@T["Sales.Totals.Title"]" Icon="coins" Tight="true">@Totals</KhPanel>
</div>
break;
case TabIds.DueDates:
<div class="kh-doc-panels single">
<KhPanel Title="@T["Sales.Totals.Installments"]" Icon="calendar" Tight="true">@Installments</KhPanel>
</div>
<p class="muted sm kh-pad"><KhIcon Name="info" /> @T[Behavior.Has(DocumentEffects.Installments) ? "Sales.Hints.Installments" : "Sales.Hints.InstallmentsForecast"]</p>
break;
case TabIds.Notes:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Notes"]" Icon="edit" Wide="true">
<KhTextArea Label="@T["Sales.Fields.Notes"]" Name="Notes" Value="@h.Notes" ValueChanged="v => Change(() => h.Notes = v)" Span="12" Rows="6"
Hint="@T["Sales.Hints.Notes"]" />
</KhFieldGroup>
@if (h.CancelReason is { } reason)
{
<KhFieldGroup Title="@T["Sales.Groups.Cancelled"]" Icon="x-circle" Wide="true">
<KhTextArea Label="@T["Sales.Fields.CancelReason"]" Name="CancelReason" Value="@reason" ReadOnly="true" Span="12" Rows="2" />
</KhFieldGroup>
}
</KhForm>
break;
case TabIds.Attachments:
<div class="kh-tab-body"><KhAttachmentList Entity="@AttachmentEntity" EntityId="h.Id" OnCountChanged="SetAttachments" /></div>
break;
case TabIds.Links:
<div class="kh-tab-body">
@if (_links.Count == 0)
{
<p class="muted">@T["Sales.Links.Empty"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Ui.Record.Tabs.Links"]">
<thead>
<tr>
<th scope="col">@T["Sales.Links.Relation"]</th>
<th scope="col">@T["Sales.Radar.Kind"]</th>
<th scope="col">@T["Sales.Fields.DocumentNumber"]</th>
<th scope="col">@T["Sales.Fields.DocumentDate"]</th>
<th scope="col">@T["Sales.Radar.State"]</th>
<th scope="col" class="num">@T["Sales.Links.Quantity"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
</tr>
</thead>
<tbody>
@foreach (var link in _links)
{
var linkState = SalesScreens.State(T, link.Kind, link.Status, null, Today);
<tr>
<td>@T["Sales.Links." + link.Direction]</td>
<td>@SalesScreens.KindName(T, link.Kind)</td>
<td class="code">
@if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url)
{
<a href="@url">@(link.DocumentNumber ?? T["Sales.DraftNumber"])</a>
}
else
{
@(link.DocumentNumber ?? T["Sales.DraftNumber"])
}
</td>
<td>@T.Date(link.Date)</td>
<td><KhBadge Tone="linkState.Tone">@linkState.Text</KhBadge></td>
<td class="num">@(link.Quantity > 0 ? T.Number(link.Quantity, 2) : null)</td>
<td class="num">@T.Money(link.Total)</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
break;
case TabIds.History:
<div class="kh-tab-body"><KhAuditList Items="_history" FieldName="FieldLabel" /></div>
break;
}
</ChildContent>
</KhRecordLayout>
<KhRadarDialog TItem="ItemRow" Id="sales.items" Open="_lookupLine is not null" Title="@T["Sales.Lines.ItemRadar"]" Columns="ItemColumns" Source="ListItemsAsync"
KeyOf="i => i.Id" InitialSearch="@_lookupText" OnPick="PickItemAsync" OnClose="CloseLookup" />
<KhDialog Open="_transform is not null" Title="@_transform?.Title" Icon="copy" Size="lg" OnClose="() => _transform = null">
<ChildContent>
@if (_transform is { } t)
{
<p class="muted">@t.Lead</p>
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Lines.Title"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(t.Selected.Count == t.Lines.Count)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAllLines" /></th>
<th scope="col">@T["Sales.Lines.Description"]</th>
<th scope="col" class="num">@T["Sales.Lines.Quantity"]</th>
@if (t.Fulfils)
{
<th scope="col" class="num">@T["Sales.Lines.Residual"]</th>
}
<th scope="col" class="num">@T["Sales.Lines.Amount"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in t.Lines)
{
var id = line.Id;
<tr class="@(line.Kind == DocumentLineKind.Description ? "kh-desc" : null)">
<td class="kh-check"><input type="checkbox" checked="@t.Selected.Contains(id)" aria-label="@line.Description" @onchange="e => ToggleLine(id, e.Value is true)" /></td>
<td>@line.Description</td>
<td class="num">@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Quantity, 2) : null)</td>
@if (t.Fulfils)
{
<td class="num">@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Residual, 2) : null)</td>
}
<td class="num">@(line.Kind == DocumentLineKind.Description ? null : T.Money(line.TaxableAmount))</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _transform = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_transform?.Selected.Count == 0 || _busy)" @onclick="TransformAsync"><KhIcon Name="copy" /> @T["Sales.Transform.Create"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_cancelling" Title="@T["Sales.Actions.Cancel"]" Icon="x-circle" OnClose="() => _cancelling = false">
<ChildContent>
<p>@T[Behavior.Lifecycle == DocumentLifecycle.Invoice ? "Sales.Cancel.LeadInvoice" : "Sales.Cancel.Lead"]</p>
<KhForm Validation="_cancelValidation" Layout="KhFormLayout.Groups">
<KhTextArea Label="@T["Sales.Fields.CancelReason"]" Name="CancelReason" Value="@_cancelReason" ValueChanged="v => _cancelReason = v" Span="12" Rows="3"
Required="@(Behavior.Lifecycle == DocumentLifecycle.Invoice)" />
</KhForm>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _cancelling = false">@T["Common.Cancel"]</button>
<button type="button" class="btn danger" disabled="@_busy" @onclick="CancelDocumentAsync"><KhIcon Name="x-circle" /> @T["Sales.Actions.Cancel"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_mailing" Title="@T["Sales.Mail.Title"]" Icon="mail" Size="lg" OnClose="() => _mailing = false">
<ChildContent>
@if (!Mails.IsConfigured)
{
<div class="callout warn kh-doc-callout"><KhIcon Name="alert" /> <span>@T[DocumentMailErrors.NotConfigured]</span></div>
}
<p class="muted">@T["Sales.Mail.Lead"]</p>
<div class="kh-mail-form">
<KhForm Validation="_mailValidation" Layout="KhFormLayout.Groups">
<KhTextBox Label="@T["Sales.Mail.To"]" Name="To" Value="@_mailTo" ValueChanged="v => _mailTo = v" Span="12" Required="true" Hint="@T["Sales.Mail.ToHint"]" />
<KhTextBox Label="@T["Sales.Mail.Subject"]" Name="Subject" Value="@_mailSubject" ValueChanged="v => _mailSubject = v" Span="12" Required="true" />
<KhTextArea Label="@T["Sales.Mail.Body"]" Name="Body" Value="@_mailBody" ValueChanged="v => _mailBody = v" Span="12" Rows="9" />
</KhForm>
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _mailing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || !Mails.IsConfigured)" @onclick="SendMailAsync"><KhIcon Name="send" /> @T["Sales.Mail.Send"]</button>
</Footer>
</KhDialog>
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,185 @@
@page "/vendite/{Segment}"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Core.Documents
@using Khaemhat.Web.Documents
@inject ShellSession Session
@inject DocumentEngine Engine
@inject DocumentEditor Editor
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The radar of a kind of sales documents (SPEC §11.3): quotations, orders, delivery notes, invoices (with pro forma
and fees), credit and debit notes. Search on number, reference and customer; filters for state, type and year;
totals of the page. Enter or double click opens the document. *@
<KhPageTitle Text="@Title" Icon="@(_section?.Icon ?? "cart")" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (_section is null)
{
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Pages.NotFound.Title"]</h1></div>
}
else if (!CanRead)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<KhRadar TItem="DocumentRow" @key="_section.Segment" Id="@("sales." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
Label="@Title">
<Toolbar>
@if (NewTypes.Count > 0)
{
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Sales.Sections." + _section.Key + ".New"]</button>
}
@if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
{
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
}
</Toolbar>
</KhRadar>
<KhDialog Open="_choosing" Title="@T["Sales.NewDocument"]" Icon="plus" OnClose="() => _choosing = false">
<ChildContent>
<div class="kh-choice-list">
@foreach (var type in NewTypes)
{
<button type="button" class="btn kh-choice" @onclick="() => Create(type.Code)">
<span class="code">@type.Code</span>
<b>@type.Type.Description</b>
<span class="muted sm">@T["Sales.Hints.Kinds." + type.Kind]</span>
</button>
}
</div>
</ChildContent>
</KhDialog>
}
@code {
private SalesSection? _section;
private IReadOnlyList<DocumentDefinition> _definitions = [];
private bool _loaded;
private bool _choosing;
/// <summary>The radar segment, such as <c>fatture</c>.</summary>
[Parameter]
public string? Segment { get; set; }
private string Title => _section is null ? T["Shell.Menu.Sales"] : T["Sales.Sections." + _section.Key + ".Title"];
private bool CanRead => _section is not null && Session.Permissions.Allows(DocumentBehaviors.Of(_section.Kinds[0]).ReadPermission);
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
// The types of the radar the user may create, in the order of the section.
private List<DocumentDefinition> NewTypes => _section is null ? [] :
[.. _section.NewTypes.Select(code => _definitions.FirstOrDefault(d => d.Code == code)).OfType<DocumentDefinition>()
.Where(d => Session.Permissions.Allows(d.Behavior.WritePermission))];
private IReadOnlyList<KhColumn<DocumentRow>> Columns =>
[
new("number", T["Sales.Fields.DocumentNumber"], r => r.DocumentNumber ?? T["Sales.DraftNumber"]) { Kind = KhColumnKind.Code, Width = "130px" },
new("date", T["Sales.Fields.DocumentDate"], r => r.Date) { Kind = KhColumnKind.Date, Width = "100px" },
new("type", T["Sales.Radar.Kind"], r => SalesScreens.KindName(T, r.Kind)) { Width = "150px", Sortable = false, Visible = _section?.Kinds.Count > 1 },
new("party", T["Sales.Fields.PartyId"], r => r.PartyName) { Sortable = false },
new("reference", T["Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" },
new("validUntil", T["Sales.Fields.ValidUntil"], r => r.ValidUntil) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment == "preventivi" },
new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" },
new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px" },
new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px" },
new("status", T["Sales.Radar.State"], r => StateOf(r).Text)
{
Width = "130px",
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
},
];
private IReadOnlyList<KhQuickFilter> QuickFilters
{
get
{
var filters = new List<KhQuickFilter>
{
new("status", T["Sales.Radar.State"], [new(string.Empty, T["Sales.Radar.All"]), .. States.Select(s => new KhOption<string>(s.ToString(), T["Sales.States." + s]))]),
};
if (_section is { Kinds.Count: > 1 })
{
filters.Add(new("kind", T["Sales.Radar.Kind"], [new(string.Empty, T["Sales.Radar.All"]), .. _section.Kinds.Select(k => new KhOption<string>(k.ToString(), SalesScreens.KindName(T, k)))]));
}
var year = Today.Year;
filters.Add(new("year", T["Sales.Radar.Year"],
[new(string.Empty, T["Sales.Radar.All"]), .. Enumerable.Range(0, 3).Select(i => new KhOption<string>((year - i).ToString(T.Culture), (year - i).ToString(T.Culture)))]));
return filters;
}
}
// The states that make sense for the life cycle of the radar.
private IEnumerable<DocumentStatus> States => _section is null ? [] :
DocumentBehaviors.Of(_section.Kinds[0]).Lifecycle == DocumentLifecycle.Invoice && _section.Kinds.All(k => DocumentBehaviors.Of(k).Lifecycle == DocumentLifecycle.Invoice)
? [DocumentStatus.Draft, DocumentStatus.Issued, DocumentStatus.Cancelled]
: [DocumentStatus.Draft, DocumentStatus.Confirmed, DocumentStatus.PartiallyFulfilled, DocumentStatus.Fulfilled, DocumentStatus.Closed, DocumentStatus.Cancelled, DocumentStatus.Issued];
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
_section = SalesScreens.Find(Segment);
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company)
{
_definitions = await Engine.DefinitionsAsync(actor, company);
}
_loaded = true;
}
private (string Text, KhTone Tone) StateOf(DocumentRow row) => SalesScreens.State(T, row.Kind, row.Status, row.ValidUntil, Today);
private static string? RowClassOf(DocumentRow row) => row.Status == DocumentStatus.Cancelled ? "muted" : null;
private Task<ListPage<DocumentRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && _section is not null
? Editor.ListAsync(actor, company, _section.Family, _section.Kinds, query, cancellationToken)
: Task.FromResult(new ListPage<DocumentRow>([], 0, new Dictionary<string, decimal>()));
private void Open(DocumentRow row)
{
if (SalesScreens.RecordUrl(row.Kind, row.Id) is { } url)
{
Navigation.NavigateTo(url);
}
}
private void New()
{
if (NewTypes.Count == 1)
{
Create(NewTypes[0].Code);
}
else
{
_choosing = true;
}
}
private void Create(string code)
{
_choosing = false;
if (_section is not null)
{
Navigation.NavigateTo(SalesScreens.NewUrl(_section, code));
}
}
}
@@ -0,0 +1,252 @@
@page "/vendite/{Segment}/{Id:long}/stampa"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Security
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Hosting
@inject ShellSession Session
@inject DocumentPrintService Prints
@inject DocumentEngine Engine
@inject FileGenerationService Generation
@inject ToastService Toasts
@* The print preview of a sales document (SPEC §9.4, issue #52, mockup 025): the A4 sheet in HTML from the same model
as the PDF, with Stampa (the print of the browser), the PDF made by Khaemhat and "Salva come allegato", which keeps
the PDF among the attachments of the document as a new version. *@
<KhPageTitle Text="@Heading" Icon="printer" />
@if (_model is null)
{
<div class="kh-message">
<KhIcon Name="@(_missing ? "alert" : "printer")" Class="lg" />
<h1>@(_missing ? T["Sales.NotFound"] : T["Common.Loading"])</h1>
</div>
}
else
{
<div class="phead">
<div>
<div class="crumbs"><a href="@BackUrl">@_model.Title @_model.Number</a> › <b>@T["Sales.Print.Title"]</b></div>
<h1>@Heading</h1>
</div>
</div>
<KhPrintPreview PdfUrl="@PdfUrl(false)" PdfDownloadUrl="@PdfUrl(true)" OnSaveAttachment="SaveAsync" Saving="_saving">
<div class="kh-sheet-head">
<div class="kh-print-company">
@if (_model.LogoAttachmentId is { } logo)
{
<img class="kh-print-logo" src="@FileEndpoints.View(logo)" alt="" />
}
<div>
<div class="kh-sheet-company">@_model.Company.Name</div>
@foreach (var line in _model.Company.Lines)
{
<div class="kh-sheet-muted">@line</div>
}
</div>
</div>
<div class="kh-sheet-title">
<div class="k">@_model.Title</div>
<div class="kh-print-number">@_model.Number</div>
<div class="n">@_model.Date</div>
@if (_model.Watermark is { } mark)
{
<div class="kh-print-mark">@mark</div>
}
</div>
</div>
<div class="kh-print-top">
<dl class="kh-print-fields">
@foreach (var field in _model.Fields)
{
<dt>@field.Label</dt>
<dd>@field.Value</dd>
}
</dl>
<div class="kh-print-party">
<div class="kh-sheet-muted">@_model.PartyLabel <span class="mono">@_model.Party.Code</span></div>
<b>@_model.Party.Name</b>
@foreach (var line in _model.Party.Lines)
{
<div>@line</div>
}
</div>
</div>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < _model.LineHeaders.Count; i++)
{
<th class="@(i >= 3 ? "num" : null)">@_model.LineHeaders[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var line in _model.Lines)
{
if (line.IsDescription)
{
<tr class="kh-print-text"><td></td><td colspan="7">@line.Description</td></tr>
}
else
{
<tr>
<td class="mono">@line.Code</td>
<td>@line.Description</td>
<td>@line.Unit</td>
<td class="num">@line.Quantity</td>
<td class="num">@line.Price</td>
<td class="num">@line.Discount</td>
<td class="num">@line.Tax</td>
<td class="num">@line.Amount</td>
</tr>
}
}
</tbody>
</table>
@foreach (var note in _model.Notes)
{
<p class="kh-print-note">@note</p>
}
<div class="kh-print-sums">
<div>
@if (_model.Summary is { } summary)
{
@Table(summary)
}
@if (_model.Installments is { } installments)
{
@Table(installments)
}
</div>
<div class="kh-print-totals">
@foreach (var row in _model.Totals)
{
<span class="@(row.Strong ? "big" : null)">@row.Label</span>
<span class="@(row.Strong ? "big num" : "num")">@row.Value</span>
}
</div>
</div>
@if (_model.Transport.Count > 0)
{
<dl class="kh-print-transport">
@foreach (var field in _model.Transport)
{
<div><dt>@field.Label</dt><dd>@field.Value</dd></div>
}
</dl>
<div class="kh-print-signatures">
@foreach (var signature in _model.Signatures)
{
<div>@signature</div>
}
</div>
}
@if (_model.Footer is { } footer)
{
<p class="kh-sheet-foot">@footer</p>
}
</KhPrintPreview>
}
@code {
private SalesSection? _section;
private DocumentPrintModel? _model;
private bool _missing;
private bool _saving;
/// <summary>The radar segment, such as <c>fatture</c>.</summary>
[Parameter]
public string? Segment { get; set; }
/// <summary>The document.</summary>
[Parameter]
public long Id { get; set; }
private string Heading => _model is null ? T["Sales.Print.Title"] : T.Format("Sales.Print.Heading", _model.Title, _model.Number);
private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.BasePath + "/" + _section.Segment + "/" + Id.ToString(T.Culture);
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
_section = SalesScreens.Find(Segment);
if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
_missing = true;
return;
}
try
{
_model = await Prints.BuildAsync(actor, company, _section.Family, Id);
}
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
{
_missing = true;
}
}
private string? PdfUrl(bool download) =>
_section is null ? null : FileEndpoints.Generated(DocumentPrintService.EntityOf(_section.Family), Id, DocumentPdfGenerator.GeneratorCode, download);
private async Task SaveAsync()
{
if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_saving = true;
try
{
var saved = await Generation.GenerateAsync(actor, company, DocumentPrintService.EntityOf(_section.Family), Id, DocumentPdfGenerator.GeneratorCode);
await Engine.MarkPrintedAsync(actor, company, _section.Family, Id);
Toasts.Show(ToastKind.Success, T["Ui.Attachments.GeneratedToast"], saved.FileName);
}
catch (Exception ex) when (ex is AccessDeniedException or ValidationFailedException or KeyNotFoundException)
{
Toasts.Show(ToastKind.Error, T["Ui.Print.SaveAttachment"], T["Ui.Attachments.Denied"]);
}
finally
{
_saving = false;
}
}
private static RenderFragment Table(PrintTable table) => __builder =>
{
<div class="kh-print-block">
<div class="kh-print-block-title">@table.Title</div>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < table.Headers.Count; i++)
{
<th class="@(table.Numeric[i] ? "num" : null)">@table.Headers[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var row in table.Rows)
{
<tr>
@for (var i = 0; i < row.Count; i++)
{
<td class="@(table.Numeric[i] ? "num" : null)">@row[i]</td>
}
</tr>
}
</tbody>
</table>
</div>
};
}
@@ -0,0 +1,120 @@
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Web.Tables;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>
/// The choices of the document screens, read once per page from the company tables: conditions, transport, the VAT
/// codes and units of the lines. Values are ids, except the currencies (by code); texts are <c>code · description</c>.
/// </summary>
public sealed class DocumentLookups
{
/// <summary>No choices, before loading.</summary>
public static DocumentLookups Empty { get; } = new();
/// <summary>Payment terms.</summary>
public IReadOnlyList<KhOption<string>> PaymentTerms { get; private init; } = [];
/// <summary>Payment methods.</summary>
public IReadOnlyList<KhOption<string>> PaymentMethods { get; private init; } = [];
/// <summary>Price lists.</summary>
public IReadOnlyList<KhOption<string>> PriceLists { get; private init; } = [];
/// <summary>Salespeople.</summary>
public IReadOnlyList<KhOption<string>> Salespeople { get; private init; } = [];
/// <summary>The company bank accounts.</summary>
public IReadOnlyList<KhOption<string>> BankAccounts { get; private init; } = [];
/// <summary>Warehouses.</summary>
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
/// <summary>Carriers.</summary>
public IReadOnlyList<KhOption<string>> Carriers { get; private init; } = [];
/// <summary>Shipping terms (porto).</summary>
public IReadOnlyList<KhOption<string>> ShippingTerms { get; private init; } = [];
/// <summary>Reasons of transport.</summary>
public IReadOnlyList<KhOption<string>> TransportReasons { get; private init; } = [];
/// <summary>Appearances of the goods.</summary>
public IReadOnlyList<KhOption<string>> GoodsAppearances { get; private init; } = [];
/// <summary>VAT codes.</summary>
public IReadOnlyList<KhOption<string>> TaxCodes { get; private init; } = [];
/// <summary>Units of measure.</summary>
public IReadOnlyList<KhOption<string>> Units { get; private init; } = [];
/// <summary>Currencies, by code.</summary>
public IReadOnlyList<KhOption<string>> Currencies { get; private init; } = [];
/// <summary>Reads the choices.</summary>
/// <param name="tables">The tables.</param>
/// <param name="actor">Who reads.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The choices.</returns>
public static async Task<DocumentLookups> ReadAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
{
PaymentTerms = await ReadAsync<PaymentTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
PaymentMethods = await ReadAsync<PaymentMethod>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
PriceLists = await ReadAsync<PriceList>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Salespeople = await ReadAsync<Salesperson>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
BankAccounts = await ReadAsync<BankAccount>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Carriers = await ReadAsync<Carrier>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
ShippingTerms = await ReadAsync<ShippingTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TransportReasons = await ReadAsync<TransportReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
GoodsAppearances = await ReadAsync<GoodsAppearance>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TaxCodes = await ReadAsync<TaxCode>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Units = await ReadAsync<UnitOfMeasure>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Currencies = await ReadAsync<Currency>(tables, actor, company, true, cancellationToken).ConfigureAwait(false),
};
/// <summary>The code of a choice (the part before <c> · </c>).</summary>
/// <param name="options">The choices.</param>
/// <param name="id">The id.</param>
/// <returns>The code, or <see langword="null"/>.</returns>
public static string? CodeOf(IReadOnlyList<KhOption<string>> options, long? id)
{
ArgumentNullException.ThrowIfNull(options);
if (id is null)
{
return null;
}
var value = id.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
var text = options.FirstOrDefault(o => o.Value == value)?.Text;
return text is null ? null : text.Split(" · ", 2)[0];
}
/// <summary>The id of the choice with a code, ignoring case.</summary>
/// <param name="options">The choices.</param>
/// <param name="code">The code typed.</param>
/// <returns>The id, or <see langword="null"/>.</returns>
public static long? IdOf(IReadOnlyList<KhOption<string>> options, string? code)
{
ArgumentNullException.ThrowIfNull(options);
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
var wanted = code.Trim();
var match = options.FirstOrDefault(o => string.Equals(o.Text.Split(" · ", 2)[0], wanted, StringComparison.OrdinalIgnoreCase));
return match is null ? null : long.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture);
}
private static async Task<IReadOnlyList<KhOption<string>>> ReadAsync<T>(TableService tables, Actor actor, string company, bool byCode,
CancellationToken cancellationToken)
{
var choices = await TableValues.LookupAsync(tables, typeof(T), byCode, actor, company, cancellationToken).ConfigureAwait(false);
return [.. choices.Select(c => new KhOption<string>(c.Value, c.Text))];
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Khaemhat.Core.Documents;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>A radar of the sales menu and the document types it holds.</summary>
/// <param name="Segment">The path segment, such as <c>fatture</c>.</param>
/// <param name="Family">The family of the documents.</param>
/// <param name="Kinds">The kinds shown.</param>
/// <param name="NewTypes">The document types a user can create from the radar, the first being the usual one.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Key">The key of the texts under <c>Sales.Sections</c>.</param>
public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key);
/// <summary>
/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under
/// <c>/vendite</c>, the record of a document under it, and the deferred invoicing.
/// </summary>
public static class SalesScreens
{
/// <summary>The menu area.</summary>
public const string BasePath = "vendite";
/// <summary>The deferred invoicing of the delivery notes.</summary>
public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita";
/// <summary>The tab of the transport data, after Testata, for delivery notes and accompanying invoices.</summary>
public const string TransportTab = "trasporto";
/// <summary>The radars, in the order of the menu.</summary>
public static IReadOnlyList<SalesSection> Sections { get; } =
[
new("preventivi", DocumentFamily.SaleQuotation, [DocumentKind.Quotation], ["PRE"], "file", "Quotes"),
new("ordini", DocumentFamily.SaleOrder, [DocumentKind.SalesOrder], ["OC"], "file-check", "Orders"),
new("ddt", DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], ["DDT"], "truck", "DeliveryNotes"),
new("fatture", DocumentFamily.SaleDocument,
[DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.Fee, DocumentKind.ProForma],
["FI", "FA", "FD", "FACC", "PAR", "PF"], "euro", "Invoices"),
new("note-credito", DocumentFamily.SaleDocument, [DocumentKind.CreditNote, DocumentKind.DebitNote], ["NC", "ND"], "undo", "CreditNotes"),
];
/// <summary>The radar of a path segment.</summary>
/// <param name="segment">The segment.</param>
/// <returns>The radar, or <see langword="null"/>.</returns>
public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase));
/// <summary>The radar that holds a kind of document.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The radar, or <see langword="null"/> for a kind outside sales.</returns>
public static SalesSection? Of(DocumentKind kind) => Sections.FirstOrDefault(s => s.Kinds.Contains(kind));
/// <summary>The address of a radar.</summary>
/// <param name="section">The radar.</param>
/// <returns>The address.</returns>
public static string RadarUrl(SalesSection section)
{
ArgumentNullException.ThrowIfNull(section);
return BasePath + "/" + section.Segment;
}
/// <summary>The address of a document.</summary>
/// <param name="kind">The kind.</param>
/// <param name="id">The document.</param>
/// <returns>The address, or <see langword="null"/> for a kind outside sales.</returns>
public static string? RecordUrl(DocumentKind kind, long id) =>
Of(kind) is { } section ? RadarUrl(section) + "/" + id.ToString(CultureInfo.InvariantCulture) : null;
/// <summary>The address of a new document of a type.</summary>
/// <param name="section">The radar.</param>
/// <param name="typeCode">The document type.</param>
/// <returns>The address.</returns>
public static string NewUrl(SalesSection section, string typeCode) => RadarUrl(section) + "/nuovo?tipo=" + Uri.EscapeDataString(typeCode);
/// <summary>The print preview of a document.</summary>
/// <param name="section">The radar.</param>
/// <param name="id">The document.</param>
/// <returns>The relative URL.</returns>
public static string PrintUrl(SalesSection section, long id)
{
ArgumentNullException.ThrowIfNull(section);
return RadarUrl(section) + "/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/stampa";
}
/// <summary>The name of a kind, such as <c>Fattura immediata</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="kind">The kind.</param>
/// <returns>The name.</returns>
public static string KindName(ITexts texts, DocumentKind kind)
{
ArgumentNullException.ThrowIfNull(texts);
return texts["Sales.Kinds." + kind];
}
/// <summary>The label and tone of a state; a quotation shows its outcome (accepted, refused, expired).</summary>
/// <param name="texts">The texts.</param>
/// <param name="kind">The kind.</param>
/// <param name="status">The state.</param>
/// <param name="validUntil">Until when a quotation is valid.</param>
/// <param name="today">Today.</param>
/// <returns>The label and the tone.</returns>
public static (string Text, KhTone Tone) State(ITexts texts, DocumentKind kind, DocumentStatus status, DateOnly? validUntil, DateOnly today)
{
ArgumentNullException.ThrowIfNull(texts);
if (kind == DocumentKind.Quotation)
{
switch (status)
{
case DocumentStatus.Fulfilled or DocumentStatus.PartiallyFulfilled:
return (texts["Sales.Outcomes.Accepted"], KhTone.Ok);
case DocumentStatus.Closed:
return (texts["Sales.Outcomes.Refused"], KhTone.Error);
case DocumentStatus.Confirmed when validUntil is { } until && until < today:
return (texts["Sales.Outcomes.Expired"], KhTone.Warning);
case DocumentStatus.Confirmed:
return (texts["Sales.Outcomes.Sent"], KhTone.Info);
}
}
var tone = status switch
{
DocumentStatus.Draft => KhTone.Neutral,
DocumentStatus.Confirmed or DocumentStatus.Issued => KhTone.Info,
DocumentStatus.PartiallyFulfilled => KhTone.Warning,
DocumentStatus.Fulfilled or DocumentStatus.SdiDelivered => KhTone.Ok,
DocumentStatus.Cancelled or DocumentStatus.SdiRejected or DocumentStatus.SdiNotDelivered => KhTone.Error,
_ => KhTone.Accent,
};
return (texts["Sales.States." + status], tone);
}
/// <summary>The choices of an enumeration, labelled from <c>Sales.{group}.{value}</c>.</summary>
/// <typeparam name="TEnum">The enumeration.</typeparam>
/// <param name="texts">The texts.</param>
/// <param name="group">The group of texts.</param>
/// <returns>The choices.</returns>
public static IReadOnlyList<KhOption<string>> Choices<TEnum>(ITexts texts, string group)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<string>(v.ToString(), texts["Sales." + group + "." + v]))];
}
}
@@ -176,6 +176,8 @@ internal static class KhaemhatServices
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
services.AddSingleton<DemoSalesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
@@ -226,6 +228,23 @@ internal static class KhaemhatServices
services.AddSingleton<IFileScanner, NoOpFileScanner>();
services.AddSingleton<IFileStore, VolumeFileStore>();
services.AddSingleton<AttachmentService>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentPrintService>();
services.AddSingleton<IFileGenerator, Khaemhat.Application.Documents.DocumentPdfGenerator>();
// Mail (#52): the SMTP client written in house, the queue that sends in the background, documents by e-mail.
services.AddSingleton(new Khaemhat.Infrastructure.Mail.SmtpSettings(
options.SmtpHost, options.SmtpPortNumber, options.SmtpUser, options.SmtpPassword, options.SmtpFrom,
options.SmtpSecurityMode switch
{
SmtpSecurity.Ssl => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.Ssl,
SmtpSecurity.None => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.None,
_ => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.StartTls,
}));
services.AddSingleton<Khaemhat.Infrastructure.Mail.IMailSender, Khaemhat.Infrastructure.Mail.SmtpMailSender>();
services.AddSingleton<Khaemhat.Infrastructure.Mail.MailQueue>();
services.AddSingleton<Khaemhat.Infrastructure.Mail.IMailQueue>(sp => sp.GetRequiredService<Khaemhat.Infrastructure.Mail.MailQueue>());
services.AddHostedService(sp => sp.GetRequiredService<Khaemhat.Infrastructure.Mail.MailQueue>());
services.AddSingleton<Khaemhat.Application.Documents.DocumentMailService>();
services.AddSingleton<IFileGenerator, DemoPdfGenerator>();
services.AddSingleton<IFileGenerator, DemoCsvGenerator>();
services.AddSingleton<IFileGenerator, DemoXlsxGenerator>();
+3
View File
@@ -129,6 +129,9 @@ public static class SeedCommand
{
Print(code, "dati dimostrativi, scala " + options.Scale.ToString(CultureInfo.InvariantCulture),
await runner.RunAsync(code, SeedKind.Demo, options.Scale).ConfigureAwait(false));
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
@@ -14,6 +14,12 @@
"party": {
"required": "Indica il cliente o il fornitore."
},
"mail": {
"not-configured": "L'invio delle e-mail non è configurato: chiedi all'amministratore di impostare il server SMTP (KHAEMHAT_SMTP_HOST e KHAEMHAT_SMTP_FROM).",
"recipient-invalid": "Indica uno o più indirizzi e-mail validi, separati da virgola.",
"subject-required": "Scrivi l'oggetto del messaggio.",
"queue-full": "Troppi messaggi in attesa di invio: riprova tra qualche minuto."
},
"date": {
"required": "Indica la data del documento.",
"numbered": "La data di un documento numerato non si può cambiare."
@@ -28,7 +34,8 @@
"below-fulfilled": "La quantità non può scendere sotto quella già evasa.",
"fulfilled-removed": "Una riga già evasa da altri documenti non si può togliere.",
"source-invalid": "La riga d'origine non esiste o non può essere evasa da questo documento.",
"discount-invalid": "Lo sconto si scrive come percentuali separate da +, ad esempio 10+5."
"discount-invalid": "Lo sconto si scrive come percentuali separate da +, ad esempio 10+5.",
"tax-required": "Indica il codice IVA della riga: serve per i registri IVA e la fattura elettronica."
},
"cancel": {
"reason-required": "Per annullare una fattura indica il motivo.",
@@ -11,6 +11,7 @@
},
"files": {
"generators": {
"document_pdf": "Stampa del documento in PDF",
"demo_pdf": "Documento di prova in PDF",
"demo_csv": "Righe in CSV (per Excel)",
"demo_xlsx": "Righe in Excel (XLSX)"
@@ -101,6 +101,9 @@
"Attachments": "Allegati",
"Birth": "Dati di nascita"
},
"Hints": {
"ExcludedMonths": "Le scadenze che cadono in un mese escluso passano a questo giorno del mese successivo (10 se vuoto)."
},
"Fields": {
"Code": "Codice",
"PreviousCode": "Codice precedente",
@@ -148,6 +151,9 @@
"WarehouseId": "Deposito",
"CreditLimit": "Fido",
"Blocked": "Ordini bloccati",
"ExcludedMonth1": "Primo mese escluso",
"ExcludedMonth2": "Secondo mese escluso",
"ExcludedMonthsDay": "Scadenza spostata al giorno",
"GroupDeliveryNotes": "Raggruppa i DDT in fattura",
"InvoiceDay": "Giorno di fatturazione",
"SendDocuments": "Invio dei documenti",
@@ -0,0 +1,93 @@
{
"Print": {
"Draft": "Bozza",
"Of": "del {0}",
"Customer": "Spett.le",
"Supplier": "Fornitore",
"NoParty": "Intestatario da indicare",
"VatNumber": "P. IVA {0}",
"TaxCode": "C.F. {0}",
"Rea": "REA {0} {1}",
"ShareCapital": "Cap. soc. {0} i.v.",
"Phone": "Tel. {0}",
"Pec": "PEC {0}",
"Watermarks": {
"Draft": "Bozza, non valida",
"Cancelled": "Annullato",
"Demo": "Dato dimostrativo"
},
"Fields": {
"Payment": "Pagamento",
"Bank": "Banca d'appoggio",
"Reference": "Vs. riferimento",
"ValidUntil": "Valido fino al",
"Delivery": "Consegna prevista",
"Salesperson": "Agente",
"Revision": "Revisione",
"Cig": "CIG",
"Cup": "CUP",
"Related": "Documento collegato"
},
"Lines": {
"Code": "Codice",
"Description": "Descrizione",
"Unit": "UM",
"Quantity": "Quantità",
"Price": "Prezzo",
"Discount": "Sconti",
"Tax": "IVA",
"Amount": "Importo"
},
"Summary": {
"Title": "Riepilogo IVA",
"Code": "Codice IVA",
"Rate": "Aliquota",
"Taxable": "Imponibile",
"Tax": "Imposta"
},
"Installments": {
"Title": "Scadenze",
"Number": "N.",
"Due": "Scadenza",
"Method": "Modalità",
"Amount": "Importo"
},
"Totals": {
"Goods": "Totale merce",
"FooterDiscount": "Sconto di piede",
"Expenses": "Spese",
"SocialSecurity": "Cassa previdenza",
"Taxable": "Imponibile",
"Tax": "IVA",
"StampDuty": "Bollo",
"Total": "Totale documento",
"Withholding": "Ritenuta d'acconto",
"Enasarco": "Enasarco",
"SplitPayment": "IVA in scissione dei pagamenti",
"Net": "Netto a pagare"
},
"Transport": {
"Reason": "Causale del trasporto",
"By": "Trasporto a cura del",
"Carrier": "Vettore",
"Port": "Porto",
"Appearance": "Aspetto dei beni",
"Packages": "Colli",
"GrossWeight": "Peso lordo (kg)",
"NetWeight": "Peso netto (kg)",
"Start": "Inizio trasporto",
"SignatureDriver": "Firma del conducente",
"SignatureCarrier": "Firma del vettore",
"SignatureRecipient": "Firma del destinatario"
},
"Mail": {
"Subject": "{{Documento}} n. {{Numero}} del {{Data}} · {{Azienda}}",
"Body": "Gentile {{Cliente}},\n\nin allegato trovate il documento {{Documento}} n. {{Numero}} del {{Data}}, per un totale di {{Totale}}.\n\nRestiamo a disposizione per qualsiasi chiarimento.\n\nCordiali saluti,\n{{Azienda}}"
},
"Notes": {
"SplitPayment": "Operazione con scissione dei pagamenti (art. 17-ter del DPR 633/1972): l'IVA è versata dal cliente all'Erario.",
"ProForma": "Documento pro forma, privo di valore fiscale: la fattura sarà emessa al pagamento.",
"Deferred": "Fattura differita (art. 21, comma 4, del DPR 633/1972) relativa ai documenti di trasporto indicati."
}
}
}
+309
View File
@@ -0,0 +1,309 @@
{
"Sales": {
"NoCompany": "Scegli un'azienda per vedere i documenti di vendita.",
"NotFound": "Documento non trovato",
"BackToList": "Torna all'elenco",
"DraftNumber": "Bozza",
"NumberOnConfirm": "Assegnato alla conferma",
"NoParty": "Cliente da scegliere",
"Demo": "Dato dimostrativo",
"NewDocument": "Nuovo documento",
"Sections": {
"Quotes": { "Title": "Preventivi", "New": "Nuovo preventivo" },
"Orders": { "Title": "Ordini clienti", "New": "Nuovo ordine" },
"DeliveryNotes": { "Title": "Documenti di trasporto", "New": "Nuovo DDT" },
"Invoices": { "Title": "Fatture di vendita", "New": "Nuova fattura" },
"CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" }
},
"Kinds": {
"Quotation": "Preventivo",
"SalesOrder": "Ordine cliente",
"DeliveryNote": "DDT",
"ImmediateInvoice": "Fattura immediata",
"AccompanyingInvoice": "Fattura accompagnatoria",
"DeferredInvoice": "Fattura differita",
"DownPaymentInvoice": "Fattura di acconto",
"CreditNote": "Nota di credito",
"DebitNote": "Nota di debito",
"Fee": "Parcella",
"ProForma": "Pro forma",
"SelfInvoice": "Autofattura",
"PurchaseOrder": "Ordine fornitore",
"PurchaseDeliveryNote": "DDT fornitore",
"PurchaseInvoice": "Fattura fornitore",
"PurchaseCreditNote": "Nota di credito fornitore",
"InventoryEntry": "Movimento di magazzino"
},
"States": {
"Draft": "Bozza",
"Confirmed": "Confermato",
"PartiallyFulfilled": "Evaso in parte",
"Fulfilled": "Evaso",
"Closed": "Chiuso",
"Cancelled": "Annullato",
"Issued": "Emessa",
"SdiGenerated": "XML generato",
"SdiSent": "Inviata allo SdI",
"SdiDelivered": "Consegnata",
"SdiRejected": "Scartata",
"SdiNotDelivered": "Non consegnata"
},
"Outcomes": {
"Sent": "In attesa di risposta",
"Accepted": "Accettato",
"Refused": "Rifiutato",
"Expired": "Scaduto"
},
"LineKinds": {
"Item": "Articolo",
"Free": "Riga libera",
"Description": "Descrizione",
"Expense": "Spese",
"Discount": "Sconto"
},
"Exigibilities": {
"Immediate": "Immediata (I)",
"Deferred": "Differita, IVA per cassa (D)",
"SplitPayment": "Scissione dei pagamenti (S)"
},
"TransportBy": {
"Sender": "Mittente",
"Recipient": "Destinatario",
"Carrier": "Vettore"
},
"Tabs": {
"Transport": "Trasporto"
},
"Head": {
"Vat": "P. IVA",
"TaxCode": "C.F."
},
"Radar": {
"Search": "Cerca per numero, riferimento o cliente",
"All": "Tutti",
"Kind": "Tipo",
"State": "Stato",
"Year": "Anno"
},
"Groups": {
"Document": "Documento",
"Party": "Cliente",
"Conditions": "Condizioni",
"Tax": "Dati fiscali",
"Withholding": "Ritenuta, cassa previdenza, ENASARCO",
"Transport": "Trasporto",
"Goods": "Merce",
"Notes": "Note",
"Cancelled": "Annullamento"
},
"Fields": {
"DocumentTypeId": "Tipo documento",
"DocumentNumber": "Numero",
"DocumentDate": "Data",
"ValidUntil": "Valido fino al",
"DeliveryDate": "Consegna",
"Revision": "Revisione",
"Related": "Rettifica",
"ExternalReference": "Riferimento cliente",
"ExternalDate": "Data riferimento",
"RelatedNumber": "Fattura rettificata",
"RelatedDate": "Data fattura rettificata",
"PartyId": "Cliente",
"SalespersonId": "Agente",
"CurrencyCode": "Valuta",
"PriceListId": "Listino",
"FooterDiscount": "Sconto di piede",
"PricesIncludeTax": "Prezzi IVA compresa",
"PaymentTermId": "Pagamento",
"PaymentMethodId": "Modalità di pagamento",
"BankAccountId": "Banca d'appoggio",
"Exigibility": "Esigibilità IVA",
"SplitPayment": "Split payment",
"StampDutyCharged": "Bollo addebitato al cliente",
"Cig": "CIG",
"Cup": "CUP",
"WithholdingRate": "Ritenuta %",
"WithholdingBasePercent": "Base ritenuta %",
"WithholdingType": "Tipo ritenuta",
"WithholdingReason": "Causale pagamento",
"SocialSecurityFund": "Cassa previdenza",
"SocialSecurityRate": "Cassa %",
"SocialSecurityTaxCodeId": "IVA sulla cassa",
"SocialSecurityWithheld": "Cassa soggetta a ritenuta",
"EnasarcoRate": "ENASARCO %",
"TransportReasonId": "Causale del trasporto",
"TransportBy": "Trasporto a cura del",
"CarrierId": "Vettore",
"ShippingTermId": "Porto",
"TransportStartDate": "Inizio trasporto",
"TransportStartTime": "Ora",
"WarehouseId": "Magazzino",
"GoodsAppearanceId": "Aspetto dei beni",
"Packages": "Colli",
"GrossWeight": "Peso lordo (kg)",
"NetWeight": "Peso netto (kg)",
"Notes": "Note",
"CancelReason": "Motivo dell'annullamento",
"TaxableAmount": "Imponibile",
"TaxAmount": "IVA",
"TotalAmount": "Totale",
"Status": "Stato",
"Number": "Progressivo",
"Printed": "Stampato",
"Sent": "Inviato"
},
"Hints": {
"PartyFirst": "Scegli prima il cliente: il documento ne riprende listino, pagamento, agente, banca e dati fiscali.",
"PartyDefaults": "Cambiando cliente il documento riprende le sue condizioni; puoi poi modificarle qui.",
"ExternalReference": "Ad esempio il numero d'ordine del cliente.",
"Related": "La fattura che questa nota corregge, riportata nel file per lo SdI.",
"Withholding": "Ritenuta, cassa ed ENASARCO si calcolano sulle righe non escluse; si tolgono dal netto a pagare, non dal totale.",
"Transport": "Colli e pesi vanno nella stampa del DDT; il magazzino si muove con la conferma (M6).",
"Installments": "Le scadenze nascono dalla condizione di pagamento, sul netto a pagare. Lo scadenzario arriva con M8.",
"InstallmentsForecast": "Per preventivi, ordini e pro forma le scadenze sono una previsione: quelle vere nascono con la fattura.",
"Notes": "Le note compaiono nella stampa, sotto le righe.",
"Kinds": {
"Quotation": "Offerta al cliente, con validità e revisioni.",
"SalesOrder": "Impegno del cliente, evaso da DDT e fatture.",
"DeliveryNote": "Accompagna la merce; si fattura con la differita.",
"ImmediateInvoice": "TD01, emessa insieme alla cessione o prestazione.",
"AccompanyingInvoice": "TD01 che accompagna anche la merce, con i dati del trasporto.",
"DeferredInvoice": "TD24, raccoglie i DDT del mese.",
"DownPaymentInvoice": "TD02, per un acconto su un ordine.",
"CreditNote": "TD04, storna in tutto o in parte una fattura.",
"DebitNote": "TD05, aggiunge importi a una fattura.",
"Fee": "TD06, per i professionisti, con ritenuta e cassa.",
"ProForma": "Non fiscale: anticipa la fattura al cliente."
}
},
"Lines": {
"Title": "Righe documento",
"Item": "Articolo",
"Description": "Descrizione",
"Unit": "UM",
"Quantity": "Quantità",
"Price": "Prezzo",
"Discount": "Sconti",
"Tax": "IVA",
"Delivery": "Consegna",
"Fulfilled": "Evasa",
"Residual": "Da evadere",
"Amount": "Importo",
"ItemRadar": "Cerca articolo",
"ItemMissing": "L'articolo non esiste più.",
"ErrorAt": "Riga {0}: {1}"
},
"Totals": {
"Title": "Totali",
"Summary": "Castelletto IVA",
"SummaryEmpty": "Il castelletto si compone mentre scrivi le righe.",
"Installments": "Scadenze",
"InstallmentsEmpty": "Nessuna scadenza: il documento non ha importo da pagare.",
"InstallmentsNoTerm": "Scegli la condizione di pagamento per vedere le scadenze.",
"TaxCode": "Codice IVA",
"Rate": "Aliquota",
"Taxable": "Imponibile",
"Tax": "IVA",
"Total": "Totale documento",
"Net": "Netto a pagare",
"Goods": "Totale merce",
"FooterDiscount": "Sconto di piede",
"Expenses": "Spese",
"SocialSecurity": "Cassa previdenza",
"StampDuty": "Bollo (a carico dell'azienda)",
"StampDutyCharged": "Bollo",
"Withholding": "Ritenuta d'acconto",
"Enasarco": "ENASARCO",
"SplitPayment": "IVA in split payment",
"DueDate": "Scadenza",
"Method": "Modalità",
"Amount": "Importo"
},
"Links": {
"Empty": "Nessun documento collegato.",
"Relation": "Relazione",
"Quantity": "Quantità evasa",
"Source": "Origine",
"Target": "Evaso da",
"Related": "Rettifica"
},
"Actions": {
"Confirm": "Conferma",
"Issue": "Emetti",
"Create": "Crea {0}",
"Duplicate": "Duplica",
"Close": "Chiudi",
"Refuse": "Segna come rifiutato",
"Reopen": "Riapri",
"Cancel": "Annulla documento",
"ChooseParty": "Scegli il cliente",
"AddExpense": "Aggiungi riga spese",
"AddDiscount": "Aggiungi riga sconto"
},
"Confirm": {
"IssueText": "La fattura riceve il numero definitivo e non si potrà più modificare: per correggerla servirà una nota di credito. Procedere?",
"Issued": "Fattura {0} emessa.",
"Confirmed": "Documento {0} confermato."
},
"Cancel": {
"Lead": "Il documento resta in archivio come annullato e non conta più nelle evasioni.",
"LeadInvoice": "Annullare una fattura emessa è un'eccezione (ad esempio mai inviata allo SdI): indica il motivo, che resta nello storico."
},
"Transform": {
"LeadFulfil": "Scegli le righe da evadere: il nuovo documento riprende la quantità ancora da evadere, che puoi ridurre prima di confermarlo.",
"LeadCopy": "Scegli le righe da copiare nel nuovo documento.",
"All": "Tutte le righe",
"Create": "Crea il documento",
"Created": "{0} creato in bozza."
},
"Mail": {
"Title": "Invia per e-mail",
"Lead": "Il PDF del documento viene salvato tra gli allegati come nuova versione e parte in allegato al messaggio.",
"To": "Destinatari",
"ToHint": "Più indirizzi separati da virgola.",
"Subject": "Oggetto",
"Body": "Messaggio",
"Send": "Invia",
"Queued": "Messaggio in coda di invio",
"QueuedDetail": "A {0}: l'esito è nel log, sezione E-mail/PEC."
},
"Print": {
"Title": "Anteprima di stampa",
"Heading": "Anteprima di stampa · {0} {1}"
},
"Deferred": {
"Title": "Fatturazione differita",
"Procedure": "Procedura",
"Steps": {
"Period": "Periodo e cliente",
"PeriodDetail": "I DDT confermati e non ancora fatturati.",
"Choose": "Scelta dei DDT",
"ChooseDetail": "Togli quelli da fatturare più avanti.",
"Generate": "Fatture",
"GenerateDetail": "Una fattura differita (TD24) per cliente o per DDT."
},
"From": "DDT dal",
"To": "DDT al",
"ToRequired": "Indica fino a quale data cercare i DDT.",
"Customer": "Cliente",
"AllCustomers": "Vuoto per i DDT di tutti i clienti.",
"InvoiceDate": "Data delle fatture",
"Grouping": "Raggruppamento",
"PerParty": "Una fattura per cliente",
"PerNote": "Una fattura per DDT",
"Issue": "Emetti subito le fatture (altrimenti restano in bozza)",
"Search": "Cerca i DDT",
"Notes": "DDT da fatturare nel periodo",
"Start": "Indica il periodo e premi Cerca i DDT.",
"None": "Nessun DDT da fatturare nel periodo.",
"Lines": "Righe",
"Invoice": "Fattura",
"InvoiceNumber": "Fattura {0} ({1} DDT)",
"Selected": "{0} DDT · {1}",
"Generate": "Genera fatture",
"Results": "Fatture generate",
"Done": "{0} fatture generate su {1}.",
"Again": "Nuova fatturazione"
}
}
}
+2 -1
View File
@@ -67,7 +67,8 @@
"Orders": "Ordini clienti",
"DeliveryNotes": "DDT",
"Invoices": "Fatture",
"CreditNotes": "Note di credito"
"CreditNotes": "Note di credito",
"DeferredInvoicing": "Fatturazione differita"
},
"Purchases": {
"_": "Acquisti",
+3 -3
View File
@@ -54,15 +54,15 @@ public static class MenuCatalog
]),
new("Shell.Menu.Section.Operations",
[
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", "M4",
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", null,
("Shell.Menu.Parties.Customers", "clienti"), ("Shell.Menu.Parties.Suppliers", "fornitori"), ("Shell.Menu.Parties.Contacts", "contatti"),
("Shell.Menu.Parties.Items", "articoli"), ("Shell.Menu.Parties.PriceLists", "listini"), ("Shell.Menu.Parties.Categories", "categorie")),
Area("Shell.Menu.Crm", "target", "/crm", ModuleCodes.Crm, "crm.lead.read", "M11",
("Shell.Menu.Crm.Dashboard", "cruscotto"), ("Shell.Menu.Crm.Leads", "lead"), ("Shell.Menu.Crm.Pipeline", "pipeline"),
("Shell.Menu.Crm.Agenda", "agenda"), ("Shell.Menu.Crm.Tickets", "ticket"), ("Shell.Menu.Crm.Campaigns", "campagne")),
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", "M5",
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", null,
("Shell.Menu.Sales.Quotes", "preventivi"), ("Shell.Menu.Sales.Orders", "ordini"), ("Shell.Menu.Sales.DeliveryNotes", "ddt"),
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito")),
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito"), ("Shell.Menu.Sales.DeferredInvoicing", "fatturazione-differita")),
Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", "M6",
("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture")),
Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", "M6",
+44
View File
@@ -356,3 +356,47 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.grid tbody tr td.kh-import-cell-err { background: var(--kh-err-soft); }
.grid tbody tr td.kh-import-cell-warn { background: var(--kh-warn-soft); }
@media (max-width: 1100px) { .kh-import { grid-template-columns: 1fr; } }
/* Sales documents (SPEC §11.3, mockups 020-030): the panels under the lines, errors of the lines, the choice of a type. */
.kh-doc-panels { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1.2fr) minmax(0, 1fr); gap: var(--kh-gap); padding: 14px 16px; align-items: start; }
.kh-doc-panels.wide { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
.kh-doc-panels.single { grid-template-columns: minmax(0, 720px); }
.kh-doc-panels .grid.compact td, .kh-doc-panels .grid.compact th { padding: 5px 10px; }
.kh-doc-panels .totals span { white-space: nowrap; }
.kh-doc-panels .kh-total-row td { font-weight: 600; border-top: 1px solid var(--kh-border); }
.kh-doc-callout { margin: 12px 16px 0; align-items: center; }
.kh-doc-callout span { flex: 1; }
.kh-doc-errors { list-style: none; margin: 8px 16px 0; padding: 8px 12px; border-radius: var(--kh-radius-lg); background: var(--kh-err-soft); font-size: 12.5px; display: grid; gap: 4px; }
.kh-choice-list { display: grid; gap: 8px; }
.kh-choice { display: grid; grid-template-columns: 56px minmax(0, 1fr); grid-template-rows: auto auto; gap: 2px 10px; height: auto; padding: 10px 12px; text-align: left; justify-content: stretch; }
.kh-choice .code { grid-row: span 2; align-self: center; font: 600 12px var(--kh-mono); color: var(--kh-accent); }
.kh-choice .muted { font-weight: 400; }
@media (max-width: 1099px) { .kh-doc-panels, .kh-doc-panels.wide { grid-template-columns: 1fr; } }
/* Print preview of a document (issue #52, mockup 025): the same model as the PDF. */
.kh-print-company { display: flex; gap: 12px; align-items: flex-start; }
.kh-print-logo { max-height: 15mm; max-width: 45mm; object-fit: contain; }
.kh-print-number { font-size: 18pt; font-weight: 700; }
.kh-print-mark { margin-top: 4px; color: #b54708; font-weight: 700; text-transform: uppercase; font-size: 9pt; }
.kh-print-top { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 14px; font-size: 9.5pt; }
.kh-print-fields { display: grid; grid-template-columns: auto 1fr; gap: 3px 12px; margin: 0; align-content: start; }
.kh-print-fields dt { color: #6b7280; }
.kh-print-fields dd { margin: 0; }
.kh-print-party { border: 1px solid #d9dde3; border-radius: 4px; padding: 8px 10px; display: grid; gap: 2px; }
.kh-print-party b { font-size: 11pt; }
.kh-print-text td { color: #6b7280; font-style: italic; }
.kh-print-note { font-size: 9pt; margin: 10px 0 0; }
.kh-print-sums { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); gap: 16px; margin-top: 14px; align-items: start; }
.kh-print-block + .kh-print-block { margin-top: 12px; }
.kh-print-block-title { font-weight: 700; color: #1F5F8B; font-size: 9.5pt; margin-bottom: 4px; }
.kh-print-totals { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; background: #eceff3; padding: 10px 12px; border-radius: 4px; font-size: 9.5pt; }
.kh-print-totals .num { text-align: right; white-space: nowrap; }
.kh-print-totals .big { font-size: 12pt; font-weight: 700; color: #1F5F8B; padding-top: 4px; }
.kh-print-transport { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px 12px; margin: 16px 0 0; font-size: 9pt; }
.kh-print-transport dt { color: #6b7280; font-size: 8pt; }
.kh-print-transport dd { margin: 0; }
.kh-print-signatures { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 16px; font-size: 8pt; color: #6b7280; }
.kh-print-signatures div { border-bottom: 1px solid #9aa1ab; padding-bottom: 28px; }
/* The message of "Invia per e-mail" (issue #52): room for the whole text proposed by the template. */
.kh-mail-form textarea.in { min-height: 190px; }