M8 · Scadenzario e tesoreria (v0.8.0) #127
No files matched your search
@@ -2,6 +2,7 @@ using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Core.Treasury;
|
||||
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
@@ -179,6 +180,27 @@ public enum PostingRole
|
||||
|
||||
/// <summary>VAT of split payment, due by the public customer.</summary>
|
||||
SplitPaymentVat = 15,
|
||||
|
||||
/// <summary>Allowances received and rounding in favour (abbuoni attivi).</summary>
|
||||
AllowanceIncome = 16,
|
||||
|
||||
/// <summary>Bank fees and charges.</summary>
|
||||
BankCharges = 17,
|
||||
|
||||
/// <summary>Effects and direct debits presented for collection (effetti all'incasso).</summary>
|
||||
BillsForCollection = 18,
|
||||
|
||||
/// <summary>Advances of the bank on effects presented subject to collection (banche c/anticipi).</summary>
|
||||
BankAdvances = 19,
|
||||
|
||||
/// <summary>Exchange gains.</summary>
|
||||
ExchangeGain = 20,
|
||||
|
||||
/// <summary>Exchange losses.</summary>
|
||||
ExchangeLoss = 21,
|
||||
|
||||
/// <summary>Late payment interest charged to customers.</summary>
|
||||
LateInterest = 22,
|
||||
}
|
||||
|
||||
/// <summary>A line of a journal template (<c>gl_journal_template_lines</c>).</summary>
|
||||
@@ -476,8 +498,38 @@ public sealed class OpenItem : Entity<long>, IDemoMarkable
|
||||
/// <summary>Fully settled.</summary>
|
||||
public bool Closed { get; set; }
|
||||
|
||||
/// <summary>The state in the schedule (M8).</summary>
|
||||
public OpenItemStatus Status { get; set; }
|
||||
|
||||
/// <summary>Contested by the customer or with the supplier: left out of reminders and remittances.</summary>
|
||||
public bool Disputed { get; set; }
|
||||
|
||||
/// <summary>The bank account of the company that collects or pays it (from the document).</summary>
|
||||
public long? BankAccountId { get; set; }
|
||||
|
||||
/// <summary>The remittance it is in.</summary>
|
||||
public long? RemittanceId { get; set; }
|
||||
|
||||
/// <summary>The times it came back unpaid.</summary>
|
||||
public int UnpaidCount { get; set; }
|
||||
|
||||
/// <summary>The item it was split from: the bank fees of an unpaid effect.</summary>
|
||||
public long? ParentId { get; set; }
|
||||
|
||||
/// <summary>The level of the last reminder.</summary>
|
||||
public int DunningLevel { get; set; }
|
||||
|
||||
/// <summary>The day of the last reminder.</summary>
|
||||
public DateOnly? LastDunningDate { get; set; }
|
||||
|
||||
/// <summary>Notes (the reason of a dispute).</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>What is left to collect or pay.</summary>
|
||||
public decimal Residual => Amount - PaidAmount;
|
||||
}
|
||||
|
||||
/// <summary>How often a recurring entry repeats.</summary>
|
||||
|
||||
@@ -0,0 +1,628 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Treasury;
|
||||
|
||||
/// <summary>The state of an open item (SPEC §11.8, mockup 053).</summary>
|
||||
public enum OpenItemStatus
|
||||
{
|
||||
/// <summary>Nothing collected or paid.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Collected or paid in part.</summary>
|
||||
Partial = 1,
|
||||
|
||||
/// <summary>Settled.</summary>
|
||||
Closed = 2,
|
||||
|
||||
/// <summary>Returned unpaid by the bank (insoluto): open again, with the bank fees in an item of their own.</summary>
|
||||
Unpaid = 3,
|
||||
|
||||
/// <summary>In a remittance presented to the bank: the customer is settled, the effect is not collected yet.</summary>
|
||||
InRemittance = 4,
|
||||
}
|
||||
|
||||
/// <summary>Whether money comes in or goes out.</summary>
|
||||
public enum PaymentDirection
|
||||
{
|
||||
/// <summary>A collection from a customer (incasso).</summary>
|
||||
Receipt = 0,
|
||||
|
||||
/// <summary>A payment to a supplier (pagamento).</summary>
|
||||
Disbursement = 1,
|
||||
}
|
||||
|
||||
/// <summary>Where a collection or payment comes from.</summary>
|
||||
public enum PaymentOrigin
|
||||
{
|
||||
/// <summary>Recorded in the dialog of the schedule.</summary>
|
||||
Manual = 0,
|
||||
|
||||
/// <summary>The presentation of a remittance (effects, direct debits, transfers).</summary>
|
||||
Remittance = 1,
|
||||
|
||||
/// <summary>A movement of the bank statement matched in the reconciliation.</summary>
|
||||
BankStatement = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A collection or payment (SPEC §11.8, mockup 054, <c>payments</c>): money moved on a bank or cash account that
|
||||
/// settles one or more open items of one customer or supplier, with allowances, exchange differences and bank fees.
|
||||
/// Its entry (<c>INC</c>, <c>PAG</c>, or <c>DIST</c> for remittances) is written in the same transaction; a cancelled
|
||||
/// payment loses its entry (or gets a reversal when final) and opens its items again.
|
||||
/// </summary>
|
||||
public sealed class Payment : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>In or out.</summary>
|
||||
public PaymentDirection Direction { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The day of the collection or payment.</summary>
|
||||
public DateOnly PaymentDate { get; set; }
|
||||
|
||||
/// <summary>The payment method.</summary>
|
||||
public long? PaymentMethodId { get; set; }
|
||||
|
||||
/// <summary>The bank account of the company, when the money goes through a bank.</summary>
|
||||
public long? BankAccountId { get; set; }
|
||||
|
||||
/// <summary>The ledger account of the money (bank, cash, effects for collection).</summary>
|
||||
public long? AccountId { get; set; }
|
||||
|
||||
/// <summary>The money moved (sum of the cash part of the lines), without fees.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The allowances of the lines (positive: granted to the customer, or received from the supplier).</summary>
|
||||
public decimal AllowanceAmount { get; set; }
|
||||
|
||||
/// <summary>The exchange differences of the lines (positive: a loss on collections, a gain on payments).</summary>
|
||||
public decimal ExchangeDifference { get; set; }
|
||||
|
||||
/// <summary>The bank fees, a cost on the same account.</summary>
|
||||
public decimal Fees { get; set; }
|
||||
|
||||
/// <summary>The bank reference (CRO, TRN, cheque number).</summary>
|
||||
public string? Reference { get; set; }
|
||||
|
||||
/// <summary>The journal template of the entry.</summary>
|
||||
public string? TemplateCode { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>Where it comes from.</summary>
|
||||
public PaymentOrigin Origin { get; set; }
|
||||
|
||||
/// <summary>The remittance, when it comes from one.</summary>
|
||||
public long? RemittanceId { get; set; }
|
||||
|
||||
/// <summary>The statement movement it was matched with.</summary>
|
||||
public long? StatementLineId { get; set; }
|
||||
|
||||
/// <summary>The entry.</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The part of a payment that settles one open item (<c>payment_lines</c>).</summary>
|
||||
public sealed class PaymentLine : Entity<long>
|
||||
{
|
||||
/// <summary>The payment.</summary>
|
||||
public long PaymentId { get; set; }
|
||||
|
||||
/// <summary>The open item.</summary>
|
||||
public long OpenItemId { get; set; }
|
||||
|
||||
/// <summary>The money of this item (negative for a credit note set off).</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The allowance on this item.</summary>
|
||||
public decimal Allowance { get; set; }
|
||||
|
||||
/// <summary>The exchange difference on this item.</summary>
|
||||
public decimal ExchangeDifference { get; set; }
|
||||
|
||||
/// <summary>What the line settles: money, allowance and exchange difference.</summary>
|
||||
public decimal Settled => Amount + Allowance + ExchangeDifference;
|
||||
}
|
||||
|
||||
/// <summary>The state of a remittance (mockup 055).</summary>
|
||||
public enum RemittanceStatus
|
||||
{
|
||||
/// <summary>Being prepared: effects can be added and removed.</summary>
|
||||
Draft = 0,
|
||||
|
||||
/// <summary>The file was written: it can still be written again, or the remittance posted.</summary>
|
||||
Generated = 1,
|
||||
|
||||
/// <summary>Posted: the customers are settled (effects) or the suppliers paid (transfers).</summary>
|
||||
Presented = 2,
|
||||
|
||||
/// <summary>Credited by the bank after the due dates: every effect collected or returned unpaid.</summary>
|
||||
Closed = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A remittance (distinta, SPEC §11.8, mockup 055, <c>remittances</c>): RiBa effects or SEPA direct debits presented
|
||||
/// to a bank, or SEPA credit transfers to suppliers, numbered per year.
|
||||
/// </summary>
|
||||
public sealed class Remittance : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The year of the number.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The number in the year.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>What it carries.</summary>
|
||||
public RemittanceKind Kind { get; set; }
|
||||
|
||||
/// <summary>The bank of the company that receives it.</summary>
|
||||
public long BankAccountId { get; set; }
|
||||
|
||||
/// <summary>The day it is presented (or the transfers executed).</summary>
|
||||
public DateOnly PresentationDate { get; set; }
|
||||
|
||||
/// <summary>The last due date taken.</summary>
|
||||
public DateOnly DueUntil { get; set; }
|
||||
|
||||
/// <summary>Presented subject to collection with an advance (salvo buon fine): the bank credits it at once.</summary>
|
||||
public bool Advance { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public RemittanceStatus Status { get; set; }
|
||||
|
||||
/// <summary>The total of the effects.</summary>
|
||||
public decimal TotalAmount { get; set; }
|
||||
|
||||
/// <summary>The number of effects.</summary>
|
||||
public int ItemCount { get; set; }
|
||||
|
||||
/// <summary>The unique identifier written in the file.</summary>
|
||||
public string? MessageId { get; set; }
|
||||
|
||||
/// <summary>The attachment with the last file written.</summary>
|
||||
public long? AttachmentId { get; set; }
|
||||
|
||||
/// <summary>The name of the last file written.</summary>
|
||||
public string? FileName { get; set; }
|
||||
|
||||
/// <summary>The entry of the presentation (effects to the bank, or the advance).</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <summary>The day the bank credited the effects.</summary>
|
||||
public DateOnly? CreditedOn { get; set; }
|
||||
|
||||
/// <summary>The entry of the credit.</summary>
|
||||
public long? CreditEntryId { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>The number as shown, such as <c>2026/018</c>.</summary>
|
||||
public string DisplayNumber => $"{Year}/{Number:000}";
|
||||
}
|
||||
|
||||
/// <summary>The state of an effect of a remittance.</summary>
|
||||
public enum RemittanceLineStatus
|
||||
{
|
||||
/// <summary>In the remittance.</summary>
|
||||
Included = 0,
|
||||
|
||||
/// <summary>Collected (or the transfer executed).</summary>
|
||||
Paid = 1,
|
||||
|
||||
/// <summary>Returned unpaid.</summary>
|
||||
Unpaid = 2,
|
||||
}
|
||||
|
||||
/// <summary>An effect, debit or transfer of a remittance (<c>remittance_lines</c>).</summary>
|
||||
public sealed class RemittanceLine : Entity<long>
|
||||
{
|
||||
/// <summary>The remittance.</summary>
|
||||
public long RemittanceId { get; set; }
|
||||
|
||||
/// <summary>The open item.</summary>
|
||||
public long OpenItemId { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The amount.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The due date.</summary>
|
||||
public DateOnly DueDate { get; set; }
|
||||
|
||||
/// <summary>The IBAN of the customer or supplier, as it was when the effect was added.</summary>
|
||||
public string? Iban { get; set; }
|
||||
|
||||
/// <summary>The direct debit mandate.</summary>
|
||||
public long? MandateId { get; set; }
|
||||
|
||||
/// <summary>The end-to-end identifier written in the file.</summary>
|
||||
public string? EndToEndId { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public RemittanceLineStatus Status { get; set; }
|
||||
|
||||
/// <summary>The day it was returned unpaid.</summary>
|
||||
public DateOnly? UnpaidOn { get; set; }
|
||||
|
||||
/// <summary>The bank fees of the unpaid effect, charged to the customer.</summary>
|
||||
public decimal UnpaidFees { get; set; }
|
||||
|
||||
/// <summary>The entry of the unpaid effect.</summary>
|
||||
public long? UnpaidEntryId { get; set; }
|
||||
|
||||
/// <summary>The payment that settled the item when the remittance was posted.</summary>
|
||||
public long? PaymentId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The scheme of a direct debit mandate.</summary>
|
||||
public enum SddScheme
|
||||
{
|
||||
/// <summary>Core: consumers and companies; the debtor can ask a refund for eight weeks.</summary>
|
||||
Core = 0,
|
||||
|
||||
/// <summary>Business to business: companies only, no refund, the debtor's bank must know the mandate.</summary>
|
||||
B2b = 1,
|
||||
}
|
||||
|
||||
/// <summary>A SEPA direct debit mandate signed by a customer (<c>sdd_mandates</c>).</summary>
|
||||
public sealed class SddMandate : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The customer.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The unique mandate reference (UMR), at most 35 characters.</summary>
|
||||
public string Reference { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The day it was signed.</summary>
|
||||
public DateOnly SignatureDate { get; set; }
|
||||
|
||||
/// <summary>Core or B2B.</summary>
|
||||
public SddScheme Scheme { get; set; }
|
||||
|
||||
/// <summary>The account debited, compact.</summary>
|
||||
public string Iban { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The BIC of the debtor's bank.</summary>
|
||||
public string? Bic { get; set; }
|
||||
|
||||
/// <summary>A one-off mandate (a single debit).</summary>
|
||||
public bool OneOff { get; set; }
|
||||
|
||||
/// <summary>The day of the last collection: none means the next one is the first.</summary>
|
||||
public DateOnly? LastCollectionDate { get; set; }
|
||||
|
||||
/// <summary>Revoked by the customer: no more debits.</summary>
|
||||
public bool Revoked { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A bank statement imported (<c>bank_statements</c>, mockup 057).</summary>
|
||||
public sealed class BankStatement : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The bank account of the company.</summary>
|
||||
public long BankAccountId { get; set; }
|
||||
|
||||
/// <summary>The format of the file.</summary>
|
||||
public StatementFormat Format { get; set; }
|
||||
|
||||
/// <summary>The name of the file.</summary>
|
||||
public string? FileName { get; set; }
|
||||
|
||||
/// <summary>The first day.</summary>
|
||||
public DateOnly FromDate { get; set; }
|
||||
|
||||
/// <summary>The last day.</summary>
|
||||
public DateOnly ToDate { get; set; }
|
||||
|
||||
/// <summary>The opening balance, if the file says it.</summary>
|
||||
public decimal? OpeningBalance { get; set; }
|
||||
|
||||
/// <summary>The closing balance, if the file says it.</summary>
|
||||
public decimal? ClosingBalance { get; set; }
|
||||
|
||||
/// <summary>The movements imported (the ones already imported before are skipped).</summary>
|
||||
public int MovementCount { get; set; }
|
||||
|
||||
/// <summary>The file, kept as an attachment.</summary>
|
||||
public long? AttachmentId { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a movement in the reconciliation (mockup 057).</summary>
|
||||
public enum StatementLineStatus
|
||||
{
|
||||
/// <summary>Nothing found: to match by hand.</summary>
|
||||
ToMatch = 0,
|
||||
|
||||
/// <summary>A match is proposed, with its confidence.</summary>
|
||||
Suggested = 1,
|
||||
|
||||
/// <summary>Matched and recorded.</summary>
|
||||
Matched = 2,
|
||||
|
||||
/// <summary>Left out on purpose (already recorded in another way).</summary>
|
||||
Ignored = 3,
|
||||
}
|
||||
|
||||
/// <summary>What a movement is matched with.</summary>
|
||||
public enum StatementMatchKind
|
||||
{
|
||||
/// <summary>Nothing.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Open items of one customer or supplier: a collection or payment is recorded.</summary>
|
||||
OpenItems = 1,
|
||||
|
||||
/// <summary>A collection or payment already recorded.</summary>
|
||||
Payment = 2,
|
||||
|
||||
/// <summary>The F24 of a due date: its payment is recorded.</summary>
|
||||
TaxPayment = 3,
|
||||
|
||||
/// <summary>A saved rule: an entry on its account is recorded.</summary>
|
||||
Rule = 4,
|
||||
|
||||
/// <summary>The credit of a remittance.</summary>
|
||||
RemittanceCredit = 5,
|
||||
|
||||
/// <summary>An effect returned unpaid.</summary>
|
||||
Unpaid = 6,
|
||||
|
||||
/// <summary>An entry of the ledger on the bank account already recorded.</summary>
|
||||
Entry = 7,
|
||||
}
|
||||
|
||||
/// <summary>A movement of a bank statement (<c>bank_statement_lines</c>).</summary>
|
||||
public sealed class BankStatementLine : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The statement.</summary>
|
||||
public long StatementId { get; set; }
|
||||
|
||||
/// <summary>The bank account of the company.</summary>
|
||||
public long BankAccountId { get; set; }
|
||||
|
||||
/// <summary>The booking date.</summary>
|
||||
public DateOnly BookingDate { get; set; }
|
||||
|
||||
/// <summary>The value date.</summary>
|
||||
public DateOnly? ValueDate { get; set; }
|
||||
|
||||
/// <summary>Positive for money in, negative for money out.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The description of the bank.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The bank reference.</summary>
|
||||
public string? Reference { get; set; }
|
||||
|
||||
/// <summary>The other party, if known.</summary>
|
||||
public string? CounterpartyName { get; set; }
|
||||
|
||||
/// <summary>Its IBAN, if known.</summary>
|
||||
public string? CounterpartyIban { get; set; }
|
||||
|
||||
/// <summary>The bank transaction code.</summary>
|
||||
public string? BankCode { get; set; }
|
||||
|
||||
/// <summary>A hash of date, amount, description and reference: the same movement is never imported twice.</summary>
|
||||
public string Fingerprint { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public StatementLineStatus Status { get; set; }
|
||||
|
||||
/// <summary>What it is (or would be) matched with.</summary>
|
||||
public StatementMatchKind MatchKind { get; set; }
|
||||
|
||||
/// <summary>The confidence of the proposal, 0-100.</summary>
|
||||
public int Confidence { get; set; }
|
||||
|
||||
/// <summary>The proposal, as shown.</summary>
|
||||
public string? Proposal { get; set; }
|
||||
|
||||
/// <summary>The ids the proposal points to (open items, payment, remittance line...), comma separated.</summary>
|
||||
public string? Targets { get; set; }
|
||||
|
||||
/// <summary>The party of the proposal.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The rule of the proposal.</summary>
|
||||
public long? RuleId { get; set; }
|
||||
|
||||
/// <summary>The collection or payment recorded or matched.</summary>
|
||||
public long? PaymentId { get; set; }
|
||||
|
||||
/// <summary>The entry recorded or matched.</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <summary>When it was matched.</summary>
|
||||
public DateTime? MatchedAt { get; set; }
|
||||
|
||||
/// <summary>Who matched it.</summary>
|
||||
public string? MatchedBy { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Which movements a rule applies to.</summary>
|
||||
public enum BankRuleDirection
|
||||
{
|
||||
/// <summary>Money in and out.</summary>
|
||||
Any = 0,
|
||||
|
||||
/// <summary>Money in.</summary>
|
||||
In = 1,
|
||||
|
||||
/// <summary>Money out.</summary>
|
||||
Out = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A rule of the reconciliation (<c>bank_match_rules</c>): the movements whose description contains a text are
|
||||
/// recorded on an account, such as bank fees on <c>21.03.011</c>.
|
||||
/// </summary>
|
||||
public sealed class BankMatchRule : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The name.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The text looked for in the description, case and accents ignored.</summary>
|
||||
public string Pattern { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Money in, out or both.</summary>
|
||||
public BankRuleDirection Direction { get; set; }
|
||||
|
||||
/// <summary>The account the movement goes to (the other side is the bank).</summary>
|
||||
public long AccountId { get; set; }
|
||||
|
||||
/// <summary>The journal template of the entry.</summary>
|
||||
public string? TemplateCode { get; set; }
|
||||
|
||||
/// <summary>The description of the entry; empty for the description of the movement.</summary>
|
||||
public string? EntryDescription { get; set; }
|
||||
|
||||
/// <summary>Not applied.</summary>
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <summary>How many movements it recorded.</summary>
|
||||
public int Uses { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>How a reminder is sent.</summary>
|
||||
[Flags]
|
||||
public enum DunningChannel
|
||||
{
|
||||
/// <summary>Not sent: printed only.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>E-mail.</summary>
|
||||
Email = 1,
|
||||
|
||||
/// <summary>Certified e-mail (PEC).</summary>
|
||||
Pec = 2,
|
||||
|
||||
/// <summary>A PDF letter, kept as an attachment of the customer.</summary>
|
||||
Letter = 4,
|
||||
}
|
||||
|
||||
/// <summary>What happens when a reminder of a level is sent.</summary>
|
||||
public enum DunningAction
|
||||
{
|
||||
/// <summary>Nothing else.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>The agent of the customer is notified.</summary>
|
||||
NotifyAgent = 1,
|
||||
|
||||
/// <summary>The customer is blocked (orders and deliveries) and the administration notified.</summary>
|
||||
BlockCustomer = 2,
|
||||
}
|
||||
|
||||
/// <summary>A level of the reminders (<c>dunning_levels</c>, mockup 056).</summary>
|
||||
public sealed class DunningLevel : Entity<long>
|
||||
{
|
||||
/// <summary>The level, from 1.</summary>
|
||||
public int Level { get; set; }
|
||||
|
||||
/// <summary>Days after the due date.</summary>
|
||||
public int DaysAfterDue { get; set; }
|
||||
|
||||
/// <summary>The name of the template, such as <c>Promemoria cortese</c>.</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The subject, with fields such as <c>{{Cliente}}</c>.</summary>
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The text, with fields such as <c>{{Elenco}}</c> and <c>{{Totale}}</c>.</summary>
|
||||
public string Body { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>How it is sent.</summary>
|
||||
public DunningChannel Channel { get; set; }
|
||||
|
||||
/// <summary>Late payment interest is computed and written.</summary>
|
||||
public bool ChargeInterest { get; set; }
|
||||
|
||||
/// <summary>What else happens.</summary>
|
||||
public DunningAction Action { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a reminder.</summary>
|
||||
public enum DunningLetterStatus
|
||||
{
|
||||
/// <summary>Waiting in the mail queue.</summary>
|
||||
Queued = 0,
|
||||
|
||||
/// <summary>Sent (or printed).</summary>
|
||||
Sent = 1,
|
||||
|
||||
/// <summary>Not sent.</summary>
|
||||
Failed = 2,
|
||||
}
|
||||
|
||||
/// <summary>A reminder sent to a customer (<c>dunning_letters</c>): the log of the reminders.</summary>
|
||||
public sealed class DunningLetter : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The customer.</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The level.</summary>
|
||||
public int Level { get; set; }
|
||||
|
||||
/// <summary>The day.</summary>
|
||||
public DateOnly SentOn { get; set; }
|
||||
|
||||
/// <summary>How it was sent.</summary>
|
||||
public DunningChannel Channel { get; set; }
|
||||
|
||||
/// <summary>The addresses.</summary>
|
||||
public string? Recipients { get; set; }
|
||||
|
||||
/// <summary>The subject.</summary>
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The open items reminded.</summary>
|
||||
public int ItemCount { get; set; }
|
||||
|
||||
/// <summary>The overdue amount.</summary>
|
||||
public decimal OverdueAmount { get; set; }
|
||||
|
||||
/// <summary>The late payment interest written.</summary>
|
||||
public decimal Interest { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public DunningLetterStatus Status { get; set; }
|
||||
|
||||
/// <summary>The PDF letter.</summary>
|
||||
public long? AttachmentId { get; set; }
|
||||
|
||||
/// <summary>The message in the mail queue.</summary>
|
||||
public long? MailId { get; set; }
|
||||
|
||||
/// <summary>Who sent it (empty for the scheduled task).</summary>
|
||||
public string? SentBy { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Core.Treasury;
|
||||
|
||||
/// <summary>The residual of the open items by age (mockup 053).</summary>
|
||||
/// <param name="NotDue">Not due yet.</param>
|
||||
/// <param name="Days1To30">Overdue by 1 to 30 days.</param>
|
||||
/// <param name="Days31To60">Overdue by 31 to 60 days.</param>
|
||||
/// <param name="Days61To90">Overdue by 61 to 90 days.</param>
|
||||
/// <param name="Over90">Overdue by more than 90 days.</param>
|
||||
/// <param name="CountNotDue">Items not due.</param>
|
||||
/// <param name="Count1To30">Items overdue by 1 to 30 days.</param>
|
||||
/// <param name="Count31To60">Items overdue by 31 to 60 days.</param>
|
||||
/// <param name="Count61To90">Items overdue by 61 to 90 days.</param>
|
||||
/// <param name="CountOver90">Items overdue by more than 90 days.</param>
|
||||
public sealed record AgingBuckets(
|
||||
decimal NotDue,
|
||||
decimal Days1To30,
|
||||
decimal Days31To60,
|
||||
decimal Days61To90,
|
||||
decimal Over90,
|
||||
int CountNotDue,
|
||||
int Count1To30,
|
||||
int Count31To60,
|
||||
int Count61To90,
|
||||
int CountOver90)
|
||||
{
|
||||
/// <summary>Everything open.</summary>
|
||||
public decimal Total => NotDue + Overdue;
|
||||
|
||||
/// <summary>Everything overdue.</summary>
|
||||
public decimal Overdue => Days1To30 + Days31To60 + Days61To90 + Over90;
|
||||
}
|
||||
|
||||
/// <summary>The age of open items (SPEC §11.8, <c>AgingCalculator</c>).</summary>
|
||||
public static class AgingCalculator
|
||||
{
|
||||
/// <summary>Days past the due date: negative while it is not due.</summary>
|
||||
/// <param name="dueDate">The due date.</param>
|
||||
/// <param name="today">Today.</param>
|
||||
/// <returns>The days.</returns>
|
||||
public static int DaysOverdue(DateOnly dueDate, DateOnly today) => today.DayNumber - dueDate.DayNumber;
|
||||
|
||||
/// <summary>Splits the residuals by age.</summary>
|
||||
/// <param name="items">The due date and residual of each item.</param>
|
||||
/// <param name="today">Today.</param>
|
||||
/// <returns>The buckets.</returns>
|
||||
public static AgingBuckets Of(IEnumerable<(DateOnly DueDate, decimal Residual)> items, DateOnly today)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
var sums = new decimal[5];
|
||||
var counts = new int[5];
|
||||
foreach (var (due, residual) in items)
|
||||
{
|
||||
if (residual == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var days = DaysOverdue(due, today);
|
||||
var bucket = days switch
|
||||
{
|
||||
<= 0 => 0,
|
||||
<= 30 => 1,
|
||||
<= 60 => 2,
|
||||
<= 90 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
sums[bucket] += residual;
|
||||
counts[bucket]++;
|
||||
}
|
||||
|
||||
return new AgingBuckets(sums[0], sums[1], sums[2], sums[3], sums[4], counts[0], counts[1], counts[2], counts[3], counts[4]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Spreads a collection or payment over open items.</summary>
|
||||
public static class PaymentAllocator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gives the amount to the items in their order (the oldest first): each item takes up to its residual; credit
|
||||
/// notes (negative residuals) are always taken whole, so they add to what the others can take.
|
||||
/// </summary>
|
||||
/// <param name="residuals">The residual of each item, in order.</param>
|
||||
/// <param name="amount">The money.</param>
|
||||
/// <returns>What each item takes; what is left over is not given to anyone.</returns>
|
||||
public static IReadOnlyList<decimal> Allocate(IReadOnlyList<decimal> residuals, decimal amount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(residuals);
|
||||
var result = new decimal[residuals.Count];
|
||||
var left = amount;
|
||||
for (var i = 0; i < residuals.Count; i++)
|
||||
{
|
||||
if (residuals[i] < 0m)
|
||||
{
|
||||
result[i] = residuals[i];
|
||||
left -= residuals[i];
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < residuals.Count; i++)
|
||||
{
|
||||
if (residuals[i] <= 0m || left <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var take = Math.Min(residuals[i], left);
|
||||
result[i] = take;
|
||||
left -= take;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The accounts of the entry of a collection or payment.</summary>
|
||||
/// <param name="Money">The bank, cash or effects account the money moves on.</param>
|
||||
/// <param name="AllowanceExpense">Allowances granted (abbuoni passivi).</param>
|
||||
/// <param name="AllowanceIncome">Allowances received (abbuoni attivi).</param>
|
||||
/// <param name="ExchangeLoss">Exchange losses.</param>
|
||||
/// <param name="ExchangeGain">Exchange gains.</param>
|
||||
/// <param name="BankCharges">Bank fees.</param>
|
||||
public sealed record PaymentPostingAccounts(long Money, long? AllowanceExpense, long? AllowanceIncome, long? ExchangeLoss, long? ExchangeGain, long? BankCharges);
|
||||
|
||||
/// <summary>A line of a collection or payment as the entry reads it.</summary>
|
||||
/// <param name="ControlAccountId">The customers or suppliers account of the item.</param>
|
||||
/// <param name="PartyId">The customer or supplier.</param>
|
||||
/// <param name="OpenItemId">The item.</param>
|
||||
/// <param name="Description">The description (the document).</param>
|
||||
/// <param name="Amount">The money.</param>
|
||||
/// <param name="Allowance">The allowance.</param>
|
||||
/// <param name="ExchangeDifference">The exchange difference.</param>
|
||||
public sealed record PaymentPostingLine(long ControlAccountId, long PartyId, long OpenItemId, string? Description, decimal Amount, decimal Allowance, decimal ExchangeDifference);
|
||||
|
||||
/// <summary>A line of the entry written for a collection or payment.</summary>
|
||||
/// <param name="AccountId">The account.</param>
|
||||
/// <param name="PartyId">The customer or supplier.</param>
|
||||
/// <param name="OpenItemId">The item it settles.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Debit">Dare.</param>
|
||||
/// <param name="Credit">Avere.</param>
|
||||
public sealed record PaymentPostedLine(long AccountId, long? PartyId, long? OpenItemId, string? Description, decimal Debit, decimal Credit);
|
||||
|
||||
/// <summary>The missing account of a collection or payment.</summary>
|
||||
public sealed class PaymentAccountMissingException : InvalidOperationException
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public PaymentAccountMissingException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The role of the missing account.</param>
|
||||
public PaymentAccountMissingException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The role.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public PaymentAccountMissingException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entry of a collection or payment (mockup 054): a collection debits the money, credits the customer for what
|
||||
/// each item settles and books allowances and exchange differences on their accounts; a payment the other way round.
|
||||
/// Bank fees are a cost paid from the same money account. The entry always balances.
|
||||
/// </summary>
|
||||
public static class PaymentPosting
|
||||
{
|
||||
/// <summary>Builds the lines.</summary>
|
||||
/// <param name="direction">Collection or payment.</param>
|
||||
/// <param name="accounts">The accounts.</param>
|
||||
/// <param name="lines">The items settled.</param>
|
||||
/// <param name="fees">The bank fees.</param>
|
||||
/// <param name="description">The description of the money line.</param>
|
||||
/// <returns>The lines, balanced.</returns>
|
||||
/// <exception cref="PaymentAccountMissingException">An allowance, exchange difference or fee has no account.</exception>
|
||||
public static IReadOnlyList<PaymentPostedLine> Build(
|
||||
PaymentDirection direction, PaymentPostingAccounts accounts, IReadOnlyList<PaymentPostingLine> lines, decimal fees, string? description)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(accounts);
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
var result = new List<PaymentPostedLine>();
|
||||
var receipt = direction == PaymentDirection.Receipt;
|
||||
|
||||
// Signed amounts: positive is Dare.
|
||||
void Add(long account, long? party, long? item, string? text, decimal signed)
|
||||
{
|
||||
if (signed > 0m)
|
||||
{
|
||||
result.Add(new PaymentPostedLine(account, party, item, text, signed, 0m));
|
||||
}
|
||||
else if (signed < 0m)
|
||||
{
|
||||
result.Add(new PaymentPostedLine(account, party, item, text, 0m, -signed));
|
||||
}
|
||||
}
|
||||
|
||||
static long Need(long? account, string role) => account ?? throw new PaymentAccountMissingException(role);
|
||||
|
||||
var money = lines.Sum(l => l.Amount);
|
||||
var allowance = lines.Sum(l => l.Allowance);
|
||||
var exchange = lines.Sum(l => l.ExchangeDifference);
|
||||
Add(accounts.Money, null, null, description, receipt ? money : -money);
|
||||
if (allowance != 0m)
|
||||
{
|
||||
// A collection grants the allowance (a cost); a payment receives it (an income). The opposite sign swaps them.
|
||||
var cost = receipt ? allowance > 0m : allowance < 0m;
|
||||
var account = cost ? Need(accounts.AllowanceExpense, "AllowanceExpense") : Need(accounts.AllowanceIncome, "AllowanceIncome");
|
||||
Add(account, null, null, "Abbuono", receipt ? allowance : -allowance);
|
||||
}
|
||||
|
||||
if (exchange != 0m)
|
||||
{
|
||||
var loss = receipt ? exchange > 0m : exchange < 0m;
|
||||
var account = loss ? Need(accounts.ExchangeLoss, "ExchangeLoss") : Need(accounts.ExchangeGain, "ExchangeGain");
|
||||
Add(account, null, null, "Differenza cambio", receipt ? exchange : -exchange);
|
||||
}
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var settled = line.Amount + line.Allowance + line.ExchangeDifference;
|
||||
Add(line.ControlAccountId, line.PartyId, line.OpenItemId, line.Description, receipt ? -settled : settled);
|
||||
}
|
||||
|
||||
if (fees != 0m)
|
||||
{
|
||||
Add(Need(accounts.BankCharges, "BankCharges"), null, null, "Spese bancarie", fees);
|
||||
Add(accounts.Money, null, null, "Spese bancarie", -fees);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Late payment interest (SPEC §11.8, D.Lgs. 231/2002 in Italy).</summary>
|
||||
public static class LateInterestCalculator
|
||||
{
|
||||
/// <summary>
|
||||
/// The interest on a residual from the day after the due date to a day, at the yearly rate of each day (the rate
|
||||
/// changes every half-year), on 365 days, rounded to the cent.
|
||||
/// </summary>
|
||||
/// <param name="residual">The amount overdue.</param>
|
||||
/// <param name="dueDate">The due date.</param>
|
||||
/// <param name="until">The last day counted.</param>
|
||||
/// <param name="rateOn">The yearly rate in percent of a day.</param>
|
||||
/// <returns>The interest; zero when not overdue.</returns>
|
||||
public static decimal Interest(decimal residual, DateOnly dueDate, DateOnly until, Func<DateOnly, decimal> rateOn)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rateOn);
|
||||
if (residual <= 0m || until <= dueDate)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var total = 0m;
|
||||
var day = dueDate.AddDays(1);
|
||||
while (day <= until)
|
||||
{
|
||||
// One step per half-year: the rate is the same inside it.
|
||||
var halfEnd = day.Month <= 6 ? new DateOnly(day.Year, 6, 30) : new DateOnly(day.Year, 12, 31);
|
||||
var last = halfEnd < until ? halfEnd : until;
|
||||
var days = last.DayNumber - day.DayNumber + 1;
|
||||
total += residual * rateOn(day) / 100m * days / 365m;
|
||||
day = last.AddDays(1);
|
||||
}
|
||||
|
||||
return Math.Round(total, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A possible match of a bank movement, built by the reconciliation from the open data of the company.</summary>
|
||||
/// <param name="Kind">What it is.</param>
|
||||
/// <param name="Targets">The ids it points to, comma separated.</param>
|
||||
/// <param name="PartyId">The customer or supplier.</param>
|
||||
/// <param name="Amount">The movement it expects: positive money in, negative money out.</param>
|
||||
/// <param name="Date">The date it expects (due date, payment date).</param>
|
||||
/// <param name="Label">The proposal as shown, such as <c>Incasso FT/2026/000388</c>.</param>
|
||||
/// <param name="Keys">Document numbers and references that may appear in the description.</param>
|
||||
/// <param name="Names">Names of the party that may appear.</param>
|
||||
/// <param name="Ibans">IBANs of the party.</param>
|
||||
/// <param name="Keywords">Words that must appear for the candidate to count (such as <c>INSOLUT</c>, <c>F24</c>); empty for none.</param>
|
||||
/// <param name="AmountTolerance">How much more the movement may be (bank fees of an unpaid effect).</param>
|
||||
public sealed record MatchCandidate(
|
||||
StatementMatchKind Kind,
|
||||
string? Targets,
|
||||
long? PartyId,
|
||||
decimal Amount,
|
||||
DateOnly Date,
|
||||
string Label,
|
||||
IReadOnlyList<string> Keys,
|
||||
IReadOnlyList<string> Names,
|
||||
IReadOnlyList<string> Ibans,
|
||||
IReadOnlyList<string> Keywords,
|
||||
decimal AmountTolerance = 0m);
|
||||
|
||||
/// <summary>A saved rule as the matcher reads it.</summary>
|
||||
/// <param name="Id">The rule.</param>
|
||||
/// <param name="Pattern">The text looked for.</param>
|
||||
/// <param name="Direction">Money in, out or both.</param>
|
||||
/// <param name="Label">The proposal, such as <c>Regola 'COMMISSIONI' → 21.03.011 Spese bancarie</c>.</param>
|
||||
public sealed record MatchRule(long Id, string Pattern, BankRuleDirection Direction, string Label);
|
||||
|
||||
/// <summary>The best match of a movement.</summary>
|
||||
/// <param name="Kind">What it is.</param>
|
||||
/// <param name="Targets">The ids.</param>
|
||||
/// <param name="PartyId">The party.</param>
|
||||
/// <param name="RuleId">The rule.</param>
|
||||
/// <param name="Confidence">0-100.</param>
|
||||
/// <param name="Label">As shown.</param>
|
||||
public sealed record MatchProposal(StatementMatchKind Kind, string? Targets, long? PartyId, long? RuleId, int Confidence, string Label);
|
||||
|
||||
/// <summary>
|
||||
/// Proposes what a bank movement is (SPEC §11.8, mockup 057, <c>BankMatcher</c>): by amount, date, document numbers
|
||||
/// and references in the description, the name and IBAN of the party; saved rules for the recurring movements (fees,
|
||||
/// commissions). The service records the proposals at or above the threshold the user confirms.
|
||||
/// </summary>
|
||||
public static class BankMatcher
|
||||
{
|
||||
/// <summary>The words before a document number in bank descriptions.</summary>
|
||||
private static readonly HashSet<string> NumberPrefixes = new(StringComparer.Ordinal)
|
||||
{
|
||||
"FT", "FATT", "FATTURA", "FATTURE", "FAT", "FA", "N", "NR", "NUM", "DOC", "RIF", "FAT.", "INV", "INVOICE",
|
||||
};
|
||||
|
||||
/// <summary>The best proposal for a movement, or <see langword="null"/> when nothing fits.</summary>
|
||||
/// <param name="movement">The movement.</param>
|
||||
/// <param name="candidates">The candidates.</param>
|
||||
/// <param name="rules">The rules.</param>
|
||||
/// <returns>The proposal.</returns>
|
||||
public static MatchProposal? Best(StatementMovement movement, IEnumerable<MatchCandidate> candidates, IEnumerable<MatchRule> rules)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movement);
|
||||
ArgumentNullException.ThrowIfNull(candidates);
|
||||
ArgumentNullException.ThrowIfNull(rules);
|
||||
var text = Normalize(movement.Description + " " + movement.Reference + " " + movement.CounterpartyName);
|
||||
var tokens = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
MatchProposal? best = null;
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
var score = Score(movement, candidate, text, tokens);
|
||||
if (score > 0 && (best is null || score > best.Confidence))
|
||||
{
|
||||
best = new MatchProposal(candidate.Kind, candidate.Targets, candidate.PartyId, null, score, candidate.Label);
|
||||
}
|
||||
}
|
||||
|
||||
if (best is { Confidence: >= 90 })
|
||||
{
|
||||
return best;
|
||||
}
|
||||
|
||||
foreach (var rule in rules)
|
||||
{
|
||||
var direction = rule.Direction switch
|
||||
{
|
||||
BankRuleDirection.In => movement.Amount > 0m,
|
||||
BankRuleDirection.Out => movement.Amount < 0m,
|
||||
_ => true,
|
||||
};
|
||||
var pattern = Normalize(rule.Pattern);
|
||||
if (direction && pattern.Length > 0 && (" " + text + " ").Contains(" " + pattern, StringComparison.Ordinal))
|
||||
{
|
||||
return new MatchProposal(StatementMatchKind.Rule, rule.Id.ToString(CultureInfo.InvariantCulture), null, rule.Id, 98, rule.Label);
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>The score of a candidate, 0 when it does not fit.</summary>
|
||||
/// <param name="movement">The movement.</param>
|
||||
/// <param name="candidate">The candidate.</param>
|
||||
/// <returns>0-100.</returns>
|
||||
public static int Score(StatementMovement movement, MatchCandidate candidate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movement);
|
||||
ArgumentNullException.ThrowIfNull(candidate);
|
||||
var text = Normalize(movement.Description + " " + movement.Reference + " " + movement.CounterpartyName);
|
||||
return Score(movement, candidate, text, text.Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
}
|
||||
|
||||
/// <summary>Upper case, no accents, only letters and digits separated by single spaces.</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns>The normalised text.</returns>
|
||||
public static string Normalize(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(text.Length);
|
||||
var space = true;
|
||||
foreach (var ch in text.Normalize(NormalizationForm.FormD))
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char.IsLetterOrDigit(ch))
|
||||
{
|
||||
builder.Append(char.ToUpperInvariant(ch));
|
||||
space = false;
|
||||
}
|
||||
else if (!space)
|
||||
{
|
||||
builder.Append(' ');
|
||||
space = true;
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString().TrimEnd();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The items of one party whose residuals add up to an amount: first the oldest items in a row, then any pair or
|
||||
/// triple among the first twelve.
|
||||
/// </summary>
|
||||
/// <param name="items">The id and residual of the items, oldest first.</param>
|
||||
/// <param name="amount">The amount.</param>
|
||||
/// <returns>The ids, or an empty list.</returns>
|
||||
public static IReadOnlyList<long> Combination(IReadOnlyList<(long Id, decimal Residual)> items, decimal amount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
var sum = 0m;
|
||||
for (var i = 0; i < items.Count; i++)
|
||||
{
|
||||
sum += items[i].Residual;
|
||||
if (sum == amount)
|
||||
{
|
||||
return [.. items.Take(i + 1).Select(x => x.Id)];
|
||||
}
|
||||
}
|
||||
|
||||
var n = Math.Min(items.Count, 12);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
if (items[i].Residual == amount)
|
||||
{
|
||||
return [items[i].Id];
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
for (var j = i + 1; j < n; j++)
|
||||
{
|
||||
if (items[i].Residual + items[j].Residual == amount)
|
||||
{
|
||||
return [items[i].Id, items[j].Id];
|
||||
}
|
||||
|
||||
for (var k = j + 1; k < n; k++)
|
||||
{
|
||||
if (items[i].Residual + items[j].Residual + items[k].Residual == amount)
|
||||
{
|
||||
return [items[i].Id, items[j].Id, items[k].Id];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private static int Score(StatementMovement movement, MatchCandidate candidate, string text, string[] tokens)
|
||||
{
|
||||
var difference = movement.Amount - candidate.Amount;
|
||||
var exact = Math.Abs(difference) < 0.005m;
|
||||
var withinTolerance = candidate.AmountTolerance > 0m && Math.Sign(movement.Amount) == Math.Sign(candidate.Amount)
|
||||
&& Math.Abs(movement.Amount) >= Math.Abs(candidate.Amount) && Math.Abs(difference) <= candidate.AmountTolerance;
|
||||
if (!exact && !withinTolerance)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (candidate.Keywords.Count > 0 && !candidate.Keywords.Any(k => text.Contains(Normalize(k), StringComparison.Ordinal)))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var score = exact ? 50 : 40;
|
||||
if (candidate.Keywords.Count > 0)
|
||||
{
|
||||
score += 30;
|
||||
}
|
||||
|
||||
if (candidate.Keys.Any(k => HasKey(text, tokens, k)))
|
||||
{
|
||||
score += 30;
|
||||
}
|
||||
|
||||
if (candidate.Ibans.Any(i => movement.CounterpartyIban is { } iban && string.Equals(Compact(iban), Compact(i), StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
score += 25;
|
||||
}
|
||||
|
||||
if (candidate.Names.Any(n => HasName(text, n)))
|
||||
{
|
||||
score += 20;
|
||||
}
|
||||
|
||||
var days = Math.Abs(movement.BookingDate.DayNumber - candidate.Date.DayNumber);
|
||||
score += days switch
|
||||
{
|
||||
<= 3 => 10,
|
||||
<= 15 => 5,
|
||||
<= 60 => 0,
|
||||
_ => -10,
|
||||
};
|
||||
return Math.Clamp(score, 1, 100);
|
||||
}
|
||||
|
||||
private static bool HasKey(string text, string[] tokens, string key)
|
||||
{
|
||||
var normalized = Normalize(key);
|
||||
if (normalized.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((" " + text + " ").Contains(" " + normalized + " ", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// The number of a document without its prefix and leading zeros, after a word such as FT or FATT.
|
||||
var parts = normalized.Split(' ');
|
||||
var last = parts[^1].TrimStart('0');
|
||||
if (last.Length == 0 || !last.All(char.IsAsciiDigit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 1; i < tokens.Length; i++)
|
||||
{
|
||||
if (tokens[i].TrimStart('0') == last && NumberPrefixes.Contains(tokens[i - 1]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool HasName(string text, string name)
|
||||
{
|
||||
// The first two significant words of the name (Rossi Impianti S.r.l. → ROSSI IMPIANTI).
|
||||
var words = Normalize(name).Split(' ', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Where(w => w.Length >= 3 && w is not ("SRL" or "SPA" or "SNC" or "SAS" or "SRLS" or "DI" or "DEL" or "DELLA" or "E" or "C"))
|
||||
.Take(2).ToList();
|
||||
return words.Count > 0 && words.All(w => (" " + text + " ").Contains(" " + w + " ", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static string Compact(string iban) => iban.Replace(" ", string.Empty, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>An open item as the reminders read it.</summary>
|
||||
/// <param name="OpenItemId">The item.</param>
|
||||
/// <param name="DueDate">The due date.</param>
|
||||
/// <param name="Residual">What is left.</param>
|
||||
/// <param name="Level">The level of its last reminder.</param>
|
||||
/// <param name="LastDunningDate">The day of its last reminder.</param>
|
||||
/// <param name="Disputed">Contested.</param>
|
||||
public sealed record DunningItem(long OpenItemId, DateOnly DueDate, decimal Residual, int Level, DateOnly? LastDunningDate, bool Disputed);
|
||||
|
||||
/// <summary>A level as the reminders read it.</summary>
|
||||
/// <param name="Level">The level.</param>
|
||||
/// <param name="DaysAfterDue">Days after the due date.</param>
|
||||
public sealed record DunningStep(int Level, int DaysAfterDue);
|
||||
|
||||
/// <summary>Which reminder a customer gets next (SPEC §11.8, mockup 056, <c>DunningRules</c>).</summary>
|
||||
public static class DunningRules
|
||||
{
|
||||
/// <summary>Days between two reminders to the same customer.</summary>
|
||||
public const int MinDaysBetween = 7;
|
||||
|
||||
/// <summary>
|
||||
/// The next level: the one after the highest already sent on the overdue items, once the oldest of them is
|
||||
/// overdue by its days and a week has passed since the last reminder; none when nothing is overdue, the items are
|
||||
/// contested or the last level was sent.
|
||||
/// </summary>
|
||||
/// <param name="items">The open items of the customer.</param>
|
||||
/// <param name="levels">The levels.</param>
|
||||
/// <param name="today">Today.</param>
|
||||
/// <returns>The level, or <see langword="null"/>.</returns>
|
||||
public static int? NextLevel(IReadOnlyList<DunningItem> items, IReadOnlyList<DunningStep> levels, DateOnly today)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
ArgumentNullException.ThrowIfNull(levels);
|
||||
var overdue = items.Where(i => !i.Disputed && i.Residual > 0m && i.DueDate < today).ToList();
|
||||
if (overdue.Count == 0 || levels.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var maxDays = overdue.Max(i => AgingCalculator.DaysOverdue(i.DueDate, today));
|
||||
var current = overdue.Max(i => i.Level);
|
||||
var last = overdue.Select(i => i.LastDunningDate).Where(d => d is not null).Max();
|
||||
if (last is { } l && today.DayNumber - l.DayNumber < MinDaysBetween)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var next = levels.Where(s => s.Level > current).OrderBy(s => s.Level).FirstOrDefault();
|
||||
return next is not null && maxDays >= next.DaysAfterDue ? next.Level : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a forecast movement comes from.</summary>
|
||||
public enum CashFlowSource
|
||||
{
|
||||
/// <summary>Open items of customers.</summary>
|
||||
Receivables = 0,
|
||||
|
||||
/// <summary>Open items of suppliers.</summary>
|
||||
Payables = 1,
|
||||
|
||||
/// <summary>Customer orders not invoiced.</summary>
|
||||
SaleOrders = 2,
|
||||
|
||||
/// <summary>Supplier orders not invoiced.</summary>
|
||||
PurchaseOrders = 3,
|
||||
|
||||
/// <summary>Recurring entries on bank or cash.</summary>
|
||||
Recurring = 4,
|
||||
|
||||
/// <summary>Taxes to pay (F24).</summary>
|
||||
Taxes = 5,
|
||||
}
|
||||
|
||||
/// <summary>A forecast movement.</summary>
|
||||
/// <param name="Date">When it is expected.</param>
|
||||
/// <param name="Amount">Positive in, negative out.</param>
|
||||
/// <param name="Source">Where it comes from.</param>
|
||||
/// <param name="Label">What it is.</param>
|
||||
public sealed record CashFlowMovement(DateOnly Date, decimal Amount, CashFlowSource Source, string Label);
|
||||
|
||||
/// <summary>A period of the forecast.</summary>
|
||||
/// <param name="From">The first day.</param>
|
||||
/// <param name="To">The last day.</param>
|
||||
/// <param name="In">Money in.</param>
|
||||
/// <param name="Out">Money out (positive).</param>
|
||||
/// <param name="Balance">The balance at the end of the period.</param>
|
||||
public sealed record CashFlowPeriod(DateOnly From, DateOnly To, decimal In, decimal Out, decimal Balance);
|
||||
|
||||
/// <summary>The cash flow forecast (SPEC §11.8, <c>CashFlowForecastService</c>): the balance period by period.</summary>
|
||||
public static class CashFlowForecaster
|
||||
{
|
||||
/// <summary>Spreads the movements over periods; the overdue ones count in the first period.</summary>
|
||||
/// <param name="opening">The money today on bank and cash.</param>
|
||||
/// <param name="movements">The movements.</param>
|
||||
/// <param name="from">The first day.</param>
|
||||
/// <param name="days">How many days.</param>
|
||||
/// <param name="periodDays">The days of a period.</param>
|
||||
/// <returns>The periods.</returns>
|
||||
public static IReadOnlyList<CashFlowPeriod> Periods(decimal opening, IEnumerable<CashFlowMovement> movements, DateOnly from, int days, int periodDays = 7)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movements);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(days, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(periodDays, 1);
|
||||
var end = from.AddDays(days - 1);
|
||||
var list = movements.Where(m => m.Date <= end).ToList();
|
||||
var result = new List<CashFlowPeriod>();
|
||||
var balance = opening;
|
||||
for (var start = from; start <= end; start = start.AddDays(periodDays))
|
||||
{
|
||||
var stop = start.AddDays(periodDays - 1) > end ? end : start.AddDays(periodDays - 1);
|
||||
var first = result.Count == 0;
|
||||
var inPeriod = list.Where(m => (first && m.Date < start) || (m.Date >= start && m.Date <= stop)).ToList();
|
||||
var money = inPeriod.Where(m => m.Amount > 0m).Sum(m => m.Amount);
|
||||
var spent = -inPeriod.Where(m => m.Amount < 0m).Sum(m => m.Amount);
|
||||
balance += money - spent;
|
||||
result.Add(new CashFlowPeriod(start, stop, money, spent, balance));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ public sealed class OpenItemMap : EntityMap<OpenItem>
|
||||
{
|
||||
ToTable("gl_open_items");
|
||||
Map(x => x.DocumentNumber).MaxLength(30);
|
||||
Map(x => x.Notes).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// The schedule and the treasury (SPEC §11.8, ADR 0038, issues #69-#72): the open items of the ledger get their state
|
||||
/// in the schedule; collections and payments with their lines; remittances of effects, direct debits and transfers
|
||||
/// with their lines; direct debit mandates; bank statements with their movements and the saved rules of the
|
||||
/// reconciliation; the levels of the reminders and the log of the reminders sent.
|
||||
/// </summary>
|
||||
[Migration(20261113_003, "create_treasury")]
|
||||
public sealed class M20261113_003_CreateTreasury : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.AlterTable("gl_open_items", t =>
|
||||
{
|
||||
t.String("status", 40).NotNull().Default("Open");
|
||||
t.Bool("disputed").NotNull().Default(false);
|
||||
t.Int64("bank_account_id");
|
||||
t.Int64("remittance_id");
|
||||
t.Int32("unpaid_count").NotNull().Default(0);
|
||||
t.Int64("parent_id");
|
||||
t.Int32("dunning_level").NotNull().Default(0);
|
||||
t.Date("last_dunning_date");
|
||||
t.String("notes", 200);
|
||||
});
|
||||
schema.CreateIndex("gl_open_items", "ix_gl_open_items_schedule", false, "direction", "status", "due_date");
|
||||
|
||||
schema.CreateTable("remittances", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int32("year").NotNull();
|
||||
t.Int32("number").NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.Int64("bank_account_id").NotNull();
|
||||
t.Date("presentation_date").NotNull();
|
||||
t.Date("due_until").NotNull();
|
||||
t.Bool("advance").NotNull().Default(false);
|
||||
t.String("status", 40).NotNull();
|
||||
t.Decimal("total_amount").NotNull().Default(0m);
|
||||
t.Int32("item_count").NotNull().Default(0);
|
||||
t.String("message_id", 35);
|
||||
t.Int64("attachment_id");
|
||||
t.String("file_name", 100);
|
||||
t.Int64("gl_entry_id");
|
||||
t.Date("credited_on");
|
||||
t.Int64("credit_entry_id");
|
||||
t.String("notes", 500);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_remittances_number", "year", "number");
|
||||
t.ForeignKey("fk_remittances_bank", "bank_account_id", "bank_accounts", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("sdd_mandates", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("reference", 35).NotNull();
|
||||
t.Date("signature_date").NotNull();
|
||||
t.String("scheme", 40).NotNull();
|
||||
t.String("iban", 34).NotNull();
|
||||
t.String("bic", 11);
|
||||
t.Bool("one_off").NotNull().Default(false);
|
||||
t.Date("last_collection_date");
|
||||
t.Bool("revoked").NotNull().Default(false);
|
||||
t.String("notes", 200);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_sdd_mandates_reference", "reference");
|
||||
t.Index("ix_sdd_mandates_party", "party_id");
|
||||
t.ForeignKey("fk_sdd_mandates_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("payments", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("direction", 40).NotNull();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Date("payment_date").NotNull();
|
||||
t.Int64("payment_method_id");
|
||||
t.Int64("bank_account_id");
|
||||
t.Int64("account_id");
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.Decimal("allowance_amount").NotNull().Default(0m);
|
||||
t.Decimal("exchange_difference").NotNull().Default(0m);
|
||||
t.Decimal("fees").NotNull().Default(0m);
|
||||
t.String("reference", 60);
|
||||
t.String("template_code", 10);
|
||||
t.String("notes", 500);
|
||||
t.String("origin", 40).NotNull();
|
||||
t.Int64("remittance_id");
|
||||
t.Int64("statement_line_id");
|
||||
t.Int64("gl_entry_id");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_payments_date", "direction", "payment_date");
|
||||
t.Index("ix_payments_party", "party_id", "payment_date");
|
||||
t.ForeignKey("fk_payments_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_payments_remittance", "remittance_id", "remittances", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("payment_lines", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("payment_id").NotNull();
|
||||
t.Int64("open_item_id").NotNull();
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.Decimal("allowance").NotNull().Default(0m);
|
||||
t.Decimal("exchange_difference").NotNull().Default(0m);
|
||||
t.AuditColumns();
|
||||
t.Index("ix_payment_lines_payment", "payment_id");
|
||||
t.Index("ix_payment_lines_item", "open_item_id");
|
||||
t.ForeignKey("fk_payment_lines_payment", "payment_id", "payments", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_payment_lines_item", "open_item_id", "gl_open_items", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("remittance_lines", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("remittance_id").NotNull();
|
||||
t.Int64("open_item_id").NotNull();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.Date("due_date").NotNull();
|
||||
t.String("iban", 34);
|
||||
t.Int64("mandate_id");
|
||||
t.String("end_to_end_id", 35);
|
||||
t.String("status", 40).NotNull();
|
||||
t.Date("unpaid_on");
|
||||
t.Decimal("unpaid_fees").NotNull().Default(0m);
|
||||
t.Int64("unpaid_entry_id");
|
||||
t.Int64("payment_id");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_remittance_lines_remittance", "remittance_id");
|
||||
t.Index("ix_remittance_lines_item", "open_item_id");
|
||||
t.ForeignKey("fk_remittance_lines_remittance", "remittance_id", "remittances", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_remittance_lines_item", "open_item_id", "gl_open_items", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_remittance_lines_mandate", "mandate_id", "sdd_mandates", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("bank_statements", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("bank_account_id").NotNull();
|
||||
t.String("format", 40).NotNull();
|
||||
t.String("file_name", 200);
|
||||
t.Date("from_date").NotNull();
|
||||
t.Date("to_date").NotNull();
|
||||
t.Decimal("opening_balance");
|
||||
t.Decimal("closing_balance");
|
||||
t.Int32("movement_count").NotNull().Default(0);
|
||||
t.Int64("attachment_id");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_bank_statements_account", "bank_account_id", "to_date");
|
||||
t.ForeignKey("fk_bank_statements_bank", "bank_account_id", "bank_accounts", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("bank_match_rules", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("name", 100).NotNull();
|
||||
t.String("pattern", 100).NotNull();
|
||||
t.String("direction", 40).NotNull();
|
||||
t.Int64("account_id").NotNull();
|
||||
t.String("template_code", 10);
|
||||
t.String("entry_description", 200);
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.Int32("uses").NotNull().Default(0);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.ForeignKey("fk_bank_match_rules_account", "account_id", "gl_accounts", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("bank_statement_lines", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("statement_id").NotNull();
|
||||
t.Int64("bank_account_id").NotNull();
|
||||
t.Date("booking_date").NotNull();
|
||||
t.Date("value_date");
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.String("description", 500).NotNull();
|
||||
t.String("reference", 60);
|
||||
t.String("counterparty_name", 140);
|
||||
t.String("counterparty_iban", 34);
|
||||
t.String("bank_code", 40);
|
||||
t.String("fingerprint", 64).NotNull();
|
||||
t.String("status", 40).NotNull();
|
||||
t.String("match_kind", 40).NotNull();
|
||||
t.Int32("confidence").NotNull().Default(0);
|
||||
t.String("proposal", 300);
|
||||
t.String("targets", 300);
|
||||
t.Int64("party_id");
|
||||
t.Int64("rule_id");
|
||||
t.Int64("payment_id");
|
||||
t.Int64("gl_entry_id");
|
||||
t.DateTimeUtc("matched_at");
|
||||
t.String("matched_by", 100);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_bank_statement_lines_fingerprint", "bank_account_id", "fingerprint");
|
||||
t.Index("ix_bank_statement_lines_date", "bank_account_id", "booking_date");
|
||||
t.Index("ix_bank_statement_lines_statement", "statement_id");
|
||||
t.ForeignKey("fk_bank_statement_lines_statement", "statement_id", "bank_statements", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("dunning_levels", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int32("level").NotNull();
|
||||
t.Int32("days_after_due").NotNull();
|
||||
t.String("name", 100).NotNull();
|
||||
t.String("subject", 200).NotNull();
|
||||
t.Text("body").NotNull();
|
||||
t.String("channel", 60).NotNull();
|
||||
t.Bool("charge_interest").NotNull().Default(false);
|
||||
t.String("action", 40).NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_dunning_levels_level", "level");
|
||||
});
|
||||
|
||||
schema.CreateTable("dunning_letters", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.Int32("level").NotNull();
|
||||
t.Date("sent_on").NotNull();
|
||||
t.String("channel", 60).NotNull();
|
||||
t.String("recipients", 300);
|
||||
t.String("subject", 200).NotNull();
|
||||
t.Int32("item_count").NotNull().Default(0);
|
||||
t.Decimal("overdue_amount").NotNull().Default(0m);
|
||||
t.Decimal("interest").NotNull().Default(0m);
|
||||
t.String("status", 40).NotNull();
|
||||
t.Int64("attachment_id");
|
||||
t.Int64("mail_id");
|
||||
t.String("sent_by", 100);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_dunning_letters_party", "party_id", "sent_on");
|
||||
t.ForeignKey("fk_dunning_letters_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using Khaemhat.Core.Treasury;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="Payment"/> to <c>payments</c>.</summary>
|
||||
public sealed class PaymentMap : EntityMap<Payment>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentMap()
|
||||
{
|
||||
ToTable("payments");
|
||||
Map(x => x.Reference).MaxLength(60);
|
||||
Map(x => x.TemplateCode).MaxLength(10);
|
||||
Map(x => x.Notes).MaxLength(500);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentLine"/> to <c>payment_lines</c>.</summary>
|
||||
public sealed class PaymentLineMap : EntityMap<PaymentLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentLineMap() => ToTable("payment_lines");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Remittance"/> to <c>remittances</c>.</summary>
|
||||
public sealed class RemittanceMap : EntityMap<Remittance>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public RemittanceMap()
|
||||
{
|
||||
ToTable("remittances");
|
||||
Map(x => x.MessageId).MaxLength(35);
|
||||
Map(x => x.FileName).MaxLength(100);
|
||||
Map(x => x.Notes).MaxLength(500);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="RemittanceLine"/> to <c>remittance_lines</c>.</summary>
|
||||
public sealed class RemittanceLineMap : EntityMap<RemittanceLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public RemittanceLineMap()
|
||||
{
|
||||
ToTable("remittance_lines");
|
||||
Map(x => x.Iban).MaxLength(34);
|
||||
Map(x => x.EndToEndId).MaxLength(35);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SddMandate"/> to <c>sdd_mandates</c>.</summary>
|
||||
public sealed class SddMandateMap : EntityMap<SddMandate>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SddMandateMap()
|
||||
{
|
||||
ToTable("sdd_mandates");
|
||||
Map(x => x.Reference).MaxLength(35);
|
||||
Map(x => x.Iban).MaxLength(34);
|
||||
Map(x => x.Bic).MaxLength(11);
|
||||
Map(x => x.Notes).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="BankStatement"/> to <c>bank_statements</c>.</summary>
|
||||
public sealed class BankStatementMap : EntityMap<BankStatement>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public BankStatementMap()
|
||||
{
|
||||
ToTable("bank_statements");
|
||||
Map(x => x.FileName).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="BankStatementLine"/> to <c>bank_statement_lines</c>.</summary>
|
||||
public sealed class BankStatementLineMap : EntityMap<BankStatementLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public BankStatementLineMap()
|
||||
{
|
||||
ToTable("bank_statement_lines");
|
||||
Map(x => x.Description).MaxLength(500);
|
||||
Map(x => x.Reference).MaxLength(60);
|
||||
Map(x => x.CounterpartyName).MaxLength(140);
|
||||
Map(x => x.CounterpartyIban).MaxLength(34);
|
||||
Map(x => x.BankCode).MaxLength(40);
|
||||
Map(x => x.Fingerprint).MaxLength(64);
|
||||
Map(x => x.Proposal).MaxLength(300);
|
||||
Map(x => x.Targets).MaxLength(300);
|
||||
Map(x => x.MatchedBy).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="BankMatchRule"/> to <c>bank_match_rules</c>.</summary>
|
||||
public sealed class BankMatchRuleMap : EntityMap<BankMatchRule>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public BankMatchRuleMap()
|
||||
{
|
||||
ToTable("bank_match_rules");
|
||||
Map(x => x.Name).MaxLength(100);
|
||||
Map(x => x.Pattern).MaxLength(100);
|
||||
Map(x => x.TemplateCode).MaxLength(10);
|
||||
Map(x => x.EntryDescription).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DunningLevel"/> to <c>dunning_levels</c>.</summary>
|
||||
public sealed class DunningLevelMap : EntityMap<DunningLevel>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DunningLevelMap()
|
||||
{
|
||||
ToTable("dunning_levels");
|
||||
Map(x => x.Name).MaxLength(100);
|
||||
Map(x => x.Subject).MaxLength(200);
|
||||
Map(x => x.Channel).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DunningLetter"/> to <c>dunning_letters</c>.</summary>
|
||||
public sealed class DunningLetterMap : EntityMap<DunningLetter>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DunningLetterMap()
|
||||
{
|
||||
ToTable("dunning_letters");
|
||||
Map(x => x.Channel).MaxLength(60);
|
||||
Map(x => x.Recipients).MaxLength(300);
|
||||
Map(x => x.Subject).MaxLength(200);
|
||||
Map(x => x.SentBy).MaxLength(100);
|
||||
}
|
||||
}
|
||||
@@ -206,6 +206,7 @@ codice;descrizione;natura;tipo;voce_cee;partitario;iva
|
||||
28.01.002;Interessi passivi su mutui;C;;C.17;;
|
||||
28.01.003;Interessi sulla liquidazione IVA trimestrale;C;;C.17;;
|
||||
28.01.004;Oneri finanziari diversi;C;;C.17;;
|
||||
28.01.005;Perdite su cambi;C;;C.17-bis;;
|
||||
29;Imposte sul reddito;C;;20;;
|
||||
29.01;Imposte sul reddito dell'esercizio;C;;20;;
|
||||
29.01.001;IRES dell'esercizio;C;;20;;
|
||||
@@ -231,6 +232,8 @@ codice;descrizione;natura;tipo;voce_cee;partitario;iva
|
||||
32.01;Proventi finanziari;R;;C.16;;
|
||||
32.01.001;Interessi attivi bancari;R;;C.16;;
|
||||
32.01.002;Altri proventi finanziari;R;;C.16;;
|
||||
32.01.003;Utili su cambi;R;;C.17-bis;;
|
||||
32.01.004;Interessi di mora attivi;R;;C.16;;
|
||||
90;Conti di apertura e chiusura;O;;;;
|
||||
90.01;Conti di apertura e chiusura;O;;;;
|
||||
90.01.001;Stato patrimoniale di apertura;O;;;;
|
||||
|
||||
|
@@ -60,6 +60,27 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate
|
||||
/// <summary>The interest of quarterly VAT payers.</summary>
|
||||
public const string VatInterest = "28.01.003";
|
||||
|
||||
/// <summary>Allowances received.</summary>
|
||||
public const string AllowanceIncome = "31.01.004";
|
||||
|
||||
/// <summary>Bank fees.</summary>
|
||||
public const string BankCharges = "21.03.011";
|
||||
|
||||
/// <summary>Effects and direct debits presented for collection.</summary>
|
||||
public const string BillsForCollection = "05.02.001";
|
||||
|
||||
/// <summary>Advances of the bank on effects.</summary>
|
||||
public const string BankAdvances = "13.01.001";
|
||||
|
||||
/// <summary>Exchange gains.</summary>
|
||||
public const string ExchangeGain = "32.01.003";
|
||||
|
||||
/// <summary>Exchange losses.</summary>
|
||||
public const string ExchangeLoss = "28.01.005";
|
||||
|
||||
/// <summary>Late payment interest charged to customers.</summary>
|
||||
public const string LateInterest = "32.01.004";
|
||||
|
||||
private readonly Lazy<IReadOnlyList<AccountTemplate>> _accounts = new(ReadAccounts);
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -101,6 +122,13 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate
|
||||
PostingRole.StampDuty => StampDutyCost,
|
||||
PostingRole.Rounding => Rounding,
|
||||
PostingRole.VatSettlement => VatSettlement,
|
||||
PostingRole.AllowanceIncome => AllowanceIncome,
|
||||
PostingRole.BankCharges => BankCharges,
|
||||
PostingRole.BillsForCollection => BillsForCollection,
|
||||
PostingRole.BankAdvances => BankAdvances,
|
||||
PostingRole.ExchangeGain => ExchangeGain,
|
||||
PostingRole.ExchangeLoss => ExchangeLoss,
|
||||
PostingRole.LateInterest => LateInterest,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -157,11 +185,39 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate
|
||||
[
|
||||
L(PostingRole.Bank, AccountSide.Debit, Bank),
|
||||
L(PostingRole.Customer, AccountSide.Credit, Customers),
|
||||
L(PostingRole.Rounding, AccountSide.Debit, Rounding, "Abbuono passivo"),
|
||||
L(PostingRole.ExchangeLoss, AccountSide.Debit, ExchangeLoss, "Differenza cambio"),
|
||||
L(PostingRole.BankCharges, AccountSide.Debit, BankCharges, "Spese bancarie"),
|
||||
]),
|
||||
new("PAG", "Pagamento a fornitore", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
|
||||
[
|
||||
L(PostingRole.Supplier, AccountSide.Debit, Suppliers),
|
||||
L(PostingRole.Bank, AccountSide.Credit, Bank),
|
||||
L(PostingRole.AllowanceIncome, AccountSide.Credit, AllowanceIncome, "Abbuono attivo"),
|
||||
L(PostingRole.ExchangeGain, AccountSide.Credit, ExchangeGain, "Differenza cambio"),
|
||||
L(PostingRole.BankCharges, AccountSide.Debit, BankCharges, "Spese bancarie"),
|
||||
]),
|
||||
new("DIST", "Presentazione effetti e addebiti SEPA", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
|
||||
[
|
||||
L(PostingRole.BillsForCollection, AccountSide.Debit, BillsForCollection),
|
||||
L(PostingRole.Customer, AccountSide.Credit, Customers),
|
||||
]),
|
||||
new("ANT", "Anticipo salvo buon fine", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
|
||||
[
|
||||
L(PostingRole.Bank, AccountSide.Debit, Bank),
|
||||
L(PostingRole.BankAdvances, AccountSide.Credit, BankAdvances),
|
||||
]),
|
||||
new("ACCR", "Accredito effetti a scadenza", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
|
||||
[
|
||||
L(PostingRole.Bank, AccountSide.Debit, Bank),
|
||||
L(PostingRole.BankAdvances, AccountSide.Debit, BankAdvances),
|
||||
L(PostingRole.BillsForCollection, AccountSide.Credit, BillsForCollection),
|
||||
]),
|
||||
new("INS", "Effetto insoluto", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
|
||||
[
|
||||
L(PostingRole.Customer, AccountSide.Debit, Customers),
|
||||
L(PostingRole.Bank, AccountSide.Credit, Bank),
|
||||
L(PostingRole.BillsForCollection, AccountSide.Credit, BillsForCollection),
|
||||
]),
|
||||
new("RIT", "Ritenuta d'acconto operata", JournalArea.Taxes, null, OpensItems: false, Reverses: false,
|
||||
[
|
||||
|
||||
@@ -15,6 +15,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
public ItalyFiscalPack()
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<ILatePaymentRules>(new LatePaymentRulesIt());
|
||||
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
|
||||
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
|
||||
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Late payment interest between companies (D.Lgs. 9 ottobre 2002, n. 231, art. 5): the reference rate is the rate of
|
||||
/// the main refinancing operations of the European Central Bank on the first calendar day of the half-year, published
|
||||
/// by the Ministry of Economy in the Gazzetta Ufficiale, plus eight points. The table below must get a row every
|
||||
/// half-year (ADR 0038); after its last row the last rate applies.
|
||||
/// </summary>
|
||||
public sealed class LatePaymentRulesIt : ILatePaymentRules
|
||||
{
|
||||
/// <summary>The points added to the reference rate.</summary>
|
||||
public const decimal Margin = 8m;
|
||||
|
||||
/// <summary>The ECB main refinancing rate on the first day of each half-year, in percent.</summary>
|
||||
private static readonly (DateOnly From, decimal Rate)[] ReferenceRates =
|
||||
[
|
||||
(new DateOnly(2022, 1, 1), 0.00m),
|
||||
(new DateOnly(2022, 7, 1), 0.00m),
|
||||
(new DateOnly(2023, 1, 1), 2.50m),
|
||||
(new DateOnly(2023, 7, 1), 4.00m),
|
||||
(new DateOnly(2024, 1, 1), 4.50m),
|
||||
(new DateOnly(2024, 7, 1), 4.25m),
|
||||
(new DateOnly(2025, 1, 1), 3.15m),
|
||||
(new DateOnly(2025, 7, 1), 2.15m),
|
||||
(new DateOnly(2026, 1, 1), 2.15m),
|
||||
(new DateOnly(2026, 7, 1), 2.15m),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string LegalReference => "D.Lgs. 231/2002";
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal RecoveryCompensation => 40m;
|
||||
|
||||
/// <summary>The reference rate of the half-year of a day, without the margin.</summary>
|
||||
/// <param name="day">A day.</param>
|
||||
/// <returns>The rate in percent.</returns>
|
||||
public static decimal ReferenceRateOn(DateOnly day)
|
||||
{
|
||||
var rate = ReferenceRates[0].Rate;
|
||||
foreach (var (from, value) in ReferenceRates)
|
||||
{
|
||||
if (from <= day)
|
||||
{
|
||||
rate = value;
|
||||
}
|
||||
}
|
||||
|
||||
return rate;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal RateOn(DateOnly day) => ReferenceRateOn(day) + Margin;
|
||||
}
|
||||
Reference in new issue
Block a user