using Khaemhat.Core.Documents; using Khaemhat.Core.Entities; namespace Khaemhat.Core.Accounting; /// What an accrual or deferral adjusts at the year end. public enum AccrualKind { /// Rateo attivo: revenue of the year to be collected or invoiced next year. AccruedIncome = 0, /// Rateo passivo: cost of the year to be paid or invoiced next year. AccruedExpense = 1, /// Risconto attivo: cost recorded this year that belongs to the next (insurance paid in advance). PrepaidExpense = 2, /// Risconto passivo: revenue recorded this year that belongs to the next. DeferredIncome = 3, } /// /// An accrual or deferral (rateo o risconto, SPEC §11.7, issue #84, accruals): an amount of a cost or revenue /// spread over a period across the year end; the share of the year (ratei) or of the next years (risconti) is posted /// at the year end and reversed at the opening. /// public sealed class AccrualDeferral : Entity, IDemoMarkable { /// The fiscal year it adjusts (the year of its end date). public int Year { get; set; } /// The kind. public AccrualKind Kind { get; set; } /// The description. public string Description { get; set; } = string.Empty; /// The cost or revenue account. public long AccountId { get; set; } /// The whole amount of the period. public decimal Amount { get; set; } /// The first day of the period. public DateOnly PeriodStart { get; set; } /// The last day of the period. public DateOnly PeriodEnd { get; set; } /// The last day of the year adjusted. public DateOnly YearEnd { get; set; } /// The share posted at the year end. public decimal Adjustment { get; set; } /// The family of the document it comes from. public DocumentFamily? SourceFamily { get; set; } /// The document it comes from. public long? SourceDocumentId { get; set; } /// The number of that document. public string? DocumentNumber { get; set; } /// The customer or supplier. public long? PartyId { get; set; } /// The entry of the year end. public long? GlEntryId { get; set; } /// The entry that reverses it at the opening of the next year. public long? ReversalEntryId { get; set; } /// public bool IsDemo { get; set; } } /// /// The share of an amount by days (SPEC §21, issue #84): what belongs to the year up to its end (ratei) or after it /// (risconti), counting the days of the period both ends included. /// public static class AccrualDeferralCalculator { /// The share of an amount posted at the year end. /// The kind. /// The whole amount. /// The first day of the period. /// The last day of the period. /// The last day of the year. /// For ratei the days up to the year end, for risconti those after it, rounded to the cent. public static decimal Share(AccrualKind kind, decimal amount, DateOnly start, DateOnly end, DateOnly yearEnd) { if (end < start) { return 0m; } var total = end.DayNumber - start.DayNumber + 1; var within = Math.Clamp(yearEnd.DayNumber - start.DayNumber + 1, 0, total); var days = kind is AccrualKind.AccruedIncome or AccrualKind.AccruedExpense ? within : total - within; return Math.Round(amount * days / total, 2, MidpointRounding.AwayFromZero); } /// The days of the period that belong to the year and to the next years. /// The first day of the period. /// The last day of the period. /// The last day of the year. /// The days of the year, the days after, the total. public static (int Within, int After, int Total) Days(DateOnly start, DateOnly end, DateOnly yearEnd) { if (end < start) { return (0, 0, 0); } var total = end.DayNumber - start.DayNumber + 1; var within = Math.Clamp(yearEnd.DayNumber - start.DayNumber + 1, 0, total); return (within, total - within, total); } /// Whether the adjustment is a cost (ratei passivi, risconti attivi on cost accounts) or a revenue. /// The kind. /// for costs. public static bool IsCost(AccrualKind kind) => kind is AccrualKind.AccruedExpense or AccrualKind.PrepaidExpense; } /// /// The exchange difference of an open item in foreign currency at the year end (SPEC §21, issue #84): the residual in /// the currency valued at the rate of the year end against its value in euro at the rate of the document. /// public static class ExchangeDifferenceCalculator { /// The residual in the currency of the document. /// The residual in euro, at the rate of the document. /// Units of the currency for one euro on the document. /// The residual in the currency. public static decimal InCurrency(decimal residualEuro, decimal documentRate) => Math.Round(residualEuro * documentRate, 2, MidpointRounding.AwayFromZero); /// The difference in euro: positive increases the residual in euro. /// The residual in euro, at the rate of the document. /// Units of the currency for one euro on the document. /// Units of the currency for one euro at the year end. /// The new value less the old one, rounded to the cent. public static decimal Difference(decimal residualEuro, decimal documentRate, decimal yearEndRate) { if (documentRate <= 0m || yearEndRate <= 0m) { return 0m; } var revalued = Math.Round(residualEuro * documentRate / yearEndRate, 2, MidpointRounding.AwayFromZero); return revalued - residualEuro; } /// Whether a difference is a gain for the company. /// A receivable or a payable. /// The difference of the residual in euro. /// A larger receivable or a smaller payable is a gain. public static bool IsGain(OpenItemDirection direction, decimal difference) => direction == OpenItemDirection.Receivable ? difference > 0m : difference < 0m; } /// The state of a year-end closing. public enum ClosingStatus { /// Steps being run. InProgress = 0, /// Every step done and the year locked: read only. Locked = 1, } /// The state of a step of the closing. public enum ClosingStepStatus { /// Not run yet. Pending = 0, /// Run, with entries or without anything to do. Done = 1, /// Checks passed. Passed = 2, /// Run with something to look at (warnings). ToVerify = 3, /// Checks failed: the next steps wait. Failed = 4, } /// /// The guided closing of a fiscal year (SPEC §11.7, mockup 050, closing_runs): its steps, the year that /// follows and the lock. /// public sealed class ClosingRun : Entity { /// The year closed. public long FiscalYearId { get; set; } /// The code of the year, such as 2026. public string YearCode { get; set; } = string.Empty; /// The state. public ClosingStatus Status { get; set; } /// The year opened by the closing. public long? NextFiscalYearId { get; set; } /// The result of the year: positive a profit. public decimal Result { get; set; } /// When the year was locked. public DateTime? LockedAt { get; set; } /// Who locked it. public string? LockedBy { get; set; } } /// A step of a closing (closing_steps): run, repeated or undone until the year is locked. public sealed class ClosingStep : Entity { /// The closing. public long RunId { get; set; } /// The number, 1-9. public int Number { get; set; } /// The state. public ClosingStepStatus Status { get; set; } /// The entries written by the step. public int Entries { get; set; } /// The amount the step worked on (depreciation, inventory, result...). public decimal Amount { get; set; } /// What happened, one message per line (codes of texts with their values). public string? Messages { get; set; } /// When it ran. public DateTime? ExecutedAt { get; set; } /// Who ran it. public string? ExecutedBy { get; set; } } /// A final print of a closing (closing_prints): the books of the year, kept with the closing. public sealed class ClosingPrint : Entity { /// The closing. public long RunId { get; set; } /// What the print is: journal, inventory, vat, assets. public string Kind { get; set; } = string.Empty; /// The file name. public string FileName { get; set; } = string.Empty; /// The pages. public int Pages { get; set; } /// The PDF. public byte[] Content { get; set; } = []; } /// The figures the financial ratios read, from the reclassified statements. /// Patrimonio netto, with the result of the year. /// The result of the year. /// The operating result (EBIT, A-B). /// The revenue of sales (A.1). /// The total assets (capitale investito). /// The fixed assets, net. /// The current assets (with accruals). /// The inventory. /// Cash and banks. /// Trade receivables. /// Liabilities due within the year (with accruals). /// Liabilities due later, funds and severance. /// Trade payables. /// Purchases of materials and services (B.6, B.7). /// The days of the period (365 for a year). public sealed record RatioInputs( decimal Equity, decimal Result, decimal OperatingResult, decimal Revenue, decimal TotalAssets, decimal FixedAssets, decimal CurrentAssets, decimal Inventory, decimal Liquidity, decimal Receivables, decimal CurrentLiabilities, decimal LongTermLiabilities, decimal Payables, decimal Purchases, int Days); /// A financial ratio. /// The code, such as ROE. /// The value; when the denominator is zero. /// Shown as a percent. /// Shown in days. public sealed record FinancialRatio(string Code, decimal? Value, bool Percent = false, bool DaysUnit = false); /// /// The financial ratios of the statements (SPEC §11.7, mockup 051): profitability (ROE, ROI, ROS), liquidity (current, /// quick), solidity (equity ratio, leverage, fixed asset coverage), rotation (days of customers and suppliers). /// public static class FinancialRatios { /// Computes the ratios. /// The figures. /// The ratios, in display order. public static IReadOnlyList Compute(RatioInputs input) { ArgumentNullException.ThrowIfNull(input); var days = input.Days <= 0 ? 365 : input.Days; return [ new("ROE", Ratio(input.Result, input.Equity, 100m), Percent: true), new("ROI", Ratio(input.OperatingResult, input.TotalAssets, 100m), Percent: true), new("ROS", Ratio(input.OperatingResult, input.Revenue, 100m), Percent: true), new("TURNOVER", Ratio(input.Revenue, input.TotalAssets, 1m)), new("CURRENT", Ratio(input.CurrentAssets, input.CurrentLiabilities, 1m)), new("QUICK", Ratio(input.CurrentAssets - input.Inventory, input.CurrentLiabilities, 1m)), new("EQUITY", Ratio(input.Equity, input.TotalAssets, 100m), Percent: true), new("LEVERAGE", Ratio(input.TotalAssets, input.Equity, 1m)), new("COVERAGE", Ratio(input.Equity + input.LongTermLiabilities, input.FixedAssets, 1m)), new("DSO", Ratio(input.Receivables * days, input.Revenue, 1m), DaysUnit: true), new("DPO", Ratio(input.Payables * days, input.Purchases, 1m), DaysUnit: true), ]; } private static decimal? Ratio(decimal numerator, decimal denominator, decimal factor) => denominator == 0m ? null : Math.Round(numerator / denominator * factor, 2, MidpointRounding.AwayFromZero); }