feat: parties with radar, record, checks, VIES and demo data (#41)
Customers, suppliers, prospects and leads live in one parties archive with a kind and a subject type (ADR 0029). A customer that also supplies carries is_also_supplier, so it shows in both radars with one code. - Three radars (/anagrafiche/clienti, /fornitori, /contatti) with search, quick filters and bulk disable/enable; the record has eight tabs (main data, addresses, contacts, terms, fiscal and SDI, banks, notes and attachments, history) on the MasterDataPage base. - PartyService saves the whole record in one transaction, checks it with the fiscal pack (VAT number, tax code, recipient code, country), treats a duplicate VAT number or a consumer without tax code as warnings, fills the default recipient code, runs VIES after commit for EU companies, and converts prospects/leads (new customer code, old one kept as previous_code) and suppliers (become customers that also supply). - Delete falls back to disable when the party is referenced. - DemoPartiesSeeder adds 3 salespeople and 21 parties with fictitious but formally valid identifiers; SeedAsync now runs demo seeders when asked. - Test host accepts service overrides so VIES can be stubbed. Docs: ADR 0029, wiki Anagrafiche and demo data pages, regenerated data model, CHANGELOG and STATUS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a9eda510f2
commit
3401271483
28 files changed
+4600
-85
No files matched your search
@@ -0,0 +1,979 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Http;
|
||||
|
||||
namespace Khaemhat.Application.Parties;
|
||||
|
||||
/// <summary>A party with every detail: what the record page shows and saves in one go.</summary>
|
||||
public sealed class PartyRecord
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public Party Party { get; set; } = new();
|
||||
|
||||
/// <summary>The sales terms (customers).</summary>
|
||||
public PartySalesTerms Sales { get; set; } = new();
|
||||
|
||||
/// <summary>The purchase terms (suppliers).</summary>
|
||||
public PartyPurchaseTerms Purchase { get; set; } = new();
|
||||
|
||||
/// <summary>The fiscal data.</summary>
|
||||
public PartyFiscal Fiscal { get; set; } = new();
|
||||
|
||||
/// <summary>The other addresses.</summary>
|
||||
public List<PartyAddress> Addresses { get; set; } = [];
|
||||
|
||||
/// <summary>The contact people.</summary>
|
||||
public List<PartyContact> Contacts { get; set; } = [];
|
||||
|
||||
/// <summary>The bank accounts.</summary>
|
||||
public List<PartyBankAccount> BankAccounts { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Which parties a radar shows (menu <i>Anagrafiche</i>).</summary>
|
||||
public enum PartyArchive
|
||||
{
|
||||
/// <summary>Customers (also those that are suppliers).</summary>
|
||||
Customers = 0,
|
||||
|
||||
/// <summary>Suppliers (also customers that are suppliers).</summary>
|
||||
Suppliers = 1,
|
||||
|
||||
/// <summary>Prospects and leads.</summary>
|
||||
Contacts = 2,
|
||||
}
|
||||
|
||||
/// <summary>A row of the radar of the parties (mockup 012).</summary>
|
||||
/// <param name="Id">The id.</param>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Kind">What the party is.</param>
|
||||
/// <param name="IsAlsoSupplier">A customer that is also a supplier.</param>
|
||||
/// <param name="SubjectType">The kind of subject.</param>
|
||||
/// <param name="VatNumber">The VAT number.</param>
|
||||
/// <param name="TaxCode">The tax code.</param>
|
||||
/// <param name="City">The city.</param>
|
||||
/// <param name="Province">The province.</param>
|
||||
/// <param name="CountryCode">The country.</param>
|
||||
/// <param name="SalespersonId">The salesperson.</param>
|
||||
/// <param name="CategoryId">The category.</param>
|
||||
/// <param name="Disabled">Disabled.</param>
|
||||
public sealed record PartyRow(
|
||||
long Id, string Code, string Name, PartyKind Kind, bool IsAlsoSupplier, SubjectType SubjectType, string? VatNumber, string? TaxCode, string? City,
|
||||
string? Province, string CountryCode, long? SalespersonId, long? CategoryId, bool Disabled)
|
||||
{
|
||||
/// <summary>The terms of the row, filled for the page shown.</summary>
|
||||
public PartyRowTerms? Terms { get; init; }
|
||||
|
||||
/// <summary>VAT number or, without one, tax code (column <i>P.IVA / C.F.</i>).</summary>
|
||||
public string? Identifier => VatNumber ?? TaxCode;
|
||||
}
|
||||
|
||||
/// <summary>The terms shown on a radar row.</summary>
|
||||
/// <param name="PaymentTermId">The payment terms.</param>
|
||||
/// <param name="PriceListId">The price list.</param>
|
||||
/// <param name="Blocked">Orders blocked.</param>
|
||||
/// <param name="SplitPayment">Split payment.</param>
|
||||
public sealed record PartyRowTerms(long? PaymentTermId, long? PriceListId, bool Blocked, bool SplitPayment);
|
||||
|
||||
/// <summary>What deleting a party did.</summary>
|
||||
public enum PartyDeleteOutcome
|
||||
{
|
||||
/// <summary>The party is gone.</summary>
|
||||
Deleted = 0,
|
||||
|
||||
/// <summary>The party is used by documents: it was disabled instead.</summary>
|
||||
Disabled = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The parties (SPEC §11.2, issue #41, ADR 0029): radar, read and save of a party with its details in one transaction,
|
||||
/// automatic codes by kind, the checks of the fiscal pack, the VIES check of EU numbers, conversion of leads and prospects
|
||||
/// into customers, delete or disable.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>parties.party.read</c>, <c>write</c>, <c>delete</c>.</remarks>
|
||||
public sealed class PartyService
|
||||
{
|
||||
/// <summary>Permission to see the parties.</summary>
|
||||
public const string ReadPermission = "parties.party.read";
|
||||
|
||||
/// <summary>Permission to create and change the parties.</summary>
|
||||
public const string WritePermission = "parties.party.write";
|
||||
|
||||
/// <summary>Permission to delete the parties.</summary>
|
||||
public const string DeletePermission = "parties.party.delete";
|
||||
|
||||
/// <summary>Error: the name is missing.</summary>
|
||||
public const string NameRequired = "parties.name.required";
|
||||
|
||||
/// <summary>Error: the VAT number is required for this kind of subject.</summary>
|
||||
public const string VatNumberRequired = "parties.vat-number.required";
|
||||
|
||||
/// <summary>Error: a public administration needs a VAT number or a tax code.</summary>
|
||||
public const string IdentifierRequired = "parties.identifier.required";
|
||||
|
||||
/// <summary>Error: the tax code is not valid.</summary>
|
||||
public const string TaxCodeInvalid = "parties.tax-code.invalid";
|
||||
|
||||
/// <summary>Warning: a private customer without tax code.</summary>
|
||||
public const string TaxCodeMissing = "parties.tax-code.missing";
|
||||
|
||||
/// <summary>Error: another party has the code.</summary>
|
||||
public const string CodeDuplicate = "parties.code.duplicate";
|
||||
|
||||
/// <summary>Error: the country is not in the table of the countries.</summary>
|
||||
public const string CountryUnknown = "parties.country.unknown";
|
||||
|
||||
/// <summary>Error: an EU subject needs a member state other than the company's.</summary>
|
||||
public const string CountryNotEu = "parties.country.not-eu";
|
||||
|
||||
/// <summary>Error: a domestic subject needs the company's country.</summary>
|
||||
public const string CountryNotDomestic = "parties.country.not-domestic";
|
||||
|
||||
/// <summary>Warning: another party has the same VAT number.</summary>
|
||||
public const string VatNumberDuplicate = "parties.vat-number.duplicate";
|
||||
|
||||
/// <summary>Error: a declaration of intent needs number and ceiling.</summary>
|
||||
public const string IntentIncomplete = "parties.intent.incomplete";
|
||||
|
||||
/// <summary>Error: the exigibility is not I, D or S.</summary>
|
||||
public const string ExigibilityInvalid = "parties.exigibility.invalid";
|
||||
|
||||
/// <summary>Error: the day of the month is not 1-31.</summary>
|
||||
public const string DayRange = "parties.day.range";
|
||||
|
||||
/// <summary>Error: a value cannot be negative.</summary>
|
||||
public const string NotNegative = "parties.value.negative";
|
||||
|
||||
/// <summary>Error: an address or contact without name, a bank account without IBAN.</summary>
|
||||
public const string DetailRequired = "parties.detail.required";
|
||||
|
||||
/// <summary>Error: the party is not a lead or prospect, nor a supplier (conversion).</summary>
|
||||
public const string AlreadyCustomer = "parties.convert.already-customer";
|
||||
|
||||
/// <summary>Error: the party changed or was deleted meanwhile.</summary>
|
||||
public const string NotFound = "parties.not-found";
|
||||
|
||||
/// <summary>The entity name of the attachments and the history.</summary>
|
||||
public const string Entity = "parties.party";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly CompanyFiscalContext _fiscal;
|
||||
private readonly CodeRuleService _codes;
|
||||
private readonly AutoFillService _autoFill;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="codes">The automatic codes.</param>
|
||||
/// <param name="autoFill">The automatic filling options and the VIES check.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public PartyService(
|
||||
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, CodeRuleService codes, AutoFillService autoFill,
|
||||
TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(codes);
|
||||
ArgumentNullException.ThrowIfNull(autoFill);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_fiscal = fiscal;
|
||||
_codes = codes;
|
||||
_autoFill = autoFill;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The fields of the radar: search on code, name, VAT number, tax code and city.</summary>
|
||||
public static ListFields<Party> Fields { get; } = new ListFields<Party>()
|
||||
.Add("code", p => p.Code, searchable: true)
|
||||
.Add("name", p => p.Name, searchable: true)
|
||||
.Add("vatNumber", p => p.VatNumber, searchable: true)
|
||||
.Add("taxCode", p => p.TaxCode, searchable: true)
|
||||
.Add("city", p => p.City, searchable: true)
|
||||
.Add("province", p => p.Province)
|
||||
.Add("country", p => p.CountryCode)
|
||||
.Add("subjectType", p => p.SubjectType)
|
||||
.Add("kind", p => p.Kind)
|
||||
.Add("salesperson", p => p.SalespersonId)
|
||||
.Add("category", p => p.CategoryId)
|
||||
.Add("disabled", p => p.Disabled)
|
||||
.OrderByDefault(new ListSort("name"));
|
||||
|
||||
/// <summary>The code archive of a kind of party (ADR 0027).</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>The key of <see cref="CodeRuleService.Definitions"/>.</returns>
|
||||
public static string CodeRuleOf(PartyKind kind) => kind switch
|
||||
{
|
||||
PartyKind.Customer => "customers",
|
||||
PartyKind.Supplier => "suppliers",
|
||||
_ => "leads",
|
||||
};
|
||||
|
||||
/// <summary>The kind of e-invoice recipient of a subject.</summary>
|
||||
/// <param name="subject">The kind of subject.</param>
|
||||
/// <returns>The recipient kind.</returns>
|
||||
public static RecipientKind RecipientOf(SubjectType subject) => subject switch
|
||||
{
|
||||
SubjectType.PublicAdministration => RecipientKind.PublicAdministration,
|
||||
SubjectType.Person => RecipientKind.Consumer,
|
||||
SubjectType.EuCompany or SubjectType.NonEuCompany => RecipientKind.Foreign,
|
||||
_ => RecipientKind.Business,
|
||||
};
|
||||
|
||||
/// <summary>A page of the radar.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="archive">Customers, suppliers or contacts.</param>
|
||||
/// <param name="query">Search, filters, ordering and page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page, with the terms of its rows.</returns>
|
||||
public async Task<ListPage<PartyRow>> ListAsync(Actor actor, string companyCode, PartyArchive archive, ListQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var select = archive switch
|
||||
{
|
||||
PartyArchive.Customers => Query.For<Party>().Where(p => p.Kind == PartyKind.Customer),
|
||||
PartyArchive.Suppliers => Query.For<Party>().Where(p => p.Kind == PartyKind.Supplier || (p.Kind == PartyKind.Customer && p.IsAlsoSupplier)),
|
||||
_ => Query.For<Party>().Where(p => p.Kind == PartyKind.Prospect || p.Kind == PartyKind.Lead),
|
||||
};
|
||||
var page = await uow.Repository<Party, long>().ListAsync(Fields.Apply(select, query), cancellationToken).ConfigureAwait(false);
|
||||
var ids = page.Items.Select(p => p.Id).ToList();
|
||||
var sales = ids.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<PartySalesTerms, long>().ListAsync(Query.For<PartySalesTerms>().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var purchase = ids.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<PartyPurchaseTerms, long>().ListAsync(Query.For<PartyPurchaseTerms>().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var fiscal = ids.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<PartyFiscal, long>().ListAsync(Query.For<PartyFiscal>().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var salesBy = sales.ToDictionary(s => s.PartyId);
|
||||
var purchaseBy = purchase.ToDictionary(s => s.PartyId);
|
||||
var fiscalBy = fiscal.ToDictionary(s => s.PartyId);
|
||||
IReadOnlyList<PartyRow> rows =
|
||||
[
|
||||
.. page.Items.Select(p => RowOf(p) with
|
||||
{
|
||||
Terms = new PartyRowTerms(
|
||||
archive == PartyArchive.Suppliers ? purchaseBy.GetValueOrDefault(p.Id)?.PaymentTermId : salesBy.GetValueOrDefault(p.Id)?.PaymentTermId,
|
||||
salesBy.GetValueOrDefault(p.Id)?.PriceListId,
|
||||
salesBy.GetValueOrDefault(p.Id)?.Blocked ?? false,
|
||||
fiscalBy.GetValueOrDefault(p.Id)?.SplitPayment ?? false),
|
||||
}),
|
||||
];
|
||||
return new ListPage<PartyRow>(rows, page.TotalCount, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
/// <summary>Parties for a hotlink: active ones whose code or name starts with or contains the text.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="archive">Customers, suppliers or contacts.</param>
|
||||
/// <param name="text">The text typed.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Up to 20 rows.</returns>
|
||||
public async Task<IReadOnlyList<PartyRow>> SearchAsync(Actor actor, string companyCode, PartyArchive archive, string? text, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var page = await ListAsync(
|
||||
actor, companyCode, archive,
|
||||
new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return page.Items;
|
||||
}
|
||||
|
||||
/// <summary>A party with every detail.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record, or <see langword="null"/>.</returns>
|
||||
public async Task<PartyRecord?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A new party of a kind, with the values proposed by the company (country, currency, defaults).</summary>
|
||||
/// <param name="actor">Who creates it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record, not saved.</returns>
|
||||
public async Task<PartyRecord> NewAsync(Actor actor, string companyCode, PartyKind kind, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
return new PartyRecord
|
||||
{
|
||||
Party = new Party { Kind = kind, CountryCode = pack.CountryCode, Since = kind is PartyKind.Customer or PartyKind.Supplier ? today : null },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Checks a record without saving it: normalizes it in place and returns errors and warnings.</summary>
|
||||
/// <param name="actor">Who checks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The problems, with fields such as <c>VatNumber</c>, <c>Fiscal.RecipientCode</c> or <c>Addresses.0.Name</c>.</returns>
|
||||
public async Task<IReadOnlyList<TableProblem>> ValidateAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves a party with its details: inserts it when its id is 0 (assigning the code when empty), updates it otherwise.
|
||||
/// An EU VAT number that is new or changed is checked on VIES when the option is on; the outcome is saved.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved record, read back.</returns>
|
||||
/// <exception cref="ValidationFailedException">A rule failed; errors are <c>Field:code</c>.</exception>
|
||||
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the party meanwhile.</exception>
|
||||
public async Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var party = record.Party;
|
||||
long id;
|
||||
PartyRecord? before;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
before = party.Id == 0 ? null : await LoadAsync(uow, party.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]);
|
||||
var problems = (await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||
var codeChanged = before is null || !string.Equals(before.Party.Code, party.Code, StringComparison.Ordinal);
|
||||
var rule = await _codes.RuleAsync(company, CodeRuleOf(party.Kind), cancellationToken).ConfigureAwait(false);
|
||||
if (party.Code.Length > 0 && codeChanged && CodeRuleService.CheckManual(rule, party.Code) is { } manual)
|
||||
{
|
||||
problems.Add(nameof(Party.Code) + ":" + manual);
|
||||
}
|
||||
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(problems);
|
||||
}
|
||||
|
||||
if (party.Code.Length == 0)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (party.SubjectType == SubjectType.EuCompany && party.VatNumber is { Length: > 0 }
|
||||
&& (before is null || before.Party.VatNumber != party.VatNumber || before.Party.CountryCode != party.CountryCode || before.Party.VatCheck == VatCheckStatus.None)
|
||||
&& await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await LoadAsync(read, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Checks the VAT number of an EU party on VIES now (action <i>VIES</i>) and saves the outcome.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The answer of VIES, or <see langword="null"/> when the party has no VAT number of a member state.</returns>
|
||||
public async Task<ViesResult?> CheckVatAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
return await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns a lead or prospect into a customer with a customer code (the old code stays in
|
||||
/// <see cref="Party.PreviousCode"/>), or makes a supplier also a customer (it keeps its code).
|
||||
/// </summary>
|
||||
/// <param name="actor">Who converts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The party.</returns>
|
||||
public async Task<PartyRecord> ConvertToCustomerAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<Party, long>();
|
||||
var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
var before = Clone(party);
|
||||
switch (party.Kind)
|
||||
{
|
||||
case PartyKind.Customer:
|
||||
throw new ValidationFailedException(["Kind:" + AlreadyCustomer]);
|
||||
case PartyKind.Supplier:
|
||||
party.Kind = PartyKind.Customer;
|
||||
party.IsAlsoSupplier = true;
|
||||
break;
|
||||
default:
|
||||
var rule = await _codes.RuleAsync(company, CodeRuleOf(PartyKind.Customer), cancellationToken).ConfigureAwait(false);
|
||||
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
party.PreviousCode = party.Code;
|
||||
party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
|
||||
party.Kind = PartyKind.Customer;
|
||||
party.Since ??= today;
|
||||
break;
|
||||
}
|
||||
|
||||
await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Disables or enables parties (radar action <i>Disabilita</i>).</summary>
|
||||
/// <param name="actor">Who acts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The parties.</param>
|
||||
/// <param name="disabled">Disable or enable.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The parties changed.</returns>
|
||||
public async Task<int> SetDisabledAsync(Actor actor, string companyCode, IEnumerable<long> ids, bool disabled, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<Party, long>();
|
||||
var changed = 0;
|
||||
foreach (var id in ids.Distinct())
|
||||
{
|
||||
if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } party && party.Disabled != disabled)
|
||||
{
|
||||
var before = Clone(party);
|
||||
party.Disabled = disabled;
|
||||
await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Deletes a party never used, or disables it when documents refer to it.</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened.</returns>
|
||||
public async Task<PartyDeleteOutcome> DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var before = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
|
||||
// The details go with the party (cascade); the documents of later milestones refuse the delete.
|
||||
await uow.Repository<Party, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, before.Party, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return PartyDeleteOutcome.Deleted;
|
||||
}
|
||||
catch (DbException)
|
||||
{
|
||||
await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
|
||||
return PartyDeleteOutcome.Disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The history of a party, newest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The changes of the party and of its details.</returns>
|
||||
public async Task<IReadOnlyList<AuditEntry>> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var entries = new List<AuditEntry>();
|
||||
foreach (var entity in new[] { nameof(Party), nameof(PartySalesTerms), nameof(PartyPurchaseTerms), nameof(PartyFiscal) })
|
||||
{
|
||||
entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
|
||||
}
|
||||
|
||||
private static PartyRow RowOf(Party p) =>
|
||||
new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled);
|
||||
|
||||
private static async Task<bool> TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.Code == code), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static async Task<PartyRecord?> LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<Party, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } party)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new PartyRecord
|
||||
{
|
||||
Party = party,
|
||||
Sales = await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false)
|
||||
?? new PartySalesTerms { PartyId = id },
|
||||
Purchase = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(Query.For<PartyPurchaseTerms>().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false)
|
||||
?? new PartyPurchaseTerms { PartyId = id },
|
||||
Fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false)
|
||||
?? new PartyFiscal { PartyId = id },
|
||||
Addresses = [.. (await uow.Repository<PartyAddress, long>().ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Contacts = [.. (await uow.Repository<PartyContact, long>().ListAsync(Query.For<PartyContact>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
BankAccounts = [.. (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<long> WriteAsync(IUnitOfWork uow, PartyRecord record, PartyRecord? before, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var party = record.Party;
|
||||
var parties = uow.Repository<Party, long>();
|
||||
if (before is null)
|
||||
{
|
||||
party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<Party>(uow, AuditAction.Insert, party.Id, null, party, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await parties.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, party.Id, before.Party, party, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var id = party.Id;
|
||||
await UpsertAsync(uow, record.Sales, before?.Sales, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||
await UpsertAsync(uow, record.Purchase, before?.Purchase, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||
await UpsertAsync(uow, record.Fiscal, before?.Fiscal, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||
return id;
|
||||
}
|
||||
|
||||
// The one-to-one details: inserted the first time, then updated; the history is kept under the id of the party.
|
||||
private async Task UpsertAsync<T>(IUnitOfWork uow, T row, T? before, long partyId, string userName, Action<T> link, CancellationToken cancellationToken)
|
||||
where T : Core.Entities.Entity<long>, new()
|
||||
{
|
||||
link(row);
|
||||
var repository = uow.Repository<T, long>();
|
||||
if (before is null || before.Id == 0)
|
||||
{
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
row.Id = before.Id;
|
||||
row.RowVersion = before.RowVersion;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, partyId, before, row, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The lists: rows removed are deleted, rows kept are updated, new rows inserted.
|
||||
private static async Task ReplaceAsync<T>(IUnitOfWork uow, List<T> rows, List<T> before, Action<T> link, CancellationToken cancellationToken)
|
||||
where T : Core.Entities.Entity<long>, new()
|
||||
{
|
||||
var repository = uow.Repository<T, long>();
|
||||
var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet();
|
||||
foreach (var old in before.Where(b => !kept.Contains(b.Id)))
|
||||
{
|
||||
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var versions = before.ToDictionary(b => b.Id, b => b.RowVersion);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
link(row);
|
||||
if (row.Id != 0 && versions.TryGetValue(row.Id, out var version))
|
||||
{
|
||||
row.RowVersion = version;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ViesResult?> CheckVatCoreAsync(string company, long id, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<Party, long>();
|
||||
var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
if (party.VatNumber is not { Length: > 0 } number || ViesClient.MemberStateCode(party.CountryCode) is not { } state)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = await _autoFill.CheckVatAsync(state, number, cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
var before = Clone(party);
|
||||
party.VatCheck = result.Status switch
|
||||
{
|
||||
ViesStatus.Valid => VatCheckStatus.Valid,
|
||||
ViesStatus.Invalid or ViesStatus.InvalidInput => VatCheckStatus.Invalid,
|
||||
_ => VatCheckStatus.Unavailable,
|
||||
};
|
||||
party.VatCheckedAt = result.CheckedAt.UtcDateTime;
|
||||
await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, userName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<TableProblem>> CheckAsync(IUnitOfWork uow, IFiscalPack pack, PartyRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = new List<TableProblem>();
|
||||
var party = record.Party;
|
||||
var trading = party.Kind is PartyKind.Customer or PartyKind.Supplier;
|
||||
Normalize(party);
|
||||
|
||||
if (party.SubjectType == SubjectType.Person && party.Name.Length == 0 && (party.LastName is not null || party.FirstName is not null))
|
||||
{
|
||||
party.Name = string.Join(' ', new[] { party.LastName, party.FirstName }.Where(n => n is not null));
|
||||
}
|
||||
|
||||
if (party.Name.Length == 0)
|
||||
{
|
||||
problems.Add(new(nameof(Party.Name), NameRequired));
|
||||
}
|
||||
|
||||
if (party.Code.Length > 0)
|
||||
{
|
||||
var code = party.Code;
|
||||
var id = party.Id;
|
||||
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.Code == code && p.Id != id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
problems.Add(new(nameof(Party.Code), CodeDuplicate));
|
||||
}
|
||||
}
|
||||
|
||||
// Country: the domestic subjects live in the company's country, the EU ones in another member state.
|
||||
var countryCode = party.CountryCode;
|
||||
var country = await uow.Repository<Country, long>().FindAsync(Query.For<Country>().Where(c => c.Code == countryCode), cancellationToken).ConfigureAwait(false);
|
||||
var domestic = party.CountryCode == pack.CountryCode;
|
||||
if (country is null)
|
||||
{
|
||||
problems.Add(new(nameof(Party.CountryCode), CountryUnknown));
|
||||
}
|
||||
else if (party.SubjectType == SubjectType.EuCompany && (!country.EuMember || domestic))
|
||||
{
|
||||
problems.Add(new(nameof(Party.CountryCode), CountryNotEu));
|
||||
}
|
||||
else if (party.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate && !domestic)
|
||||
{
|
||||
problems.Add(new(nameof(Party.CountryCode), CountryNotDomestic));
|
||||
}
|
||||
|
||||
var rules = pack.GetFeature<ITaxIdentifierRules>();
|
||||
if (party.VatNumber is not null)
|
||||
{
|
||||
if (domestic && rules is not null)
|
||||
{
|
||||
party.VatNumber = rules.NormalizeVatNumber(party.VatNumber);
|
||||
if (!rules.IsValidVatNumber(party.VatNumber))
|
||||
{
|
||||
problems.Add(new(nameof(Party.VatNumber), TableCatalog.VatNumberInvalid));
|
||||
}
|
||||
}
|
||||
else if ((country?.VatPrefix ?? country?.Code) is { } prefix && party.VatNumber.StartsWith(prefix, StringComparison.Ordinal))
|
||||
{
|
||||
party.VatNumber = party.VatNumber[prefix.Length..];
|
||||
}
|
||||
|
||||
var vat = party.VatNumber;
|
||||
var self = party.Id;
|
||||
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.VatNumber == vat && p.CountryCode == countryCode && p.Id != self), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
problems.Add(new(nameof(Party.VatNumber), VatNumberDuplicate, IsWarning: true));
|
||||
}
|
||||
}
|
||||
else if (trading && party.SubjectType is SubjectType.Company or SubjectType.FlatRate or SubjectType.EuCompany)
|
||||
{
|
||||
problems.Add(new(nameof(Party.VatNumber), VatNumberRequired));
|
||||
}
|
||||
|
||||
if (party.TaxCode is not null && domestic && rules is not null && !rules.IsValidTaxCode(party.TaxCode))
|
||||
{
|
||||
problems.Add(new(nameof(Party.TaxCode), TaxCodeInvalid));
|
||||
}
|
||||
|
||||
if (trading && party.SubjectType == SubjectType.PublicAdministration && party.VatNumber is null && party.TaxCode is null)
|
||||
{
|
||||
problems.Add(new(nameof(Party.TaxCode), IdentifierRequired));
|
||||
}
|
||||
|
||||
if (party.Kind == PartyKind.Customer && party.SubjectType == SubjectType.Person && party.TaxCode is null)
|
||||
{
|
||||
problems.Add(new(nameof(Party.TaxCode), TaxCodeMissing, IsWarning: true));
|
||||
}
|
||||
|
||||
Email(party.Email, nameof(Party.Email), problems);
|
||||
Email(party.Pec, nameof(Party.Pec), problems);
|
||||
CheckFiscal(record.Fiscal, party, rules, problems);
|
||||
CheckTerms(record, problems);
|
||||
CheckDetails(record, pack, problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static void Normalize(Party party)
|
||||
{
|
||||
party.Code = party.Code.Trim().ToUpperInvariant();
|
||||
party.Name = party.Name.Trim();
|
||||
party.FirstName = Clean(party.FirstName);
|
||||
party.LastName = Clean(party.LastName);
|
||||
party.FiscalName = Clean(party.FiscalName);
|
||||
party.VatNumber = Clean(party.VatNumber)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
|
||||
party.TaxCode = Clean(party.TaxCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
|
||||
party.Province = Clean(party.Province)?.ToUpperInvariant();
|
||||
party.CountryCode = (Clean(party.CountryCode) ?? string.Empty).ToUpperInvariant();
|
||||
party.CurrencyCode = (Clean(party.CurrencyCode) ?? "EUR").ToUpperInvariant();
|
||||
party.Language = (Clean(party.Language) ?? "it").ToLowerInvariant();
|
||||
party.Email = Clean(party.Email);
|
||||
party.Pec = Clean(party.Pec);
|
||||
party.PostalCode = Clean(party.PostalCode);
|
||||
party.City = Clean(party.City);
|
||||
party.Address = Clean(party.Address);
|
||||
}
|
||||
|
||||
private static void CheckFiscal(PartyFiscal fiscal, Party party, ITaxIdentifierRules? rules, List<TableProblem> problems)
|
||||
{
|
||||
fiscal.RecipientCode = Clean(fiscal.RecipientCode)?.ToUpperInvariant();
|
||||
fiscal.RecipientPec = Clean(fiscal.RecipientPec);
|
||||
fiscal.Exigibility = Clean(fiscal.Exigibility)?.ToUpperInvariant();
|
||||
var recipient = RecipientOf(party.SubjectType);
|
||||
if (party.Kind is PartyKind.Customer && rules is not null)
|
||||
{
|
||||
// Consumers and foreign customers get the code of the e-invoice format; a business with only a PEC gets 0000000.
|
||||
if (fiscal.RecipientCode is null && (recipient is RecipientKind.Consumer or RecipientKind.Foreign || fiscal.RecipientPec is not null))
|
||||
{
|
||||
fiscal.RecipientCode = rules.DefaultRecipientCode(recipient);
|
||||
}
|
||||
|
||||
problems.AddRange(rules.CheckRecipientCode(fiscal.RecipientCode, recipient)
|
||||
.Select(p => new TableProblem("Fiscal." + p.Field, p.Code, p.Severity == FiscalProblemSeverity.Warning)));
|
||||
}
|
||||
|
||||
Email(fiscal.RecipientPec, "Fiscal." + nameof(PartyFiscal.RecipientPec), problems);
|
||||
if (fiscal.SplitPayment)
|
||||
{
|
||||
fiscal.Exigibility = "S";
|
||||
}
|
||||
|
||||
if (fiscal.Exigibility is not (null or "I" or "D" or "S"))
|
||||
{
|
||||
problems.Add(new("Fiscal." + nameof(PartyFiscal.Exigibility), ExigibilityInvalid));
|
||||
}
|
||||
|
||||
Percent(fiscal.WithholdingRate, "Fiscal." + nameof(PartyFiscal.WithholdingRate), problems);
|
||||
Percent(fiscal.PensionFundRate, "Fiscal." + nameof(PartyFiscal.PensionFundRate), problems);
|
||||
if (fiscal.IntentActive)
|
||||
{
|
||||
fiscal.IntentNumber = Clean(fiscal.IntentNumber);
|
||||
if (fiscal.IntentNumber is null)
|
||||
{
|
||||
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentNumber), IntentIncomplete));
|
||||
}
|
||||
|
||||
if (fiscal.IntentCeiling is null)
|
||||
{
|
||||
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), IntentIncomplete));
|
||||
}
|
||||
}
|
||||
|
||||
if (fiscal.IntentCeiling < 0)
|
||||
{
|
||||
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), NotNegative));
|
||||
}
|
||||
|
||||
if (fiscal.IntentFrom is { } from && fiscal.IntentTo is { } to && to < from)
|
||||
{
|
||||
problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentTo), TableCatalog.ValidityOrder));
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckTerms(PartyRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var sales = record.Sales;
|
||||
Percent(sales.Discount1, "Sales." + nameof(PartySalesTerms.Discount1), problems);
|
||||
Percent(sales.Discount2, "Sales." + nameof(PartySalesTerms.Discount2), problems);
|
||||
if (sales.CreditLimit < 0)
|
||||
{
|
||||
problems.Add(new("Sales." + nameof(PartySalesTerms.CreditLimit), NotNegative));
|
||||
}
|
||||
|
||||
if (sales.InvoiceDay is < 1 or > 31)
|
||||
{
|
||||
problems.Add(new("Sales." + nameof(PartySalesTerms.InvoiceDay), DayRange));
|
||||
}
|
||||
|
||||
sales.DocumentsEmail = Clean(sales.DocumentsEmail);
|
||||
Email(sales.DocumentsEmail, "Sales." + nameof(PartySalesTerms.DocumentsEmail), problems);
|
||||
|
||||
var purchase = record.Purchase;
|
||||
Percent(purchase.Discount, "Purchase." + nameof(PartyPurchaseTerms.Discount), problems);
|
||||
if (purchase.LeadTimeDays < 0)
|
||||
{
|
||||
problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.LeadTimeDays), NotNegative));
|
||||
}
|
||||
|
||||
if (purchase.MinimumOrder < 0)
|
||||
{
|
||||
problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.MinimumOrder), NotNegative));
|
||||
}
|
||||
|
||||
purchase.OrdersEmail = Clean(purchase.OrdersEmail);
|
||||
Email(purchase.OrdersEmail, "Purchase." + nameof(PartyPurchaseTerms.OrdersEmail), problems);
|
||||
}
|
||||
|
||||
private static void CheckDetails(PartyRecord record, IFiscalPack pack, List<TableProblem> problems)
|
||||
{
|
||||
for (var i = 0; i < record.Addresses.Count; i++)
|
||||
{
|
||||
var address = record.Addresses[i];
|
||||
address.Name = address.Name.Trim();
|
||||
address.CountryCode = (Clean(address.CountryCode) ?? pack.CountryCode).ToUpperInvariant();
|
||||
address.Province = Clean(address.Province)?.ToUpperInvariant();
|
||||
if (address.Name.Length == 0)
|
||||
{
|
||||
problems.Add(new($"Addresses.{i}.{nameof(PartyAddress.Name)}", DetailRequired));
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < record.Contacts.Count; i++)
|
||||
{
|
||||
var contact = record.Contacts[i];
|
||||
contact.Name = contact.Name.Trim();
|
||||
contact.Email = Clean(contact.Email);
|
||||
if (contact.Name.Length == 0)
|
||||
{
|
||||
problems.Add(new($"Contacts.{i}.{nameof(PartyContact.Name)}", DetailRequired));
|
||||
}
|
||||
|
||||
Email(contact.Email, $"Contacts.{i}.{nameof(PartyContact.Email)}", problems);
|
||||
}
|
||||
|
||||
var directory = pack.GetFeature<IBankDirectory>();
|
||||
for (var i = 0; i < record.BankAccounts.Count; i++)
|
||||
{
|
||||
var account = record.BankAccounts[i];
|
||||
account.Iban = IbanValidator.Normalize(account.Iban);
|
||||
account.Bic = Clean(account.Bic)?.ToUpperInvariant();
|
||||
if (account.Iban.Length == 0)
|
||||
{
|
||||
problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", DetailRequired));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!IbanValidator.IsValid(account.Iban))
|
||||
{
|
||||
problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", TableCatalog.IbanInvalid));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (directory?.ReadIban(account.Iban) is { } bank)
|
||||
{
|
||||
account.BankCode = bank.BankCode;
|
||||
account.BranchCode = bank.BranchCode;
|
||||
account.BankName ??= bank.Name;
|
||||
account.Bic ??= bank.Bic;
|
||||
}
|
||||
}
|
||||
|
||||
// One default per list: the first one marked wins.
|
||||
OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v);
|
||||
OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v);
|
||||
foreach (var kind in record.Addresses.Select(a => a.Kind).Distinct().ToList())
|
||||
{
|
||||
OneDefault([.. record.Addresses.Where(a => a.Kind == kind)], a => a.IsDefault, (a, v) => a.IsDefault = v);
|
||||
}
|
||||
}
|
||||
|
||||
private static void OneDefault<T>(List<T> rows, Func<T, bool> get, Action<T, bool> set)
|
||||
{
|
||||
var found = false;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (get(row))
|
||||
{
|
||||
if (found)
|
||||
{
|
||||
set(row, false);
|
||||
}
|
||||
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Email(string? value, string field, List<TableProblem> problems)
|
||||
{
|
||||
if (value is not null && !EmailValidator.IsValid(value))
|
||||
{
|
||||
problems.Add(new(field, TableCatalog.EmailInvalid));
|
||||
}
|
||||
}
|
||||
|
||||
private static void Percent(decimal? value, string field, List<TableProblem> problems)
|
||||
{
|
||||
if (value is < 0 or > 100)
|
||||
{
|
||||
problems.Add(new(field, TableCatalog.PercentRange));
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
private static Party Clone(Party party)
|
||||
{
|
||||
var copy = new Party();
|
||||
foreach (var property in typeof(Party).GetProperties().Where(p => p.CanRead && p.CanWrite))
|
||||
{
|
||||
property.SetValue(copy, property.GetValue(party));
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// The parties of the demo company (SPEC §14, issue #41): customers of every kind of subject (companies, public
|
||||
/// administration with split payment, private persons, EU and non-EU companies, flat rate, a declaration of intent, a
|
||||
/// customer blocked over its credit, one that is also a supplier, one disabled), suppliers (a professional with
|
||||
/// withholding, an ENASARCO agent, an EU supplier), prospects and leads, and three salespeople. Every name, number and
|
||||
/// bank account is fictitious: the VAT numbers have a valid check digit, the IBANs a valid check, the ABI codes belong
|
||||
/// to no bank. Runs only on a company without parties; the rows are marked as demo.
|
||||
/// </summary>
|
||||
/// <param name="codes">The automatic code rules.</param>
|
||||
public sealed class DemoPartiesSeeder(CodeRuleService codes) : ISeeder
|
||||
{
|
||||
/// <summary>The fictitious VAT numbers, valid for the Italian check digit (tests check them with the pack).</summary>
|
||||
public static readonly IReadOnlyList<string> VatNumbers =
|
||||
[
|
||||
"04123456784", "05234567898", "06345678905", "07456789010", "08567890127", "09678901233", "10789012340", "11890123455",
|
||||
"12901234562", "13012345677", "14123456700", "15234567814", "16345678920", "17456789035",
|
||||
];
|
||||
|
||||
/// <summary>The fictitious tax code of the public administration (numeric, valid check digit).</summary>
|
||||
public const string AdministrationTaxCode = "80012345676";
|
||||
|
||||
/// <summary>The fictitious IBANs, with a valid check and ABI codes of no bank.</summary>
|
||||
public static readonly IReadOnlyList<string> Ibans = ["IT53X0123410100000012345678", "IT21X0567822000000000987654", "IT11X0987645600000101234567"];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public SeedKind Kind => SeedKind.Demo;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 10;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var uow = context.UnitOfWork;
|
||||
if (await uow.Repository<Party, long>().CountAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var rules = new Dictionary<PartyKind, CodeRule>();
|
||||
foreach (var kind in Enum.GetValues<PartyKind>())
|
||||
{
|
||||
rules[kind] = await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var salespeople = await context.EnsureAsync(
|
||||
"salespeople",
|
||||
[
|
||||
new Salesperson { Code = "VERDI", Description = "Marco Verdi", Email = "m.verdi@demo.example", CommissionPercent = 5m, Enasarco = true },
|
||||
new Salesperson { Code = "NERI", Description = "Laura Neri", Email = "l.neri@demo.example", CommissionPercent = 4m, Enasarco = true },
|
||||
new Salesperson { Code = "BIANCO", Description = "Paolo Bianco", Email = "p.bianco@demo.example", CommissionPercent = 3m },
|
||||
],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var terms = (await uow.Repository<PaymentTerm, long>().ListAsync(Query.For<PaymentTerm>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(t => t.Code, t => t.Id, StringComparer.OrdinalIgnoreCase);
|
||||
var priceList = (await uow.Repository<PriceList, long>().FindAsync(Query.For<PriceList>().Where(p => p.Code == "BASE"), cancellationToken).ConfigureAwait(false))?.Id;
|
||||
long? Term(string code) => terms.TryGetValue(code, out var id) ? id : null;
|
||||
long? Agent(string code) => salespeople.TryGetValue(code, out var s) ? s.Id : null;
|
||||
var identifiers = context.Pack.GetFeature<ITaxIdentifierRules>();
|
||||
var year = context.Today.Year;
|
||||
|
||||
var seeds = new List<PartyRecord>
|
||||
{
|
||||
Customer("Rossi Impianti S.r.l.", SubjectType.Company, VatNumbers[0], "Via Nizza", "120", "10126", "Torino", "TO", Term("RB60FM"), Agent("VERDI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "M5UXCR1";
|
||||
r.Party.Phone = "011 5550101";
|
||||
r.Party.Email = "amministrazione@rossi-impianti.example";
|
||||
r.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Titolare", Mobile = "333 5550101", Email = "mario@rossi-impianti.example", IsDefault = true });
|
||||
r.Contacts.Add(new PartyContact { Name = "Anna Ferri", Role = "Amministrazione", Phone = "011 5550102", Email = "amministrazione@rossi-impianti.example" });
|
||||
r.Addresses.Add(new PartyAddress { Kind = PartyAddressKind.Site, Name = "Cantiere Lingotto", Address = "Via Ventimiglia", StreetNumber = "88", PostalCode = "10126", City = "Torino", Province = "TO", IsDefault = true });
|
||||
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[0], BankCode = "01234", BranchCode = "10100", IsDefault = true });
|
||||
r.Sales.Discount1 = 5m;
|
||||
r.Sales.CreditLimit = 30000m;
|
||||
r.Sales.SendDocuments = DocumentDelivery.Email;
|
||||
r.Sales.DocumentsEmail = "amministrazione@rossi-impianti.example";
|
||||
}),
|
||||
Customer("Bianchi & Figli S.n.c.", SubjectType.Company, VatNumbers[1], "Corso Langhe", "5", "12051", "Alba", "CN", Term("RB3060FM"), Agent("VERDI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "0000000";
|
||||
r.Fiscal.RecipientPec = "bianchiefigli@pec.demo.example";
|
||||
r.Party.Pec = "bianchiefigli@pec.demo.example";
|
||||
}),
|
||||
Customer("Comune di Valdora", SubjectType.PublicAdministration, null, "Piazza del Municipio", "1", "12060", "Valdora", "CN", Term("BB30"), null, r =>
|
||||
{
|
||||
r.Party.TaxCode = AdministrationTaxCode;
|
||||
r.Fiscal.RecipientCode = "UFX9K2";
|
||||
r.Fiscal.SplitPayment = true;
|
||||
r.Fiscal.Exigibility = "S";
|
||||
r.Fiscal.AdministrationReference = "SETT-TECNICO";
|
||||
}),
|
||||
Customer("Ferramenta Gallo", SubjectType.Company, VatNumbers[2], "Corso Alfieri", "210", "14100", "Asti", "AT", Term("RD"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "KRRH6B9";
|
||||
r.Sales.CreditLimit = 5000m;
|
||||
r.Sales.Blocked = true;
|
||||
r.Party.Notes = "Ordini bloccati: fido superato, rientro concordato entro fine mese.";
|
||||
}),
|
||||
Customer("Bergwerk Bau GmbH", SubjectType.EuCompany, "U12345678", "Museumstrasse", "12", "6020", "Innsbruck", null, Term("BB30"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Party.CountryCode = "AT";
|
||||
r.Party.Language = "de";
|
||||
r.Fiscal.RecipientCode = "XXXXXXX";
|
||||
}),
|
||||
Customer("Esposito Mario", SubjectType.Person, null, "Via Po", "18", "10124", "Torino", "TO", Term("RD"), null, r =>
|
||||
{
|
||||
r.Party.LastName = "Esposito";
|
||||
r.Party.FirstName = "Mario";
|
||||
r.Party.TaxCode = Personal(identifiers, "Esposito", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219");
|
||||
r.Party.Email = "mario.esposito@posta.example";
|
||||
r.Fiscal.RecipientCode = "0000000";
|
||||
r.Party.PrivacyAccepted = true;
|
||||
}),
|
||||
Customer("Idrotermica Piemonte S.r.l.", SubjectType.Company, VatNumbers[3], "Via Roma", "44", "12100", "Cuneo", "CN", Term("RB3060FM"), Agent("VERDI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "T04ZHR3";
|
||||
r.Fiscal.IntentActive = true;
|
||||
r.Fiscal.IntentNumber = "14/" + year;
|
||||
r.Fiscal.IntentDate = new DateOnly(year, 1, 15);
|
||||
r.Fiscal.IntentProtocol = "26011512345678901-000001";
|
||||
r.Fiscal.IntentCeiling = 150000m;
|
||||
r.Fiscal.IntentFrom = new DateOnly(year, 1, 1);
|
||||
r.Fiscal.IntentTo = new DateOnly(year, 12, 31);
|
||||
}),
|
||||
Customer("Nordic Pipes AS", SubjectType.NonEuCompany, "987654321", "Storgata", "7", "0155", "Oslo", null, Term("RD"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Party.CountryCode = "NO";
|
||||
r.Party.Language = "en";
|
||||
r.Fiscal.RecipientCode = "XXXXXXX";
|
||||
}),
|
||||
Customer("Studio Tecnico Ing. Ferrero", SubjectType.FlatRate, VatNumbers[4], "Via Vittorio Emanuele", "3", "12051", "Alba", "CN", Term("BB30"), null, r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "USAL8PV";
|
||||
r.Fiscal.StampDutyCharged = true;
|
||||
}),
|
||||
Customer("Edilizia Moderna S.p.A.", SubjectType.Company, VatNumbers[5], "Viale Monza", "250", "20126", "Milano", "MI", Term("RB3060FM"), Agent("BIANCO"), r =>
|
||||
{
|
||||
r.Party.IsAlsoSupplier = true;
|
||||
r.Fiscal.RecipientCode = "W7YVJK9";
|
||||
r.Purchase.PaymentTermId = Term("BB30FM");
|
||||
r.Sales.Discount1 = 10m;
|
||||
r.Sales.Discount2 = 3m;
|
||||
}),
|
||||
Customer("Termoidraulica Sacco", SubjectType.Company, VatNumbers[6], "Via Cavour", "9", "12042", "Bra", "CN", Term("RD"), Agent("NERI"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "SUBM70N";
|
||||
r.Party.Disabled = true;
|
||||
r.Party.Notes = "Attività cessata.";
|
||||
}),
|
||||
Customer("Hotel Belvedere S.r.l.", SubjectType.Company, VatNumbers[7], "Passeggiata Cadorna", "15", "17021", "Alassio", "SV", Term("BB30FM"), Agent("BIANCO"), r =>
|
||||
{
|
||||
r.Fiscal.RecipientCode = "5RUO82D";
|
||||
r.Contacts.Add(new PartyContact { Name = "Giulia Marino", Role = "Direzione", Phone = "0182 555010", IsDefault = true });
|
||||
}),
|
||||
Supplier("Metalli Nord S.p.A.", VatNumbers[8], "Via Industriale", "40", "25125", "Brescia", "BS", Term("RB60FM"), r =>
|
||||
{
|
||||
r.Purchase.LeadTimeDays = 10;
|
||||
r.Purchase.MinimumOrder = 500m;
|
||||
r.Purchase.OrdersEmail = "ordini@metalli-nord.example";
|
||||
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[1], BankCode = "05678", BranchCode = "22000", IsDefault = true });
|
||||
}),
|
||||
Supplier("Plastica Sud S.r.l.", VatNumbers[9], "Via Appia", "301", "81100", "Caserta", "CE", Term("BB30FM"), r => r.Purchase.LeadTimeDays = 15),
|
||||
Supplier("Studio Rag. Neri Paola", VatNumbers[10], "Via Vittorio Veneto", "21", "12100", "Cuneo", "CN", Term("RD"), r =>
|
||||
{
|
||||
r.Fiscal.Withholding = true;
|
||||
r.Fiscal.WithholdingRate = 20m;
|
||||
r.Fiscal.WithholdingReason = "A";
|
||||
r.Fiscal.PensionFund = "TC04";
|
||||
r.Fiscal.PensionFundRate = 4m;
|
||||
r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[2], BankCode = "09876", BranchCode = "45600", IsDefault = true });
|
||||
}),
|
||||
Supplier("Agenzia Commerciale Bruno", VatNumbers[11], "Corso Francia", "77", "10138", "Torino", "TO", Term("BB30FM"), r =>
|
||||
{
|
||||
r.Fiscal.Withholding = true;
|
||||
r.Fiscal.WithholdingRate = 23m;
|
||||
r.Fiscal.WithholdingReason = "R";
|
||||
r.Fiscal.Enasarco = true;
|
||||
}),
|
||||
Supplier("Elektro Werke Süd GmbH", "123456789", "Industriestrasse", "5", "80331", "München", null, Term("BB30"), r =>
|
||||
{
|
||||
r.Party.SubjectType = SubjectType.EuCompany;
|
||||
r.Party.CountryCode = "DE";
|
||||
r.Party.Language = "de";
|
||||
}),
|
||||
Contact(PartyKind.Prospect, "Caseificio Valle Stura S.r.l.", VatNumbers[12], "12014", "Demonte", "CN", Agent("VERDI")),
|
||||
Contact(PartyKind.Prospect, "Agriturismo Le Vigne", VatNumbers[13], "12060", "Barolo", "CN", Agent("BIANCO")),
|
||||
Contact(PartyKind.Lead, "Fontana Marco (fiera di Bologna)", null, null, null, null, Agent("NERI")),
|
||||
Contact(PartyKind.Lead, "Cantina Sociale del Roero", null, "12043", "Canale", "CN", null),
|
||||
};
|
||||
|
||||
foreach (var record in seeds)
|
||||
{
|
||||
record.Sales.PriceListId ??= record.Party.IsCustomer ? priceList : null;
|
||||
await InsertAsync(uow, record, rules[record.Party.Kind], context.Today, cancellationToken).ConfigureAwait(false);
|
||||
context.Count("parties");
|
||||
}
|
||||
}
|
||||
|
||||
private static PartyRecord Customer(string name, SubjectType subject, string? vat, string address, string number, string postalCode, string city, string? province,
|
||||
long? paymentTermId, long? salespersonId, Action<PartyRecord> more)
|
||||
{
|
||||
var record = New(PartyKind.Customer, name, subject, vat, postalCode, city, province, salespersonId);
|
||||
record.Party.Address = address;
|
||||
record.Party.StreetNumber = number;
|
||||
record.Sales.PaymentTermId = paymentTermId;
|
||||
more(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
private static PartyRecord Supplier(string name, string vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId,
|
||||
Action<PartyRecord> more)
|
||||
{
|
||||
var record = New(PartyKind.Supplier, name, SubjectType.Company, vat, postalCode, city, province, null);
|
||||
record.Party.Address = address;
|
||||
record.Party.StreetNumber = number;
|
||||
record.Purchase.PaymentTermId = paymentTermId;
|
||||
more(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
private static PartyRecord Contact(PartyKind kind, string name, string? vat, string? postalCode, string? city, string? province, long? salespersonId) =>
|
||||
New(kind, name, SubjectType.Company, vat, postalCode, city, province, salespersonId);
|
||||
|
||||
private static PartyRecord New(PartyKind kind, string name, SubjectType subject, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => new()
|
||||
{
|
||||
Party = new Party
|
||||
{
|
||||
Kind = kind, Name = name, SubjectType = subject, VatNumber = vat, PostalCode = postalCode, City = city, Province = province, SalespersonId = salespersonId,
|
||||
CategoryId = null, PrivacyAccepted = kind is PartyKind.Customer or PartyKind.Supplier, IsDemo = true,
|
||||
},
|
||||
};
|
||||
|
||||
private static string? Personal(ITaxIdentifierRules? rules, string surname, string name, DateOnly birth, PersonSex sex, string place) =>
|
||||
rules?.ComputePersonalTaxCode(new PersonalTaxCodeData(surname, name, birth, sex, place));
|
||||
|
||||
private static async Task InsertAsync(IUnitOfWork uow, PartyRecord record, CodeRule rule, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
var parties = uow.Repository<Party, long>();
|
||||
var party = record.Party;
|
||||
party.Code = await CodeRuleService.AssignAsync(
|
||||
uow, rule, today, null,
|
||||
async (code, ct) => await parties.CountAsync(Query.For<Party>().Where(p => p.Code == code), ct).ConfigureAwait(false) > 0,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false);
|
||||
if (party.IsCustomer)
|
||||
{
|
||||
record.Sales.PartyId = party.Id;
|
||||
await uow.Repository<PartySalesTerms, long>().InsertAsync(record.Sales, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (party.IsSupplier)
|
||||
{
|
||||
record.Purchase.PartyId = party.Id;
|
||||
await uow.Repository<PartyPurchaseTerms, long>().InsertAsync(record.Purchase, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
record.Fiscal.PartyId = party.Id;
|
||||
await uow.Repository<PartyFiscal, long>().InsertAsync(record.Fiscal, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var address in record.Addresses)
|
||||
{
|
||||
address.PartyId = party.Id;
|
||||
address.CountryCode = address.CountryCode.Length == 0 ? party.CountryCode : address.CountryCode;
|
||||
await uow.Repository<PartyAddress, long>().InsertAsync(address, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var contact in record.Contacts)
|
||||
{
|
||||
contact.PartyId = party.Id;
|
||||
await uow.Repository<PartyContact, long>().InsertAsync(contact, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var account in record.BankAccounts)
|
||||
{
|
||||
account.PartyId = party.Id;
|
||||
await uow.Repository<PartyBankAccount, long>().InsertAsync(account, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,6 +207,12 @@ public sealed partial class SeedRunner : ICompanySeeder
|
||||
{
|
||||
await RunAsync(companyCode, SeedKind.Base, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The demo seeders fill only a company without data of their own (each checks its tables).
|
||||
if (context.Demo)
|
||||
{
|
||||
await RunAsync(companyCode, SeedKind.Demo, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The button <i>Aggiorna tabelle di base</i>: runs the base seeders for a company.</summary>
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Parties;
|
||||
|
||||
/// <summary>What a party is to the company (SPEC §11.2): the archive and the code mask follow from it.</summary>
|
||||
public enum PartyKind
|
||||
{
|
||||
/// <summary>A customer (it may also be a supplier).</summary>
|
||||
Customer = 0,
|
||||
|
||||
/// <summary>A supplier that is not a customer.</summary>
|
||||
Supplier = 1,
|
||||
|
||||
/// <summary>A qualified potential customer, without fiscal documents.</summary>
|
||||
Prospect = 2,
|
||||
|
||||
/// <summary>A commercial contact still to qualify (CRM).</summary>
|
||||
Lead = 3,
|
||||
}
|
||||
|
||||
/// <summary>The kind of subject: it decides the checks and the values proposed (SDI code, split payment, VAT number).</summary>
|
||||
public enum SubjectType
|
||||
{
|
||||
/// <summary>A domestic business.</summary>
|
||||
Company = 0,
|
||||
|
||||
/// <summary>A private person (consumer).</summary>
|
||||
Person = 1,
|
||||
|
||||
/// <summary>A public administration (split payment, office code of 6 characters).</summary>
|
||||
PublicAdministration = 2,
|
||||
|
||||
/// <summary>A business in another EU member state (VIES).</summary>
|
||||
EuCompany = 3,
|
||||
|
||||
/// <summary>A business outside the EU.</summary>
|
||||
NonEuCompany = 4,
|
||||
|
||||
/// <summary>A domestic business under the flat-rate scheme (no VAT charged, stamp duty).</summary>
|
||||
FlatRate = 5,
|
||||
}
|
||||
|
||||
/// <summary>The outcome of the last check of the VAT number on VIES, saved on the party.</summary>
|
||||
public enum VatCheckStatus
|
||||
{
|
||||
/// <summary>Not checked.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Registered for intra-EU operations.</summary>
|
||||
Valid = 1,
|
||||
|
||||
/// <summary>Not registered.</summary>
|
||||
Invalid = 2,
|
||||
|
||||
/// <summary>The service could not answer; to repeat.</summary>
|
||||
Unavailable = 3,
|
||||
}
|
||||
|
||||
/// <summary>How the documents are sent to a customer.</summary>
|
||||
public enum DocumentDelivery
|
||||
{
|
||||
/// <summary>Not sent: printed or downloaded.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>By e-mail.</summary>
|
||||
Email = 1,
|
||||
|
||||
/// <summary>By certified e-mail (PEC).</summary>
|
||||
Pec = 2,
|
||||
}
|
||||
|
||||
/// <summary>What an address of a party is used for.</summary>
|
||||
public enum PartyAddressKind
|
||||
{
|
||||
/// <summary>Delivery address (destination of delivery notes).</summary>
|
||||
Delivery = 0,
|
||||
|
||||
/// <summary>Address for invoices, when different from the registered office.</summary>
|
||||
Billing = 1,
|
||||
|
||||
/// <summary>A building site or a branch.</summary>
|
||||
Site = 2,
|
||||
|
||||
/// <summary>Another address.</summary>
|
||||
Other = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A party (SPEC §11.2, wiki <i>Anagrafiche</i>): customer, supplier, prospect or lead, registered once. The code follows
|
||||
/// the mask of its kind (ADR 0027); converting a lead or prospect into a customer gives it a customer code and keeps the
|
||||
/// old one in <see cref="PreviousCode"/>.
|
||||
/// </summary>
|
||||
public sealed class Party : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The code, unique among the parties.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The code it had before a conversion.</summary>
|
||||
public string? PreviousCode { get; set; }
|
||||
|
||||
/// <summary>What the party is.</summary>
|
||||
public PartyKind Kind { get; set; }
|
||||
|
||||
/// <summary>A customer that also sells to the company.</summary>
|
||||
public bool IsAlsoSupplier { get; set; }
|
||||
|
||||
/// <summary>The kind of subject.</summary>
|
||||
public SubjectType SubjectType { get; set; }
|
||||
|
||||
/// <summary>The business name, or "last name first name" for a person.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The first name of a person.</summary>
|
||||
public string? FirstName { get; set; }
|
||||
|
||||
/// <summary>The last name of a person.</summary>
|
||||
public string? LastName { get; set; }
|
||||
|
||||
/// <summary>The name on fiscal documents, when different.</summary>
|
||||
public string? FiscalName { get; set; }
|
||||
|
||||
/// <summary>The VAT number, compact, without the country prefix.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The tax code.</summary>
|
||||
public string? TaxCode { get; set; }
|
||||
|
||||
/// <summary>The registration in the companies register (REA).</summary>
|
||||
public string? Rea { get; set; }
|
||||
|
||||
/// <summary>The category (<c>party_categories</c>).</summary>
|
||||
public long? CategoryId { get; set; }
|
||||
|
||||
/// <summary>Street of the registered office.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>Street number.</summary>
|
||||
public string? StreetNumber { get; set; }
|
||||
|
||||
/// <summary>Postal code.</summary>
|
||||
public string? PostalCode { get; set; }
|
||||
|
||||
/// <summary>Municipality or city.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>Province abbreviation (or region abroad).</summary>
|
||||
public string? Province { get; set; }
|
||||
|
||||
/// <summary>Country (ISO 3166-1 alpha-2).</summary>
|
||||
public string CountryCode { get; set; } = "IT";
|
||||
|
||||
/// <summary>Phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>E-mail.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>Certified e-mail (PEC).</summary>
|
||||
public string? Pec { get; set; }
|
||||
|
||||
/// <summary>Web site.</summary>
|
||||
public string? Website { get; set; }
|
||||
|
||||
/// <summary>The salesperson (<c>salespeople</c>).</summary>
|
||||
public long? SalespersonId { get; set; }
|
||||
|
||||
/// <summary>Language of the documents (ISO 639-1).</summary>
|
||||
public string Language { get; set; } = "it";
|
||||
|
||||
/// <summary>Currency of the documents (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>Start of the relationship.</summary>
|
||||
public DateOnly? Since { get; set; }
|
||||
|
||||
/// <summary>Privacy notice accepted.</summary>
|
||||
public bool PrivacyAccepted { get; set; }
|
||||
|
||||
/// <summary>Consent to marketing.</summary>
|
||||
public bool Marketing { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>Last VIES outcome.</summary>
|
||||
public VatCheckStatus VatCheck { get; set; }
|
||||
|
||||
/// <summary>When VIES answered (or failed), UTC.</summary>
|
||||
public DateTime? VatCheckedAt { get; set; }
|
||||
|
||||
/// <summary>The customer sub-account of the ledger, created at the first posting (M7).</summary>
|
||||
public string? CustomerAccountCode { get; set; }
|
||||
|
||||
/// <summary>The supplier sub-account of the ledger, created at the first posting (M7).</summary>
|
||||
public string? SupplierAccountCode { get; set; }
|
||||
|
||||
/// <summary>Hidden from new documents and default searches; kept with its documents.</summary>
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>Whether the party is a customer (also a supplier that is a customer).</summary>
|
||||
public bool IsCustomer => Kind == PartyKind.Customer;
|
||||
|
||||
/// <summary>Whether the party is a supplier, alone or also a customer.</summary>
|
||||
public bool IsSupplier => Kind == PartyKind.Supplier || (Kind == PartyKind.Customer && IsAlsoSupplier);
|
||||
}
|
||||
|
||||
/// <summary>An address of a party besides the registered office.</summary>
|
||||
public sealed class PartyAddress : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>What it is used for.</summary>
|
||||
public PartyAddressKind Kind { get; set; }
|
||||
|
||||
/// <summary>The name shown on documents (site, branch).</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Street.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>Street number.</summary>
|
||||
public string? StreetNumber { get; set; }
|
||||
|
||||
/// <summary>Postal code.</summary>
|
||||
public string? PostalCode { get; set; }
|
||||
|
||||
/// <summary>City.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>Province.</summary>
|
||||
public string? Province { get; set; }
|
||||
|
||||
/// <summary>Country (ISO 3166-1 alpha-2).</summary>
|
||||
public string CountryCode { get; set; } = "IT";
|
||||
|
||||
/// <summary>The address proposed first for its kind.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
|
||||
/// <summary>Notes (opening hours, how to reach it).</summary>
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A contact person of a party.</summary>
|
||||
public sealed class PartyContact : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>Name and surname.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Role (purchasing, administration...).</summary>
|
||||
public string? Role { get; set; }
|
||||
|
||||
/// <summary>Phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>Mobile phone.</summary>
|
||||
public string? Mobile { get; set; }
|
||||
|
||||
/// <summary>E-mail.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The main contact.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A bank account of a party: the bank of its RiBa, or where the company pays it.</summary>
|
||||
public sealed class PartyBankAccount : Entity<long>
|
||||
{
|
||||
/// <summary>The party.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The IBAN, compact.</summary>
|
||||
public string Iban { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The BIC.</summary>
|
||||
public string? Bic { get; set; }
|
||||
|
||||
/// <summary>The bank.</summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>The national bank code (ABI), read from the IBAN.</summary>
|
||||
public string? BankCode { get; set; }
|
||||
|
||||
/// <summary>The branch code (CAB), read from the IBAN.</summary>
|
||||
public string? BranchCode { get; set; }
|
||||
|
||||
/// <summary>The account proposed on documents.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The sales terms of a customer, proposed on its documents (M5).</summary>
|
||||
public sealed class PartySalesTerms : Entity<long>
|
||||
{
|
||||
/// <summary>The party (one row per party).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The price list (<c>price_lists</c>).</summary>
|
||||
public long? PriceListId { get; set; }
|
||||
|
||||
/// <summary>First discount, percent.</summary>
|
||||
public decimal? Discount1 { get; set; }
|
||||
|
||||
/// <summary>Second discount, percent.</summary>
|
||||
public decimal? Discount2 { get; set; }
|
||||
|
||||
/// <summary>The payment terms (<c>payment_terms</c>).</summary>
|
||||
public long? PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>The account of the company where the customer pays (<c>bank_accounts</c>).</summary>
|
||||
public long? CompanyBankAccountId { get; set; }
|
||||
|
||||
/// <summary>The carrier (<c>carriers</c>).</summary>
|
||||
public long? CarrierId { get; set; }
|
||||
|
||||
/// <summary>The shipping terms (<c>shipping_terms</c>).</summary>
|
||||
public long? ShippingTermId { get; set; }
|
||||
|
||||
/// <summary>The warehouse goods leave from (<c>warehouses</c>).</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The credit limit: the most the customer may owe.</summary>
|
||||
public decimal? CreditLimit { get; set; }
|
||||
|
||||
/// <summary>Orders and deliveries are blocked.</summary>
|
||||
public bool Blocked { get; set; }
|
||||
|
||||
/// <summary>Delivery notes are grouped into one deferred invoice.</summary>
|
||||
public bool GroupDeliveryNotes { get; set; } = true;
|
||||
|
||||
/// <summary>The day of the month the deferred invoices are issued, if fixed.</summary>
|
||||
public int? InvoiceDay { get; set; }
|
||||
|
||||
/// <summary>How the documents are sent.</summary>
|
||||
public DocumentDelivery SendDocuments { get; set; }
|
||||
|
||||
/// <summary>Where the documents are sent, when not the main e-mail or PEC.</summary>
|
||||
public string? DocumentsEmail { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The purchase terms of a supplier, proposed on its orders (M6).</summary>
|
||||
public sealed class PartyPurchaseTerms : Entity<long>
|
||||
{
|
||||
/// <summary>The party (one row per party).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The payment terms (<c>payment_terms</c>).</summary>
|
||||
public long? PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>Days between order and delivery.</summary>
|
||||
public int? LeadTimeDays { get; set; }
|
||||
|
||||
/// <summary>The smallest order accepted.</summary>
|
||||
public decimal? MinimumOrder { get; set; }
|
||||
|
||||
/// <summary>Discount, percent.</summary>
|
||||
public decimal? Discount { get; set; }
|
||||
|
||||
/// <summary>The shipping terms (<c>shipping_terms</c>).</summary>
|
||||
public long? ShippingTermId { get; set; }
|
||||
|
||||
/// <summary>The VAT register of the purchases (M7).</summary>
|
||||
public string? VatRegisterCode { get; set; }
|
||||
|
||||
/// <summary>The cost account proposed (M7).</summary>
|
||||
public string? CostAccountCode { get; set; }
|
||||
|
||||
/// <summary>The e-mail for the orders.</summary>
|
||||
public string? OrdersEmail { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The fiscal data of a party (mockup 015, 016): e-invoicing, VAT regime, withholding and contributions, the declaration
|
||||
/// of intent of a habitual exporter and the identifiers.
|
||||
/// </summary>
|
||||
public sealed class PartyFiscal : Entity<long>
|
||||
{
|
||||
/// <summary>The party (one row per party).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The SDI recipient code (7 characters, 6 for a public administration).</summary>
|
||||
public string? RecipientCode { get; set; }
|
||||
|
||||
/// <summary>The PEC the e-invoices go to, without a recipient code.</summary>
|
||||
public string? RecipientPec { get; set; }
|
||||
|
||||
/// <summary>The reference of the administration (public administrations).</summary>
|
||||
public string? AdministrationReference { get; set; }
|
||||
|
||||
/// <summary>A courtesy PDF goes with the e-invoice.</summary>
|
||||
public bool AttachPdf { get; set; } = true;
|
||||
|
||||
/// <summary>A copy is sent by e-mail when the invoice is issued.</summary>
|
||||
public bool SendCopy { get; set; }
|
||||
|
||||
/// <summary>Split payment (art. 17-ter DPR 633/72).</summary>
|
||||
public bool SplitPayment { get; set; }
|
||||
|
||||
/// <summary>Reverse charge by default.</summary>
|
||||
public bool ReverseCharge { get; set; }
|
||||
|
||||
/// <summary>The VAT code proposed (<c>tax_codes</c>).</summary>
|
||||
public long? TaxCodeId { get; set; }
|
||||
|
||||
/// <summary>VAT exigibility: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment.</summary>
|
||||
public string? Exigibility { get; set; }
|
||||
|
||||
/// <summary>The stamp duty is charged to the customer.</summary>
|
||||
public bool StampDutyCharged { get; set; } = true;
|
||||
|
||||
/// <summary>Subject to withholding tax (professionals).</summary>
|
||||
public bool Withholding { get; set; }
|
||||
|
||||
/// <summary>Withholding rate, percent.</summary>
|
||||
public decimal? WithholdingRate { get; set; }
|
||||
|
||||
/// <summary>Withholding reason of the e-invoice (A, M, Q...).</summary>
|
||||
public string? WithholdingReason { get; set; }
|
||||
|
||||
/// <summary>Pension fund of the e-invoice (TC01-TC22).</summary>
|
||||
public string? PensionFund { get; set; }
|
||||
|
||||
/// <summary>Pension fund rate, percent.</summary>
|
||||
public decimal? PensionFundRate { get; set; }
|
||||
|
||||
/// <summary>Agent subject to ENASARCO.</summary>
|
||||
public bool Enasarco { get; set; }
|
||||
|
||||
/// <summary>Declaration of intent active.</summary>
|
||||
public bool IntentActive { get; set; }
|
||||
|
||||
/// <summary>Number of the declaration.</summary>
|
||||
public string? IntentNumber { get; set; }
|
||||
|
||||
/// <summary>Date of the declaration.</summary>
|
||||
public DateOnly? IntentDate { get; set; }
|
||||
|
||||
/// <summary>Protocol of the revenue agency.</summary>
|
||||
public string? IntentProtocol { get; set; }
|
||||
|
||||
/// <summary>The non-taxable VAT code used under the declaration (<c>tax_codes</c>, nature N3.5).</summary>
|
||||
public long? IntentTaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The ceiling of the declaration.</summary>
|
||||
public decimal? IntentCeiling { get; set; }
|
||||
|
||||
/// <summary>The amount already invoiced under the declaration (updated by the invoices, M5).</summary>
|
||||
public decimal IntentUsed { get; set; }
|
||||
|
||||
/// <summary>The declaration is valid from.</summary>
|
||||
public DateOnly? IntentFrom { get; set; }
|
||||
|
||||
/// <summary>The declaration is valid until.</summary>
|
||||
public DateOnly? IntentTo { get; set; }
|
||||
|
||||
/// <summary>Global location number.</summary>
|
||||
public string? Gln { get; set; }
|
||||
|
||||
/// <summary>Economic operators registration and identification number (customs).</summary>
|
||||
public string? Eori { get; set; }
|
||||
|
||||
/// <summary>The code of the company at the party.</summary>
|
||||
public string? OurCode { get; set; }
|
||||
|
||||
/// <summary>What remains of the ceiling of the declaration.</summary>
|
||||
public decimal? IntentRemaining => IntentCeiling is { } ceiling ? ceiling - IntentUsed : null;
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Parties and their details (SPEC §11.2, issue #41): addresses, contacts, bank accounts, sales and purchase terms and
|
||||
/// fiscal data. The details go with the party; the company tables they point to cannot be deleted while used.
|
||||
/// </summary>
|
||||
[Migration(20261112_001, "create_parties")]
|
||||
public sealed class M20261112_001_CreateParties : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("parties", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 30).NotNull();
|
||||
t.String("previous_code", 30);
|
||||
t.String("kind", 40).NotNull();
|
||||
t.Bool("is_also_supplier").NotNull().Default(false);
|
||||
t.String("subject_type", 40).NotNull();
|
||||
t.String("name", 200).NotNull();
|
||||
t.String("first_name", 80);
|
||||
t.String("last_name", 80);
|
||||
t.String("fiscal_name", 200);
|
||||
t.String("vat_number", 30);
|
||||
t.String("tax_code", 30);
|
||||
t.String("rea", 20);
|
||||
t.Int64("category_id");
|
||||
t.String("address", 200);
|
||||
t.String("street_number", 20);
|
||||
t.String("postal_code", 10);
|
||||
t.String("city", 100);
|
||||
t.String("province", 10);
|
||||
t.String("country_code", 2).NotNull();
|
||||
t.String("phone", 40);
|
||||
t.String("email", 200);
|
||||
t.String("pec", 200);
|
||||
t.String("website", 200);
|
||||
t.Int64("salesperson_id");
|
||||
t.String("language", 5).NotNull();
|
||||
t.String("currency_code", 3).NotNull();
|
||||
t.Date("since");
|
||||
t.Bool("privacy_accepted").NotNull().Default(false);
|
||||
t.Bool("marketing").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.String("vat_check", 40).NotNull();
|
||||
t.DateTimeUtc("vat_checked_at");
|
||||
t.String("customer_account_code", 20);
|
||||
t.String("supplier_account_code", 20);
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_parties_code", "code");
|
||||
t.Index("ix_parties_name", "name");
|
||||
t.Index("ix_parties_vat_number", "vat_number");
|
||||
t.Index("ix_parties_tax_code", "tax_code");
|
||||
t.Index("ix_parties_kind", "kind");
|
||||
t.ForeignKey("fk_parties_category", "category_id", "party_categories", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_parties_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_addresses", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("name", 200).NotNull();
|
||||
t.String("address", 200);
|
||||
t.String("street_number", 20);
|
||||
t.String("postal_code", 10);
|
||||
t.String("city", 100);
|
||||
t.String("province", 10);
|
||||
t.String("country_code", 2).NotNull();
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_party_addresses_party", "party_id");
|
||||
t.ForeignKey("fk_party_addresses_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_contacts", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("name", 120).NotNull();
|
||||
t.String("role", 80);
|
||||
t.String("phone", 40);
|
||||
t.String("mobile", 40);
|
||||
t.String("email", 200);
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_party_contacts_party", "party_id");
|
||||
t.ForeignKey("fk_party_contacts_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_bank_accounts", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("iban", 34).NotNull();
|
||||
t.String("bic", 11);
|
||||
t.String("bank_name", 100);
|
||||
t.String("bank_code", 10);
|
||||
t.String("branch_code", 10);
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.AuditColumns();
|
||||
t.Index("ix_party_bank_accounts_party", "party_id");
|
||||
t.ForeignKey("fk_party_bank_accounts_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_sales_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Int64("price_list_id");
|
||||
t.Decimal("discount1");
|
||||
t.Decimal("discount2");
|
||||
t.Int64("payment_term_id");
|
||||
t.Int64("company_bank_account_id");
|
||||
t.Int64("carrier_id");
|
||||
t.Int64("shipping_term_id");
|
||||
t.Int64("warehouse_id");
|
||||
t.Decimal("credit_limit");
|
||||
t.Bool("blocked").NotNull().Default(false);
|
||||
t.Bool("group_delivery_notes").NotNull().Default(true);
|
||||
t.Int32("invoice_day");
|
||||
t.String("send_documents", 40).NotNull();
|
||||
t.String("documents_email", 200);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_sales_terms_party", "party_id");
|
||||
t.ForeignKey("fk_party_sales_terms_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_sales_terms_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_bank_account", "company_bank_account_id", "bank_accounts", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_carrier", "carrier_id", "carriers", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_sales_terms_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_purchase_terms", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Int64("payment_term_id");
|
||||
t.Int32("lead_time_days");
|
||||
t.Decimal("minimum_order");
|
||||
t.Decimal("discount");
|
||||
t.Int64("shipping_term_id");
|
||||
t.String("vat_register_code", 10);
|
||||
t.String("cost_account_code", 20);
|
||||
t.String("orders_email", 200);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_purchase_terms_party", "party_id");
|
||||
t.ForeignKey("fk_party_purchase_terms_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_purchase_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_purchase_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("party_fiscal", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("recipient_code", 7);
|
||||
t.String("recipient_pec", 200);
|
||||
t.String("administration_reference", 20);
|
||||
t.Bool("attach_pdf").NotNull().Default(true);
|
||||
t.Bool("send_copy").NotNull().Default(false);
|
||||
t.Bool("split_payment").NotNull().Default(false);
|
||||
t.Bool("reverse_charge").NotNull().Default(false);
|
||||
t.Int64("tax_code_id");
|
||||
t.String("exigibility", 1);
|
||||
t.Bool("stamp_duty_charged").NotNull().Default(true);
|
||||
t.Bool("withholding").NotNull().Default(false);
|
||||
t.Decimal("withholding_rate");
|
||||
t.String("withholding_reason", 4);
|
||||
t.String("pension_fund", 4);
|
||||
t.Decimal("pension_fund_rate");
|
||||
t.Bool("enasarco").NotNull().Default(false);
|
||||
t.Bool("intent_active").NotNull().Default(false);
|
||||
t.String("intent_number", 40);
|
||||
t.Date("intent_date");
|
||||
t.String("intent_protocol", 40);
|
||||
t.Int64("intent_tax_code_id");
|
||||
t.Decimal("intent_ceiling");
|
||||
t.Decimal("intent_used").NotNull().Default(0m);
|
||||
t.Date("intent_from");
|
||||
t.Date("intent_to");
|
||||
t.String("gln", 13);
|
||||
t.String("eori", 17);
|
||||
t.String("our_code", 40);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_party_fiscal_party", "party_id");
|
||||
t.ForeignKey("fk_party_fiscal_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_party_fiscal_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_party_fiscal_intent_tax_code", "intent_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="Party"/> to <c>parties</c>.</summary>
|
||||
public sealed class PartyMap : EntityMap<Party>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyMap()
|
||||
{
|
||||
ToTable("parties");
|
||||
Map(x => x.Code).MaxLength(30);
|
||||
Map(x => x.PreviousCode).MaxLength(30);
|
||||
Map(x => x.Name).MaxLength(200);
|
||||
Map(x => x.FirstName).MaxLength(80);
|
||||
Map(x => x.LastName).MaxLength(80);
|
||||
Map(x => x.FiscalName).MaxLength(200);
|
||||
Map(x => x.VatNumber).MaxLength(30);
|
||||
Map(x => x.TaxCode).MaxLength(30);
|
||||
Map(x => x.Rea).MaxLength(20);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.StreetNumber).MaxLength(20);
|
||||
Map(x => x.PostalCode).MaxLength(10);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.Province).MaxLength(10);
|
||||
Map(x => x.CountryCode).MaxLength(2);
|
||||
Map(x => x.Phone).MaxLength(40);
|
||||
Map(x => x.Email).MaxLength(200);
|
||||
Map(x => x.Pec).MaxLength(200);
|
||||
Map(x => x.Website).MaxLength(200);
|
||||
Map(x => x.Language).MaxLength(5);
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
Map(x => x.CustomerAccountCode).MaxLength(20);
|
||||
Map(x => x.SupplierAccountCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyAddress"/> to <c>party_addresses</c>.</summary>
|
||||
public sealed class PartyAddressMap : EntityMap<PartyAddress>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyAddressMap()
|
||||
{
|
||||
ToTable("party_addresses");
|
||||
Map(x => x.Name).MaxLength(200);
|
||||
Map(x => x.Address).MaxLength(200);
|
||||
Map(x => x.StreetNumber).MaxLength(20);
|
||||
Map(x => x.PostalCode).MaxLength(10);
|
||||
Map(x => x.City).MaxLength(100);
|
||||
Map(x => x.Province).MaxLength(10);
|
||||
Map(x => x.CountryCode).MaxLength(2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyContact"/> to <c>party_contacts</c>.</summary>
|
||||
public sealed class PartyContactMap : EntityMap<PartyContact>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyContactMap()
|
||||
{
|
||||
ToTable("party_contacts");
|
||||
Map(x => x.Name).MaxLength(120);
|
||||
Map(x => x.Role).MaxLength(80);
|
||||
Map(x => x.Phone).MaxLength(40);
|
||||
Map(x => x.Mobile).MaxLength(40);
|
||||
Map(x => x.Email).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyBankAccount"/> to <c>party_bank_accounts</c>.</summary>
|
||||
public sealed class PartyBankAccountMap : EntityMap<PartyBankAccount>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyBankAccountMap()
|
||||
{
|
||||
ToTable("party_bank_accounts");
|
||||
Map(x => x.Iban).MaxLength(34);
|
||||
Map(x => x.Bic).MaxLength(11);
|
||||
Map(x => x.BankName).MaxLength(100);
|
||||
Map(x => x.BankCode).MaxLength(10);
|
||||
Map(x => x.BranchCode).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartySalesTerms"/> to <c>party_sales_terms</c>.</summary>
|
||||
public sealed class PartySalesTermsMap : EntityMap<PartySalesTerms>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartySalesTermsMap()
|
||||
{
|
||||
ToTable("party_sales_terms");
|
||||
Map(x => x.DocumentsEmail).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyPurchaseTerms"/> to <c>party_purchase_terms</c>.</summary>
|
||||
public sealed class PartyPurchaseTermsMap : EntityMap<PartyPurchaseTerms>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyPurchaseTermsMap()
|
||||
{
|
||||
ToTable("party_purchase_terms");
|
||||
Map(x => x.VatRegisterCode).MaxLength(10);
|
||||
Map(x => x.CostAccountCode).MaxLength(20);
|
||||
Map(x => x.OrdersEmail).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyFiscal"/> to <c>party_fiscal</c>.</summary>
|
||||
public sealed class PartyFiscalMap : EntityMap<PartyFiscal>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyFiscalMap()
|
||||
{
|
||||
ToTable("party_fiscal");
|
||||
Map(x => x.RecipientCode).MaxLength(7);
|
||||
Map(x => x.RecipientPec).MaxLength(200);
|
||||
Map(x => x.AdministrationReference).MaxLength(20);
|
||||
Map(x => x.Exigibility).MaxLength(1);
|
||||
Map(x => x.WithholdingReason).MaxLength(4);
|
||||
Map(x => x.PensionFund).MaxLength(4);
|
||||
Map(x => x.IntentNumber).MaxLength(40);
|
||||
Map(x => x.IntentProtocol).MaxLength(40);
|
||||
Map(x => x.Gln).MaxLength(13);
|
||||
Map(x => x.Eori).MaxLength(17);
|
||||
Map(x => x.OurCode).MaxLength(40);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
@* The foot of a list of details of a party (addresses, contacts, bank accounts): what to say when it is empty and the
|
||||
button that adds one. *@
|
||||
<div class="kh-detailfoot">
|
||||
@if (Empty is not null)
|
||||
{
|
||||
<span class="muted">@Empty</span>
|
||||
}
|
||||
@if (CanAdd)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="OnAdd"><KhIcon Name="plus" /> @AddText</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
/// <summary>The text of an empty list, or <see langword="null"/>.</summary>
|
||||
[Parameter]
|
||||
public string? Empty { get; set; }
|
||||
|
||||
/// <summary>Whether a detail can be added.</summary>
|
||||
[Parameter]
|
||||
public bool CanAdd { get; set; }
|
||||
|
||||
/// <summary>The text of the button.</summary>
|
||||
[Parameter]
|
||||
public string AddText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Adds a detail.</summary>
|
||||
[Parameter]
|
||||
public EventCallback OnAdd { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
@page "/anagrafiche/clienti"
|
||||
@page "/anagrafiche/fornitori"
|
||||
@page "/anagrafiche/contatti"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Parties
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Parties
|
||||
@using Khaemhat.Web.Parties
|
||||
@inject ShellSession Session
|
||||
@inject PartyService Parties
|
||||
@inject TableService Tables
|
||||
@inject ToastService Toasts
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The radar of the parties (SPEC §11.2, mockups 012 and 013): customers, suppliers, or prospects and leads. Search on
|
||||
code, name, VAT number, tax code and city; filters for kind, subject and state; selection to disable or enable; Enter
|
||||
or double click opens the record. Turnover and overdue arrive with sales (M5) and the schedule (M9). *@
|
||||
<KhPageTitle Text="@Title" Icon="users" />
|
||||
|
||||
@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["Parties.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
<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="PartyRow" @key="_archive" @ref="_radar" Id="@("parties." + PartyScreens.SegmentOf(_archive))" Columns="Columns" Source="ListAsync"
|
||||
KeyOf="r => r.Id" Selectable="CanWrite" SelectionChanged="SetSelection" OnOpen="Open" QuickFilters="QuickFilters"
|
||||
InitialFilters="InitialFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Parties.Radar.Search"]"
|
||||
ExportName="@PartyScreens.SegmentOf(_archive)" Label="@Title">
|
||||
<Toolbar>
|
||||
@if (CanWrite)
|
||||
{
|
||||
<button type="button" class="btn primary" @onclick="() => New(null)"><KhIcon Name="plus" /> @T["Parties.New." + PartyScreens.NewKindOf(_archive)]</button>
|
||||
@if (_archive == PartyArchive.Contacts)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="() => New(PartyKind.Lead)"><KhIcon Name="plus" /> @T["Parties.New.Lead"]</button>
|
||||
}
|
||||
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(true)">
|
||||
<KhIcon Name="x-circle" /> @T["Parties.Actions.Disable"]
|
||||
</button>
|
||||
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(false)">
|
||||
<KhIcon Name="check-circle" /> @T["Parties.Actions.Enable"]
|
||||
</button>
|
||||
}
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
}
|
||||
|
||||
@code {
|
||||
private PartyArchive _archive;
|
||||
private PartyLookups _lookups = PartyLookups.Empty;
|
||||
private KhRadar<PartyRow>? _radar;
|
||||
private List<long> _selected = [];
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
|
||||
private string Title => T["Parties.Archives." + _archive];
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission);
|
||||
|
||||
private static IReadOnlyList<ListFilter> InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")];
|
||||
|
||||
private IReadOnlyList<KhColumn<PartyRow>> Columns =>
|
||||
[
|
||||
new("code", T["Parties.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "110px" },
|
||||
new("name", T["Parties.Fields.Name"], r => r.Name),
|
||||
new("vatNumber", T["Parties.Radar.Identifier"], r => r.Identifier) { Width = "170px" },
|
||||
new("city", T["Parties.Radar.City"], r => r.Province is { } p ? r.City + " (" + p + ")" : r.City) { Width = "170px" },
|
||||
new("payment", T["Parties.Radar.Payment"], r => PartyScreens.Describe(_lookups.PaymentTerms, r.Terms?.PaymentTermId, full: true)) { Sortable = false, Visible = _archive != PartyArchive.Contacts },
|
||||
new("priceList", T["Parties.Radar.PriceList"], r => PartyScreens.Describe(_lookups.PriceLists, r.Terms?.PriceListId)) { Sortable = false, Width = "90px", Visible = _archive == PartyArchive.Customers },
|
||||
new("salesperson", T["Parties.Radar.Salesperson"], r => PartyScreens.Describe(_lookups.Salespeople, r.SalespersonId, full: true)) { Width = "120px" },
|
||||
new("kind", T["Parties.Radar.Kind"], r => T["Parties.Kinds." + r.Kind]) { Width = "100px", Visible = _archive == PartyArchive.Contacts },
|
||||
new("state", T["Parties.Radar.State"], r => StateOf(r).Text)
|
||||
{
|
||||
Sortable = false, Width = "130px",
|
||||
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||
[
|
||||
.. _archive == PartyArchive.Contacts
|
||||
? [new KhQuickFilter("kind", T["Parties.Radar.Kind"],
|
||||
[new(string.Empty, T["Parties.Radar.All"]), new(nameof(PartyKind.Prospect), T["Parties.Kinds.Prospect"]), new(nameof(PartyKind.Lead), T["Parties.Kinds.Lead"])])]
|
||||
: Array.Empty<KhQuickFilter>(),
|
||||
new("subjectType", T["Parties.Radar.Subject"],
|
||||
[new(string.Empty, T["Parties.Radar.All"]), .. PartyScreens.Choices<SubjectType>(T, "SubjectTypes")]),
|
||||
new("salesperson", T["Parties.Radar.Salesperson"], [new(string.Empty, T["Parties.Radar.All"]), .. _lookups.Salespeople]),
|
||||
new("disabled", T["Parties.Radar.State"],
|
||||
[new(string.Empty, T["Parties.Radar.All"]), new("false", T["Parties.Radar.Active"]), new("true", T["Parties.Radar.Disabled"])]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
_archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri));
|
||||
_selected = [];
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
_lookups = await PartyLookups.ForRadarAsync(Tables, actor, company);
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
private (string Text, KhTone Tone) StateOf(PartyRow row) => row switch
|
||||
{
|
||||
{ Disabled: true } => (T["Parties.States.Disabled"], KhTone.Neutral),
|
||||
{ Terms.Blocked: true } => (T["Parties.States.Blocked"], KhTone.Error),
|
||||
{ Terms.SplitPayment: true } => (T["Parties.States.Split"], KhTone.Info),
|
||||
{ SubjectType: SubjectType.EuCompany or SubjectType.NonEuCompany or SubjectType.Person } => (T["Parties.SubjectTypes." + row.SubjectType], KhTone.Info),
|
||||
{ Kind: PartyKind.Customer, IsAlsoSupplier: true } when _archive == PartyArchive.Suppliers => (T["Parties.States.AlsoCustomer"], KhTone.Accent),
|
||||
{ IsAlsoSupplier: true } => (T["Parties.States.AlsoSupplier"], KhTone.Accent),
|
||||
_ => (T["Parties.States.Active"], KhTone.Ok),
|
||||
};
|
||||
|
||||
private Task<ListPage<PartyRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? Parties.ListAsync(actor, company, _archive, query, cancellationToken)
|
||||
: Task.FromResult(new ListPage<PartyRow>([], 0, new Dictionary<string, decimal>()));
|
||||
|
||||
private void SetSelection(IReadOnlyCollection<object> keys) => _selected = [.. keys.OfType<long>()];
|
||||
|
||||
private static string? RowClassOf(PartyRow row) => row.Disabled ? "muted" : null;
|
||||
|
||||
private void Open(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, row.Id));
|
||||
|
||||
private void New(PartyKind? kind) => Navigation.NavigateTo(PartyScreens.NewUrl(_archive, kind));
|
||||
|
||||
private async Task SetDisabledAsync(bool disabled)
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var count = await Parties.SetDisabledAsync(actor, company, _selected, disabled);
|
||||
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", count));
|
||||
if (_radar is not null)
|
||||
{
|
||||
await _radar.ReloadAsync();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,939 @@
|
||||
@page "/anagrafiche/clienti/nuovo"
|
||||
@page "/anagrafiche/clienti/{Id:long}"
|
||||
@page "/anagrafiche/fornitori/nuovo"
|
||||
@page "/anagrafiche/fornitori/{Id:long}"
|
||||
@page "/anagrafiche/contatti/nuovo"
|
||||
@page "/anagrafiche/contatti/{Id:long}"
|
||||
@attribute [Authorize]
|
||||
@inherits MasterDataPage<PartyRecord>
|
||||
@using Khaemhat.Application.Audit
|
||||
@using Khaemhat.Application.Parties
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Application.Tables
|
||||
@using Khaemhat.Core.Common
|
||||
@using Khaemhat.Core.Parties
|
||||
@using Khaemhat.Fiscal.Abstractions
|
||||
@using Khaemhat.Infrastructure.Http
|
||||
@using Khaemhat.Web.Parties
|
||||
@using Khaemhat.Web.Tables
|
||||
@inject ShellSession Session
|
||||
@inject PartyService Parties
|
||||
@inject TableService Tables
|
||||
@inject AutoFillService AutoFill
|
||||
@inject AttachmentService Attachments
|
||||
|
||||
@* The record of a party (SPEC §11.2, mockups 014-016): header with identity and conditions, tabs for main data,
|
||||
addresses, contacts, terms, fiscal data and e-invoice, banks, notes with attachments, history. The checks are those
|
||||
of PartyService: errors stop the save and open the tab of the first one, warnings are shown after saving. *@
|
||||
<KhPageTitle Text="@PageTitle" Icon="@KindIcon" />
|
||||
|
||||
@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["Parties.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
<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)
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="alert" Class="lg" />
|
||||
<h1>@T["Parties.NotFound"]</h1>
|
||||
<a class="btn" href="@PartyScreens.RadarUrl(_archive)">@T["Parties.Archives." + _archive]</a>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhRecordLayout Page="this">
|
||||
<Heading>
|
||||
<KhDocHead KindIcon="@KindIcon" KindLabel="@T["Parties.Kinds." + P.Kind]" Number="@(P.Code.Length > 0 ? P.Code : T["Parties.CodeAuto"])"
|
||||
PartyName="@(P.Name.Length > 0 ? P.Name : T["Parties.NewTitle"])" PartyLines="HeadLines">
|
||||
<Facts>
|
||||
<span>@T["Parties.SubjectTypes." + P.SubjectType]</span>
|
||||
@if (P.PreviousCode is { } previous)
|
||||
{
|
||||
<span>· @T["Parties.Fields.PreviousCode"] <b>@previous</b></span>
|
||||
}
|
||||
</Facts>
|
||||
<State>
|
||||
@if (P.Disabled)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Neutral">@T["Parties.States.Disabled"]</KhBadge>
|
||||
}
|
||||
else if (Record.Sales.Blocked)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Error">@T["Parties.States.Blocked"]</KhBadge>
|
||||
}
|
||||
else if (!IsNew)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Ok">@T["Parties.States.Active"]</KhBadge>
|
||||
}
|
||||
@if (P.Kind == PartyKind.Customer && P.IsAlsoSupplier)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Accent">@T["Parties.States.AlsoSupplier"]</KhBadge>
|
||||
}
|
||||
@if (P.IsDemo)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Parties.States.Demo"]</KhBadge>
|
||||
}
|
||||
@if (IsModified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||
}
|
||||
</State>
|
||||
<Chips>
|
||||
@if (PartyScreens.Describe(_lookups.PaymentTerms, PaymentTermId, full: true) is { } payment)
|
||||
{
|
||||
<KhChip Icon="coins" Text="@T["Parties.Fields.PaymentTermId"]" Value="@payment" />
|
||||
}
|
||||
@if (P.IsCustomer && PartyScreens.Describe(_lookups.PriceLists, Record.Sales.PriceListId) is { } list)
|
||||
{
|
||||
<KhChip Icon="tag" Text="@T["Parties.Fields.PriceListId"]" Value="@list" />
|
||||
}
|
||||
@if (PartyScreens.Describe(_lookups.Salespeople, P.SalespersonId, full: true) is { } salesperson)
|
||||
{
|
||||
<KhChip Icon="user" Text="@T["Parties.Fields.SalespersonId"]" Value="@salesperson" />
|
||||
}
|
||||
@if (P.VatCheck != VatCheckStatus.None)
|
||||
{
|
||||
<KhChip Icon="@(P.VatCheck == VatCheckStatus.Valid ? "shield-check" : "alert")" Text="VIES" Value="@T["Parties.Vies." + P.VatCheck]"
|
||||
Tone="@(P.VatCheck == VatCheckStatus.Valid ? KhTone.Ok : KhTone.Warning)"
|
||||
Title="@(P.VatCheckedAt is { } at ? T.Format("Parties.Vies.Checked", T.Date(DateOnly.FromDateTime(at.ToLocalTime()))) : null)" />
|
||||
}
|
||||
@if (Record.Fiscal.SplitPayment)
|
||||
{
|
||||
<KhChip Icon="file-check" Text="@T["Parties.Fields.SplitPayment"]" />
|
||||
}
|
||||
</Chips>
|
||||
</KhDocHead>
|
||||
</Heading>
|
||||
<ChildContent>
|
||||
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
|
||||
@switch (ActiveTab)
|
||||
{
|
||||
case PartyScreens.Tabs.Main:
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Identity"]" Icon="user">
|
||||
<KhTextBox Label="@T["Parties.Fields.Code"]" Name="Code" Value="@P.Code" ValueChanged="v => Change(() => P.Code = v ?? string.Empty)" Mono="true"
|
||||
Placeholder="@T["Parties.CodeAuto"]" Span="4" MaxLength="30" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.Kind"]" Name="Kind" Options="KindChoices" Value="@P.Kind.ToString()" Span="4"
|
||||
Disabled="@(!IsNew || _archive != PartyArchive.Contacts)" ValueChanged="SetKind" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.SubjectType"]" Name="SubjectType" Options="SubjectChoices" Value="@P.SubjectType.ToString()" Span="4"
|
||||
ValueChanged="SetSubjectAsync" />
|
||||
@if (P.SubjectType == SubjectType.Person)
|
||||
{
|
||||
<KhTextBox Label="@T["Parties.Fields.LastName"]" Name="LastName" Value="@P.LastName" ValueChanged="v => Change(() => P.LastName = v)" MaxLength="80" />
|
||||
<KhTextBox Label="@T["Parties.Fields.FirstName"]" Name="FirstName" Value="@P.FirstName" ValueChanged="v => Change(() => P.FirstName = v)" MaxLength="80" />
|
||||
}
|
||||
<KhTextBox Label="@T["Parties.Fields.Name"]" Name="Name" Value="@P.Name" ValueChanged="v => Change(() => P.Name = v ?? string.Empty)" Span="12" MaxLength="200"
|
||||
Required="@(P.SubjectType != SubjectType.Person)" />
|
||||
<KhTextBox Label="@T["Parties.Fields.VatNumber"]" Name="VatNumber" Value="@P.VatNumber" ValueChanged="v => Change(() => P.VatNumber = v)" Mono="true" Span="4" MaxLength="30" />
|
||||
<KhTextBox Label="@T["Parties.Fields.TaxCode"]" Name="TaxCode" Value="@P.TaxCode" ValueChanged="v => Change(() => P.TaxCode = v)" Mono="true" Span="4" MaxLength="30" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Rea"]" Name="Rea" Value="@P.Rea" ValueChanged="v => Change(() => P.Rea = v)" Span="4" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Parties.Fields.FiscalName"]" Name="FiscalName" Value="@P.FiscalName" ValueChanged="v => Change(() => P.FiscalName = v)" Span="12" MaxLength="200" />
|
||||
</KhFieldGroup>
|
||||
@if (P.SubjectType == SubjectType.Person && !IsReadOnly)
|
||||
{
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Birth"]" Icon="calendar">
|
||||
<KhDateBox Label="@T["Parties.Fields.BirthDate"]" Name="BirthDate" @bind-Value="_birthDate" Span="4" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.Sex"]" Name="Sex" Options="SexChoices" @bind-Value="_sex" Span="2" />
|
||||
<KhTextBox Label="@T["Parties.Fields.BirthPlace"]" Name="BirthPlace" @bind-Value="_birthPlace" Span="6" />
|
||||
<div class="c12">
|
||||
<button type="button" class="btn" @onclick="ComputeTaxCodeAsync"><KhIcon Name="refresh" /> @T["Parties.Actions.TaxCode"]</button>
|
||||
</div>
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Office"]" Icon="building">
|
||||
<KhTextBox Label="@T["Parties.Fields.Address"]" Name="Address" Value="@P.Address" ValueChanged="v => Change(() => P.Address = v)" Span="9" MaxLength="200" />
|
||||
<KhTextBox Label="@T["Parties.Fields.StreetNumber"]" Name="StreetNumber" Value="@P.StreetNumber" ValueChanged="v => Change(() => P.StreetNumber = v)" Span="3" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Parties.Fields.PostalCode"]" Name="PostalCode" Value="@P.PostalCode" ValueChanged="SetPostalCodeAsync" Mono="true" Span="3" MaxLength="10" />
|
||||
<KhTextBox Label="@T["Parties.Fields.City"]" Name="City" Value="@P.City" ValueChanged="SetCityAsync" Span="6" MaxLength="100" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Province"]" Name="Province" Value="@P.Province" ValueChanged="v => Change(() => P.Province = v)" Span="3" MaxLength="10" />
|
||||
@if (_places.Count > 1)
|
||||
{
|
||||
<div class="c12 kh-places">
|
||||
<span class="muted sm">@T.Format("Parties.Actions.Places", _places.Count)</span>
|
||||
@foreach (var place in _places)
|
||||
{
|
||||
<button type="button" class="btn sm" @onclick="() => PickPlace(place)">@place.Name (@place.ProvinceCode)</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.CountryCode"]" Name="CountryCode" Options="_lookups.Countries" Value="@P.CountryCode" Span="6"
|
||||
ValueChanged="v => Change(() => P.CountryCode = v ?? string.Empty)" Required="true" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Reach"]" Icon="phone">
|
||||
<KhTextBox Label="@T["Parties.Fields.Phone"]" Name="Phone" Value="@P.Phone" ValueChanged="v => Change(() => P.Phone = v)" Type="tel" MaxLength="40" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Email"]" Name="Email" Value="@P.Email" ValueChanged="v => Change(() => P.Email = v)" Type="email" MaxLength="200" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Pec"]" Name="Pec" Value="@P.Pec" ValueChanged="v => Change(() => P.Pec = v)" Type="email" MaxLength="200" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Website"]" Name="Website" Value="@P.Website" ValueChanged="v => Change(() => P.Website = v)" MaxLength="200" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Classification"]" Icon="tag" Wide="true">
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.CategoryId"]" Name="CategoryId" Options="_lookups.Categories" Empty="" Span="4"
|
||||
Value="@PartyScreens.Text(P.CategoryId)" ValueChanged="v => Change(() => P.CategoryId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="4"
|
||||
Value="@PartyScreens.Text(P.SalespersonId)" ValueChanged="v => Change(() => P.SalespersonId = PartyScreens.Id(v))" />
|
||||
<KhDateBox Label="@T["Parties.Fields.Since"]" Name="Since" Value="P.Since" ValueChanged="v => Change(() => P.Since = v)" Span="4" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Language"]" Name="Language" Value="@P.Language" ValueChanged="v => Change(() => P.Language = v ?? string.Empty)" Span="2" MaxLength="5" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_lookups.Currencies" Value="@P.CurrencyCode" Span="4"
|
||||
ValueChanged="v => Change(() => P.CurrencyCode = v ?? string.Empty)" />
|
||||
<KhCheck Label="@T["Parties.Fields.PrivacyAccepted"]" Name="PrivacyAccepted" Value="P.PrivacyAccepted" ValueChanged="v => Change(() => P.PrivacyAccepted = v)" Span="3" />
|
||||
<KhCheck Label="@T["Parties.Fields.Marketing"]" Name="Marketing" Value="P.Marketing" ValueChanged="v => Change(() => P.Marketing = v)" Span="3" />
|
||||
@if (P.Kind == PartyKind.Customer)
|
||||
{
|
||||
<KhCheck Label="@T["Parties.Fields.IsAlsoSupplier"]" Name="IsAlsoSupplier" Value="P.IsAlsoSupplier" ValueChanged="v => Change(() => P.IsAlsoSupplier = v)" Span="4" />
|
||||
}
|
||||
<KhCheck Label="@T["Parties.Fields.Disabled"]" Name="Disabled" Value="P.Disabled" ValueChanged="v => Change(() => P.Disabled = v)" Span="4" />
|
||||
</KhFieldGroup>
|
||||
break;
|
||||
|
||||
case PartyScreens.Tabs.Addresses:
|
||||
@for (var i = 0; i < Record.Addresses.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var a = Record.Addresses[i];
|
||||
<KhFieldGroup Title="@(string.IsNullOrWhiteSpace(a.Name) ? T["Parties.AddressKinds." + a.Kind] : a.Name)" Icon="pin" Wide="true">
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.AddressKind"]" Name="@Key("Addresses", index, "Kind")" Options="AddressKindChoices" Value="@a.Kind.ToString()" Span="3"
|
||||
ValueChanged="v => SetAddressKind(a, v)" />
|
||||
<KhTextBox Label="@T["Parties.Fields.AddressName"]" Name="@Key("Addresses", index, "Name")" Value="@a.Name" ValueChanged="v => Change(() => a.Name = v ?? string.Empty)" Span="6" Required="true" MaxLength="200" />
|
||||
<KhCheck Label="@T["Parties.Fields.IsDefault"]" Name="@Key("Addresses", index, "IsDefault")" Value="a.IsDefault" ValueChanged="v => Change(() => a.IsDefault = v)" Span="3" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Address"]" Name="@Key("Addresses", index, "Address")" Value="@a.Address" ValueChanged="v => Change(() => a.Address = v)" Span="5" MaxLength="200" />
|
||||
<KhTextBox Label="@T["Parties.Fields.StreetNumber"]" Name="@Key("Addresses", index, "StreetNumber")" Value="@a.StreetNumber" ValueChanged="v => Change(() => a.StreetNumber = v)" Span="1" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Parties.Fields.PostalCode"]" Name="@Key("Addresses", index, "PostalCode")" Value="@a.PostalCode" ValueChanged="v => Change(() => a.PostalCode = v)" Mono="true" Span="2" MaxLength="10" />
|
||||
<KhTextBox Label="@T["Parties.Fields.City"]" Name="@Key("Addresses", index, "City")" Value="@a.City" ValueChanged="v => Change(() => a.City = v)" Span="2" MaxLength="100" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Province"]" Name="@Key("Addresses", index, "Province")" Value="@a.Province" ValueChanged="v => Change(() => a.Province = v)" Span="1" MaxLength="10" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.CountryCode"]" Name="@Key("Addresses", index, "CountryCode")" Options="_lookups.Countries" Value="@a.CountryCode" Span="1"
|
||||
ValueChanged="v => Change(() => a.CountryCode = v ?? string.Empty)" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Notes"]" Name="@Key("Addresses", index, "Notes")" Value="@a.Notes" ValueChanged="v => Change(() => a.Notes = v)" Span="10" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Addresses, index)"><KhIcon Name="trash" /> @T["Parties.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.Addresses.Count == 0 ? T["Parties.Empty.Addresses"] : null)" CanAdd="!IsReadOnly" AddText="@T["Parties.Actions.AddAddress"]"
|
||||
OnAdd="() => Add(Record.Addresses, new PartyAddress { CountryCode = P.CountryCode, Kind = PartyAddressKind.Delivery, IsDefault = Record.Addresses.Count == 0 })" />
|
||||
break;
|
||||
|
||||
case PartyScreens.Tabs.Contacts:
|
||||
@for (var i = 0; i < Record.Contacts.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var c = Record.Contacts[i];
|
||||
<KhFieldGroup Title="@(string.IsNullOrWhiteSpace(c.Name) ? T["Parties.Actions.AddContact"] : c.Name)" Icon="user" Wide="true">
|
||||
<KhTextBox Label="@T["Parties.Fields.ContactName"]" Name="@Key("Contacts", index, "Name")" Value="@c.Name" ValueChanged="v => Change(() => c.Name = v ?? string.Empty)" Span="4" Required="true" MaxLength="120" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Role"]" Name="@Key("Contacts", index, "Role")" Value="@c.Role" ValueChanged="v => Change(() => c.Role = v)" Span="3" MaxLength="80" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Phone"]" Name="@Key("Contacts", index, "Phone")" Value="@c.Phone" ValueChanged="v => Change(() => c.Phone = v)" Type="tel" Span="2" MaxLength="40" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Mobile"]" Name="@Key("Contacts", index, "Mobile")" Value="@c.Mobile" ValueChanged="v => Change(() => c.Mobile = v)" Type="tel" Span="3" MaxLength="40" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Email"]" Name="@Key("Contacts", index, "Email")" Value="@c.Email" ValueChanged="v => Change(() => c.Email = v)" Type="email" Span="4" MaxLength="200" />
|
||||
<KhCheck Label="@T["Parties.Fields.MainContact"]" Name="@Key("Contacts", index, "IsDefault")" Value="c.IsDefault" ValueChanged="v => Change(() => c.IsDefault = v)" Span="3" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Notes"]" Name="@Key("Contacts", index, "Notes")" Value="@c.Notes" ValueChanged="v => Change(() => c.Notes = v)" Span="3" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c2 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.Contacts, index)"><KhIcon Name="trash" /> @T["Parties.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.Contacts.Count == 0 ? T["Parties.Empty.Contacts"] : null)" CanAdd="!IsReadOnly" AddText="@T["Parties.Actions.AddContact"]"
|
||||
OnAdd="() => Add(Record.Contacts, new PartyContact { IsDefault = Record.Contacts.Count == 0 })" />
|
||||
break;
|
||||
|
||||
case PartyScreens.Tabs.Terms:
|
||||
@if (!P.IsCustomer && !P.IsSupplier)
|
||||
{
|
||||
<p class="muted kh-pad"><KhIcon Name="info" /> @T["Parties.NoTerms"]</p>
|
||||
}
|
||||
@if (P.IsCustomer)
|
||||
{
|
||||
var s = Record.Sales;
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Sales"]" Icon="cart">
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.PaymentTermId"]" Name="Sales.PaymentTermId" Options="_lookups.PaymentTerms" Empty="" Span="12"
|
||||
Value="@PartyScreens.Text(s.PaymentTermId)" ValueChanged="v => Change(() => s.PaymentTermId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.PriceListId"]" Name="Sales.PriceListId" Options="_lookups.PriceLists" Empty=""
|
||||
Value="@PartyScreens.Text(s.PriceListId)" ValueChanged="v => Change(() => s.PriceListId = PartyScreens.Id(v))" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.Discount1"]" Name="Sales.Discount1" Value="s.Discount1" ValueChanged="v => Change(() => s.Discount1 = v)" Min="0" Max="100" Span="3" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.Discount2"]" Name="Sales.Discount2" Value="s.Discount2" ValueChanged="v => Change(() => s.Discount2 = v)" Min="0" Max="100" Span="3" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.CompanyBankAccountId"]" Name="Sales.CompanyBankAccountId" Options="_lookups.BankAccounts" Empty=""
|
||||
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" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Delivery"]" Icon="truck">
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.CarrierId"]" Name="Sales.CarrierId" Options="_lookups.Carriers" Empty=""
|
||||
Value="@PartyScreens.Text(s.CarrierId)" ValueChanged="v => Change(() => s.CarrierId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.ShippingTermId"]" Name="Sales.ShippingTermId" Options="_lookups.ShippingTerms" Empty=""
|
||||
Value="@PartyScreens.Text(s.ShippingTermId)" ValueChanged="v => Change(() => s.ShippingTermId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.WarehouseId"]" Name="Sales.WarehouseId" Options="_lookups.Warehouses" Empty=""
|
||||
Value="@PartyScreens.Text(s.WarehouseId)" ValueChanged="v => Change(() => s.WarehouseId = PartyScreens.Id(v))" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.InvoiceDay"]" Name="Sales.InvoiceDay" Value="s.InvoiceDay" ValueChanged="v => Change(() => s.InvoiceDay = (int?)v)" Min="1" Max="31" Decimals="0" Span="3" />
|
||||
<KhCheck Label="@T["Parties.Fields.GroupDeliveryNotes"]" Name="Sales.GroupDeliveryNotes" Value="s.GroupDeliveryNotes" ValueChanged="v => Change(() => s.GroupDeliveryNotes = v)" Span="3" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.SendDocuments"]" Name="Sales.SendDocuments" Options="DeliveryChoices" Value="@s.SendDocuments.ToString()" Span="4"
|
||||
ValueChanged="v => SetDelivery(s, v)" />
|
||||
<KhTextBox Label="@T["Parties.Fields.DocumentsEmail"]" Name="Sales.DocumentsEmail" Value="@s.DocumentsEmail" ValueChanged="v => Change(() => s.DocumentsEmail = v)" Type="email" Span="8" MaxLength="200" />
|
||||
</KhFieldGroup>
|
||||
}
|
||||
@if (P.IsSupplier)
|
||||
{
|
||||
var u = Record.Purchase;
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Purchase"]" Icon="box" Wide="true">
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.PaymentTermId"]" Name="Purchase.PaymentTermId" Options="_lookups.PaymentTerms" Empty="" Span="4"
|
||||
Value="@PartyScreens.Text(u.PaymentTermId)" ValueChanged="v => Change(() => u.PaymentTermId = PartyScreens.Id(v))" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.LeadTimeDays"]" Name="Purchase.LeadTimeDays" Value="u.LeadTimeDays" ValueChanged="v => Change(() => u.LeadTimeDays = (int?)v)" Min="0" Decimals="0" Span="2" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.MinimumOrder"]" Name="Purchase.MinimumOrder" Value="u.MinimumOrder" ValueChanged="v => Change(() => u.MinimumOrder = v)" Min="0" Span="2" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.Discount"]" Name="Purchase.Discount" Value="u.Discount" ValueChanged="v => Change(() => u.Discount = v)" Min="0" Max="100" Span="2" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.ShippingTermId"]" Name="Purchase.ShippingTermId" Options="_lookups.ShippingTerms" Empty="" Span="2"
|
||||
Value="@PartyScreens.Text(u.ShippingTermId)" ValueChanged="v => Change(() => u.ShippingTermId = PartyScreens.Id(v))" />
|
||||
<KhTextBox Label="@T["Parties.Fields.VatRegisterCode"]" Name="Purchase.VatRegisterCode" Value="@u.VatRegisterCode" ValueChanged="v => Change(() => u.VatRegisterCode = v)" Span="2" MaxLength="10" />
|
||||
<KhTextBox Label="@T["Parties.Fields.CostAccountCode"]" Name="Purchase.CostAccountCode" Value="@u.CostAccountCode" ValueChanged="v => Change(() => u.CostAccountCode = v)" Mono="true" Span="3" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Parties.Fields.OrdersEmail"]" Name="Purchase.OrdersEmail" Value="@u.OrdersEmail" ValueChanged="v => Change(() => u.OrdersEmail = v)" Type="email" Span="7" MaxLength="200" />
|
||||
</KhFieldGroup>
|
||||
}
|
||||
@if (P.IsCustomer || P.IsSupplier)
|
||||
{
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Accounts"]" Icon="book" Wide="true">
|
||||
@if (P.IsCustomer)
|
||||
{
|
||||
<KhTextBox Label="@T["Parties.Fields.CustomerAccountCode"]" Name="CustomerAccountCode" Value="@P.CustomerAccountCode" ValueChanged="v => Change(() => P.CustomerAccountCode = v)" Mono="true" Span="3" MaxLength="20" />
|
||||
}
|
||||
@if (P.IsSupplier)
|
||||
{
|
||||
<KhTextBox Label="@T["Parties.Fields.SupplierAccountCode"]" Name="SupplierAccountCode" Value="@P.SupplierAccountCode" ValueChanged="v => Change(() => P.SupplierAccountCode = v)" Mono="true" Span="3" MaxLength="20" />
|
||||
}
|
||||
<p class="muted sm c6">@T["Parties.AccountsHint"]</p>
|
||||
</KhFieldGroup>
|
||||
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Parties.TermsHint"]</p>
|
||||
}
|
||||
break;
|
||||
|
||||
case PartyScreens.Tabs.Fiscal:
|
||||
var f = Record.Fiscal;
|
||||
<KhFieldGroup Title="@T["Parties.Groups.EInvoice"]" Icon="send">
|
||||
<KhTextBox Label="@T["Parties.Fields.RecipientCode"]" Name="Fiscal.RecipientCode" Value="@f.RecipientCode" ValueChanged="v => Change(() => f.RecipientCode = v)" Mono="true" Span="4" MaxLength="7" />
|
||||
<KhTextBox Label="@T["Parties.Fields.RecipientPec"]" Name="Fiscal.RecipientPec" Value="@f.RecipientPec" ValueChanged="v => Change(() => f.RecipientPec = v)" Type="email" Span="8" MaxLength="200" />
|
||||
<KhTextBox Label="@T["Parties.Fields.AdministrationReference"]" Name="Fiscal.AdministrationReference" Value="@f.AdministrationReference" ValueChanged="v => Change(() => f.AdministrationReference = v)" Span="6" MaxLength="20" />
|
||||
<KhTextBox Label="@T["Parties.Fields.OurCode"]" Name="Fiscal.OurCode" Value="@f.OurCode" ValueChanged="v => Change(() => f.OurCode = v)" Span="6" MaxLength="40" />
|
||||
<KhCheck Label="@T["Parties.Fields.AttachPdf"]" Name="Fiscal.AttachPdf" Value="f.AttachPdf" ValueChanged="v => Change(() => f.AttachPdf = v)" />
|
||||
<KhCheck Label="@T["Parties.Fields.SendCopy"]" Name="Fiscal.SendCopy" Value="f.SendCopy" ValueChanged="v => Change(() => f.SendCopy = v)" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Vat"]" Icon="euro">
|
||||
<KhCheck Label="@T["Parties.Fields.SplitPayment"]" Name="Fiscal.SplitPayment" Value="f.SplitPayment" ValueChanged="v => Change(() => f.SplitPayment = v)" />
|
||||
<KhCheck Label="@T["Parties.Fields.ReverseCharge"]" Name="Fiscal.ReverseCharge" Value="f.ReverseCharge" ValueChanged="v => Change(() => f.ReverseCharge = v)" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.TaxCodeId"]" Name="Fiscal.TaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="12"
|
||||
Value="@PartyScreens.Text(f.TaxCodeId)" ValueChanged="v => Change(() => f.TaxCodeId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.Exigibility"]" Name="Fiscal.Exigibility" Options="ExigibilityChoices" Empty="" Value="@f.Exigibility"
|
||||
ValueChanged="v => Change(() => f.Exigibility = v)" Disabled="f.SplitPayment" />
|
||||
<KhCheck Label="@T["Parties.Fields.StampDutyCharged"]" Name="Fiscal.StampDutyCharged" Value="f.StampDutyCharged" ValueChanged="v => Change(() => f.StampDutyCharged = v)" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Withholding"]" Icon="coins">
|
||||
<KhCheck Label="@T["Parties.Fields.Withholding"]" Name="Fiscal.Withholding" Value="f.Withholding" ValueChanged="v => Change(() => f.Withholding = v)" Span="4" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.WithholdingRate"]" Name="Fiscal.WithholdingRate" Value="f.WithholdingRate" ValueChanged="v => Change(() => f.WithholdingRate = v)" Min="0" Max="100" Span="4" />
|
||||
<KhTextBox Label="@T["Parties.Fields.WithholdingReason"]" Name="Fiscal.WithholdingReason" Value="@f.WithholdingReason" ValueChanged="v => Change(() => f.WithholdingReason = v)" Mono="true" Span="4" MaxLength="4" />
|
||||
<KhTextBox Label="@T["Parties.Fields.PensionFund"]" Name="Fiscal.PensionFund" Value="@f.PensionFund" ValueChanged="v => Change(() => f.PensionFund = v)" Mono="true" Span="4" MaxLength="4" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.PensionFundRate"]" Name="Fiscal.PensionFundRate" Value="f.PensionFundRate" ValueChanged="v => Change(() => f.PensionFundRate = v)" Min="0" Max="100" Span="4" />
|
||||
<KhCheck Label="@T["Parties.Fields.Enasarco"]" Name="Fiscal.Enasarco" Value="f.Enasarco" ValueChanged="v => Change(() => f.Enasarco = v)" Span="4" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Codes"]" Icon="key">
|
||||
<KhTextBox Label="@T["Parties.Fields.Gln"]" Name="Fiscal.Gln" Value="@f.Gln" ValueChanged="v => Change(() => f.Gln = v)" Mono="true" MaxLength="13" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Eori"]" Name="Fiscal.Eori" Value="@f.Eori" ValueChanged="v => Change(() => f.Eori = v)" Mono="true" MaxLength="17" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Intent"]" Icon="file-check" Wide="true">
|
||||
<KhCheck Label="@T["Parties.Fields.IntentActive"]" Name="Fiscal.IntentActive" Value="f.IntentActive" ValueChanged="v => Change(() => f.IntentActive = v)" Span="3" />
|
||||
<KhTextBox Label="@T["Parties.Fields.IntentNumber"]" Name="Fiscal.IntentNumber" Value="@f.IntentNumber" ValueChanged="v => Change(() => f.IntentNumber = v)" Span="3" MaxLength="40" />
|
||||
<KhDateBox Label="@T["Parties.Fields.IntentDate"]" Name="Fiscal.IntentDate" Value="f.IntentDate" ValueChanged="v => Change(() => f.IntentDate = v)" Span="2" />
|
||||
<KhTextBox Label="@T["Parties.Fields.IntentProtocol"]" Name="Fiscal.IntentProtocol" Value="@f.IntentProtocol" ValueChanged="v => Change(() => f.IntentProtocol = v)" Mono="true" Span="4" MaxLength="40" />
|
||||
<KhSelect TValue="string" Label="@T["Parties.Fields.IntentTaxCodeId"]" Name="Fiscal.IntentTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="4"
|
||||
Value="@PartyScreens.Text(f.IntentTaxCodeId)" ValueChanged="v => Change(() => f.IntentTaxCodeId = PartyScreens.Id(v))" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.IntentCeiling"]" Name="Fiscal.IntentCeiling" Value="f.IntentCeiling" ValueChanged="v => Change(() => f.IntentCeiling = v)" Min="0" Span="2" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.IntentUsed"]" Name="Fiscal.IntentUsed" Value="f.IntentUsed" ReadOnly="true" Span="2" />
|
||||
<KhNumberBox Label="@T["Parties.Fields.IntentRemaining"]" Name="Fiscal.IntentRemaining" Value="f.IntentRemaining" ReadOnly="true" Span="2" />
|
||||
<KhDateBox Label="@T["Parties.Fields.IntentFrom"]" Name="Fiscal.IntentFrom" Value="f.IntentFrom" ValueChanged="v => Change(() => f.IntentFrom = v)" Span="1" />
|
||||
<KhDateBox Label="@T["Parties.Fields.IntentTo"]" Name="Fiscal.IntentTo" Value="f.IntentTo" ValueChanged="v => Change(() => f.IntentTo = v)" Span="1" />
|
||||
<p class="muted sm c12">@T["Parties.IntentHint"]</p>
|
||||
</KhFieldGroup>
|
||||
break;
|
||||
|
||||
case PartyScreens.Tabs.Banks:
|
||||
@for (var i = 0; i < Record.BankAccounts.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var b = Record.BankAccounts[i];
|
||||
<KhFieldGroup Title="@(b.BankName ?? T["Parties.Fields.Iban"])" Icon="euro" Wide="true">
|
||||
<KhTextBox Label="@T["Parties.Fields.Iban"]" Name="@Key("BankAccounts", index, "Iban")" Value="@b.Iban" ValueChanged="v => SetIbanAsync(b, v)" Mono="true" Span="5" Required="true" MaxLength="42" />
|
||||
<KhTextBox Label="@T["Parties.Fields.BankName"]" Name="@Key("BankAccounts", index, "BankName")" Value="@b.BankName" ValueChanged="v => Change(() => b.BankName = v)" Span="4" MaxLength="100" />
|
||||
<KhTextBox Label="@T["Parties.Fields.Bic"]" Name="@Key("BankAccounts", index, "Bic")" Value="@b.Bic" ValueChanged="v => Change(() => b.Bic = v)" Mono="true" Span="3" MaxLength="11" />
|
||||
<KhTextBox Label="@T["Parties.Fields.BankCode"]" Name="@Key("BankAccounts", index, "BankCode")" Value="@b.BankCode" ReadOnly="true" Mono="true" Span="2" />
|
||||
<KhTextBox Label="@T["Parties.Fields.BranchCode"]" Name="@Key("BankAccounts", index, "BranchCode")" Value="@b.BranchCode" ReadOnly="true" Mono="true" Span="2" />
|
||||
<KhCheck Label="@T["Parties.Fields.IsDefault"]" Name="@Key("BankAccounts", index, "IsDefault")" Value="b.IsDefault" ValueChanged="v => Change(() => b.IsDefault = v)" Span="4" />
|
||||
@if (!IsReadOnly)
|
||||
{
|
||||
<div class="c4 kh-endrow">
|
||||
<button type="button" class="btn danger" @onclick="() => Remove(Record.BankAccounts, index)"><KhIcon Name="trash" /> @T["Parties.Actions.Remove"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
<DetailFooter Empty="@(Record.BankAccounts.Count == 0 ? T["Parties.Empty.Banks"] : null)" CanAdd="!IsReadOnly" AddText="@T["Parties.Actions.AddBank"]"
|
||||
OnAdd="() => Add(Record.BankAccounts, new PartyBankAccount { IsDefault = Record.BankAccounts.Count == 0 })" />
|
||||
break;
|
||||
|
||||
case PartyScreens.Tabs.Notes:
|
||||
<KhFieldGroup Title="@T["Parties.Groups.Notes"]" Icon="edit" Wide="true">
|
||||
<KhTextArea Label="@T["Parties.Fields.Notes"]" Name="Notes" Value="@P.Notes" ValueChanged="v => Change(() => P.Notes = v)" Span="12" Rows="6" />
|
||||
</KhFieldGroup>
|
||||
break;
|
||||
}
|
||||
</KhForm>
|
||||
@if (ActiveTab == PartyScreens.Tabs.Notes && !IsNew && Session.Permissions.Allows(AttachmentService.ReadPermission))
|
||||
{
|
||||
<div class="kh-tab-body"><KhAttachmentList Entity="@PartyService.Entity" EntityId="P.Id" OnCountChanged="c => _attachments = c" /></div>
|
||||
}
|
||||
@if (ActiveTab == PartyScreens.Tabs.History)
|
||||
{
|
||||
<div class="kh-tab-body"><KhAuditList Items="_history" FieldName="FieldLabel" /></div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhRecordLayout>
|
||||
}
|
||||
|
||||
@code {
|
||||
private PartyArchive _archive;
|
||||
private PartyLookups _lookups = PartyLookups.Empty;
|
||||
private IReadOnlyList<AuditItem> _history = [];
|
||||
private IReadOnlyList<PlaceSuggestion> _places = [];
|
||||
private int _attachments;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
private DateOnly? _birthDate;
|
||||
private string? _sex;
|
||||
private string? _birthPlace;
|
||||
|
||||
/// <summary>The party, absent for a new one.</summary>
|
||||
[Parameter]
|
||||
public long? Id { get; set; }
|
||||
|
||||
/// <summary>The kind of a new party among the contacts (<c>?tipo=lead</c>).</summary>
|
||||
[SupplyParameterFromQuery(Name = "tipo")]
|
||||
public string? Kind { get; set; }
|
||||
|
||||
private Party P => Record!.Party;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission);
|
||||
|
||||
private string KindIcon => Record?.Party.Kind switch
|
||||
{
|
||||
PartyKind.Supplier => "truck",
|
||||
PartyKind.Prospect or PartyKind.Lead => "target",
|
||||
_ => "users",
|
||||
};
|
||||
|
||||
private string PageTitle => Record is null ? T["Parties.Archives." + _archive]
|
||||
: IsNew ? T["Parties.New." + Record.Party.Kind]
|
||||
: (Record.Party.Code + " · " + Record.Party.Name);
|
||||
|
||||
private long? PaymentTermId => P.IsCustomer ? Record!.Sales.PaymentTermId : Record!.Purchase.PaymentTermId;
|
||||
|
||||
private IReadOnlyList<string> HeadLines
|
||||
{
|
||||
get
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var street = string.Join(' ', new[] { P.Address, P.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
var place = string.Join(' ', new[] { P.PostalCode, P.City, P.Province is { } p ? "(" + p + ")" : null }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
if (string.Join(" · ", new[] { street, place }.Where(s => s.Length > 0)) is { Length: > 0 } address)
|
||||
{
|
||||
lines.Add(address);
|
||||
}
|
||||
|
||||
var ids = new List<string>();
|
||||
if (P.VatNumber is { } vat)
|
||||
{
|
||||
ids.Add(T["Parties.Fields.VatNumber"] + " " + (P.CountryCode == "IT" ? vat : P.CountryCode + vat));
|
||||
}
|
||||
|
||||
if (P.TaxCode is { } tax && tax != P.VatNumber)
|
||||
{
|
||||
ids.Add(T["Parties.Fields.TaxCode"] + " " + tax);
|
||||
}
|
||||
|
||||
if (ids.Count > 0)
|
||||
{
|
||||
lines.Add(string.Join(" · ", ids));
|
||||
}
|
||||
|
||||
if (string.Join(" · ", new[] { P.Phone, P.Email ?? P.Pec }.Where(s => !string.IsNullOrWhiteSpace(s))) is { Length: > 0 } reach)
|
||||
{
|
||||
lines.Add(reach);
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<KhOption<string>> KindChoices => PartyScreens.Choices<PartyKind>(T, "Kinds");
|
||||
|
||||
private IReadOnlyList<KhOption<string>> SubjectChoices => PartyScreens.Choices<SubjectType>(T, "SubjectTypes");
|
||||
|
||||
private IReadOnlyList<KhOption<string>> AddressKindChoices => PartyScreens.Choices<PartyAddressKind>(T, "AddressKinds");
|
||||
|
||||
private IReadOnlyList<KhOption<string>> DeliveryChoices => PartyScreens.Choices<DocumentDelivery>(T, "Delivery");
|
||||
|
||||
private IReadOnlyList<KhOption<string>> SexChoices => PartyScreens.Choices<PersonSex>(T, "Sexes");
|
||||
|
||||
private IReadOnlyList<KhOption<string>> ExigibilityChoices => [.. new[] { "I", "D", "S" }.Select(v => new KhOption<string>(v, T["Parties.Exigibilities." + v]))];
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsReadOnly => !CanWrite;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool IsNew => Record is { Party.Id: 0 };
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool CanDelete => base.CanDelete && Session.Permissions.Allows(PartyService.DeletePermission);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string? NewUrl => CanWrite ? PartyScreens.NewUrl(_archive) : null;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] :
|
||||
[
|
||||
TabOf(PartyScreens.Tabs.Main, "user", "Main"),
|
||||
TabOf(PartyScreens.Tabs.Addresses, "pin", "Addresses", Record.Addresses.Count),
|
||||
TabOf(PartyScreens.Tabs.Contacts, "phone", "Contacts", Record.Contacts.Count),
|
||||
TabOf(PartyScreens.Tabs.Terms, "coins", "Terms"),
|
||||
TabOf(PartyScreens.Tabs.Fiscal, "file-check", "Fiscal"),
|
||||
TabOf(PartyScreens.Tabs.Banks, "euro", "Banks", Record.BankAccounts.Count),
|
||||
TabOf(PartyScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments),
|
||||
TabOf(PartyScreens.Tabs.History, "history", "History"),
|
||||
];
|
||||
|
||||
private KhTabItem TabOf(string id, string icon, string text, int? count = null)
|
||||
{
|
||||
// A tab with errors shows how many; otherwise how many details it holds.
|
||||
var errors = Validation.Messages.Count(m => PartyScreens.TabOf(m.Field) == id);
|
||||
return new(id, icon, T["Parties.Tabs." + text], errors > 0 ? errors : count is > 0 ? count : null);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
_archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri));
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission))
|
||||
{
|
||||
if (!_loaded)
|
||||
{
|
||||
_lookups = await PartyLookups.ForRecordAsync(Tables, actor, company);
|
||||
}
|
||||
|
||||
if (Record is null || Record.Party.Id != (Id ?? 0))
|
||||
{
|
||||
await ReloadAsync();
|
||||
MarkSaved();
|
||||
}
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task ReloadAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Validation.Clear();
|
||||
_places = [];
|
||||
if (Id is { } id)
|
||||
{
|
||||
Record = await Parties.GetAsync(actor, company, id);
|
||||
await LoadSideAsync(actor, company);
|
||||
}
|
||||
else
|
||||
{
|
||||
Record = await Parties.NewAsync(actor, company, PartyScreens.KindOf(_archive, Kind));
|
||||
_history = [];
|
||||
_attachments = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadSideAsync(Actor actor, string company)
|
||||
{
|
||||
if (Record is not { Party.Id: > 0 } record)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_history = [.. (await Parties.HistoryAsync(actor, company, record.Party.Id)).Select(AuditTrailService.Item)];
|
||||
_attachments = Session.Permissions.Allows(AttachmentService.ReadPermission)
|
||||
? await Attachments.CountAsync(actor, company, PartyService.Entity, record.Party.Id)
|
||||
: 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<bool> SaveCoreAsync()
|
||||
{
|
||||
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
Validation.Clear();
|
||||
try
|
||||
{
|
||||
var wasNew = IsNew;
|
||||
var problems = await Parties.ValidateAsync(actor, company, Record);
|
||||
if (problems.Any(p => !p.IsWarning))
|
||||
{
|
||||
Refuse(problems.Where(p => !p.IsWarning).Select(p => ((string?)p.Field, p.Code)));
|
||||
return false;
|
||||
}
|
||||
|
||||
Record = await Parties.SaveAsync(actor, company, Record);
|
||||
await LoadSideAsync(actor, company);
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T.Format("Parties.Actions.Warnings", string.Join(" ", problems.Select(p => Message(p.Code)))));
|
||||
}
|
||||
|
||||
if (wasNew)
|
||||
{
|
||||
MarkSaved();
|
||||
Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, Record.Party.Id), new NavigationOptions { ReplaceHistoryEntry = true });
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Refuse(ex.Errors.Select(TableValues.SplitError));
|
||||
return false;
|
||||
}
|
||||
catch (ConcurrencyException)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Refuse(IEnumerable<(string? Field, string Code)> errors)
|
||||
{
|
||||
foreach (var (field, code) in errors)
|
||||
{
|
||||
Validation.Add(field, Message(code));
|
||||
}
|
||||
|
||||
// Show the tab of the first error when the open one has none.
|
||||
if (!Validation.Messages.Any(m => PartyScreens.TabOf(m.Field) == ActiveTab) && Validation.Messages.FirstOrDefault() is { } first)
|
||||
{
|
||||
_ = ShowTabAsync(PartyScreens.TabOf(first.Field));
|
||||
}
|
||||
}
|
||||
|
||||
private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task DeleteCoreAsync()
|
||||
{
|
||||
if (Record is not { Party.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (await Parties.DeleteAsync(actor, company, record.Party.Id) == PartyDeleteOutcome.Disabled)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T["Parties.Actions.DeletedInstead"]);
|
||||
}
|
||||
|
||||
Navigation.NavigateTo(PartyScreens.RadarUrl(_archive));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task RadarAsync()
|
||||
{
|
||||
Navigation.NavigateTo(PartyScreens.RadarUrl(_archive));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task AttachmentsAsync() => ShowTabAsync(PartyScreens.Tabs.Notes);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IEnumerable<ToolbarItem> ContextActions()
|
||||
{
|
||||
if (Record is null || IsNew || !CanWrite)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (P.VatNumber is not null && P.SubjectType is SubjectType.EuCompany or SubjectType.Company)
|
||||
{
|
||||
yield return new ToolbarItem("vies", "shield-check", T["Parties.Actions.Vies"])
|
||||
{
|
||||
Kind = ToolbarKind.Action, Disabled = IsModified || _busy, OnClick = CheckVatAsync,
|
||||
};
|
||||
}
|
||||
|
||||
if (P.Kind != PartyKind.Customer)
|
||||
{
|
||||
yield return new ToolbarItem("convert", "users", T["Parties.Actions.Convert"])
|
||||
{
|
||||
Kind = ToolbarKind.Action, Primary = P.Kind is PartyKind.Prospect or PartyKind.Lead, Disabled = IsModified || _busy, OnClick = ConvertAsync,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IEnumerable<ToolbarItem> MenuCommands()
|
||||
{
|
||||
if (Record is null || IsNew || !CanWrite)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
yield return new ToolbarItem("disable", P.Disabled ? "check-circle" : "x-circle", T[P.Disabled ? "Parties.Actions.Enable" : "Parties.Actions.Disable"])
|
||||
{
|
||||
Kind = ToolbarKind.Menu, Disabled = IsModified || _busy, OnClick = ToggleDisabledAsync,
|
||||
};
|
||||
}
|
||||
|
||||
private async Task CheckVatAsync()
|
||||
{
|
||||
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var result = await Parties.CheckVatAsync(actor, company, P.Id);
|
||||
if (result is null)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T["Parties.Vies.NeedsVat"]);
|
||||
return;
|
||||
}
|
||||
|
||||
Record = await Parties.GetAsync(actor, company, P.Id) ?? Record;
|
||||
var tone = result.Status == ViesStatus.Valid ? ToastKind.Success : result.Status == ViesStatus.Invalid ? ToastKind.Error : ToastKind.Warning;
|
||||
Toasts.Show(tone, T["Parties.Vies." + result.Status], result.Name);
|
||||
await LoadSideAsync(actor, company);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConvertAsync()
|
||||
{
|
||||
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company
|
||||
|| !await Dialogs.ConfirmAsync(new(T["Parties.Actions.ConvertTitle"], T["Parties.Actions.ConvertText"], T["Parties.Actions.Convert"], T["Common.Cancel"])))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var converted = await Parties.ConvertToCustomerAsync(actor, company, P.Id);
|
||||
Toasts.Show(ToastKind.Success, T.Format("Parties.Actions.Converted", converted.Party.Code));
|
||||
Record = converted;
|
||||
Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, converted.Party.Id));
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(TableValues.SplitError).Select(e => Message(e.Code))));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleDisabledAsync()
|
||||
{
|
||||
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var disabled = !P.Disabled;
|
||||
await Parties.SetDisabledAsync(actor, company, [P.Id], disabled);
|
||||
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", 1));
|
||||
Record = await Parties.GetAsync(actor, company, P.Id) ?? Record;
|
||||
await LoadSideAsync(actor, company);
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void Change(Action change)
|
||||
{
|
||||
change();
|
||||
MarkModified();
|
||||
}
|
||||
|
||||
private static string Key(string list, int index, string field) => list + "." + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + field;
|
||||
|
||||
private void Add<TDetail>(List<TDetail> list, TDetail detail)
|
||||
{
|
||||
list.Add(detail);
|
||||
MarkModified();
|
||||
}
|
||||
|
||||
private void Remove<TDetail>(List<TDetail> list, int index)
|
||||
{
|
||||
if (index < list.Count)
|
||||
{
|
||||
list.RemoveAt(index);
|
||||
Validation.Clear();
|
||||
MarkModified();
|
||||
}
|
||||
}
|
||||
|
||||
private void SetKind(string? value) => Change(() => P.Kind = Enum.Parse<PartyKind>(value!));
|
||||
|
||||
private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse<PartyAddressKind>(value!));
|
||||
|
||||
private void SetDelivery(PartySalesTerms terms, string? value) => Change(() => terms.SendDocuments = Enum.Parse<DocumentDelivery>(value!));
|
||||
|
||||
private Task SetSubjectAsync(string? value)
|
||||
{
|
||||
Change(() =>
|
||||
{
|
||||
P.SubjectType = Enum.Parse<SubjectType>(value!);
|
||||
// A foreign subject lives abroad: the country is chosen again.
|
||||
if (P.SubjectType is SubjectType.EuCompany or SubjectType.NonEuCompany && P.CountryCode == "IT")
|
||||
{
|
||||
P.CountryCode = string.Empty;
|
||||
}
|
||||
else if (P.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate or SubjectType.Person && P.CountryCode.Length == 0)
|
||||
{
|
||||
P.CountryCode = "IT";
|
||||
}
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task SetPostalCodeAsync(string? value)
|
||||
{
|
||||
Change(() => P.PostalCode = value);
|
||||
_places = [];
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || P.CountryCode != "IT"
|
||||
|| !await AutoFill.IsOnAsync(company, AutoFillService.PostalCode))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var places = await AutoFill.PlacesByPostalCodeAsync(actor, company, value);
|
||||
if (places.Count == 1)
|
||||
{
|
||||
PickPlace(places[0]);
|
||||
}
|
||||
else if (!places.Any(p => string.Equals(p.Name, P.City, StringComparison.CurrentCultureIgnoreCase)))
|
||||
{
|
||||
_places = places;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SetCityAsync(string? value)
|
||||
{
|
||||
Change(() => P.City = value);
|
||||
_places = [];
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || P.CountryCode != "IT"
|
||||
|| !await AutoFill.IsOnAsync(company, AutoFillService.PostalCode))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var exact = (await AutoFill.PlacesByNameAsync(actor, company, value))
|
||||
.Where(p => string.Equals(p.Name, value?.Trim(), StringComparison.CurrentCultureIgnoreCase)).ToList();
|
||||
if (exact.Count == 1)
|
||||
{
|
||||
P.Province = exact[0].ProvinceCode;
|
||||
// A single postal code is filled; a city with many keeps what was typed.
|
||||
if (string.IsNullOrWhiteSpace(P.PostalCode) && exact[0].PostalCode is { } code && code.All(char.IsAsciiDigit))
|
||||
{
|
||||
P.PostalCode = code;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void PickPlace(PlaceSuggestion place)
|
||||
{
|
||||
P.City = place.Name;
|
||||
P.Province = place.ProvinceCode;
|
||||
_places = [];
|
||||
MarkModified();
|
||||
}
|
||||
|
||||
private async Task SetIbanAsync(PartyBankAccount account, string? value)
|
||||
{
|
||||
Change(() => account.Iban = value ?? string.Empty);
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !await AutoFill.IsOnAsync(company, AutoFillService.BankFromIban))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (await AutoFill.BankFromIbanAsync(actor, company, value) is { } bank)
|
||||
{
|
||||
account.BankCode = bank.BankCode;
|
||||
account.BranchCode = bank.BranchCode;
|
||||
account.BankName ??= bank.Name;
|
||||
account.Bic ??= bank.Bic;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ComputeTaxCodeAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Record is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var place = _birthPlace?.Trim().ToUpperInvariant();
|
||||
if (place is { Length: > 0 } && !(place.Length == 4 && char.IsAsciiLetter(place[0]) && place[1..].All(char.IsAsciiDigit)))
|
||||
{
|
||||
// A name: the municipality with exactly that name.
|
||||
place = (await AutoFill.PlacesByNameAsync(actor, company, _birthPlace))
|
||||
.FirstOrDefault(p => string.Equals(p.Name, _birthPlace?.Trim(), StringComparison.CurrentCultureIgnoreCase))?.MunicipalityCode;
|
||||
}
|
||||
|
||||
string? code = null;
|
||||
if (_birthDate is { } date && Enum.TryParse<PersonSex>(_sex, out var sex) && place is { Length: > 0 })
|
||||
{
|
||||
code = await AutoFill.PersonalTaxCodeAsync(company, new PersonalTaxCodeData(P.LastName ?? string.Empty, P.FirstName ?? string.Empty, date, sex, place));
|
||||
}
|
||||
|
||||
if (code is null)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T["Parties.Actions.TaxCodeMissing"]);
|
||||
return;
|
||||
}
|
||||
|
||||
Change(() => P.TaxCode = code);
|
||||
Toasts.Show(ToastKind.Success, T["Parties.Actions.TaxCodeDone"], code);
|
||||
}
|
||||
|
||||
private string? FieldLabel(string field)
|
||||
{
|
||||
var key = "Parties.Fields." + field.Split('.')[^1];
|
||||
return T.Contains(key) ? T[key] : null;
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,14 @@ public static class KhaemhatApp
|
||||
/// <param name="args">Command-line arguments (ASP.NET Core host conventions, e.g. <c>--urls</c>; also <c>--KHAEMHAT_*=value</c>).</param>
|
||||
/// <returns>The application.</returns>
|
||||
/// <exception cref="ConfigurationException">The <c>KHAEMHAT_*</c> variables are missing or not valid.</exception>
|
||||
public static WebApplication Build(string[] args)
|
||||
public static WebApplication Build(string[] args) => Build(args, null);
|
||||
|
||||
/// <summary>Creates the configured application with last changes to its services (tests: fake external services).</summary>
|
||||
/// <param name="args">Command-line arguments.</param>
|
||||
/// <param name="configureServices">Runs after every registration, before the application is built.</param>
|
||||
/// <returns>The application.</returns>
|
||||
/// <exception cref="ConfigurationException">The <c>KHAEMHAT_*</c> variables are missing or not valid.</exception>
|
||||
public static WebApplication Build(string[] args, Action<IServiceCollection>? configureServices)
|
||||
{
|
||||
// ApplicationName pins the static web assets manifest to this assembly, also when tests host the app.
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
||||
@@ -81,6 +88,7 @@ public static class KhaemhatApp
|
||||
builder.Services.AddSingleton(ProductVersion.FromAssembly(typeof(KhaemhatApp).Assembly));
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
configureServices?.Invoke(builder.Services);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
|
||||
@@ -144,11 +144,13 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<PaymentTermService>();
|
||||
services.AddSingleton<CodeRuleService>();
|
||||
services.AddSingleton<AutoFillService>();
|
||||
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
|
||||
services.AddSingleton<ExchangeRateService>();
|
||||
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
|
||||
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
|
||||
services.AddSingleton<IScheduledJob, EcbRatesJob>();
|
||||
services.AddSingleton<ISeeder, BaseTablesSeeder>();
|
||||
services.AddSingleton<ISeeder, DemoPartiesSeeder>();
|
||||
services.AddSingleton<SeedRunner>();
|
||||
|
||||
// Companies and start.
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Web.Tables;
|
||||
using Khaemhat.Web.Ui;
|
||||
|
||||
namespace Khaemhat.Web.Parties;
|
||||
|
||||
/// <summary>The company tables a party points to, read once per page as choices (<c>code · description</c>).</summary>
|
||||
public sealed class PartyLookups
|
||||
{
|
||||
/// <summary>Nothing loaded.</summary>
|
||||
public static PartyLookups Empty { get; } = new();
|
||||
|
||||
/// <summary>Payment terms, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> PaymentTerms { get; private init; } = [];
|
||||
|
||||
/// <summary>Price lists, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> PriceLists { get; private init; } = [];
|
||||
|
||||
/// <summary>Salespeople, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Salespeople { get; private init; } = [];
|
||||
|
||||
/// <summary>Party categories, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Categories { get; private init; } = [];
|
||||
|
||||
/// <summary>Carriers, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Carriers { get; private init; } = [];
|
||||
|
||||
/// <summary>Shipping terms, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> ShippingTerms { get; private init; } = [];
|
||||
|
||||
/// <summary>Warehouses, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
|
||||
|
||||
/// <summary>Company bank accounts, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> BankAccounts { get; private init; } = [];
|
||||
|
||||
/// <summary>VAT codes, by id.</summary>
|
||||
public IReadOnlyList<KhOption<string>> TaxCodes { get; private init; } = [];
|
||||
|
||||
/// <summary>Countries, by code.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Countries { get; private init; } = [];
|
||||
|
||||
/// <summary>Currencies, by code.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Currencies { get; private init; } = [];
|
||||
|
||||
/// <summary>Reads the choices the radar needs.</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<PartyLookups> ForRadarAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
|
||||
{
|
||||
PaymentTerms = await ReadAsync<PaymentTerm>(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),
|
||||
Categories = await ReadAsync<PartyCategory>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
|
||||
/// <summary>Reads every choice of the record page.</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<PartyLookups> ForRecordAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
|
||||
{
|
||||
PaymentTerms = await ReadAsync<PaymentTerm>(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),
|
||||
Categories = await ReadAsync<PartyCategory>(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),
|
||||
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
BankAccounts = await ReadAsync<BankAccount>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
TaxCodes = await ReadAsync<TaxCode>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
Countries = await ReadAsync<Country>(tables, actor, company, true, cancellationToken).ConfigureAwait(false),
|
||||
Currencies = await ReadAsync<Currency>(tables, actor, company, true, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
|
||||
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))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Web.Ui;
|
||||
|
||||
namespace Khaemhat.Web.Parties;
|
||||
|
||||
/// <summary>
|
||||
/// Addresses, tabs and choices of the party screens (SPEC §11.2, mockups 012-016): the radars
|
||||
/// <c>/anagrafiche/clienti</c>, <c>/fornitori</c>, <c>/contatti</c> and the record of a party under each of them.
|
||||
/// </summary>
|
||||
public static class PartyScreens
|
||||
{
|
||||
/// <summary>The menu area.</summary>
|
||||
public const string BasePath = "/anagrafiche";
|
||||
|
||||
/// <summary>The tab ids of the record page, in order.</summary>
|
||||
public static class Tabs
|
||||
{
|
||||
/// <summary>Main data.</summary>
|
||||
public const string Main = "dati";
|
||||
|
||||
/// <summary>Other addresses.</summary>
|
||||
public const string Addresses = "indirizzi";
|
||||
|
||||
/// <summary>Contact people.</summary>
|
||||
public const string Contacts = "contatti";
|
||||
|
||||
/// <summary>Sales and purchase terms.</summary>
|
||||
public const string Terms = "condizioni";
|
||||
|
||||
/// <summary>Fiscal data and e-invoice.</summary>
|
||||
public const string Fiscal = "fiscale";
|
||||
|
||||
/// <summary>Bank accounts.</summary>
|
||||
public const string Banks = "banche";
|
||||
|
||||
/// <summary>Notes and attachments.</summary>
|
||||
public const string Notes = "note";
|
||||
|
||||
/// <summary>History.</summary>
|
||||
public const string History = "storico";
|
||||
}
|
||||
|
||||
/// <summary>The path segment of an archive.</summary>
|
||||
/// <param name="archive">The archive.</param>
|
||||
/// <returns><c>clienti</c>, <c>fornitori</c> or <c>contatti</c>.</returns>
|
||||
public static string SegmentOf(PartyArchive archive) => archive switch
|
||||
{
|
||||
PartyArchive.Suppliers => "fornitori",
|
||||
PartyArchive.Contacts => "contatti",
|
||||
_ => "clienti",
|
||||
};
|
||||
|
||||
/// <summary>The archive of an address such as <c>/anagrafiche/fornitori/12</c>.</summary>
|
||||
/// <param name="path">The path, absolute or relative, with or without query.</param>
|
||||
/// <returns>The archive; customers when the segment is not recognised.</returns>
|
||||
public static PartyArchive ArchiveOf(string? path)
|
||||
{
|
||||
var segments = (path ?? string.Empty).Split('?', '#')[0].Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
var index = Array.IndexOf(segments, BasePath.TrimStart('/'));
|
||||
return (index >= 0 && index + 1 < segments.Length ? segments[index + 1] : null) switch
|
||||
{
|
||||
"fornitori" => PartyArchive.Suppliers,
|
||||
"contatti" => PartyArchive.Contacts,
|
||||
_ => PartyArchive.Customers,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The archive a party belongs to first.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>The archive.</returns>
|
||||
public static PartyArchive ArchiveOf(PartyKind kind) => kind switch
|
||||
{
|
||||
PartyKind.Supplier => PartyArchive.Suppliers,
|
||||
PartyKind.Prospect or PartyKind.Lead => PartyArchive.Contacts,
|
||||
_ => PartyArchive.Customers,
|
||||
};
|
||||
|
||||
/// <summary>The kind of a new party of an archive.</summary>
|
||||
/// <param name="archive">The archive.</param>
|
||||
/// <returns>The kind.</returns>
|
||||
public static PartyKind NewKindOf(PartyArchive archive) => archive switch
|
||||
{
|
||||
PartyArchive.Suppliers => PartyKind.Supplier,
|
||||
PartyArchive.Contacts => PartyKind.Prospect,
|
||||
_ => PartyKind.Customer,
|
||||
};
|
||||
|
||||
/// <summary>The radar of an archive.</summary>
|
||||
/// <param name="archive">The archive.</param>
|
||||
/// <returns>The address, relative to the base.</returns>
|
||||
public static string RadarUrl(PartyArchive archive) => "anagrafiche/" + SegmentOf(archive);
|
||||
|
||||
/// <summary>The record of a party.</summary>
|
||||
/// <param name="archive">The archive it is opened from.</param>
|
||||
/// <param name="id">The party.</param>
|
||||
/// <returns>The address, relative to the base.</returns>
|
||||
public static string RecordUrl(PartyArchive archive, long id) => RadarUrl(archive) + "/" + id.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>A new party of an archive.</summary>
|
||||
/// <param name="archive">The archive.</param>
|
||||
/// <param name="kind">The kind, when not the default of the archive (a lead among the contacts).</param>
|
||||
/// <returns>The address, relative to the base.</returns>
|
||||
public static string NewUrl(PartyArchive archive, PartyKind? kind = null) =>
|
||||
RadarUrl(archive) + "/nuovo" + (kind is { } k && k != NewKindOf(archive) ? "?tipo=" + k.ToString().ToLowerInvariant() : string.Empty);
|
||||
|
||||
/// <summary>The kind asked by <c>?tipo=</c>, when it fits the archive.</summary>
|
||||
/// <param name="archive">The archive.</param>
|
||||
/// <param name="value">The value of the query.</param>
|
||||
/// <returns>The kind.</returns>
|
||||
public static PartyKind KindOf(PartyArchive archive, string? value) =>
|
||||
Enum.TryParse<PartyKind>(value, ignoreCase: true, out var kind) && ArchiveOf(kind) == archive ? kind : NewKindOf(archive);
|
||||
|
||||
/// <summary>The tab that holds a field of the service (<c>Fiscal.RecipientCode</c>, <c>Contacts.0.Email</c>).</summary>
|
||||
/// <param name="field">The field.</param>
|
||||
/// <returns>The tab id.</returns>
|
||||
public static string TabOf(string? field)
|
||||
{
|
||||
var head = (field ?? string.Empty).Split('.')[0];
|
||||
return head switch
|
||||
{
|
||||
"Addresses" => Tabs.Addresses,
|
||||
"Contacts" => Tabs.Contacts,
|
||||
"BankAccounts" => Tabs.Banks,
|
||||
"Sales" or "Purchase" => Tabs.Terms,
|
||||
"Fiscal" => Tabs.Fiscal,
|
||||
nameof(Party.Notes) => Tabs.Notes,
|
||||
_ => Tabs.Main,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The choices of an enum, with the texts <c>Parties.<group>.<value></c>.</summary>
|
||||
/// <typeparam name="TEnum">The enum.</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["Parties." + group + "." + v]))];
|
||||
}
|
||||
|
||||
/// <summary>An id as the value of a select.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string? Text(long? id) => id?.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>The value of a select as an id.</summary>
|
||||
/// <param name="value">The text.</param>
|
||||
/// <returns>The id.</returns>
|
||||
public static long? Id(string? value) => long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : null;
|
||||
|
||||
/// <summary>The code part of a lookup text (<c>RB60 · Ricevuta bancaria 60 gg</c>).</summary>
|
||||
/// <param name="options">The choices.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="full">Whether to keep the description.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public static string? Describe(IReadOnlyList<KhOption<string>> options, long? id, bool full = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (Text(id) is not { } value || options.FirstOrDefault(o => o.Value == value) is not { } option)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var parts = option.Text.Split(" · ", 2);
|
||||
return full && parts.Length > 1 ? parts[1] : parts[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
{
|
||||
"Parties": {
|
||||
"Archives": {
|
||||
"Customers": "Clienti",
|
||||
"Suppliers": "Fornitori",
|
||||
"Contacts": "Contatti"
|
||||
},
|
||||
"New": {
|
||||
"Customer": "Nuovo cliente",
|
||||
"Supplier": "Nuovo fornitore",
|
||||
"Prospect": "Nuovo prospect",
|
||||
"Lead": "Nuovo lead"
|
||||
},
|
||||
"NewTitle": "Nuova anagrafica",
|
||||
"NotFound": "Anagrafica non trovata: forse è stata eliminata.",
|
||||
"NoCompany": "Apri un'azienda per vedere le anagrafiche.",
|
||||
"CodeAuto": "automatico",
|
||||
"Since": "dal {0}",
|
||||
"Radar": {
|
||||
"Identifier": "P.IVA / C.F.",
|
||||
"City": "Città",
|
||||
"Payment": "Pagamento",
|
||||
"PriceList": "Listino",
|
||||
"Salesperson": "Agente",
|
||||
"Kind": "Tipo",
|
||||
"Subject": "Soggetto",
|
||||
"State": "Stato",
|
||||
"Search": "Cerca per codice, nome, P.IVA, codice fiscale o città",
|
||||
"Summary": "{0} anagrafiche",
|
||||
"Selected": "{0} selezionate",
|
||||
"All": "Tutti",
|
||||
"Active": "Attivi",
|
||||
"Disabled": "Disattivati"
|
||||
},
|
||||
"States": {
|
||||
"Active": "Attivo",
|
||||
"Disabled": "Disattivato",
|
||||
"Blocked": "Bloccato",
|
||||
"Split": "PA · split",
|
||||
"Demo": "Demo",
|
||||
"AlsoSupplier": "Anche fornitore",
|
||||
"AlsoCustomer": "Anche cliente"
|
||||
},
|
||||
"Actions": {
|
||||
"Disable": "Disattiva",
|
||||
"Enable": "Riattiva",
|
||||
"Disabled": "{0} anagrafiche disattivate",
|
||||
"Enabled": "{0} anagrafiche riattivate",
|
||||
"Vies": "Verifica VIES",
|
||||
"Convert": "Converti in cliente",
|
||||
"ConvertTitle": "Convertire in cliente?",
|
||||
"ConvertText": "L'anagrafica diventa un cliente: un prospect o un lead riceve il codice cliente e conserva il vecchio come codice precedente; un fornitore resta anche fornitore con lo stesso codice.",
|
||||
"Converted": "Ora è un cliente: {0}",
|
||||
"DeletedInstead": "Anagrafica usata da altri dati: è stata disattivata invece che eliminata.",
|
||||
"AddAddress": "Aggiungi indirizzo",
|
||||
"AddContact": "Aggiungi contatto",
|
||||
"AddBank": "Aggiungi conto",
|
||||
"Remove": "Rimuovi",
|
||||
"TaxCode": "Calcola dal nome e dai dati di nascita",
|
||||
"TaxCodeTitle": "Calcolo del codice fiscale",
|
||||
"TaxCodeDone": "Codice fiscale calcolato",
|
||||
"TaxCodeMissing": "Servono cognome, nome, data, sesso e comune di nascita.",
|
||||
"Places": "{0} comuni con questo CAP: scegli quello giusto.",
|
||||
"Warnings": "Salvato con avvisi: {0}"
|
||||
},
|
||||
"Vies": {
|
||||
"Valid": "Partita IVA valida nel VIES",
|
||||
"Invalid": "Partita IVA non valida nel VIES",
|
||||
"Unavailable": "VIES non raggiungibile: riprova più tardi",
|
||||
"InvalidInput": "Numero non accettato dal VIES",
|
||||
"Checked": "Verificata il {0}",
|
||||
"NeedsVat": "Serve una partita IVA di un paese dell'Unione europea."
|
||||
},
|
||||
"Tabs": {
|
||||
"Main": "Dati principali",
|
||||
"Addresses": "Indirizzi",
|
||||
"Contacts": "Contatti",
|
||||
"Terms": "Condizioni",
|
||||
"Fiscal": "Fiscale e SDI",
|
||||
"Banks": "Banche",
|
||||
"Notes": "Note e allegati",
|
||||
"History": "Storico"
|
||||
},
|
||||
"Groups": {
|
||||
"Identity": "Identità",
|
||||
"Office": "Sede legale",
|
||||
"Reach": "Recapiti",
|
||||
"Classification": "Classificazione e consensi",
|
||||
"Sales": "Condizioni di vendita",
|
||||
"Delivery": "Consegna e documenti",
|
||||
"Purchase": "Condizioni di acquisto",
|
||||
"EInvoice": "Fatturazione elettronica",
|
||||
"Vat": "Regime IVA",
|
||||
"Withholding": "Ritenute e casse",
|
||||
"Intent": "Dichiarazione d'intento",
|
||||
"Codes": "Identificativi",
|
||||
"Accounts": "Conti contabili",
|
||||
"Notes": "Note",
|
||||
"Attachments": "Allegati",
|
||||
"Birth": "Dati di nascita"
|
||||
},
|
||||
"Fields": {
|
||||
"Code": "Codice",
|
||||
"PreviousCode": "Codice precedente",
|
||||
"Kind": "Tipo",
|
||||
"SubjectType": "Tipo soggetto",
|
||||
"Name": "Ragione sociale",
|
||||
"FirstName": "Nome",
|
||||
"LastName": "Cognome",
|
||||
"FiscalName": "Denominazione per i documenti",
|
||||
"VatNumber": "Partita IVA",
|
||||
"TaxCode": "Codice fiscale",
|
||||
"Rea": "REA",
|
||||
"CategoryId": "Categoria",
|
||||
"Address": "Indirizzo",
|
||||
"StreetNumber": "Civico",
|
||||
"PostalCode": "CAP",
|
||||
"City": "Comune",
|
||||
"Province": "Provincia",
|
||||
"CountryCode": "Paese",
|
||||
"Phone": "Telefono",
|
||||
"Mobile": "Cellulare",
|
||||
"Email": "E-mail",
|
||||
"Pec": "PEC",
|
||||
"Website": "Sito web",
|
||||
"SalespersonId": "Agente",
|
||||
"Language": "Lingua",
|
||||
"CurrencyCode": "Valuta",
|
||||
"Since": "In anagrafica dal",
|
||||
"PrivacyAccepted": "Informativa privacy accettata",
|
||||
"Marketing": "Consenso al marketing",
|
||||
"Notes": "Note",
|
||||
"VatCheck": "Verifica VIES",
|
||||
"VatCheckedAt": "Data della verifica VIES",
|
||||
"CustomerAccountCode": "Conto cliente",
|
||||
"SupplierAccountCode": "Conto fornitore",
|
||||
"Disabled": "Disattivato",
|
||||
"IsAlsoSupplier": "È anche fornitore",
|
||||
"PriceListId": "Listino",
|
||||
"Discount1": "Sconto 1 %",
|
||||
"Discount2": "Sconto 2 %",
|
||||
"PaymentTermId": "Pagamento",
|
||||
"CompanyBankAccountId": "Nostra banca d'appoggio",
|
||||
"CarrierId": "Vettore",
|
||||
"ShippingTermId": "Porto",
|
||||
"WarehouseId": "Deposito",
|
||||
"CreditLimit": "Fido",
|
||||
"Blocked": "Ordini bloccati",
|
||||
"GroupDeliveryNotes": "Raggruppa i DDT in fattura",
|
||||
"InvoiceDay": "Giorno di fatturazione",
|
||||
"SendDocuments": "Invio dei documenti",
|
||||
"DocumentsEmail": "E-mail per i documenti",
|
||||
"LeadTimeDays": "Tempo di consegna (giorni)",
|
||||
"MinimumOrder": "Ordine minimo",
|
||||
"Discount": "Sconto %",
|
||||
"VatRegisterCode": "Registro IVA",
|
||||
"CostAccountCode": "Conto di costo",
|
||||
"OrdersEmail": "E-mail per gli ordini",
|
||||
"RecipientCode": "Codice destinatario",
|
||||
"RecipientPec": "PEC per la fattura elettronica",
|
||||
"AdministrationReference": "Riferimento amministrazione",
|
||||
"AttachPdf": "Allega il PDF all'XML",
|
||||
"SendCopy": "Invia una copia di cortesia",
|
||||
"SplitPayment": "Scissione dei pagamenti",
|
||||
"ReverseCharge": "Inversione contabile",
|
||||
"TaxCodeId": "Codice IVA abituale",
|
||||
"Exigibility": "Esigibilità IVA",
|
||||
"StampDutyCharged": "Bollo a carico del cliente",
|
||||
"Withholding": "Ritenuta d'acconto",
|
||||
"WithholdingRate": "Aliquota ritenuta %",
|
||||
"WithholdingReason": "Causale del pagamento",
|
||||
"PensionFund": "Cassa previdenziale",
|
||||
"PensionFundRate": "Aliquota cassa %",
|
||||
"Enasarco": "ENASARCO",
|
||||
"IntentActive": "Dichiarazione attiva",
|
||||
"IntentNumber": "Numero",
|
||||
"IntentDate": "Data",
|
||||
"IntentProtocol": "Protocollo telematico",
|
||||
"IntentTaxCodeId": "Codice IVA",
|
||||
"IntentCeiling": "Plafond",
|
||||
"IntentUsed": "Utilizzato",
|
||||
"IntentRemaining": "Residuo",
|
||||
"IntentFrom": "Valida dal",
|
||||
"IntentTo": "Valida al",
|
||||
"Gln": "GLN",
|
||||
"Eori": "EORI",
|
||||
"OurCode": "Nostro codice presso di lui",
|
||||
"AddressKind": "Tipo indirizzo",
|
||||
"AddressName": "Denominazione",
|
||||
"IsDefault": "Predefinito",
|
||||
"ContactName": "Nome e cognome",
|
||||
"Role": "Ruolo",
|
||||
"MainContact": "Contatto principale",
|
||||
"Iban": "IBAN",
|
||||
"Bic": "BIC",
|
||||
"BankName": "Banca",
|
||||
"BankCode": "ABI",
|
||||
"BranchCode": "CAB",
|
||||
"BirthDate": "Data di nascita",
|
||||
"Sex": "Sesso",
|
||||
"BirthPlace": "Comune di nascita (codice catastale)"
|
||||
},
|
||||
"Kinds": {
|
||||
"Customer": "Cliente",
|
||||
"Supplier": "Fornitore",
|
||||
"Prospect": "Prospect",
|
||||
"Lead": "Lead"
|
||||
},
|
||||
"SubjectTypes": {
|
||||
"Company": "Impresa italiana",
|
||||
"Person": "Privato",
|
||||
"PublicAdministration": "Pubblica amministrazione",
|
||||
"EuCompany": "Impresa UE",
|
||||
"NonEuCompany": "Impresa extra-UE",
|
||||
"FlatRate": "Forfettario"
|
||||
},
|
||||
"Delivery": {
|
||||
"None": "Non inviare",
|
||||
"Email": "E-mail",
|
||||
"Pec": "PEC"
|
||||
},
|
||||
"AddressKinds": {
|
||||
"Delivery": "Destinazione merce",
|
||||
"Billing": "Fatturazione",
|
||||
"Site": "Cantiere / sede operativa",
|
||||
"Other": "Altro"
|
||||
},
|
||||
"Exigibilities": {
|
||||
"I": "I · immediata",
|
||||
"D": "D · differita",
|
||||
"S": "S · scissione dei pagamenti"
|
||||
},
|
||||
"Sexes": {
|
||||
"Male": "M",
|
||||
"Female": "F"
|
||||
},
|
||||
"Empty": {
|
||||
"Addresses": "Nessun altro indirizzo: la sede legale è nei dati principali.",
|
||||
"Contacts": "Nessun contatto.",
|
||||
"Banks": "Nessun conto corrente."
|
||||
},
|
||||
"TermsHint": "Le condizioni si propongono nei documenti; nel documento si possono cambiare.",
|
||||
"NoTerms": "Un prospect o un lead non ha condizioni: si impostano quando diventa cliente.",
|
||||
"IntentHint": "Il residuo scende con le fatture emesse in esenzione (arriva con la fatturazione, M5).",
|
||||
"AccountsHint": "I sottoconti del partitario si creano alla prima registrazione (M7)."
|
||||
},
|
||||
"parties": {
|
||||
"name": {
|
||||
"required": "Indica la ragione sociale, oppure cognome e nome."
|
||||
},
|
||||
"vat-number": {
|
||||
"required": "Per un'impresa la partita IVA è obbligatoria.",
|
||||
"duplicate": "Un'altra anagrafica ha la stessa partita IVA (va bene per filiali e sedi distinte)."
|
||||
},
|
||||
"identifier": {
|
||||
"required": "Per una pubblica amministrazione serve il codice fiscale o la partita IVA."
|
||||
},
|
||||
"tax-code": {
|
||||
"invalid": "Codice fiscale non valido.",
|
||||
"missing": "Manca il codice fiscale: serve per fatturare a un privato."
|
||||
},
|
||||
"code": {
|
||||
"duplicate": "Codice già usato da un'altra anagrafica."
|
||||
},
|
||||
"country": {
|
||||
"unknown": "Paese non presente nella tabella dei paesi.",
|
||||
"not-eu": "Un'impresa UE ha sede in un altro paese dell'Unione europea.",
|
||||
"not-domestic": "Per questo tipo di soggetto il paese è quello dell'azienda."
|
||||
},
|
||||
"intent": {
|
||||
"incomplete": "Per una dichiarazione attiva servono numero e plafond."
|
||||
},
|
||||
"exigibility": {
|
||||
"invalid": "Esigibilità non valida: I, D oppure S."
|
||||
},
|
||||
"day": {
|
||||
"range": "Il giorno va da 1 a 31."
|
||||
},
|
||||
"value": {
|
||||
"negative": "Il valore non può essere negativo."
|
||||
},
|
||||
"detail": {
|
||||
"required": "Campo obbligatorio."
|
||||
},
|
||||
"convert": {
|
||||
"already-customer": "L'anagrafica è già un cliente."
|
||||
},
|
||||
"not-found": "Anagrafica non trovata."
|
||||
}
|
||||
}
|
||||
@@ -244,6 +244,11 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
|
||||
|
||||
/* Attachments and generated files (SPEC §9.4, mockup 024). */
|
||||
.kh-tab-body { padding: 14px 16px; }
|
||||
|
||||
/* Parties (issue #41): the lists of details of a record and the choice of a municipality from its postal code. */
|
||||
.kh-detailfoot { display: flex; align-items: center; gap: 12px; padding: 12px 16px; }
|
||||
.kh-endrow { display: flex; align-items: flex-end; justify-content: flex-end; }
|
||||
.kh-places { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.kh-att { display: flex; flex-direction: column; gap: 10px; }
|
||||
.kh-att-head { display: flex; align-items: center; gap: 8px; }
|
||||
.kh-att-title, .kh-att-section { font-size: 10.5px; text-transform: uppercase; letter-spacing: .5px; color: var(--kh-text-3); font-weight: 600; }
|
||||
|
||||
Reference in new issue
Block a user