diff --git a/src/Khaemhat.Core/Accounting/Ledger.cs b/src/Khaemhat.Core/Accounting/Ledger.cs index 662276e..d991b79 100644 --- a/src/Khaemhat.Core/Accounting/Ledger.cs +++ b/src/Khaemhat.Core/Accounting/Ledger.cs @@ -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 /// VAT of split payment, due by the public customer. SplitPaymentVat = 15, + + /// Allowances received and rounding in favour (abbuoni attivi). + AllowanceIncome = 16, + + /// Bank fees and charges. + BankCharges = 17, + + /// Effects and direct debits presented for collection (effetti all'incasso). + BillsForCollection = 18, + + /// Advances of the bank on effects presented subject to collection (banche c/anticipi). + BankAdvances = 19, + + /// Exchange gains. + ExchangeGain = 20, + + /// Exchange losses. + ExchangeLoss = 21, + + /// Late payment interest charged to customers. + LateInterest = 22, } /// A line of a journal template (gl_journal_template_lines). @@ -476,8 +498,38 @@ public sealed class OpenItem : Entity, IDemoMarkable /// Fully settled. public bool Closed { get; set; } + /// The state in the schedule (M8). + public OpenItemStatus Status { get; set; } + + /// Contested by the customer or with the supplier: left out of reminders and remittances. + public bool Disputed { get; set; } + + /// The bank account of the company that collects or pays it (from the document). + public long? BankAccountId { get; set; } + + /// The remittance it is in. + public long? RemittanceId { get; set; } + + /// The times it came back unpaid. + public int UnpaidCount { get; set; } + + /// The item it was split from: the bank fees of an unpaid effect. + public long? ParentId { get; set; } + + /// The level of the last reminder. + public int DunningLevel { get; set; } + + /// The day of the last reminder. + public DateOnly? LastDunningDate { get; set; } + + /// Notes (the reason of a dispute). + public string? Notes { get; set; } + /// public bool IsDemo { get; set; } + + /// What is left to collect or pay. + public decimal Residual => Amount - PaidAmount; } /// How often a recurring entry repeats. diff --git a/src/Khaemhat.Core/Treasury/Treasury.cs b/src/Khaemhat.Core/Treasury/Treasury.cs new file mode 100644 index 0000000..f81e93d --- /dev/null +++ b/src/Khaemhat.Core/Treasury/Treasury.cs @@ -0,0 +1,628 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Treasury; + +/// The state of an open item (SPEC §11.8, mockup 053). +public enum OpenItemStatus +{ + /// Nothing collected or paid. + Open = 0, + + /// Collected or paid in part. + Partial = 1, + + /// Settled. + Closed = 2, + + /// Returned unpaid by the bank (insoluto): open again, with the bank fees in an item of their own. + Unpaid = 3, + + /// In a remittance presented to the bank: the customer is settled, the effect is not collected yet. + InRemittance = 4, +} + +/// Whether money comes in or goes out. +public enum PaymentDirection +{ + /// A collection from a customer (incasso). + Receipt = 0, + + /// A payment to a supplier (pagamento). + Disbursement = 1, +} + +/// Where a collection or payment comes from. +public enum PaymentOrigin +{ + /// Recorded in the dialog of the schedule. + Manual = 0, + + /// The presentation of a remittance (effects, direct debits, transfers). + Remittance = 1, + + /// A movement of the bank statement matched in the reconciliation. + BankStatement = 2, +} + +/// +/// A collection or payment (SPEC §11.8, mockup 054, payments): 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 (INC, PAG, or DIST 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. +/// +public sealed class Payment : Entity, IDemoMarkable +{ + /// In or out. + public PaymentDirection Direction { get; set; } + + /// The customer or supplier. + public long PartyId { get; set; } + + /// The day of the collection or payment. + public DateOnly PaymentDate { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } + + /// The bank account of the company, when the money goes through a bank. + public long? BankAccountId { get; set; } + + /// The ledger account of the money (bank, cash, effects for collection). + public long? AccountId { get; set; } + + /// The money moved (sum of the cash part of the lines), without fees. + public decimal Amount { get; set; } + + /// The allowances of the lines (positive: granted to the customer, or received from the supplier). + public decimal AllowanceAmount { get; set; } + + /// The exchange differences of the lines (positive: a loss on collections, a gain on payments). + public decimal ExchangeDifference { get; set; } + + /// The bank fees, a cost on the same account. + public decimal Fees { get; set; } + + /// The bank reference (CRO, TRN, cheque number). + public string? Reference { get; set; } + + /// The journal template of the entry. + public string? TemplateCode { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// Where it comes from. + public PaymentOrigin Origin { get; set; } + + /// The remittance, when it comes from one. + public long? RemittanceId { get; set; } + + /// The statement movement it was matched with. + public long? StatementLineId { get; set; } + + /// The entry. + public long? GlEntryId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// The part of a payment that settles one open item (payment_lines). +public sealed class PaymentLine : Entity +{ + /// The payment. + public long PaymentId { get; set; } + + /// The open item. + public long OpenItemId { get; set; } + + /// The money of this item (negative for a credit note set off). + public decimal Amount { get; set; } + + /// The allowance on this item. + public decimal Allowance { get; set; } + + /// The exchange difference on this item. + public decimal ExchangeDifference { get; set; } + + /// What the line settles: money, allowance and exchange difference. + public decimal Settled => Amount + Allowance + ExchangeDifference; +} + +/// The state of a remittance (mockup 055). +public enum RemittanceStatus +{ + /// Being prepared: effects can be added and removed. + Draft = 0, + + /// The file was written: it can still be written again, or the remittance posted. + Generated = 1, + + /// Posted: the customers are settled (effects) or the suppliers paid (transfers). + Presented = 2, + + /// Credited by the bank after the due dates: every effect collected or returned unpaid. + Closed = 3, +} + +/// +/// A remittance (distinta, SPEC §11.8, mockup 055, remittances): RiBa effects or SEPA direct debits presented +/// to a bank, or SEPA credit transfers to suppliers, numbered per year. +/// +public sealed class Remittance : Entity, IDemoMarkable +{ + /// The year of the number. + public int Year { get; set; } + + /// The number in the year. + public int Number { get; set; } + + /// What it carries. + public RemittanceKind Kind { get; set; } + + /// The bank of the company that receives it. + public long BankAccountId { get; set; } + + /// The day it is presented (or the transfers executed). + public DateOnly PresentationDate { get; set; } + + /// The last due date taken. + public DateOnly DueUntil { get; set; } + + /// Presented subject to collection with an advance (salvo buon fine): the bank credits it at once. + public bool Advance { get; set; } + + /// The state. + public RemittanceStatus Status { get; set; } + + /// The total of the effects. + public decimal TotalAmount { get; set; } + + /// The number of effects. + public int ItemCount { get; set; } + + /// The unique identifier written in the file. + public string? MessageId { get; set; } + + /// The attachment with the last file written. + public long? AttachmentId { get; set; } + + /// The name of the last file written. + public string? FileName { get; set; } + + /// The entry of the presentation (effects to the bank, or the advance). + public long? GlEntryId { get; set; } + + /// The day the bank credited the effects. + public DateOnly? CreditedOn { get; set; } + + /// The entry of the credit. + public long? CreditEntryId { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } + + /// The number as shown, such as 2026/018. + public string DisplayNumber => $"{Year}/{Number:000}"; +} + +/// The state of an effect of a remittance. +public enum RemittanceLineStatus +{ + /// In the remittance. + Included = 0, + + /// Collected (or the transfer executed). + Paid = 1, + + /// Returned unpaid. + Unpaid = 2, +} + +/// An effect, debit or transfer of a remittance (remittance_lines). +public sealed class RemittanceLine : Entity +{ + /// The remittance. + public long RemittanceId { get; set; } + + /// The open item. + public long OpenItemId { get; set; } + + /// The customer or supplier. + public long PartyId { get; set; } + + /// The amount. + public decimal Amount { get; set; } + + /// The due date. + public DateOnly DueDate { get; set; } + + /// The IBAN of the customer or supplier, as it was when the effect was added. + public string? Iban { get; set; } + + /// The direct debit mandate. + public long? MandateId { get; set; } + + /// The end-to-end identifier written in the file. + public string? EndToEndId { get; set; } + + /// The state. + public RemittanceLineStatus Status { get; set; } + + /// The day it was returned unpaid. + public DateOnly? UnpaidOn { get; set; } + + /// The bank fees of the unpaid effect, charged to the customer. + public decimal UnpaidFees { get; set; } + + /// The entry of the unpaid effect. + public long? UnpaidEntryId { get; set; } + + /// The payment that settled the item when the remittance was posted. + public long? PaymentId { get; set; } +} + +/// The scheme of a direct debit mandate. +public enum SddScheme +{ + /// Core: consumers and companies; the debtor can ask a refund for eight weeks. + Core = 0, + + /// Business to business: companies only, no refund, the debtor's bank must know the mandate. + B2b = 1, +} + +/// A SEPA direct debit mandate signed by a customer (sdd_mandates). +public sealed class SddMandate : Entity, IDemoMarkable +{ + /// The customer. + public long PartyId { get; set; } + + /// The unique mandate reference (UMR), at most 35 characters. + public string Reference { get; set; } = string.Empty; + + /// The day it was signed. + public DateOnly SignatureDate { get; set; } + + /// Core or B2B. + public SddScheme Scheme { get; set; } + + /// The account debited, compact. + public string Iban { get; set; } = string.Empty; + + /// The BIC of the debtor's bank. + public string? Bic { get; set; } + + /// A one-off mandate (a single debit). + public bool OneOff { get; set; } + + /// The day of the last collection: none means the next one is the first. + public DateOnly? LastCollectionDate { get; set; } + + /// Revoked by the customer: no more debits. + public bool Revoked { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A bank statement imported (bank_statements, mockup 057). +public sealed class BankStatement : Entity, IDemoMarkable +{ + /// The bank account of the company. + public long BankAccountId { get; set; } + + /// The format of the file. + public StatementFormat Format { get; set; } + + /// The name of the file. + public string? FileName { get; set; } + + /// The first day. + public DateOnly FromDate { get; set; } + + /// The last day. + public DateOnly ToDate { get; set; } + + /// The opening balance, if the file says it. + public decimal? OpeningBalance { get; set; } + + /// The closing balance, if the file says it. + public decimal? ClosingBalance { get; set; } + + /// The movements imported (the ones already imported before are skipped). + public int MovementCount { get; set; } + + /// The file, kept as an attachment. + public long? AttachmentId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// The state of a movement in the reconciliation (mockup 057). +public enum StatementLineStatus +{ + /// Nothing found: to match by hand. + ToMatch = 0, + + /// A match is proposed, with its confidence. + Suggested = 1, + + /// Matched and recorded. + Matched = 2, + + /// Left out on purpose (already recorded in another way). + Ignored = 3, +} + +/// What a movement is matched with. +public enum StatementMatchKind +{ + /// Nothing. + None = 0, + + /// Open items of one customer or supplier: a collection or payment is recorded. + OpenItems = 1, + + /// A collection or payment already recorded. + Payment = 2, + + /// The F24 of a due date: its payment is recorded. + TaxPayment = 3, + + /// A saved rule: an entry on its account is recorded. + Rule = 4, + + /// The credit of a remittance. + RemittanceCredit = 5, + + /// An effect returned unpaid. + Unpaid = 6, + + /// An entry of the ledger on the bank account already recorded. + Entry = 7, +} + +/// A movement of a bank statement (bank_statement_lines). +public sealed class BankStatementLine : Entity, IDemoMarkable +{ + /// The statement. + public long StatementId { get; set; } + + /// The bank account of the company. + public long BankAccountId { get; set; } + + /// The booking date. + public DateOnly BookingDate { get; set; } + + /// The value date. + public DateOnly? ValueDate { get; set; } + + /// Positive for money in, negative for money out. + public decimal Amount { get; set; } + + /// The description of the bank. + public string Description { get; set; } = string.Empty; + + /// The bank reference. + public string? Reference { get; set; } + + /// The other party, if known. + public string? CounterpartyName { get; set; } + + /// Its IBAN, if known. + public string? CounterpartyIban { get; set; } + + /// The bank transaction code. + public string? BankCode { get; set; } + + /// A hash of date, amount, description and reference: the same movement is never imported twice. + public string Fingerprint { get; set; } = string.Empty; + + /// The state. + public StatementLineStatus Status { get; set; } + + /// What it is (or would be) matched with. + public StatementMatchKind MatchKind { get; set; } + + /// The confidence of the proposal, 0-100. + public int Confidence { get; set; } + + /// The proposal, as shown. + public string? Proposal { get; set; } + + /// The ids the proposal points to (open items, payment, remittance line...), comma separated. + public string? Targets { get; set; } + + /// The party of the proposal. + public long? PartyId { get; set; } + + /// The rule of the proposal. + public long? RuleId { get; set; } + + /// The collection or payment recorded or matched. + public long? PaymentId { get; set; } + + /// The entry recorded or matched. + public long? GlEntryId { get; set; } + + /// When it was matched. + public DateTime? MatchedAt { get; set; } + + /// Who matched it. + public string? MatchedBy { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// Which movements a rule applies to. +public enum BankRuleDirection +{ + /// Money in and out. + Any = 0, + + /// Money in. + In = 1, + + /// Money out. + Out = 2, +} + +/// +/// A rule of the reconciliation (bank_match_rules): the movements whose description contains a text are +/// recorded on an account, such as bank fees on 21.03.011. +/// +public sealed class BankMatchRule : Entity, IDemoMarkable +{ + /// The name. + public string Name { get; set; } = string.Empty; + + /// The text looked for in the description, case and accents ignored. + public string Pattern { get; set; } = string.Empty; + + /// Money in, out or both. + public BankRuleDirection Direction { get; set; } + + /// The account the movement goes to (the other side is the bank). + public long AccountId { get; set; } + + /// The journal template of the entry. + public string? TemplateCode { get; set; } + + /// The description of the entry; empty for the description of the movement. + public string? EntryDescription { get; set; } + + /// Not applied. + public bool Disabled { get; set; } + + /// How many movements it recorded. + public int Uses { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// How a reminder is sent. +[Flags] +public enum DunningChannel +{ + /// Not sent: printed only. + None = 0, + + /// E-mail. + Email = 1, + + /// Certified e-mail (PEC). + Pec = 2, + + /// A PDF letter, kept as an attachment of the customer. + Letter = 4, +} + +/// What happens when a reminder of a level is sent. +public enum DunningAction +{ + /// Nothing else. + None = 0, + + /// The agent of the customer is notified. + NotifyAgent = 1, + + /// The customer is blocked (orders and deliveries) and the administration notified. + BlockCustomer = 2, +} + +/// A level of the reminders (dunning_levels, mockup 056). +public sealed class DunningLevel : Entity +{ + /// The level, from 1. + public int Level { get; set; } + + /// Days after the due date. + public int DaysAfterDue { get; set; } + + /// The name of the template, such as Promemoria cortese. + public string Name { get; set; } = string.Empty; + + /// The subject, with fields such as {{Cliente}}. + public string Subject { get; set; } = string.Empty; + + /// The text, with fields such as {{Elenco}} and {{Totale}}. + public string Body { get; set; } = string.Empty; + + /// How it is sent. + public DunningChannel Channel { get; set; } + + /// Late payment interest is computed and written. + public bool ChargeInterest { get; set; } + + /// What else happens. + public DunningAction Action { get; set; } +} + +/// The state of a reminder. +public enum DunningLetterStatus +{ + /// Waiting in the mail queue. + Queued = 0, + + /// Sent (or printed). + Sent = 1, + + /// Not sent. + Failed = 2, +} + +/// A reminder sent to a customer (dunning_letters): the log of the reminders. +public sealed class DunningLetter : Entity, IDemoMarkable +{ + /// The customer. + public long PartyId { get; set; } + + /// The level. + public int Level { get; set; } + + /// The day. + public DateOnly SentOn { get; set; } + + /// How it was sent. + public DunningChannel Channel { get; set; } + + /// The addresses. + public string? Recipients { get; set; } + + /// The subject. + public string Subject { get; set; } = string.Empty; + + /// The open items reminded. + public int ItemCount { get; set; } + + /// The overdue amount. + public decimal OverdueAmount { get; set; } + + /// The late payment interest written. + public decimal Interest { get; set; } + + /// The state. + public DunningLetterStatus Status { get; set; } + + /// The PDF letter. + public long? AttachmentId { get; set; } + + /// The message in the mail queue. + public long? MailId { get; set; } + + /// Who sent it (empty for the scheduled task). + public string? SentBy { get; set; } + + /// + public bool IsDemo { get; set; } +} diff --git a/src/Khaemhat.Core/Treasury/TreasuryRules.cs b/src/Khaemhat.Core/Treasury/TreasuryRules.cs new file mode 100644 index 0000000..130713f --- /dev/null +++ b/src/Khaemhat.Core/Treasury/TreasuryRules.cs @@ -0,0 +1,688 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Core.Treasury; + +/// The residual of the open items by age (mockup 053). +/// Not due yet. +/// Overdue by 1 to 30 days. +/// Overdue by 31 to 60 days. +/// Overdue by 61 to 90 days. +/// Overdue by more than 90 days. +/// Items not due. +/// Items overdue by 1 to 30 days. +/// Items overdue by 31 to 60 days. +/// Items overdue by 61 to 90 days. +/// Items overdue by more than 90 days. +public sealed record AgingBuckets( + decimal NotDue, + decimal Days1To30, + decimal Days31To60, + decimal Days61To90, + decimal Over90, + int CountNotDue, + int Count1To30, + int Count31To60, + int Count61To90, + int CountOver90) +{ + /// Everything open. + public decimal Total => NotDue + Overdue; + + /// Everything overdue. + public decimal Overdue => Days1To30 + Days31To60 + Days61To90 + Over90; +} + +/// The age of open items (SPEC §11.8, AgingCalculator). +public static class AgingCalculator +{ + /// Days past the due date: negative while it is not due. + /// The due date. + /// Today. + /// The days. + public static int DaysOverdue(DateOnly dueDate, DateOnly today) => today.DayNumber - dueDate.DayNumber; + + /// Splits the residuals by age. + /// The due date and residual of each item. + /// Today. + /// The buckets. + 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]); + } +} + +/// Spreads a collection or payment over open items. +public static class PaymentAllocator +{ + /// + /// 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. + /// + /// The residual of each item, in order. + /// The money. + /// What each item takes; what is left over is not given to anyone. + public static IReadOnlyList Allocate(IReadOnlyList 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; + } +} + +/// The accounts of the entry of a collection or payment. +/// The bank, cash or effects account the money moves on. +/// Allowances granted (abbuoni passivi). +/// Allowances received (abbuoni attivi). +/// Exchange losses. +/// Exchange gains. +/// Bank fees. +public sealed record PaymentPostingAccounts(long Money, long? AllowanceExpense, long? AllowanceIncome, long? ExchangeLoss, long? ExchangeGain, long? BankCharges); + +/// A line of a collection or payment as the entry reads it. +/// The customers or suppliers account of the item. +/// The customer or supplier. +/// The item. +/// The description (the document). +/// The money. +/// The allowance. +/// The exchange difference. +public sealed record PaymentPostingLine(long ControlAccountId, long PartyId, long OpenItemId, string? Description, decimal Amount, decimal Allowance, decimal ExchangeDifference); + +/// A line of the entry written for a collection or payment. +/// The account. +/// The customer or supplier. +/// The item it settles. +/// The description. +/// Dare. +/// Avere. +public sealed record PaymentPostedLine(long AccountId, long? PartyId, long? OpenItemId, string? Description, decimal Debit, decimal Credit); + +/// The missing account of a collection or payment. +public sealed class PaymentAccountMissingException : InvalidOperationException +{ + /// Creates the exception. + public PaymentAccountMissingException() + { + } + + /// Creates the exception. + /// The role of the missing account. + public PaymentAccountMissingException(string message) + : base(message) + { + } + + /// Creates the exception. + /// The role. + /// The cause. + public PaymentAccountMissingException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// 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. +/// +public static class PaymentPosting +{ + /// Builds the lines. + /// Collection or payment. + /// The accounts. + /// The items settled. + /// The bank fees. + /// The description of the money line. + /// The lines, balanced. + /// An allowance, exchange difference or fee has no account. + public static IReadOnlyList Build( + PaymentDirection direction, PaymentPostingAccounts accounts, IReadOnlyList lines, decimal fees, string? description) + { + ArgumentNullException.ThrowIfNull(accounts); + ArgumentNullException.ThrowIfNull(lines); + var result = new List(); + 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; + } +} + +/// Late payment interest (SPEC §11.8, D.Lgs. 231/2002 in Italy). +public static class LateInterestCalculator +{ + /// + /// 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. + /// + /// The amount overdue. + /// The due date. + /// The last day counted. + /// The yearly rate in percent of a day. + /// The interest; zero when not overdue. + public static decimal Interest(decimal residual, DateOnly dueDate, DateOnly until, Func 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); + } +} + +/// A possible match of a bank movement, built by the reconciliation from the open data of the company. +/// What it is. +/// The ids it points to, comma separated. +/// The customer or supplier. +/// The movement it expects: positive money in, negative money out. +/// The date it expects (due date, payment date). +/// The proposal as shown, such as Incasso FT/2026/000388. +/// Document numbers and references that may appear in the description. +/// Names of the party that may appear. +/// IBANs of the party. +/// Words that must appear for the candidate to count (such as INSOLUT, F24); empty for none. +/// How much more the movement may be (bank fees of an unpaid effect). +public sealed record MatchCandidate( + StatementMatchKind Kind, + string? Targets, + long? PartyId, + decimal Amount, + DateOnly Date, + string Label, + IReadOnlyList Keys, + IReadOnlyList Names, + IReadOnlyList Ibans, + IReadOnlyList Keywords, + decimal AmountTolerance = 0m); + +/// A saved rule as the matcher reads it. +/// The rule. +/// The text looked for. +/// Money in, out or both. +/// The proposal, such as Regola 'COMMISSIONI' → 21.03.011 Spese bancarie. +public sealed record MatchRule(long Id, string Pattern, BankRuleDirection Direction, string Label); + +/// The best match of a movement. +/// What it is. +/// The ids. +/// The party. +/// The rule. +/// 0-100. +/// As shown. +public sealed record MatchProposal(StatementMatchKind Kind, string? Targets, long? PartyId, long? RuleId, int Confidence, string Label); + +/// +/// Proposes what a bank movement is (SPEC §11.8, mockup 057, BankMatcher): 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. +/// +public static class BankMatcher +{ + /// The words before a document number in bank descriptions. + private static readonly HashSet NumberPrefixes = new(StringComparer.Ordinal) + { + "FT", "FATT", "FATTURA", "FATTURE", "FAT", "FA", "N", "NR", "NUM", "DOC", "RIF", "FAT.", "INV", "INVOICE", + }; + + /// The best proposal for a movement, or when nothing fits. + /// The movement. + /// The candidates. + /// The rules. + /// The proposal. + public static MatchProposal? Best(StatementMovement movement, IEnumerable candidates, IEnumerable 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; + } + + /// The score of a candidate, 0 when it does not fit. + /// The movement. + /// The candidate. + /// 0-100. + 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)); + } + + /// Upper case, no accents, only letters and digits separated by single spaces. + /// The text. + /// The normalised text. + 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(); + } + + /// + /// 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. + /// + /// The id and residual of the items, oldest first. + /// The amount. + /// The ids, or an empty list. + public static IReadOnlyList 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); +} + +/// An open item as the reminders read it. +/// The item. +/// The due date. +/// What is left. +/// The level of its last reminder. +/// The day of its last reminder. +/// Contested. +public sealed record DunningItem(long OpenItemId, DateOnly DueDate, decimal Residual, int Level, DateOnly? LastDunningDate, bool Disputed); + +/// A level as the reminders read it. +/// The level. +/// Days after the due date. +public sealed record DunningStep(int Level, int DaysAfterDue); + +/// Which reminder a customer gets next (SPEC §11.8, mockup 056, DunningRules). +public static class DunningRules +{ + /// Days between two reminders to the same customer. + public const int MinDaysBetween = 7; + + /// + /// 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. + /// + /// The open items of the customer. + /// The levels. + /// Today. + /// The level, or . + public static int? NextLevel(IReadOnlyList items, IReadOnlyList 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; + } +} + +/// What a forecast movement comes from. +public enum CashFlowSource +{ + /// Open items of customers. + Receivables = 0, + + /// Open items of suppliers. + Payables = 1, + + /// Customer orders not invoiced. + SaleOrders = 2, + + /// Supplier orders not invoiced. + PurchaseOrders = 3, + + /// Recurring entries on bank or cash. + Recurring = 4, + + /// Taxes to pay (F24). + Taxes = 5, +} + +/// A forecast movement. +/// When it is expected. +/// Positive in, negative out. +/// Where it comes from. +/// What it is. +public sealed record CashFlowMovement(DateOnly Date, decimal Amount, CashFlowSource Source, string Label); + +/// A period of the forecast. +/// The first day. +/// The last day. +/// Money in. +/// Money out (positive). +/// The balance at the end of the period. +public sealed record CashFlowPeriod(DateOnly From, DateOnly To, decimal In, decimal Out, decimal Balance); + +/// The cash flow forecast (SPEC §11.8, CashFlowForecastService): the balance period by period. +public static class CashFlowForecaster +{ + /// Spreads the movements over periods; the overdue ones count in the first period. + /// The money today on bank and cash. + /// The movements. + /// The first day. + /// How many days. + /// The days of a period. + /// The periods. + public static IReadOnlyList Periods(decimal opening, IEnumerable 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(); + 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; + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs b/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs index 23bd9a4..ca8d095 100644 --- a/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs @@ -99,6 +99,7 @@ public sealed class OpenItemMap : EntityMap { ToTable("gl_open_items"); Map(x => x.DocumentNumber).MaxLength(30); + Map(x => x.Notes).MaxLength(200); } } diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs new file mode 100644 index 0000000..d8d3b30 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs @@ -0,0 +1,250 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// 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. +/// +[Migration(20261113_003, "create_treasury")] +public sealed class M20261113_003_CreateTreasury : IMigration +{ + /// + 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); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/TreasuryMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TreasuryMaps.cs new file mode 100644 index 0000000..4c5ce44 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/TreasuryMaps.cs @@ -0,0 +1,134 @@ +using Khaemhat.Core.Treasury; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to payments. +public sealed class PaymentMap : EntityMap +{ + /// Creates the map. + public PaymentMap() + { + ToTable("payments"); + Map(x => x.Reference).MaxLength(60); + Map(x => x.TemplateCode).MaxLength(10); + Map(x => x.Notes).MaxLength(500); + } +} + +/// Map of to payment_lines. +public sealed class PaymentLineMap : EntityMap +{ + /// Creates the map. + public PaymentLineMap() => ToTable("payment_lines"); +} + +/// Map of to remittances. +public sealed class RemittanceMap : EntityMap +{ + /// Creates the map. + public RemittanceMap() + { + ToTable("remittances"); + Map(x => x.MessageId).MaxLength(35); + Map(x => x.FileName).MaxLength(100); + Map(x => x.Notes).MaxLength(500); + } +} + +/// Map of to remittance_lines. +public sealed class RemittanceLineMap : EntityMap +{ + /// Creates the map. + public RemittanceLineMap() + { + ToTable("remittance_lines"); + Map(x => x.Iban).MaxLength(34); + Map(x => x.EndToEndId).MaxLength(35); + } +} + +/// Map of to sdd_mandates. +public sealed class SddMandateMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to bank_statements. +public sealed class BankStatementMap : EntityMap +{ + /// Creates the map. + public BankStatementMap() + { + ToTable("bank_statements"); + Map(x => x.FileName).MaxLength(200); + } +} + +/// Map of to bank_statement_lines. +public sealed class BankStatementLineMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to bank_match_rules. +public sealed class BankMatchRuleMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to dunning_levels. +public sealed class DunningLevelMap : EntityMap +{ + /// Creates the map. + public DunningLevelMap() + { + ToTable("dunning_levels"); + Map(x => x.Name).MaxLength(100); + Map(x => x.Subject).MaxLength(200); + Map(x => x.Channel).MaxLength(60); + } +} + +/// Map of to dunning_letters. +public sealed class DunningLetterMap : EntityMap +{ + /// Creates the map. + 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); + } +} diff --git a/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv b/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv index 4d206da..2774f7d 100644 --- a/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv +++ b/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv @@ -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;;;; diff --git a/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs b/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs index cb71a0d..cf81448 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs @@ -60,6 +60,27 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate /// The interest of quarterly VAT payers. public const string VatInterest = "28.01.003"; + /// Allowances received. + public const string AllowanceIncome = "31.01.004"; + + /// Bank fees. + public const string BankCharges = "21.03.011"; + + /// Effects and direct debits presented for collection. + public const string BillsForCollection = "05.02.001"; + + /// Advances of the bank on effects. + public const string BankAdvances = "13.01.001"; + + /// Exchange gains. + public const string ExchangeGain = "32.01.003"; + + /// Exchange losses. + public const string ExchangeLoss = "28.01.005"; + + /// Late payment interest charged to customers. + public const string LateInterest = "32.01.004"; + private readonly Lazy> _accounts = new(ReadAccounts); /// @@ -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, [ diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index be01d51..9cb07d6 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -15,6 +15,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase public ItalyFiscalPack() { AddFeature(new FatturaPaFormat()); + AddFeature(new LatePaymentRulesIt()); AddFeature(new FatturaPaReader()); AddFeature(new IncomingInvoiceRulesIt()); AddFeature(new SelfInvoiceRulesIt()); diff --git a/src/Khaemhat.Fiscal.Italy/LatePaymentRulesIt.cs b/src/Khaemhat.Fiscal.Italy/LatePaymentRulesIt.cs new file mode 100644 index 0000000..4f4288e --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/LatePaymentRulesIt.cs @@ -0,0 +1,56 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// 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. +/// +public sealed class LatePaymentRulesIt : ILatePaymentRules +{ + /// The points added to the reference rate. + public const decimal Margin = 8m; + + /// The ECB main refinancing rate on the first day of each half-year, in percent. + 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), + ]; + + /// + public string LegalReference => "D.Lgs. 231/2002"; + + /// + public decimal RecoveryCompensation => 40m; + + /// The reference rate of the half-year of a day, without the margin. + /// A day. + /// The rate in percent. + public static decimal ReferenceRateOn(DateOnly day) + { + var rate = ReferenceRates[0].Rate; + foreach (var (from, value) in ReferenceRates) + { + if (from <= day) + { + rate = value; + } + } + + return rate; + } + + /// + public decimal RateOn(DateOnly day) => ReferenceRateOn(day) + Margin; +}