From ced689b297148f63b1a3ecba9464d80c2ba9a523 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 12 Nov 2026 22:01:32 +0100 Subject: [PATCH] feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60) Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP) become draft purchase invoices with supplier, items and tax codes matched, the file attached and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase invoices show price differences against the order and the self-invoice still to issue, with a pending list on the self-invoice screen. The opening stock import now writes an opening movement. The demo company gets purchases, an opening stock, a pending self-invoice and a stock take being counted. Co-Authored-By: Claude Opus 5.5 --- docs/DATA-MODEL.md | 129 +++++ .../Dashboard/WidgetCatalog.cs | 2 +- .../ImportExport/CheckOnlyImportTargets.cs | 102 ---- .../ImportExport/OpeningStockImportTarget.cs | 191 +++++++ .../Purchases/PurchaseInvoiceImportService.cs | 522 +++++++++++++++++ .../Seeding/DemoPurchasesSeeder.cs | 260 +++++++++ .../IncomingInvoices.cs | 12 + .../IncomingInvoiceRulesIt.cs | 22 + src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs | 1 + .../Dashboard/DashboardWidget.razor | 3 + .../Dashboard/UnderstockWidget.razor | 74 +++ .../Pages/Admin/ImportExportPage.razor.cs | 2 +- .../Pages/Inventory/ReorderPage.razor | 247 +++++++++ .../Pages/Inventory/StockPage.razor | 450 +++++++++++++++ .../Pages/Inventory/StockTakePage.razor | 524 ++++++++++++++++++ .../Pages/Purchases/PurchaseImportPage.razor | 384 +++++++++++++ .../Pages/Sales/SalesDocumentPage.razor | 23 + .../Pages/Sales/SalesDocumentPage.razor.cs | 44 ++ .../Pages/Sales/SalesDocumentsPage.razor | 8 + .../Purchases/PendingSelfInvoicesPanel.razor | 98 ++++ src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 3 + src/Khaemhat.Web/Hosting/SeedCommand.cs | 1 + .../Resources/it-IT/Dashboard.json | 5 +- .../Resources/it-IT/ImportExport.json | 2 +- .../Resources/it-IT/Inventory.json | 143 +++++ .../Resources/it-IT/Purchases.json | 65 +++ src/Khaemhat.Web/wwwroot/app.css | 14 + tests/Khaemhat.Data.Tests/MappingTests.cs | 1 + .../ImportExport/ImportServiceTests.cs | 12 +- .../Inventory/DemoPurchasesTests.cs | 74 +++ .../Inventory/PurchaseImportTests.cs | 170 ++++++ 31 files changed, 3478 insertions(+), 110 deletions(-) create mode 100644 src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs create mode 100644 src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs create mode 100644 src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs create mode 100644 src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs create mode 100644 src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor create mode 100644 src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor create mode 100644 tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs create mode 100644 tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index d60d59f..94d8181 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -730,6 +730,7 @@ Migrazioni applicate in ordine: - `core` 20261112001 `create_parties` (M20261112_001_CreateParties) - `core` 20261112002 `create_items` (M20261112_002_CreateItems) - `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments) +- `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory) #### `attachments` @@ -1306,12 +1307,61 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_inventory_documents_date` su `document_date` - indice `ix_inventory_documents_party` su `party_id` - indice `ix_inventory_documents_status` su `status` - indice unico `ux_inventory_documents_number` su `numerator_id`, `number` +#### `inventory_entries` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `entry_date` | Date | no | | | +| `source_family` | String(40) | sì | | | +| `source_document_id` | Int64 | sì | | | +| `source_kind` | String(40) | sì | | | +| `source_number` | String(30) | sì | | | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `party_id` | Int64 | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_inventory_entries_date` su `entry_date` +- indice `ix_inventory_entries_source` su `source_family`, `source_document_id` + +#### `inventory_entry_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `entry_id` | Int64 | no | | -> `inventory_entries` (Cascade) | +| `entry_date` | Date | no | | | +| `item_id` | Int64 | no | | -> `items` (Restrict) | +| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) | +| `quantity` | Decimal(19,6) | no | | | +| `valued` | Bool | no | `false` | | +| `unit_cost` | Decimal(19,6) | no | `0` | | +| `value` | Decimal(19,6) | no | `0` | | +| `source_line_id` | Int64 | sì | | | +| `sort_order` | Int32 | no | `0` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_inventory_entry_lines_entry` su `entry_id` +- indice `ix_inventory_entry_lines_item` su `item_id`, `entry_date` +- indice `ix_inventory_entry_lines_warehouse` su `warehouse_id`, `item_id` + #### `inventory_reasons` | Colonna | Tipo | Null | Default | Note | @@ -1332,6 +1382,31 @@ Migrazioni applicate in ordine: - indice unico `ux_inventory_reasons_code` su `code` +#### `item_balances` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) | +| `on_hand` | Decimal(19,6) | no | `0` | | +| `committed` | Decimal(19,6) | no | `0` | | +| `ordered` | Decimal(19,6) | no | `0` | | +| `in_transit` | Decimal(19,6) | no | `0` | | +| `average_cost` | Decimal(19,6) | no | `0` | | +| `value` | Decimal(19,6) | no | `0` | | +| `last_cost` | Decimal(19,6) | sì | | | +| `last_load_date` | Date | sì | | | +| `last_unload_date` | Date | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_item_balances_warehouse` su `warehouse_id` +- indice unico `ux_item_balances_item_warehouse` su `item_id`, `warehouse_id` + #### `item_barcodes` | Colonna | Tipo | Null | Default | Note | @@ -2038,6 +2113,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_purchase_documents_date` su `document_date` - indice `ix_purchase_documents_party` su `party_id` @@ -2169,6 +2246,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_purchase_orders_date` su `document_date` - indice `ix_purchase_orders_party` su `party_id` @@ -2333,6 +2412,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_sale_documents_date` su `document_date` - indice `ix_sale_documents_party` su `party_id` @@ -2464,6 +2545,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_sale_orders_date` su `document_date` - indice `ix_sale_orders_party` su `party_id` @@ -2595,6 +2678,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_sale_quotations_date` su `document_date` - indice `ix_sale_quotations_party` su `party_id` @@ -2651,6 +2736,50 @@ Chiave primaria: `module`, `version`. - indice unico `ux_shipping_terms_code` su `code` +#### `stock_take_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `stock_take_id` | Int64 | no | | -> `stock_takes` (Cascade) | +| `item_id` | Int64 | no | | -> `items` (Restrict) | +| `book_quantity` | Decimal(19,6) | no | `0` | | +| `counted_quantity` | Decimal(19,6) | sì | | | +| `unit_cost` | Decimal(19,6) | no | `0` | | +| `notes` | String(200) | sì | | | +| `sort_order` | Int32 | no | `0` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_stock_take_lines_item` su `stock_take_id`, `item_id` + +#### `stock_takes` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `take_date` | Date | no | | | +| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) | +| `description` | String(100) | no | | | +| `category_id` | Int64 | sì | | -> `item_categories` (Restrict) | +| `status` | String(40) | no | | | +| `adjustment_document_id` | Int64 | sì | | | +| `loss_document_id` | Int64 | sì | | | +| `posted_at` | DateTimeUtc | sì | | | +| `posted_by` | String(100) | sì | | | +| `notes` | Text | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_stock_takes_date` su `take_date` + #### `tax_codes` | Colonna | Tipo | Null | Default | Note | diff --git a/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs b/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs index af7b74c..a0d7f63 100644 --- a/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs +++ b/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs @@ -105,7 +105,7 @@ public static class WidgetCatalog new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"), new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core), new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core), - new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"), + new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read"), new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"), new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"), new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true), diff --git a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs index 108a6b3..d66782f 100644 --- a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs +++ b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs @@ -2,10 +2,6 @@ using Khaemhat.Application.Modules; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Accounting; -using Khaemhat.Core.Items; -using Khaemhat.Core.Tables; -using Khaemhat.Data; -using Khaemhat.Data.Querying; namespace Khaemhat.Application.ImportExport; @@ -232,101 +228,3 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => Task.FromResult>>([]); } - -/// -/// The opening stock (giacenze-iniziali): item, warehouse, quantity and unit cost. Until the stock entries exist -/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts. -/// -/// Opens the company databases. -/// Checks the permission. -public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget -{ - private static readonly ImportField[] StockFields = - [ - new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), - new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), - new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), - new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), - ]; - - /// - public string Key => "giacenze-iniziali"; - - /// - public string ModuleCode => ModuleCodes.Core; - - /// - public string Permission => "inventory.entry.write"; - - /// - public string ExportPermission => "inventory.stock.read"; - - /// - public bool CanApply => false; - - /// - public bool CanExport => false; - - /// - public IReadOnlyList Fields => StockFields; - - /// - public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(context); - ArgumentNullException.ThrowIfNull(rows); - var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); - await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); - var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; - var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); - var byId = items.ToDictionary(i => i.Id); - var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); - var seen = new HashSet<(long, long)>(); - var results = new List(rows.Count); - foreach (var row in rows) - { - var messages = new List(); - var cells = new CellReader(row, messages); - messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); - var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; - var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId); - if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) - { - messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); - } - - if (item is not null && warehouse is null && !cells.Has("deposito")) - { - messages.Add(new("deposito", ImportErrors.Required)); - } - - if (cells.Number("quantita") is <= 0) - { - messages.Add(new("quantita", ImportErrors.Positive)); - } - - if (cells.Number("costo_unitario") is < 0) - { - messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); - } - - var label = row["articolo"] ?? string.Empty; - if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) - { - messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); - } - - results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); - } - - return results; - } - - /// - public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => - throw new InvalidOperationException(ImportErrors.CheckOnly); - - /// - public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => - Task.FromResult>>([]); -} diff --git a/src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs b/src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs new file mode 100644 index 0000000..c10bff1 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs @@ -0,0 +1,191 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The opening stock (giacenze-iniziali, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted +/// become one warehouse movement per warehouse with the reason APE (opening stock), confirmed at the day of the +/// import: the stock and the average cost start from there. +/// +/// Opens the company databases. +/// Checks the permission. +/// Writes the movements. +/// The day of the movements. +public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget +{ + /// The reason of the opening stock. + public const string OpeningReason = "APE"; + + /// Error: the reason APE is missing. + public const string ReasonMissing = "import.stock.reason-missing"; + + private static readonly ImportField[] StockFields = + [ + new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), + new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), + new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), + new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), + ]; + + /// + public string Key => "giacenze-iniziali"; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public string Permission => "inventory.entry.write"; + + /// + public string ExportPermission => "inventory.stock.read"; + + /// + public bool CanApply => true; + + /// + public bool CanExport => false; + + /// + public IReadOnlyList Fields => StockFields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + [.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)]; + + /// + public async Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var read = await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + long? reason; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + reason = (await uow.Repository().FindAsync(Query.For().Where(r => r.Code == OpeningReason), cancellationToken) + .ConfigureAwait(false))?.Id; + } + + var results = read.Select(r => r.Result).ToArray(); + var good = read.Select((r, i) => (Row: r, Index: i)).Where(x => x.Row.Result.Action == ImportAction.Create && x.Row.Stock is not null).ToList(); + if (reason is null) + { + foreach (var (_, index) in good) + { + results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, new ImportMessage("articolo", ReasonMissing)] }; + } + + return results; + } + + var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime); + foreach (var group in good.GroupBy(x => x.Row.Stock!.Value.WarehouseId)) + { + var movement = await engine.NewAsync(context.Actor, company, "MM", cancellationToken).ConfigureAwait(false); + movement.Header.DocumentDate = today; + movement.Header.WarehouseId = group.Key; + movement.Header.InventoryReasonId = reason; + foreach (var (row, _) in group) + { + var stock = row.Stock!.Value; + movement.Lines.Add(new InventoryDocumentLine + { + Kind = DocumentLineKind.Item, + ItemId = stock.Item.Id, + Description = stock.Item.Description, + UnitOfMeasureId = stock.Item.UnitOfMeasureId, + Quantity = stock.Quantity, + Price = stock.Cost, + WarehouseId = group.Key, + }); + } + + try + { + var saved = await engine.SaveAsync(context.Actor, company, movement, cancellationToken).ConfigureAwait(false); + await engine.ConfirmAsync(context.Actor, company, saved.Family, saved.Header.Id, cancellationToken).ConfigureAwait(false); + } + catch (ValidationFailedException ex) + { + var message = new ImportMessage("articolo", ex.Errors.Count > 0 ? ex.Errors[0].Split(':', 2)[^1] : ImportErrors.Required); + foreach (var (_, index) in group) + { + results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, message] }; + } + } + } + + return results; + } + + /// + public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => + Task.FromResult>>([]); + + private async Task> ReadAsync( + ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); + var byId = items.ToDictionary(i => i.Id); + var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var fallback = (await uow.Repository().ListAsync(Query.For().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items + .OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; + var seen = new HashSet<(long, long)>(); + var results = new List<(ImportRowResult, (Item, long, decimal, decimal)?)>(rows.Count); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; + var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId ?? fallback); + if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) + { + messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); + } + + if (item is not null && warehouse is null && !cells.Has("deposito")) + { + messages.Add(new("deposito", ImportErrors.Required)); + } + + var quantity = cells.Number("quantita"); + if (quantity is <= 0) + { + messages.Add(new("quantita", ImportErrors.Positive)); + } + + var cost = cells.Number("costo_unitario"); + if (cost is < 0) + { + messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); + } + + var label = row["articolo"] ?? string.Empty; + if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) + { + messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); + } + + var failed = messages.Any(m => !m.IsWarning); + (Item, long, decimal, decimal)? stock = !failed && item is not null && warehouse is { } where && quantity is { } q + ? (item, where, q, cost ?? item.AverageCost ?? item.StandardCost ?? item.LastCost ?? 0m) + : null; + results.Add((new ImportRowResult(row.Line, label, failed ? ImportAction.Skip : ImportAction.Create, messages), stock)); + } + + return results; + } +} diff --git a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs new file mode 100644 index 0000000..19bff2a --- /dev/null +++ b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs @@ -0,0 +1,522 @@ +using System.IO.Compression; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Files; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Purchases; + +/// An invoice found in a received file, as the import screen shows it before registering (mockup 034). +/// The file (inside a ZIP, its entry). +/// The file as read. +/// The invoice (a file may hold several). +/// The purchase document type that registers it, or none. +/// The supplier already in the archive, by VAT number or tax code. +/// Whether the supplier already has a document with this number in this year. +/// Taxable plus tax of the summary, plus rounding: what the total should be. +/// What stops or warns (resource codes). +public sealed record IncomingCandidate( + string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal, + IReadOnlyList Problems) +{ + /// Whether it can be registered. + public bool CanImport => DocumentTypeCode is not null && !Duplicate; + + /// The total in the file, or the computed one. + public decimal Total => Invoice.Total ?? ComputedTotal; +} + +/// A file that could not be read. +/// The file. +/// Why (resource code). +public sealed record IncomingRejected(string FileName, string Error); + +/// What the files hold. +/// The invoices found. +/// The files not read. +public sealed record IncomingReading(IReadOnlyList Invoices, IReadOnlyList Rejected); + +/// An invoice registered, or why not. +/// The invoice. +/// The draft document. +/// Whether the supplier was added to the archive. +/// Why it was not registered (resource code). +/// What to check on the draft (resource codes). +public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList Warnings); + +/// +/// The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files are read by the fiscal pack; +/// each invoice finds its supplier by VAT number or tax code (or adds it), its items by the supplier code, bar code or +/// code, its tax codes by rate and nature; it becomes a draft supplier invoice or credit note with the file attached, to +/// check and confirm. Duplicates (same supplier, number and year) are refused; a total that does not match the lines is +/// reported. +/// +public sealed class PurchaseInvoiceImportService +{ + /// The largest file accepted, ZIP included. + public const int MaxFileSize = 50 * 1024 * 1024; + + /// Problem: the type of the invoice is not a purchase (a self-invoice). + public const string UnsupportedType = "purchase.import.unsupported-type"; + + /// Problem: already registered. + public const string DuplicateProblem = "purchase.import.duplicate"; + + /// Warning: the total in the file differs from the lines. + public const string TotalMismatch = "purchase.import.total-mismatch"; + + /// Warning: the signature of the file could not be verified. + public const string SignatureNotVerified = "purchase.import.signature"; + + /// Warning: the discounts of the whole document are not carried to the lines. + public const string DocumentDiscount = "purchase.import.document-discount"; + + /// Error: no tax code of the company has the rate and nature of a line. + public const string TaxCodeMissing = "purchase.import.tax-code"; + + /// Error: the archive is empty of invoices. + public const string EmptyArchive = "purchase.import.empty"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly DocumentEngine _engine; + private readonly DocumentEditor _editor; + private readonly PartyService _parties; + private readonly AttachmentService _attachments; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The document engine. + /// The editor (terms of the supplier). + /// The parties (new suppliers). + /// The attachments (the file). + /// The clock. + public PurchaseInvoiceImportService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, DocumentEditor editor, PartyService parties, + AttachmentService attachments, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(parties); + ArgumentNullException.ThrowIfNull(attachments); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _engine = engine; + _editor = editor; + _parties = parties; + _attachments = attachments; + _clock = clock; + } + + /// Reads files: each XML or P7M, and those inside a ZIP. + /// Who imports: needs purchases.invoice.write. + /// The company. + /// The files, by name. + /// Cancellation. + /// The invoices found and the files not read. + public async Task ReadAsync( + Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(files); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var reader = pack.GetFeature(); + var rules = pack.GetFeature(); + var found = new List<(string Name, IncomingInvoiceFile File)>(); + var rejected = new List(); + foreach (var (name, content) in Expand(files, rejected)) + { + if (reader is null || !reader.CanRead(name, content)) + { + rejected.Add(new(name, IncomingInvoiceErrors.NotReadable)); + continue; + } + + try + { + found.Add((name, reader.Read(name, content))); + } + catch (IncomingInvoiceException ex) + { + rejected.Add(new(name, ex.Code)); + } + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var result = new List(); + foreach (var (name, file) in found) + { + var supplierId = await FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false); + foreach (var invoice in file.Invoices) + { + var problems = new List(); + var typeCode = rules?.DocumentTypeCode(invoice.DocumentType); + if (typeCode is null) + { + problems.Add(UnsupportedType); + } + + var duplicate = supplierId is { } supplier && await IsDuplicateAsync(uow, supplier, invoice, cancellationToken).ConfigureAwait(false); + if (duplicate) + { + problems.Add(DuplicateProblem); + } + + var computed = invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) + (invoice.Rounding ?? 0m); + if (invoice.Total is { } total && Math.Abs(total - computed) > 0.01m && invoice.Discounts.Count == 0) + { + problems.Add(TotalMismatch); + } + + if (invoice.Discounts.Count > 0) + { + problems.Add(DocumentDiscount); + } + + if (file.Signature is { Verified: false }) + { + problems.Add(SignatureNotVerified); + } + + result.Add(new IncomingCandidate(name, file, invoice, typeCode, supplierId, duplicate, computed, problems)); + } + } + + if (result.Count == 0 && rejected.Count == 0) + { + rejected.Add(new(files.Count == 1 ? files[0].FileName : string.Empty, EmptyArchive)); + } + + return new IncomingReading([.. result.OrderBy(c => c.Invoice.Date).ThenBy(c => c.File.Supplier.DisplayName, StringComparer.CurrentCulture)], rejected); + } + + /// + /// Registers the invoices as drafts: the supplier is found or added, each line takes its item and tax code, the + /// file is attached. One invoice that fails does not stop the others. + /// + /// Who imports. + /// The company. + /// The invoices to register. + /// Cancellation. + /// What happened to each. + public async Task> ImportAsync( + Actor actor, string companyCode, IReadOnlyList candidates, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(candidates); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + var created = new Dictionary(StringComparer.OrdinalIgnoreCase); + var result = new List(); + foreach (var candidate in candidates) + { + if (candidate.DocumentTypeCode is not { } typeCode) + { + result.Add(new(candidate, null, false, UnsupportedType, [])); + continue; + } + + var supplierCreated = false; + try + { + long supplierId; + var key = KeyOf(candidate.File.Supplier); + if (candidate.SupplierId is { } known) + { + supplierId = known; + } + else if (key.Length > 0 && created.TryGetValue(key, out var made)) + { + supplierId = made; + } + else + { + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + supplierId = await FindSupplierAsync(uow, candidate.File.Supplier, cancellationToken).ConfigureAwait(false) ?? 0; + } + + if (supplierId == 0) + { + supplierId = await CreateSupplierAsync(actor, company, candidate.File.Supplier, cancellationToken).ConfigureAwait(false); + supplierCreated = true; + } + + if (key.Length > 0) + { + created[key] = supplierId; + } + } + + var (record, warnings) = await DraftAsync(actor, company, candidate, typeCode, supplierId, today, cancellationToken).ConfigureAwait(false); + result.Add(new(candidate, record, supplierCreated, null, warnings)); + } + catch (ValidationFailedException ex) + { + result.Add(new(candidate, null, supplierCreated, (ex.Errors.Count > 0 ? ex.Errors[0] : null)?.Split(':', 2)[^1] ?? IncomingInvoiceErrors.Invalid, [])); + } + } + + return result; + } + + // ZIP archives are opened (one level, entries .xml and .p7m); other files pass as they are. + private static List<(string Name, byte[] Content)> Expand(IReadOnlyList<(string FileName, byte[] Content)> files, List rejected) + { + var result = new List<(string, byte[])>(); + foreach (var (name, content) in files) + { + if (content.Length > MaxFileSize) + { + rejected.Add(new(name, IncomingInvoiceErrors.NotReadable)); + continue; + } + + if (content.Length < 4 || content[0] != (byte)'P' || content[1] != (byte)'K') + { + result.Add((name, content)); + continue; + } + + try + { + using var archive = new ZipArchive(new MemoryStream(content, writable: false), ZipArchiveMode.Read); + long total = 0; + foreach (var entry in archive.Entries.Where(e => e.Length > 0 && !e.FullName.EndsWith('/'))) + { + var entryName = Path.GetFileName(entry.FullName); + if (!entryName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && !entryName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + total += entry.Length; + if (entry.Length > MaxFileSize || total > 4L * MaxFileSize) + { + rejected.Add(new(entryName, IncomingInvoiceErrors.NotReadable)); + continue; + } + + using var stream = entry.Open(); + using var buffer = new MemoryStream(); + stream.CopyTo(buffer); + result.Add((entryName, buffer.ToArray())); + } + } + catch (InvalidDataException) + { + rejected.Add(new(name, IncomingInvoiceErrors.NotReadable)); + } + } + + return result; + } + + private static string KeyOf(IncomingParty party) => + (party.VatNumber is { Length: > 0 } vat ? (party.CountryCode ?? "IT") + vat : party.TaxCode ?? string.Empty).ToUpperInvariant(); + + // The VAT number as the archive keeps it: digits only for Italy, with the country prefix abroad. + private static string? VatOf(IncomingParty party) => + party.VatNumber is not { Length: > 0 } vat ? null + : party.CountryCode is null or "IT" ? vat + : vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat; + + private static async Task FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken) + { + var parties = uow.Repository(); + if (VatOf(party) is { } vat) + { + var bare = party.VatNumber!; + var byVat = (await parties.ListAsync(Query.For().Where(p => p.VatNumber == vat || p.VatNumber == bare), cancellationToken).ConfigureAwait(false)).Items; + if (Pick(byVat) is { } found) + { + return found; + } + } + + if (party.TaxCode is { Length: > 0 } taxCode) + { + var byTaxCode = (await parties.ListAsync(Query.For().Where(p => p.TaxCode == taxCode), cancellationToken).ConfigureAwait(false)).Items; + return Pick(byTaxCode); + } + + return null; + + // A supplier first, then a customer that is also a supplier, then any party; the enabled ones first. + static long? Pick(IReadOnlyList parties) => parties + .OrderBy(p => p.Disabled).ThenBy(p => p.Kind == PartyKind.Supplier ? 0 : p.IsSupplier ? 1 : 2).ThenBy(p => p.Id).FirstOrDefault()?.Id; + } + + private static async Task IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken) + { + var number = invoice.Number.Trim(); + var from = new DateOnly(invoice.Date.Year, 1, 1); + var to = new DateOnly(invoice.Date.Year, 12, 31); + return await uow.Repository().CountAsync( + Query.For().Where(d => d.PartyId == supplierId && d.ExternalReference == number && d.ExternalDate >= from && d.ExternalDate <= to + && d.Status != DocumentStatus.Cancelled + && (d.Kind == DocumentKind.PurchaseInvoice || d.Kind == DocumentKind.PurchaseCreditNote)), + cancellationToken).ConfigureAwait(false) > 0; + } + + private async Task CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken) + { + var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false); + var p = record.Party; + var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant(); + bool inEu; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + inEu = (await uow.Repository().FindAsync(Query.For().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false; + } + + p.CountryCode = country; + p.SubjectType = country == "IT" + ? (party.Name is null && party.VatNumber is null ? SubjectType.Person : SubjectType.Company) + : inEu ? SubjectType.EuCompany : SubjectType.NonEuCompany; + p.Name = Limit(party.DisplayName, 200) ?? string.Empty; + p.FirstName = p.SubjectType == SubjectType.Person ? Limit(party.FirstName, 100) : null; + p.LastName = p.SubjectType == SubjectType.Person ? Limit(party.LastName, 100) : null; + p.VatNumber = VatOf(party); + p.TaxCode = Limit(party.TaxCode, 16); + p.Address = Limit(party.Address, 200); + p.StreetNumber = Limit(party.StreetNumber, 20); + p.PostalCode = Limit(party.PostalCode, 10); + p.City = Limit(party.City, 100); + p.Province = country == "IT" ? Limit(party.Province, 2) : null; + p.Email = Limit(party.Email, 200); + p.Phone = Limit(party.Phone, 40); + p.Rea = party.ReaOffice is null || party.ReaNumber is null ? null : Limit(party.ReaOffice + "-" + party.ReaNumber, 30); + return (await _parties.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false)).Party.Id; + } + + private static string? Limit(string? text, int length) => + string.IsNullOrWhiteSpace(text) ? null : text.Trim() is var trimmed && trimmed.Length > length ? trimmed[..length] : text.Trim(); + + private async Task<(DocumentRecord Record, IReadOnlyList Warnings)> DraftAsync( + Actor actor, string company, IncomingCandidate candidate, string typeCode, long supplierId, DateOnly today, CancellationToken cancellationToken) + { + var invoice = candidate.Invoice; + var record = await _engine.NewAsync(actor, company, typeCode, cancellationToken).ConfigureAwait(false); + await _editor.ApplyPartyAsync(actor, company, record, supplierId, cancellationToken).ConfigureAwait(false); + var header = record.Header; + header.DocumentDate = invoice.Date > today ? invoice.Date : today; + header.ExternalReference = Limit(invoice.Number, 50); + header.ExternalDate = invoice.Date; + if (invoice.Causals.Count > 0) + { + header.Notes = Limit(string.Join(Environment.NewLine, invoice.Causals), 2000); + } + + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var codes = invoice.Lines.SelectMany(l => l.Codes).Select(c => c.Value.Trim()).Where(v => v.Length > 0).Distinct(StringComparer.Ordinal).ToList(); + var bySupplierCode = codes.Count == 0 ? [] : (await uow.Repository().ListAsync( + Query.For().Where(s => s.PartyId == supplierId && codes.Contains(s.SupplierCode!)), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(s => s.SupplierCode!, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal); + var byBarcode = codes.Count == 0 ? [] : (await uow.Repository().ListAsync( + Query.For().Where(b => codes.Contains(b.Code)), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(b => b.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal); + var byCode = codes.Count == 0 ? [] : (await uow.Repository().ListAsync( + Query.For().Where(i => codes.Contains(i.Code)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Code, StringComparer.Ordinal); + var itemIds = bySupplierCode.Values.Concat(byBarcode.Values).Distinct().ToList(); + var items = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(i => i.Id); + foreach (var item in byCode.Values) + { + items.TryAdd(item.Id, item); + } + + var credit = record.Header.Kind == DocumentKind.PurchaseCreditNote; + foreach (var source in invoice.Lines.OrderBy(l => l.Number)) + { + var line = new PurchaseDocumentLine(); + line.Kind = DocumentLineKind.Free; + line.Description = Limit(source.Description, 1000) ?? "-"; + line.TaxCodeId = TaxCodeOf(taxes, source.TaxRate, source.Nature) + ?? throw new ValidationFailedException([":" + TaxCodeMissing]); + var quantity = source.Quantity is { } q && q != 0m ? q : 1m; + var price = source.UnitPrice; + var discounts = source.Discounts; + if (discounts.Count > 0 && discounts.All(d => d.Percent is > 0m and <= 100m && !d.IsSurcharge)) + { + line.DiscountFormula = string.Join('+', discounts.Select(d => d.Percent!.Value.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture))); + } + else if (discounts.Count > 0 || (source.Quantity is null && source.TotalPrice != source.UnitPrice)) + { + // Amounts or surcharges: the net price keeps the total of the line. + price = Math.Round(source.TotalPrice / quantity, 6); + } + + line.Quantity = credit ? Math.Abs(quantity) : quantity; + line.Price = credit && quantity < 0m ? -price : price; + if (ItemOf(source, bySupplierCode, byBarcode, byCode) is { } itemId && items.TryGetValue(itemId, out var item) && !item.Disabled) + { + line.Kind = DocumentLineKind.Item; + line.ItemId = item.Id; + line.UnitOfMeasureId = item.UnitOfMeasureId; + } + + record.Lines.Add(line); + } + } + + var saved = await _engine.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false); + await _attachments.AddAsync( + actor, company, DocumentPrintService.EntityOf(saved.Family), saved.Header.Id, new AttachmentFile(AttachmentKind.EInvoice, candidate.File.FileName, null), + (stream, ct) => stream.WriteAsync(candidate.File.Xml, ct).AsTask(), cancellationToken).ConfigureAwait(false); + var warnings = candidate.Problems.Where(p => p is TotalMismatch or SignatureNotVerified or DocumentDiscount).ToList(); + if (invoice.Total is { } total && Math.Abs(total - saved.Header.TotalAmount) > 0.01m && !warnings.Contains(TotalMismatch)) + { + warnings.Add(TotalMismatch); + } + + return (saved, warnings); + } + + private static long? ItemOf(IncomingLine line, Dictionary bySupplierCode, Dictionary byBarcode, Dictionary byCode) + { + foreach (var code in line.Codes.Select(c => c.Value.Trim())) + { + if (bySupplierCode.TryGetValue(code, out var id) || byBarcode.TryGetValue(code, out id)) + { + return id; + } + } + + return line.Codes.Select(c => c.Value.Trim()).FirstOrDefault(byCode.ContainsKey) is { } own ? byCode[own].Id : null; + } + + // The tax code with the rate and nature of the line: the exact nature first, then the family of the nature (N3 for + // N3.2), then for an ordinary rate the ordinary codes before the others. + private static long? TaxCodeOf(IReadOnlyList taxes, decimal rate, string? nature) + { + var withRate = taxes.Where(t => t.Rate == rate).OrderBy(t => t.ValidTo is not null).ThenBy(t => t.Code, StringComparer.Ordinal).ToList(); + if (nature is null) + { + return (withRate.FirstOrDefault(t => t.Nature is null && t.Kind == TaxCodeKind.Taxable) ?? withRate.FirstOrDefault(t => t.Nature is null))?.Id; + } + + return (withRate.FirstOrDefault(t => string.Equals(t.Nature, nature, StringComparison.OrdinalIgnoreCase)) + ?? withRate.FirstOrDefault(t => t.Nature is not null && t.Nature.StartsWith(nature.Split('.')[0], StringComparison.OrdinalIgnoreCase)))?.Id; + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs new file mode 100644 index 0000000..8f4edbd --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs @@ -0,0 +1,260 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Seeding; + +/// +/// The purchases and the warehouse of the demo company (SPEC §14, issue #61), made through the document engine like a +/// user makes them: the opening stock on the first of January, supplier orders received in full and in part, the +/// supplier invoice of a receipt with a price that differs from the order, a professional's invoice, an invoice from a +/// German supplier still waiting for its self-invoice, and a stock take being counted. Some items start low, so that the +/// sales bring them under their minimum and the reorder proposal has something to propose. Runs only when the demo data +/// are asked and the company has no purchase documents yet; every document is marked as demo. +/// +/// The document engine. +/// The document editor (supplier terms, item costs). +/// The transformations between documents. +/// The stock takes. +/// The units of work. +/// The clock. +public sealed class DemoPurchasesSeeder( + DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, StockTakeService stockTakes, IUnitOfWorkFactory factory, TimeProvider clock) + : ICompanySeeder +{ + private static readonly Actor Seed = Actor.System; + + private DocumentEngine Engine { get; } = engine; + + private DocumentEditor Editor { get; } = editor; + + private DocumentCopyService Copies { get; } = copies; + + private StockTakeService StockTakes { get; } = stockTakes; + + /// + public int Order => 30; + + /// + public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + if (!context.Demo) + { + return; + } + + var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (data is null) + { + return; + } + + var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + var run = new Run(this, companyCode, data, today, cancellationToken); + await run.ExecuteAsync().ConfigureAwait(false); + } + + // The suppliers, goods and reasons the documents use; null when the company already has purchases or lacks them. + private async Task ReadAsync(string companyCode, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return null; + } + + var parties = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal); + var goods = (await uow.Repository().ListAsync(Query.For().Where(i => i.IsDemo && i.Kind == ItemKind.Goods && i.Stocked), cancellationToken) + .ConfigureAwait(false)).Items.OrderBy(i => i.Id).ToList(); + var goodIds = goods.Select(g => g.Id).ToList(); + var suppliers = (await uow.Repository().ListAsync(Query.For().Where(s => goodIds.Contains(s.ItemId)), cancellationToken) + .ConfigureAwait(false)).Items.GroupBy(s => s.PartyId).ToDictionary(g => g.Key, g => (IReadOnlyList)[.. g.Select(s => s.ItemId).Distinct()]); + var reasons = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(r => r.Code, r => r.Id, StringComparer.Ordinal); + var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var warehouse = (await uow.Repository().ListAsync(Query.For().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items + .OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; + string[] names = ["Metalli Nord S.p.A.", "Plastica Sud S.r.l.", "Studio Rag. Neri Paola", "Elektro Werke Süd GmbH"]; + var ordinary = taxes.FirstOrDefault(t => t.Code == "22")?.Id; + var intraEu = taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N3.2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault() + ?? taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault(); + if (goods.Count < 12 || !names.All(parties.ContainsKey) || !reasons.TryGetValue("APE", out var opening) || warehouse is null || ordinary is null || intraEu is null) + { + return null; + } + + return new DemoData(parties, goods, suppliers, opening, warehouse.Value, ordinary.Value, intraEu.Value); + } + + private sealed record DemoData( + IReadOnlyDictionary Parties, IReadOnlyList Goods, IReadOnlyDictionary> ItemsBySupplier, long OpeningReason, + long Warehouse, long Ordinary, long IntraEu); + + // One seeding, with its company and dates. + private sealed class Run(DemoPurchasesSeeder owner, string company, DemoData data, DateOnly today, CancellationToken cancellationToken) + { + private long Party(string name) => data.Parties[name]; + + // A date some months before today, kept between the first of January and today (as the sales do). + private DateOnly D(int monthsBack, int day) + { + var month = today.AddMonths(-monthsBack); + var date = new DateOnly(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month))); + var first = new DateOnly(today.Year, 1, 1); + return date < first ? first : date > today ? today : date; + } + + // The goods a supplier sells, else the first goods. + private List GoodsOf(string supplier, int count) + { + var ids = data.ItemsBySupplier.GetValueOrDefault(Party(supplier)) ?? []; + var own = data.Goods.Where(g => ids.Contains(g.Id)).Take(count).ToList(); + return own.Count >= count ? own : [.. own, .. data.Goods.Where(g => !own.Contains(g)).Take(count - own.Count)]; + } + + public async Task ExecuteAsync() + { + await OpeningAsync().ConfigureAwait(false); + + // Metalli Nord: an order received in full, invoiced at a higher price on one line. + var metals = GoodsOf("Metalli Nord S.p.A.", 3); + var o1 = await OrderAsync("Metalli Nord S.p.A.", D(4, 5), [(metals[0], 30m), (metals[1], 20m), (metals[2], 50m)], "Riordino trimestrale").ConfigureAwait(false); + var r1 = await ReceiveAsync(o1, D(4, 15), "DDT 1184", null).ConfigureAwait(false); + var f1 = await CopyAsync(r1, "FF", D(4, 30)).ConfigureAwait(false); + var dearer = f1.Lines.First(l => l.Kind == DocumentLineKind.Item); + dearer.Price = Math.Round(dearer.Price * 1.04m, 2); + f1.Header.ExternalReference = "MN/2026/0311"; + f1.Header.ExternalDate = D(4, 28); + await ConfirmAsync(await SaveAsync(f1).ConfigureAwait(false)).ConfigureAwait(false); + + // Plastica Sud: an order received in part; the rest is still on its way. + var plastics = GoodsOf("Plastica Sud S.r.l.", 3); + var o2 = await OrderAsync("Plastica Sud S.r.l.", D(2, 3), [(plastics[0], 40m), (plastics[1], 60m), (plastics[2], 25m)], null).ConfigureAwait(false); + await ReceiveAsync(o2, D(1, 10), "Bolla 552", [o2.Lines[0].Id, o2.Lines[1].Id]).ConfigureAwait(false); + + // The accountant's fees, with withholding tax. + await InvoiceAsync("Studio Rag. Neri Paola", D(1, 28), "12/2026", D(1, 27), "Tenuta contabilità e dichiarativi", 450m, data.Ordinary).ConfigureAwait(false); + + // Goods from Germany: no Italian VAT on the invoice, the self-invoice is still to issue. + var german = data.Goods[^1]; + await InvoiceAsync("Elektro Werke Süd GmbH", D(0, 3), "RE-2026-08841", D(0, 1), german.Description, 1280m, data.IntraEu, german).ConfigureAwait(false); + + // A stock take being counted: half of the list, two items differ from the books. + var take = await owner.StockTakes.CreateAsync(Seed, company, data.Warehouse, today, null, null, cancellationToken).ConfigureAwait(false); + var counts = new Dictionary(); + foreach (var (line, index) in take.Lines.Take(Math.Min(12, take.Lines.Count)).Select((l, i) => (l, i))) + { + counts[line.Line.Id] = Math.Max(0m, line.Line.BookQuantity + index switch { 2 => -2m, 7 => 1m, _ => 0m }); + } + + await owner.StockTakes.SaveCountsAsync(Seed, company, take.Take.Id, counts, cancellationToken).ConfigureAwait(false); + } + + // The opening stock: plenty of most goods, little of one in five, so that the year's sales bring them under. + private async Task OpeningAsync() + { + var movement = await owner.Engine.NewAsync(Seed, company, "MM", cancellationToken).ConfigureAwait(false); + movement.Header.IsDemo = true; + movement.Header.DocumentDate = new DateOnly(today.Year, 1, 1); + movement.Header.WarehouseId = data.Warehouse; + movement.Header.InventoryReasonId = data.OpeningReason; + movement.Header.Notes = "Esistenze iniziali dall'inventario di fine anno."; + foreach (var (item, index) in data.Goods.Select((g, i) => (g, i))) + { + var bulk = item.ReorderPoint is null; + movement.Lines.Add(new InventoryDocumentLine + { + Kind = DocumentLineKind.Item, + ItemId = item.Id, + Description = item.Description, + UnitOfMeasureId = item.UnitOfMeasureId, + Quantity = index % 5 == 0 ? (bulk ? 30m : 6m) : bulk ? 400m : 60m, + Price = item.StandardCost ?? 0m, + WarehouseId = data.Warehouse, + }); + } + + await ConfirmAsync(await SaveAsync(movement).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task OrderAsync(string supplier, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, string? notes) + { + var order = await owner.Engine.NewAsync(Seed, company, "OF", cancellationToken).ConfigureAwait(false); + order.Header.IsDemo = true; + order.Header.DocumentDate = date; + order.Header.Notes = notes; + await owner.Editor.ApplyPartyAsync(Seed, company, order, Party(supplier), cancellationToken).ConfigureAwait(false); + foreach (var (item, quantity) in lines) + { + var line = new PurchaseOrderLine { Quantity = quantity }; + await owner.Editor.FillLineAsync(Seed, company, order, line, item.Id, cancellationToken).ConfigureAwait(false); + line.Quantity = quantity; + order.Lines.Add(line); + } + + return await ConfirmAsync(await SaveAsync(order).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task ReceiveAsync(DocumentRecord order, DateOnly date, string reference, IReadOnlyCollection? lines) + { + var receipt = await CopyAsync(order, "DDTF", date, lines).ConfigureAwait(false); + receipt.Header.ExternalReference = reference; + receipt.Header.ExternalDate = date; + return await ConfirmAsync(await SaveAsync(receipt).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task InvoiceAsync(string supplier, DateOnly date, string number, DateOnly numberDate, string description, decimal amount, long taxCode, Item? item = null) + { + var invoice = await owner.Engine.NewAsync(Seed, company, "FF", cancellationToken).ConfigureAwait(false); + invoice.Header.IsDemo = true; + invoice.Header.DocumentDate = date; + invoice.Header.ExternalReference = number; + invoice.Header.ExternalDate = numberDate; + await owner.Editor.ApplyPartyAsync(Seed, company, invoice, Party(supplier), cancellationToken).ConfigureAwait(false); + var line = new PurchaseDocumentLine { Quantity = 1m }; + if (item is not null) + { + await owner.Editor.FillLineAsync(Seed, company, invoice, line, item.Id, cancellationToken).ConfigureAwait(false); + line.Quantity = 10m; + line.Price = Math.Round(amount / 10m, 2); + } + else + { + line.Kind = DocumentLineKind.Free; + line.Description = description; + line.Price = amount; + } + + line.TaxCodeId = taxCode; + invoice.Lines.Add(line); + await ConfirmAsync(await SaveAsync(invoice).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection? lines = null) + { + var copy = await owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken).ConfigureAwait(false); + copy.Header.IsDemo = true; + return copy; + } + + private Task SaveAsync(DocumentRecord record) + { + record.Header.IsDemo = true; + return owner.Engine.SaveAsync(Seed, company, record, cancellationToken); + } + + private Task ConfirmAsync(DocumentRecord record) => + owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs index 1c8c3e4..6949382 100644 --- a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs +++ b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs @@ -267,3 +267,15 @@ public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal A /// The description, if any. /// The decoded content. public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content); + +/// +/// How a received e-invoice becomes a document of the company: which document type registers each type of the format +/// (Italy: TD01 and the like as supplier invoice FF, TD04 and TD08 as supplier credit note NCF). +/// +public interface IIncomingInvoiceRules +{ + /// The code of the document type that registers an invoice of this type of the format. + /// The type in the file (TD01...). + /// The document type code, or none when the type is not registered as a purchase (a self-invoice). + string? DocumentTypeCode(string formatType); +} diff --git a/src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs b/src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs new file mode 100644 index 0000000..b82fb56 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs @@ -0,0 +1,22 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The types of a received FatturaPA and the purchase document that registers them: invoices, deposits, fee notes, +/// debit notes and deferred invoices (TD01, TD02, TD03, TD05, TD06, TD24, TD25, TD26, TD27) as supplier invoice FF, +/// credit notes (TD04, TD08) as supplier credit note NCF. The self-invoice types TD16-TD23, TD28 and TD29 are issued by +/// the company itself and are not purchases. +/// +public sealed class IncomingInvoiceRulesIt : IIncomingInvoiceRules +{ + private static readonly HashSet Invoices = new(StringComparer.Ordinal) { "TD01", "TD02", "TD03", "TD05", "TD06", "TD24", "TD25", "TD26", "TD27" }; + private static readonly HashSet CreditNotes = new(StringComparer.Ordinal) { "TD04", "TD08" }; + + /// + public string? DocumentTypeCode(string formatType) + { + var type = formatType?.Trim().ToUpperInvariant() ?? string.Empty; + return Invoices.Contains(type) ? "FF" : CreditNotes.Contains(type) ? "NCF" : null; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index b15da11..4289fa3 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -16,6 +16,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase { AddFeature(new FatturaPaFormat()); AddFeature(new FatturaPaReader()); + AddFeature(new IncomingInvoiceRulesIt()); AddFeature(new SelfInvoiceRulesIt()); AddFeature(new WithholdingRulesIt()); AddFeature(new FixedAssetRulesIt()); diff --git a/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor b/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor index 56f417d..f416e84 100644 --- a/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor +++ b/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor @@ -19,6 +19,9 @@ case WidgetIds.SystemStatus: break; + case WidgetIds.Understock: + + break; default: break; diff --git a/src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor b/src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor new file mode 100644 index 0000000..92b0ccc --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor @@ -0,0 +1,74 @@ +@using Khaemhat.Application.Inventory +@inject ShellSession Session +@inject InventoryService Inventory + +@* Sottoscorta (SPEC §10.3, §11.6): the items under their minimum stock or reorder point, the most urgent first, with a + link to the reorder proposal. *@ + + + @if (_rows is { Count: > 0 }) + { + @T.Number(_rows.Count) + } + + + @if (_failed) + { +

@T["Dashboard.Feed.Error"]

+ } + else if (_rows is null) + { +

@T["Dashboard.Feed.Loading"]

+ } + else if (_rows.Count == 0) + { +

@T["Dashboard.Widgets.Understock.Empty"]

+ } + else + { + + + } +
+
+ +@code { + private IReadOnlyList? _rows; + private bool _failed; + + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(InventoryService.StockPermission)) + { + _rows = []; + return; + } + + try + { + _rows = await Inventory.UnderstockAsync(actor, company, 8); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _failed = true; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs index 57ac76f..052d287 100644 --- a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs @@ -46,7 +46,7 @@ public partial class ImportExportPage private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null; - private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6"; + private static string CheckOnlyMilestone => "M7"; private IReadOnlyList> TargetChoices => [.. Targets.Select(t => new KhOption(t.Key, TargetName(t.Key)))]; diff --git a/src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor b/src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor new file mode 100644 index 0000000..aa759b8 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor @@ -0,0 +1,247 @@ +@page "/magazzino/riordino" +@attribute [Authorize] +@using Khaemhat.Application.Documents +@using Khaemhat.Application.Inventory +@using Khaemhat.Application.Items +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Documents +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject ReorderService Reorder +@inject PartyService Parties +@inject TableService Tables +@inject ToastService Toasts + +@* The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the + reorder point or the minimum stock, with the quantity to order and the usual supplier; the lines chosen, perhaps with + another quantity or supplier, become draft supplier orders, one per supplier. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(InventoryService.StockPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (_orders.Count > 0) + { +
+ + + @T.Format("Inventory.Reorder.Created", _orders.Count) + @foreach (var order in _orders) + { + @order.Supplier + } + +
+ } + + + + @T.Format("Inventory.Reorder.Selected", Chosen.Count(), T.Money(ChosenValue)) + + @if (CanOrder) + { + + } + + + @if (_lines.Count == 0) + { +

@T["Inventory.Reorder.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + + @foreach (var line in _lines) + { + var row = line.Proposal; + + + + + + + + + + + + + + + } + +
@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Items.Radar.Unit"]@T["Inventory.Stock.Available"]@T["Inventory.Stock.OrderedColumn"]@T["Inventory.Stock.Minimum"]@T["Inventory.Stock.ReorderPoint"]@T["Inventory.Reorder.Quantity"]@T["Purchases.Fields.Supplier"]@T["Inventory.Reorder.Price"]@T["Inventory.Reorder.Expected"]
@row.Code@row.Description@PartyScreens.Describe(_lookups.Units, row.UnitOfMeasureId)@Qty(row.Available)@Qty(row.Ordered)@(row.MinimumStock is { } m ? Qty(m) : null)@(row.ReorderPoint is { } p ? Qty(p) : null) + + + + @(row.Price is { } price ? T.Money(price) : null)@(row.ExpectedDate is { } date ? T.Date(date) : null)
+
+ } +
+
+

@T["Inventory.Reorder.Hint"]

+} + +@code { + private List _lines = []; + private List<(DocumentRecord Record, string Supplier)> _orders = []; + private ItemLookups _lookups = ItemLookups.Empty; + private bool _loaded; + private bool _busy; + + private bool CanOrder => Session.Permissions.Allows("purchases.order.write"); + + private IEnumerable Chosen => _lines.Where(l => l.Chosen && l.Supplier is not null && l.Quantity > 0m); + + private decimal ChosenValue => Chosen.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2)); + + private IReadOnlyList Stats => + [ + new(T["Inventory.Reorder.Items"], T.Number(_lines.Count), _lines.Count > 0 ? KhTone.Warning : KhTone.Ok), + new(T["Inventory.Reorder.Suppliers"], T.Number(_lines.Where(l => l.Supplier is not null).Select(l => l.Supplier!.Id).Distinct().Count())), + new(T["Inventory.Reorder.Value"], T.Money(_lines.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2)))), + new(T["Inventory.Reorder.WithoutSupplier"], T.Number(_lines.Count(l => l.Supplier is null)), _lines.Any(l => l.Supplier is null) ? KhTone.Warning : KhTone.Neutral), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission)) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + await LoadAsync(); + } + + _loaded = true; + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + var proposals = await Reorder.ProposalsAsync(actor, company); + var supplierIds = proposals.Where(p => p.SupplierId is not null).Select(p => p.SupplierId!.Value).Distinct().ToList(); + var suppliers = Session.Permissions.Allows(PartyService.ReadPermission) + ? (await Parties.RowsAsync(actor, company, supplierIds)).ToDictionary(r => r.Id) + : []; + + _lines = [.. proposals.Select(p => new Line(p) + { + Quantity = p.Quantity, + Supplier = p.SupplierId is { } s ? suppliers.GetValueOrDefault(s) : null, + Chosen = p.SupplierId is not null, + })]; + } + + private async Task> SearchAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken) + : []; + + private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); + + private void SetQuantity(Line line, string? text) + { + if (decimal.TryParse((text ?? string.Empty).Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value) + && value >= 0m) + { + line.Quantity = value; + } + } + + private void ToggleAll(ChangeEventArgs e) + { + foreach (var line in _lines) + { + line.Chosen = e.Value is true; + } + } + + private async Task CreateAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (_lines.Any(l => l.Chosen && l.Supplier is null)) + { + Toasts.Show(ToastKind.Warning, T["Inventory.Reorder.MissingSupplier"]); + } + + _busy = true; + try + { + var names = Chosen.Select(l => l.Supplier!).DistinctBy(r => r.Id).ToDictionary(r => r.Id, r => r.Name); + var orders = await Reorder.CreateOrdersAsync(actor, company, [.. Chosen.Select(l => new ReorderChoice(l.Proposal.ItemId, l.Supplier!.Id, l.Quantity))]); + _orders = [.. orders.Select(o => (o, names.GetValueOrDefault(o.Header.PartyId ?? 0) ?? string.Empty))]; + Toasts.Show(ToastKind.Success, T.Format("Inventory.Reorder.Created", _orders.Count)); + await LoadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); + } + finally + { + _busy = false; + } + } + + private sealed class Line(ReorderProposal proposal) + { + public ReorderProposal Proposal { get; } = proposal; + + public decimal Quantity { get; set; } + + public PartyRow? Supplier { get; set; } + + public bool Chosen { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor b/src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor new file mode 100644 index 0000000..07d6136 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor @@ -0,0 +1,450 @@ +@page "/magazzino/giacenze" +@attribute [Authorize] +@using Khaemhat.Application.Inventory +@using Khaemhat.Application.Items +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Inventory +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@inject ShellSession Session +@inject InventoryService Inventory +@inject ItemService Items +@inject TableService Tables +@inject ToastService Toasts +@inject DialogService Dialogs +@inject TimeProvider Clock + +@* Stock and availability (SPEC §11.6, mockup 036): every stocked item with on hand, committed, ordered and available, + its thresholds and, for who may see costs, the average cost and the value; the state under the thresholds. One + warehouse or all together. The movements of an item with their running balance; the value at a date with the ABC + classes; the rebuild of the warehouse from its documents. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(InventoryService.StockPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + + + + + + + @T["Shell.Menu.Inventory.Reorder"] + @T["Shell.Menu.Inventory.StockTake"] + @if (_costs) + { + + } + @if (Session.Permissions.Allows(InventoryService.PostPermission)) + { + + } + + + + @if (_rebuild is { } progress) + { +
+ + @T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total)) +
+ } + + + + @if (_balances is { Count: > 1 }) + { + + } + @if (_movements is null) + { +

@T["Common.Loading"]

+ } + else if (_movements.Count == 0) + { +

@T["Inventory.Movements.None"]

+ } + else + { +
+ + + + + + + + + + @if (_costs) + { + + } + + + + + @foreach (var move in _movements) + { + + + + + + + + @if (_costs) + { + + } + + + } + +
@T["Inventory.Movements.Date"]@T["Inventory.Movements.Document"]@T["Inventory.Fields.Reason"]@T["Inventory.Movements.Party"]@T["Inventory.Fields.Warehouse"]@T["Inventory.Movements.Quantity"]@T["Inventory.Movements.UnitCost"]@T["Inventory.Movements.Balance"]
@T.Date(move.Date) + @if (move.Kind is { } kind && move.DocumentId is { } document) + { + @T["Sales.Kinds." + kind] @move.Number + } + @move.ReasonCode@move.PartyName@PartyScreens.Describe(_warehouses, move.WarehouseId)@Qty(move.Quantity)@Cost(move.UnitCost)@Qty(move.Balance)
+
+ } +
+ +
+ + + + + + +
+ +
+
+ @if (_valuation is { } rows) + { + +
+ + + + + + + + + + + + + @foreach (var row in rows) + { + + + + + + + + + } + +
@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Inventory.Movements.Quantity"]@T["Inventory.Movements.UnitCost"]@T["Inventory.Stock.Value"]@T["Inventory.Valuation.Class"]
@row.Code@row.Description@Qty(row.Quantity)@T.Money(row.UnitCost)@T.Money(row.Value)@row.AbcClass
+
+ } +

@T["Inventory.Valuation.Hint"]

+
+
+ +
+
+} + +@code { + private static readonly ListFields Fields = new ListFields() + .Add("code", r => r.Code, searchable: true) + .Add("description", r => r.Description, searchable: true) + .Add("category", r => r.CategoryId) + .Add("unit", r => r.UnitOfMeasureId) + .Add("onHand", r => r.OnHand) + .Add("committed", r => r.Committed) + .Add("ordered", r => r.Ordered) + .Add("available", r => r.Available) + .Add("minimum", r => r.MinimumStock) + .Add("reorderPoint", r => r.ReorderPoint) + .Add("averageCost", r => r.AverageCost) + .Add("value", r => r.Value, total: true) + .Add("lastLoad", r => r.LastLoad) + .Add("lastUnload", r => r.LastUnload) + .Add("level", r => r.Level) + .OrderByDefault(new ListSort("code")); + + private InMemoryListSource _source = new([], Fields); + private IReadOnlyList _rows = []; + private ItemLookups _lookups = ItemLookups.Empty; + private IReadOnlyList> _warehouses = []; + private KhRadar? _radar; + private long? _warehouse; + private bool _includeEmpty; + private bool _costs; + private bool _loaded; + private bool _busy; + private RebuildProgress? _rebuild; + + private StockRow? _item; + private IReadOnlyList? _movements; + private IReadOnlyList? _balances; + + private bool _valuationOpen; + private DateOnly? _valuationDate; + private StockValuationMethod _method = StockValuationMethod.WeightedAverage; + private IReadOnlyList? _valuation; + + /// An item to open at once, from the dashboard. + [SupplyParameterFromQuery(Name = "articolo")] + public long? ItemId { get; set; } + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private IReadOnlyList Stats => + [ + new(T["Inventory.Stock.Items"], T.Number(_rows.Count(r => r.OnHand != 0m))), + new(T["Inventory.Stock.Understock"], T.Number(_rows.Count(r => r.Level is StockLevel.Understock or StockLevel.Reorder)), + _rows.Any(r => r.Level is StockLevel.Understock or StockLevel.Reorder) ? KhTone.Warning : KhTone.Neutral), + new(T["Inventory.Stock.Out"], T.Number(_rows.Count(r => r.Level == StockLevel.Out)), _rows.Any(r => r.Level == StockLevel.Out) ? KhTone.Error : KhTone.Neutral), + new(T["Inventory.Stock.Ordered"], T.Number(_rows.Count(r => r.Ordered > 0m))), + .. _costs ? [new KhStat(T["Inventory.Stock.TotalValue"], T.Money(_rows.Sum(r => r.Value ?? 0m)))] : Array.Empty(), + ]; + + private IReadOnlyList BalanceStats => _balances is null ? [] : + [.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))]; + + private IReadOnlyList ValuationStats => _valuation is null ? [] : + [ + new(T["Inventory.Stock.Items"], T.Number(_valuation.Count)), + new(T["Inventory.Stock.TotalValue"], T.Money(_valuation.Sum(r => r.Value))), + new(T["Inventory.Valuation.ClassA"], T.Number(_valuation.Count(r => r.AbcClass == 'A'))), + new(T["Inventory.Valuation.ClassB"], T.Number(_valuation.Count(r => r.AbcClass == 'B'))), + new(T["Inventory.Valuation.ClassC"], T.Number(_valuation.Count(r => r.AbcClass == 'C'))), + ]; + + private IReadOnlyList> Methods => + [ + new(nameof(StockValuationMethod.WeightedAverage), T["Inventory.Valuation.Methods.WeightedAverage"]), + new(nameof(StockValuationMethod.LastCost), T["Inventory.Valuation.Methods.LastCost"]), + new(nameof(StockValuationMethod.StandardCost), T["Inventory.Valuation.Methods.StandardCost"]), + ]; + + private string MovementsTitle => _item is { } item ? item.Code + " · " + item.Description : T["Inventory.Movements.Title"]; + + private IReadOnlyList> Columns => + [ + new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" }, + new("description", T["Items.Fields.Description"], r => r.Description), + new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" }, + new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "50px" }, + new("onHand", T["Inventory.Stock.OnHand"], r => r.OnHand) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, + new("committed", T["Inventory.Stock.Committed"], r => r.Committed) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, + new("ordered", T["Inventory.Stock.OrderedColumn"], r => r.Ordered) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, + new("available", T["Inventory.Stock.Available"], r => r.Available) + { + Kind = KhColumnKind.Number, Decimals = 2, Width = "90px", CellClass = r => r.Available < 0m ? "err" : null, + }, + new("minimum", T["Inventory.Stock.Minimum"], r => r.MinimumStock) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px" }, + new("reorderPoint", T["Inventory.Stock.ReorderPoint"], r => r.ReorderPoint) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px", Visible = false }, + new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "100px", Visible = _costs, Export = _costs }, + new("value", T["Inventory.Stock.Value"], r => r.Value) { Kind = KhColumnKind.Money, Width = "110px", Visible = _costs, Export = _costs, Total = _costs }, + new("lastLoad", T["Inventory.Stock.LastLoad"], r => r.LastLoad) { Kind = KhColumnKind.Date, Width = "95px", Visible = false }, + new("lastUnload", T["Inventory.Stock.LastUnload"], r => r.LastUnload) { Kind = KhColumnKind.Date, Width = "95px", Visible = false }, + new("level", T["Items.Radar.State"], r => T["Inventory.Levels." + r.Level]) + { + Width = "120px", + Template = r => @@T["Inventory.Levels." + r.Level], + }, + ]; + + private IReadOnlyList QuickFilters => + [ + new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]), + new("level", T["Items.Radar.State"], + [ + new(string.Empty, T["Items.Radar.All"]), + .. Enum.GetValues().Select(l => new KhOption(l.ToString(), T["Inventory.Levels." + l])), + ]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission)) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + _warehouses = [.. (await Tables.ActiveAsync(actor, company)).Select(w => new KhOption(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))]; + _costs = await Items.CanSeeCostsAsync(actor, company); + _valuationDate = Today; + await LoadAsync(); + if (ItemId is { } id && _rows.FirstOrDefault(r => r.ItemId == id) is { } row) + { + await OpenMovementsAsync(row); + } + } + + _loaded = true; + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _rows = await Inventory.StockAsync(actor, company, new StockFilter { WarehouseId = _warehouse, IncludeEmpty = _includeEmpty }); + _source = new InMemoryListSource(_rows, Fields); + } + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => _source.QueryAsync(query, cancellationToken); + + private async Task ReloadAsync() + { + await LoadAsync(); + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + + private async Task SetWarehouseAsync(string? value) + { + _warehouse = PartyScreens.Id(value); + await ReloadAsync(); + } + + private async Task SetIncludeEmptyAsync(bool value) + { + _includeEmpty = value; + await ReloadAsync(); + } + + private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); + + private string Cost(decimal? value) => value is { } cost ? T.Money(cost) : string.Empty; + + private static KhTone ToneOf(StockLevel level) => level switch + { + StockLevel.Out => KhTone.Error, + StockLevel.Understock => KhTone.Warning, + StockLevel.Reorder => KhTone.Info, + _ => KhTone.Ok, + }; + + private static string? RowClassOf(StockRow row) => row.Level is StockLevel.Out or StockLevel.Understock ? "hl" : null; + + private async Task OpenMovementsAsync(StockRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _item = row; + _movements = null; + _balances = null; + if (!Session.Permissions.Allows(InventoryService.EntryReadPermission)) + { + _movements = []; + return; + } + + _balances = await Inventory.BalancesAsync(actor, company, row.ItemId); + _movements = await Inventory.MovementsAsync(actor, company, row.ItemId, _warehouse, null, null); + } + + private void OpenValuation() + { + _valuation = null; + _valuationOpen = true; + } + + private void SetMethod(string? value) => + _method = Enum.TryParse(value, out var method) ? method : StockValuationMethod.WeightedAverage; + + private async Task ValueAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _valuationDate is not { } date) + { + return; + } + + _busy = true; + try + { + _valuation = await Inventory.ValuationAsync(actor, company, date, _warehouse, _method); + } + finally + { + _busy = false; + } + } + + private async Task RebuildAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(T["Inventory.Rebuild.Title"], T["Inventory.Rebuild.Text"], T["Inventory.Rebuild.Action"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + var progress = new Progress(p => + { + _rebuild = p; + _ = InvokeAsync(StateHasChanged); + }); + try + { + var (documents, items) = await Task.Run(() => Inventory.RebuildAsync(actor, company, progress)); + Toasts.Show(ToastKind.Success, T.Format("Inventory.Rebuild.Done", T.Number(documents), T.Number(items))); + await ReloadAsync(); + } + finally + { + _busy = false; + _rebuild = null; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor b/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor new file mode 100644 index 0000000..a55016e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor @@ -0,0 +1,524 @@ +@page "/magazzino/inventario" +@page "/magazzino/inventario/{Id:long}" +@attribute [Authorize] +@using Khaemhat.Application.Documents +@using Khaemhat.Application.Inventory +@using Khaemhat.Application.Items +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Documents +@using Khaemhat.Core.Inventory +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject StockTakeService StockTakes +@inject ItemService Items +@inject TableService Tables +@inject ToastService Toasts +@inject DialogService Dialogs +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The physical stock take (SPEC §11.6, mockup 038): opened on a warehouse at a date (and perhaps a category), it freezes + the book quantity and cost of each item; the counts are typed on the list or read from a scanner file; posting turns + the differences into gain and loss movements at the date of the count. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(InventoryService.EntryReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Id is null) +{ +
+
+ + @if (CanWrite) + { + + + + + +
+ +
+
+ } +

@T["Inventory.StockTake.Hint"]

+
+
+
+ + @if (_takes.Count == 0) + { +

@T["Inventory.StockTake.None"]

+ } + else + { +
+ + + + + + + + + + + @foreach (var take in _takes) + { + + + + + + + } + +
@T["Inventory.StockTake.Date"]@T["Inventory.StockTake.Description"]@T["Inventory.Fields.Warehouse"]@T["Items.Radar.State"]
@T.Date(take.TakeDate)@take.Description@PartyScreens.Describe(_warehouses, take.WarehouseId)@T["Inventory.StockTake.States." + take.Status]
+
+ } +
+
+
+} +else if (_view is null) +{ +

@T["Inventory.StockTake.Missing"]

@T["Inventory.StockTake.List"]

+} +else +{ + var take = _view.Take; +
+
+ + +
+
@T["Inventory.Fields.Warehouse"]
@PartyScreens.Describe(_warehouses, take.WarehouseId)
+
@T["Inventory.StockTake.Date"]
@T.Date(take.TakeDate)
+
@T["Items.Radar.Category"]
@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])
+
@T["Items.Radar.State"]
@T["Inventory.StockTake.States." + take.Status]
+ @if (take.Status == StockTakeStatus.Posted) + { +
@T["Inventory.StockTake.Movements"]
+
+ @if (take.AdjustmentDocumentId is { } gain) + { + @StockTakeService.GainReason + } + @if (take.LossDocumentId is { } loss) + { + @StockTakeService.LossReason + } +
+ } +
+ @if (IsOpen && CanWrite) + { +
+ +
+ } +
+
+
+ + + + + + @if (IsOpen && CanWrite) + { + + + @if (Session.Permissions.Allows(InventoryService.PostPermission)) + { + + } + } + + +
+ + + + + + + + + + @if (_costs) + { + + + } + + + + + @foreach (var line in Shown) + { + var id = line.Line.Id; + var counted = CountOf(line); + var difference = counted is { } c ? c - line.Line.BookQuantity : 0m; + + + + + + + + @if (_costs) + { + + + } + + + } + +
@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Items.Radar.Unit"]@T["Inventory.StockTake.Book"]@T["Inventory.StockTake.Counted"]@T["Inventory.StockTake.Difference"]@T["Inventory.Movements.UnitCost"]@T["Inventory.StockTake.DifferenceValue"]@T["Items.Radar.State"]
@line.Code@line.Description@PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId)@Qty(line.Line.BookQuantity) + @if (IsOpen && CanWrite) + { + + } + else + { + @(counted is { } v ? Qty(v) : "—") + } + 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))@T.Money(line.Line.UnitCost)@(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2))) + @if (counted is null) + { + @T["Inventory.StockTake.ToCount"] + } + else if (difference == 0m) + { + @T["Inventory.StockTake.Matches"] + } + else + { + @T["Inventory.StockTake.Differs"] + } +
+
+
+
+
+
+} + +@code { + private readonly KhValidation _validation = new(); + private readonly Dictionary _counts = []; + private IReadOnlyList _takes = []; + private IReadOnlyList> _warehouses = []; + private ItemLookups _lookups = ItemLookups.Empty; + private StockTakeView? _view; + private long? _warehouse; + private long? _category; + private DateOnly? _date; + private string? _description; + private string? _search; + private string _show = string.Empty; + private bool _costs; + private bool _loaded; + private bool _busy; + + /// The stock take shown, or none for the list. + [Parameter] + public long? Id { get; set; } + + private string Title => _view?.Take.Description is { } description && Id is not null ? description : T["Inventory.StockTake.Title"]; + + private bool CanWrite => Session.Permissions.Allows("inventory.entry.write"); + + private bool IsOpen => _view?.Take.Status == StockTakeStatus.Open; + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private IReadOnlyList Steps => + [ + new(T["Inventory.StockTake.Steps.Open"], T["Inventory.StockTake.Steps.OpenDetail"]), + new(T["Inventory.StockTake.Steps.Count"], T["Inventory.StockTake.Steps.CountDetail"]), + new(T["Inventory.StockTake.Steps.Check"], T["Inventory.StockTake.Steps.CheckDetail"]), + new(T["Inventory.StockTake.Steps.Post"], T["Inventory.StockTake.Steps.PostDetail"]), + ]; + + private int Step => _view is null ? 0 : _view.Take.Status != StockTakeStatus.Open ? 4 : Counted == 0 ? 1 : Counted < _view.Lines.Count ? 1 : 2; + + private int Counted => _view?.Lines.Count(l => CountOf(l) is not null) ?? 0; + + private IReadOnlyList Stats + { + get + { + if (_view is null) + { + return []; + } + + var counted = _view.Lines.Where(l => CountOf(l) is not null).ToList(); + var differences = counted.Where(l => CountOf(l) != l.Line.BookQuantity).ToList(); + var value = differences.Sum(l => Math.Round((CountOf(l)!.Value - l.Line.BookQuantity) * l.Line.UnitCost, 2)); + return + [ + new(T["Inventory.StockTake.Items"], T.Number(_view.Lines.Count)), + new(T["Inventory.StockTake.CountedItems"], T.Number(counted.Count), counted.Count == _view.Lines.Count ? KhTone.Ok : KhTone.Neutral), + new(T["Inventory.StockTake.Differences"], T.Number(differences.Count), differences.Count > 0 ? KhTone.Warning : KhTone.Neutral), + .. _costs ? [new KhStat(T["Inventory.StockTake.DifferenceValue"], T.Money(value), value < 0m ? KhTone.Error : KhTone.Neutral)] : Array.Empty(), + ]; + } + } + + private IEnumerable Shown => (_view?.Lines ?? []).Where(l => + (string.IsNullOrWhiteSpace(_search) + || l.Code.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase) + || l.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase)) + && _show switch + { + "todo" => CountOf(l) is null, + "diff" => CountOf(l) is { } c && c != l.Line.BookQuantity, + _ => true, + }); + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.EntryReadPermission)) + { + if (!_loaded) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + _warehouses = [.. (await Tables.ActiveAsync(actor, company)).Select(w => new KhOption(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))]; + _warehouse = await DefaultWarehouseAsync(actor, company); + _costs = await Items.CanSeeCostsAsync(actor, company); + _date = Today; + } + + _counts.Clear(); + if (Id is { } id) + { + _view = await StockTakes.GetAsync(actor, company, id); + } + else + { + _view = null; + _takes = await StockTakes.ListAsync(actor, company); + } + } + + _loaded = true; + } + + private async Task DefaultWarehouseAsync(Actor actor, string company) => + (await Tables.ActiveAsync(actor, company)).OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; + + private decimal? CountOf(StockTakeLineView line) => _counts.TryGetValue(line.Line.Id, out var count) ? count : line.Line.CountedQuantity; + + private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); + + private static KhTone ToneOf(StockTakeStatus status) => status switch + { + StockTakeStatus.Posted => KhTone.Ok, + StockTakeStatus.Cancelled => KhTone.Neutral, + _ => KhTone.Info, + }; + + private void SetCount(long lineId, string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + _counts[lineId] = null; + return; + } + + if (decimal.TryParse(text.Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value) && value >= 0m) + { + _counts[lineId] = value; + } + else + { + Toasts.Show(ToastKind.Error, T["inventory.stock-take.negative"]); + } + } + + private async Task CreateAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _warehouse is not { } warehouse || _date is not { } date) + { + return; + } + + _busy = true; + try + { + var view = await StockTakes.CreateAsync(actor, company, warehouse, date, _category, _description); + Toasts.Show(ToastKind.Success, T.Format("Inventory.StockTake.Opened", view.Lines.Count)); + Navigation.NavigateTo("magazzino/inventario/" + view.Take.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + finally + { + _busy = false; + } + } + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id || _counts.Count == 0) + { + return; + } + + _busy = true; + try + { + _view = await StockTakes.SaveCountsAsync(actor, company, id, _counts); + _counts.Clear(); + Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Saved"]); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + finally + { + _busy = false; + } + } + + private async Task ImportAsync(InputFileChangeEventArgs e) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) + { + return; + } + + _busy = true; + try + { + if (_counts.Count > 0) + { + await StockTakes.SaveCountsAsync(actor, company, id, _counts); + _counts.Clear(); + } + + using var buffer = new MemoryStream(); + await using (var stream = e.File.OpenReadStream(5 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + buffer.Position = 0; + var result = await StockTakes.ImportCountsAsync(actor, company, id, buffer); + _view = await StockTakes.GetAsync(actor, company, id); + Toasts.Show(result.Unknown.Count == 0 ? ToastKind.Success : ToastKind.Warning, + T.Format("Inventory.StockTake.Imported", result.Applied, result.Unknown.Count) + (result.Unknown.Count == 0 ? string.Empty : " " + string.Join(", ", result.Unknown.Take(5)))); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + catch (IOException) + { + Toasts.Show(ToastKind.Error, T["Inventory.StockTake.FileTooLarge"]); + } + finally + { + _busy = false; + } + } + + private async Task PostAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.PostTitle"], T["Inventory.StockTake.PostText"], T["Inventory.StockTake.Post"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + if (_counts.Count > 0) + { + await StockTakes.SaveCountsAsync(actor, company, id, _counts); + _counts.Clear(); + } + + _view = await StockTakes.PostAsync(actor, company, id); + Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Posted"]); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + catch (InvalidDocumentActionException) + { + Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); + } + finally + { + _busy = false; + } + } + + private async Task CancelAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.CancelTitle"], T["Inventory.StockTake.CancelText"], T["Inventory.StockTake.Cancel"], T["Common.Back"], Danger: true))) + { + return; + } + + await StockTakes.CancelAsync(actor, company, id); + _view = await StockTakes.GetAsync(actor, company, id); + } + + private void ShowErrors(ValidationFailedException ex) => + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); +} diff --git a/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor new file mode 100644 index 0000000..3196542 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor @@ -0,0 +1,384 @@ +@page "/acquisti/importa-fatture" +@attribute [Authorize] +@using Khaemhat.Application.Purchases +@using Khaemhat.Fiscal.Abstractions +@using Khaemhat.Web.Documents +@inject ShellSession Session +@inject PurchaseInvoiceImportService Import +@inject ToastService Toasts + +@* The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files; each invoice shows its + supplier (known or to add), number, date, total and what to check; the chosen ones become draft supplier invoices or + credit notes with the file attached. The invoice can be read as a page before registering it. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(PurchaseService.WritePermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ +
+
+ + +
+
+ + + @T["Purchases.Import.FilesHint"] +
+
+
+
+
+ @if (_results.Count > 0) + { + +
+ + + + + + + + + + + @foreach (var result in _results) + { + + + + @if (result.Record is { } record) + { + + + } + else + { + + } + + } + +
@T["Purchases.Fields.Supplier"]@T["Purchases.Fields.SupplierNumber"]@T["Purchases.Import.Draft"]@T["Purchases.Import.Check"]
+ @result.Candidate.File.Supplier.DisplayName + @if (result.SupplierCreated) + { + @T["Purchases.Import.NewSupplier"] + } + @result.Candidate.Invoice.Number@T["Sales.Kinds." + record.Header.Kind] · @T.Money(record.Header.TotalAmount)@string.Join(" ", result.Warnings.Select(w => T[w])) @(T.Contains(result.Error ?? string.Empty) ? T[result.Error!] : result.Error)
+
+
+ @T["Sales.Sections.PurchaseInvoices.Title"] + +
+
+ } + else + { + @if (_rejected.Count > 0) + { + + } + + + @T.Format("Purchases.Import.Selected", _selected.Count, T.Money(SelectedTotal)) + + + + @if (_invoices.Count == 0) + { +

@T["Purchases.Import.Start"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @for (var i = 0; i < _invoices.Count; i++) + { + var index = i; + var invoice = _invoices[i]; + + + + + + + + + + + + } + +
@T["Purchases.Fields.Supplier"]@T["Purchases.Import.VatNumber"]@T["Purchases.Import.Type"]@T["Purchases.Fields.SupplierNumber"]@T["Purchases.Fields.SupplierDate"]@T["Sales.Totals.Total"]@T["Purchases.Import.Check"]@T["Purchases.Import.View"]
+ + + @invoice.File.Supplier.DisplayName + @if (invoice.SupplierId is null) + { + @T["Purchases.Import.NewSupplier"] + } + @(invoice.File.Supplier.CountryCode)@invoice.File.Supplier.VatNumber@invoice.Invoice.DocumentType @(invoice.DocumentTypeCode is { } code ? "→ " + code : null)@invoice.Invoice.Number@T.Date(invoice.Invoice.Date)@T.Money(invoice.Total) + @if (invoice.Problems.Count == 0) + { + @T["Purchases.Import.Ready"] + } + @foreach (var problem in invoice.Problems) + { + @T[problem + ".short"] + } +
+
+ } +
+
+ } +
+
+ + + + @if (_shown is { } shown) + { + var supplier = shown.File.Supplier; + var invoice = shown.Invoice; +
+
+
@T["Purchases.Fields.Supplier"]
+
@supplier.DisplayName
@supplier.Address @supplier.StreetNumber, @supplier.PostalCode @supplier.City @(supplier.Province is null ? null : "(" + supplier.Province + ")")
+
@T["Purchases.Import.VatNumber"]
@supplier.CountryCode@supplier.VatNumber @(supplier.TaxCode is null ? null : " · " + supplier.TaxCode)
+
@T["Purchases.Import.Type"]
@invoice.DocumentType · @invoice.Currency
+
@T["Purchases.Fields.SupplierNumber"]
@invoice.Number · @T.Date(invoice.Date)
+ @if (invoice.Causals.Count > 0) + { +
@T["Purchases.Import.Causal"]
@string.Join(" ", invoice.Causals)
+ } + @if (shown.File.Signature is { } signature) + { +
@T["Purchases.Import.Signature"]
+
+ @T[signature.Verified ? "Purchases.Import.SignatureOk" : "Purchases.Import.SignatureKo"] + @signature.Signer +
+ } +
+
+ + + + + + + + + + + + + + @foreach (var line in invoice.Lines) + { + + + + + + + + + + } + +
#@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Inventory.Movements.Quantity"]@T["Inventory.Reorder.Price"]@T["Sales.Totals.Taxable"]@T["Purchases.Import.Rate"]
@line.Number@string.Join(" ", line.Codes.Select(c => c.Value))@line.Description@(line.Quantity is { } q ? q.ToString("#,##0.###", T.Culture) + " " + line.Unit : null)@T.Money(line.UnitPrice)@T.Money(line.TotalPrice)@(line.Nature ?? line.TaxRate.ToString("0.##", T.Culture) + "%")
+
+ + @if (invoice.Payments.Count > 0) + { +
    + @foreach (var payment in invoice.Payments) + { +
  • @T["Purchases.Import.Payment"] @(payment.DueDate is { } due ? T.Date(due) : null) · @T.Money(payment.Amount) @(payment.Iban is null ? null : " · " + payment.Iban)
  • + } +
+ } +
+ } +
+
+ +
+
+} + +@code { + private readonly HashSet _selected = []; + private List _invoices = []; + private List _rejected = []; + private List _results = []; + private IncomingCandidate? _shown; + private bool _loaded; + private bool _busy; + private int _step; + + private IReadOnlyList Steps => + [ + new(T["Purchases.Import.Steps.Load"], T["Purchases.Import.Steps.LoadDetail"]), + new(T["Purchases.Import.Steps.Check"], T["Purchases.Import.Steps.CheckDetail"]), + new(T["Purchases.Import.Steps.Register"], T["Purchases.Import.Steps.RegisterDetail"]), + ]; + + private IEnumerable Importable => Enumerable.Range(0, _invoices.Count).Where(i => _invoices[i].CanImport); + + private decimal SelectedTotal => _selected.Sum(i => _invoices[i].Total); + + private string ShownTitle => _shown is { } shown ? shown.File.Supplier.DisplayName + " · " + shown.Invoice.Number : T["Purchases.Import.View"]; + + private IReadOnlyList SummaryOf(IncomingInvoice invoice) => + [ + new(T["Sales.Totals.Taxable"], T.Money(invoice.TaxSummary.Sum(t => t.Taxable))), + new(T["Sales.Totals.Tax"], T.Money(invoice.TaxSummary.Sum(t => t.Tax))), + new(T["Sales.Totals.Total"], T.Money(invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax))), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } + + private async Task ReadAsync(InputFileChangeEventArgs e) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var files = new List<(string, byte[])>(); + foreach (var file in e.GetMultipleFiles(200)) + { + using var buffer = new MemoryStream(); + await using (var stream = file.OpenReadStream(PurchaseInvoiceImportService.MaxFileSize)) + { + await stream.CopyToAsync(buffer); + } + + files.Add((file.Name, buffer.ToArray())); + } + + var reading = await Import.ReadAsync(actor, company, files); + _invoices = [.. reading.Invoices]; + _rejected = [.. reading.Rejected]; + _results.Clear(); + _selected.Clear(); + _selected.UnionWith(Importable); + _step = _invoices.Count > 0 ? 1 : 0; + } + catch (IOException) + { + Toasts.Show(ToastKind.Error, T["Purchases.Import.TooLarge"]); + } + finally + { + _busy = false; + } + } + + private void Toggle(int index, bool on) + { + if (on) + { + _selected.Add(index); + } + else + { + _selected.Remove(index); + } + } + + private void ToggleAll(ChangeEventArgs e) + { + _selected.Clear(); + if (e.Value is true) + { + _selected.UnionWith(Importable); + } + } + + private async Task ImportAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + _results = [.. await Import.ImportAsync(actor, company, [.. _selected.Order().Select(i => _invoices[i])])]; + _step = 2; + var made = _results.Count(r => r.Record is not null); + Toasts.Show(made == _results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("Purchases.Import.Done", made, _results.Count)); + } + finally + { + _busy = false; + } + } + + private void Restart() + { + _results.Clear(); + _invoices.Clear(); + _rejected.Clear(); + _selected.Clear(); + _step = 0; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor index 240206d..e1e6485 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor @@ -6,6 +6,7 @@ @page "/magazzino/{Segment}/{Id:long}" @attribute [Authorize] @inherits DocumentPage +@using Khaemhat.Application.Purchases @using Khaemhat.Application.Audit @using Khaemhat.Application.Documents @using Khaemhat.Application.Items @@ -109,6 +110,28 @@ else @switch (ActiveTab) { case TabIds.Lines: + @if (_differences.Count > 0) + { +
+ @T.Format("Purchases.PriceDifferences.Summary", _differences.Count, T.Money(_differences.Sum(d => d.Amount))) + @foreach (var difference in _differences.Take(5)) + { +
@T.Format("Purchases.PriceDifferences.Line", difference.LineNumber, difference.Description, difference.SourceNumber ?? string.Empty, + T.Money(difference.SourcePrice), T.Money(difference.InvoicePrice)) + } +
+
+ } + @if (_selfAdvice is { } advice) + { +
+ @T.Format("Purchases.SelfInvoices.Advice", advice.DocumentTypeCode, advice.Reason, T.Date(advice.Deadline)) + @if (Session.Permissions.Allows(PurchaseService.WritePermission) && DocumentStateMachine.IsInForce(h.Status)) + { + + } +
+ } @if (h.PartyId is null && !IsReadOnly && !IsInternal) {
@T["Sales.Hints.PartyFirst"] diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs index 78fa0fd..d0eaa8e 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs @@ -5,12 +5,14 @@ using Khaemhat.Application.Files; using Khaemhat.Application.Items; using Khaemhat.Application.Localization; using Khaemhat.Application.Parties; +using Khaemhat.Application.Purchases; using Khaemhat.Application.Querying; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Common; using Khaemhat.Core.Documents; using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; using Khaemhat.Web.Components.Ui; using Khaemhat.Web.Documents; using Khaemhat.Web.Parties; @@ -34,6 +36,8 @@ public sealed partial class SalesDocumentPage private PartyRow? _party; private IReadOnlyList _actions = []; private IReadOnlyList _links = []; + private IReadOnlyList _differences = []; + private SelfInvoiceAdvice? _selfAdvice; private IReadOnlyList _history = []; private int _attachments; private bool _loaded; @@ -100,6 +104,9 @@ public sealed partial class SalesDocumentPage [Inject] private TimeProvider Clock { get; set; } = default!; + [Inject] + private PurchaseService Purchases { get; set; } = default!; + private DocumentHeader H => Record!.Header; private DocumentBehavior Behavior => DocumentBehaviors.Of(Record!.Header.Kind); @@ -315,16 +322,53 @@ public sealed partial class SalesDocumentPage _links = []; _history = []; _attachments = 0; + _differences = []; + _selfAdvice = null; return; } _links = await Editor.LinksAsync(actor, company, Record); + await LoadPurchaseChecksAsync(actor, company); _history = await Audit.HistoryAsync(actor, company, Record.Header.GetType().Name, Record.Header.Id.ToString(CultureInfo.InvariantCulture), Behavior.ReadPermission); _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) ? await Attachments.CountAsync(actor, company, AttachmentEntity, Record.Header.Id) : 0; } + // A supplier invoice: the prices that differ from its order or receipt, and the self-invoice it needs. + private async Task LoadPurchaseChecksAsync(Actor actor, string company) + { + _differences = []; + _selfAdvice = null; + if (Record is null || H.Kind != DocumentKind.PurchaseInvoice || !Session.Permissions.Allows(PurchaseService.ReadPermission)) + { + return; + } + + _differences = await Purchases.PriceDifferencesAsync(actor, company, Record); + _selfAdvice = _links.Any(l => l.Kind == DocumentKind.SelfInvoice && l.Status != DocumentStatus.Cancelled) + ? null + : await Purchases.AdviseAsync(actor, company, Record); + } + + private async Task CreateSelfInvoiceAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Record is null || _selfAdvice is not { } advice) + { + return; + } + + try + { + var self = await Purchases.CreateSelfInvoiceAsync(actor, company, H.Id, advice.DocumentTypeCode); + Navigation.NavigateTo(SalesScreens.RecordUrl(self.Header.Kind, self.Header.Id)!); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); + } + } + // ---- Head ------------------------------------------------------------------------------------------------------- private IReadOnlyList PartyLines diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor index c33ce9c..f234831 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor @@ -39,6 +39,10 @@ else if (!CanRead) } else { + @if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "autofatture") + { + + } @@ -51,6 +55,10 @@ else { @T["Sales.Deferred.Title"] } + @if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "fatture" && Session.Permissions.Allows("purchases.invoice.write")) + { + @T["Shell.Menu.Purchases.Import"] + } diff --git a/src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor b/src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor new file mode 100644 index 0000000..637600e --- /dev/null +++ b/src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor @@ -0,0 +1,98 @@ +@using Khaemhat.Application.Purchases +@using Khaemhat.Application.Security +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject PurchaseService Purchases +@inject ToastService Toasts +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The supplier invoices still waiting for their self-invoice (SPEC §11.5, mockup 035): reverse charge from Italian + suppliers, services and goods from abroad, San Marino; the type to issue, why, and the deadline. One click creates + the self-invoice as a draft. *@ +@if (_pending is { Count: > 0 } pending) +{ + + @T.Number(pending.Count) + +
+ + + + + + + + + + + + + + @foreach (var item in pending) + { + var row = item.Invoice; + + + + + + + + + + } + +
@T["Purchases.SelfInvoices.Invoice"]@T["Purchases.Fields.Supplier"]@T["Sales.Totals.Taxable"]@T["Purchases.SelfInvoices.Type"]@T["Purchases.SelfInvoices.Reason"]@T["Purchases.SelfInvoices.Deadline"]@T["Purchases.SelfInvoices.Create"]
@row.DocumentNumber · @T.Date(row.Date)@row.PartyName@T.Money(row.Taxable)@item.Advice.DocumentTypeCode@item.Advice.Reason@T.Date(item.Advice.Deadline) + @if (CanWrite) + { + + } +
+
+
+
+} + +@code { + private IReadOnlyList? _pending; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(PurchaseService.WritePermission); + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PurchaseService.ReadPermission)) + { + _pending = await Purchases.PendingSelfInvoicesAsync(actor, company); + } + } + + private async Task CreateAsync(PendingSelfInvoice item) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var self = await Purchases.CreateSelfInvoiceAsync(actor, company, item.Invoice.Id, item.Advice.DocumentTypeCode); + Navigation.NavigateTo(SalesScreens.RecordUrl(self.Header.Kind, self.Header.Id)!); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index d1de147..2e19bf2 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -148,6 +148,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -183,6 +184,8 @@ internal static class KhaemhatServices services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index 0972cd0..bc58caf 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -132,6 +132,7 @@ public static class SeedCommand // The demo documents go through the document engine, after the masters they use. await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); + await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json index ea07685..b09b36b 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -125,7 +125,10 @@ }, "Understock": { "Title": "Sottoscorta", - "Description": "Gli articoli sotto la scorta minima." + "Description": "Gli articoli sotto la scorta minima o il punto di riordino.", + "Empty": "Nessun articolo sotto scorta.", + "Line": "Disponibile {0}, scorta {1}", + "Reorder": "Apri la proposta di riordino" }, "Pipeline": { "Title": "Pipeline CRM", diff --git a/src/Khaemhat.Web/Resources/it-IT/ImportExport.json b/src/Khaemhat.Web/Resources/it-IT/ImportExport.json index d1f53ad..fae9415 100644 --- a/src/Khaemhat.Web/Resources/it-IT/ImportExport.json +++ b/src/Khaemhat.Web/Resources/it-IT/ImportExport.json @@ -220,7 +220,7 @@ "target": "Indica il listino oppure il cliente, non entrambi." }, "stock": { - "not-stocked": "L'articolo {0} non è merce gestita a magazzino." + "reason-missing": "Manca la causale di magazzino APE (esistenza iniziale): aggiornala da Tabelle azienda, Aggiorna tabelle di base." }, "write": { "failed": "Riga non scritta: il dato è cambiato nel frattempo o una regola l'ha rifiutata." diff --git a/src/Khaemhat.Web/Resources/it-IT/Inventory.json b/src/Khaemhat.Web/Resources/it-IT/Inventory.json index 3fd6ec1..48ccf2a 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Inventory.json +++ b/src/Khaemhat.Web/Resources/it-IT/Inventory.json @@ -12,6 +12,149 @@ }, "Hints": { "Movement": "La causale decide se il movimento carica, scarica o trasferisce; senza deposito vale quello dell’articolo." + }, + "NoCompany": "Scegli un'azienda per lavorare sul magazzino.", + "Levels": { + "Ok": "Disponibile", + "Reorder": "Da riordinare", + "Understock": "Sottoscorta", + "Out": "Esaurito" + }, + "Stock": { + "Title": "Giacenze e disponibilità", + "Search": "Cerca per codice o descrizione", + "AllWarehouses": "Tutti i depositi", + "IncludeEmpty": "Anche gli articoli senza giacenza", + "Items": "Articoli in giacenza", + "Understock": "Sottoscorta", + "Out": "Esauriti", + "Ordered": "Articoli in arrivo", + "TotalValue": "Valore di magazzino", + "OnHand": "Giacenza", + "Committed": "Impegnato", + "OrderedColumn": "Ordinato", + "Available": "Disponibile", + "Minimum": "Scorta min.", + "ReorderPoint": "Punto riordino", + "Value": "Valore", + "LastLoad": "Ultimo carico", + "LastUnload": "Ultimo scarico" + }, + "Movements": { + "Title": "Movimenti dell'articolo", + "ByWarehouse": "Giacenza per deposito", + "None": "Nessun movimento per questo articolo.", + "Date": "Data", + "Document": "Documento", + "Party": "Cliente o fornitore", + "Quantity": "Quantità", + "UnitCost": "Costo unitario", + "Balance": "Saldo", + "OpenItem": "Apri l'articolo" + }, + "Valuation": { + "Title": "Valorizzazione", + "Date": "Alla data", + "Method": "Criterio", + "Compute": "Calcola", + "Class": "Classe ABC", + "ClassA": "Classe A", + "ClassB": "Classe B", + "ClassC": "Classe C", + "Methods": { + "WeightedAverage": "Costo medio ponderato", + "LastCost": "Ultimo costo", + "StandardCost": "Costo standard" + }, + "Hint": "Classe A: gli articoli che fanno l'80% del valore; B fino al 95%; C il resto. FIFO e LIFO arriveranno con la contabilità di magazzino a lotti." + }, + "Rebuild": { + "Action": "Ricostruisci", + "Title": "Ricostruire il magazzino?", + "Text": "Tutti i movimenti vengono riscritti dai documenti in vigore e costi e giacenze ricalcolati. Su molti documenti può richiedere qualche minuto; i dati restano consultabili.", + "Progress": "Ricostruzione in corso: {0} {1} di {2}", + "Phases": { + "Documents": "documenti", + "Items": "articoli" + }, + "Done": "Magazzino ricostruito: {0} documenti, {1} articoli ricalcolati." + }, + "StockTake": { + "Title": "Inventario fisico", + "New": "Nuovo inventario", + "Open": "Apri inventario", + "Opened": "Inventario aperto con {0} articoli da contare.", + "Date": "Data del conteggio", + "Description": "Descrizione", + "DescriptionHint": "Vuota: deposito e data.", + "AllCategories": "Tutte le categorie", + "Hint": "L'inventario fotografa la giacenza contabile del deposito alla data scelta. Conta gli articoli, scrivi le quantità o importa il file del lettore, poi registra: le differenze diventano movimenti di rettifica INVP e INVN alla data del conteggio.", + "List": "Inventari", + "None": "Nessun inventario ancora.", + "Missing": "Questo inventario non esiste più.", + "Procedure": "Procedura", + "Movements": "Rettifiche", + "Lines": "Articoli da contare", + "Show": "Mostra", + "ShowAll": "Tutti", + "ShowToCount": "Da contare", + "ShowDifferences": "Con differenze", + "Import": "Importa conteggi", + "Save": "Salva conteggi", + "Saved": "Conteggi salvati.", + "Imported": "{0} articoli contati dal file, {1} codici non in lista.", + "FileTooLarge": "Il file è troppo grande: al massimo 5 MB.", + "Post": "Registra rettifiche", + "PostTitle": "Registrare l'inventario?", + "PostText": "Le differenze contate diventano movimenti di magazzino alla data del conteggio e l'inventario si chiude. Gli articoli non contati restano come sono.", + "Posted": "Inventario registrato.", + "Cancel": "Annulla inventario", + "CancelTitle": "Annullare l'inventario?", + "CancelText": "L'inventario si chiude senza muovere il magazzino; i conteggi restano consultabili.", + "Book": "Contabile", + "Counted": "Contato", + "Difference": "Differenza", + "DifferenceValue": "Valore differenze", + "ToCount": "Da contare", + "Matches": "Corrisponde", + "Differs": "Differenza", + "Items": "Articoli", + "CountedItems": "Contati", + "Differences": "Con differenze", + "States": { + "Open": "Aperto", + "Posted": "Registrato", + "Cancelled": "Annullato" + }, + "Steps": { + "Open": "Apertura", + "OpenDetail": "Deposito, data e categoria: giacenza contabile congelata.", + "Count": "Conteggio", + "CountDetail": "Quantità scritte o importate dal lettore.", + "Check": "Verifica differenze", + "CheckDetail": "Controlla gli scostamenti e il loro valore.", + "Post": "Registrazione", + "PostDetail": "Movimenti INVP e INVN alla data del conteggio." + } + }, + "Reorder": { + "Title": "Proposta di riordino", + "Lines": "Articoli da riordinare", + "None": "Nessun articolo da riordinare: le disponibilità coprono scorte minime e punti di riordino.", + "Selected": "{0} righe scelte, {1}", + "Refresh": "Ricalcola", + "Create": "Genera ordini fornitore", + "Created": "Ordini fornitore creati in bozza: {0}.", + "Quantity": "Da ordinare", + "Price": "Prezzo", + "Expected": "Arrivo previsto", + "ChooseSupplier": "Scegli il fornitore", + "MissingSupplier": "Le righe senza fornitore non vengono ordinate.", + "Items": "Articoli sotto il punto di riordino", + "Suppliers": "Fornitori coinvolti", + "Value": "Valore stimato", + "WithoutSupplier": "Senza fornitore", + "Hint": "La quantità proposta è il lotto di riordino dell'articolo, oppure quanto riporta al punto di riordino o alla scorta minima, almeno il minimo d'ordine del fornitore. Gli ordini nascono in bozza: controllali e confermali da Acquisti, Ordini fornitore." } }, "inventory": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Purchases.json b/src/Khaemhat.Web/Resources/it-IT/Purchases.json index faef5c5..2a62a3c 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Purchases.json +++ b/src/Khaemhat.Web/Resources/it-IT/Purchases.json @@ -10,11 +10,76 @@ "Hints": { "SupplierNumber": "Il numero scritto dal fornitore sulla sua fattura o sul DDT.", "VatDate": "Il mese in cui l’IVA entra in detrazione; vuota, vale la data di registrazione." + }, + "Import": { + "Title": "Importa fatture passive", + "Procedure": "Procedura", + "Files": "File da importare", + "FilesHint": "XML FatturaPA, file firmati .p7m o archivi ZIP che li contengono; anche più file insieme.", + "Invoices": "Fatture nei file", + "Start": "Carica i file ricevuti dallo SDI o dal tuo intermediario: le fatture appaiono qui per il controllo.", + "Selected": "{0} fatture scelte, {1}", + "Register": "Registra in bozza", + "Results": "Fatture registrate", + "Draft": "Documento in bozza", + "Check": "Da controllare", + "NewSupplier": "Nuovo fornitore", + "VatNumber": "Partita IVA", + "Type": "Tipo", + "Ready": "Pronta", + "View": "Leggi", + "Causal": "Causale", + "Signature": "Firma", + "SignatureOk": "Firma verificata", + "SignatureKo": "Firma non verificata", + "Lines": "Righe della fattura", + "Rate": "IVA", + "Summary": "Riepilogo", + "Payment": "Pagamento", + "Rejected": "{0} file non letti", + "Done": "Registrate {0} fatture su {1}: controllale e confermale per protocollarle.", + "Again": "Importa altri file", + "TooLarge": "Un file supera la dimensione massima di 50 MB.", + "Steps": { + "Load": "Caricamento", + "LoadDetail": "XML, P7M o ZIP.", + "Check": "Controllo", + "CheckDetail": "Fornitore, duplicati e totali.", + "Register": "Registrazione", + "RegisterDetail": "Fatture in bozza con il file allegato." + } + }, + "SelfInvoices": { + "Pending": "Integrazioni da emettere", + "Invoice": "Fattura fornitore", + "Type": "Tipo", + "Reason": "Motivo", + "Deadline": "Entro il", + "Create": "Crea autofattura", + "Advice": "Serve un'autofattura {0}: {1}. Da emettere entro il {2}." + }, + "PriceDifferences": { + "Summary": "{0} righe hanno un prezzo diverso dall'ordine o dal ricevimento: differenza totale {1}.", + "Line": "Riga {0}, {1}: {2} a {3}, in fattura {4}." } }, "purchase": { "self-invoice": { "not-needed": "Per questa fattura non serve un'autofattura: il fornitore applica già l'IVA italiana." + }, + "import": { + "unsupported-type": "Questo tipo di documento non è un acquisto da registrare (per esempio un'autofattura emessa dall'azienda).", + "duplicate": "Fattura già registrata: lo stesso fornitore ha un documento con questo numero nello stesso anno.", + "total-mismatch": "Il totale indicato nel file non corrisponde alle righe: controlla la bozza prima di confermarla.", + "signature": "La firma del file non è stata verificata: controlla la provenienza.", + "document-discount": "Il file contiene sconti o maggiorazioni sul totale: riportali a mano nella bozza.", + "tax-code": "Nessun codice IVA dell'azienda ha l'aliquota o la natura di una riga: aggiungilo in Tabelle azienda, Codici IVA.", + "empty": "Nei file non ci sono fatture elettroniche.", + "unsupported-type.short": "Non è un acquisto", + "duplicate.short": "Già registrata", + "total-mismatch.short": "Totale diverso", + "signature.short": "Firma non verificata", + "document-discount.short": "Sconto sul totale" } }, "incoming": { diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 469eb44..6b513a0 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -159,6 +159,8 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .kh-tone { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--kh-text-3); } .kh-tone.ok { background: var(--kh-ok); } .kh-tone.info { background: var(--kh-info, var(--kh-accent)); } .kh-tone.warn { background: var(--kh-warn); } .kh-tone.err { background: var(--kh-err); } +.kh-wfoot { padding: 8px 12px; border-top: 1px solid var(--kh-border); font-size: 12.5px; } +.kh-wfoot a { display: inline-flex; align-items: center; gap: 6px; } .kh-status .li { padding: 7px 12px; } .kh-status .li .s { text-align: right; } .chk-row input[type="checkbox"] { margin: 0; accent-color: var(--kh-accent); } @@ -403,3 +405,15 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } /* The message of "Invia per e-mail" (issue #52): room for the whole text proposed by the template. */ .kh-mail-form textarea.in { min-height: 190px; } + +/* Warehouse (M6): filters above a radar, count boxes, file picker as a button, grids inside dialogs. */ +.kh-pagefilters { margin: 10px 0 4px; } +.kh-searchbox { width: 220px; } +.in.kh-countbox { width: 96px; height: 26px; text-align: right; } +.kh-filebtn { position: relative; overflow: hidden; cursor: pointer; } +.kh-filebtn input[type=file] { position: absolute; inset: 0; opacity: 0; cursor: pointer; } +.kh-dialoggrid { max-height: 52vh; overflow: auto; margin-top: 10px; } +.kh-cellpick { min-width: 220px; } +.kh-cellpick .f > label:empty { display: none; } +.kh-plainlist { margin: 4px 0 0; padding-left: 18px; } +.kh-pendingself { margin-bottom: 12px; } diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 69cc632..8e4321f 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -81,6 +81,7 @@ public sealed class MappingTests "sale_quotations", "sale_quotation_lines", "sale_orders", "sale_order_lines", "sale_documents", "sale_document_lines", "purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines", "document_links", "document_tax_summaries", "document_installments", + "inventory_entries", "inventory_entry_lines", "item_balances", "stock_takes", "stock_take_lines", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs b/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs index e97d3f5..ad513df 100644 --- a/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs +++ b/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs @@ -148,13 +148,14 @@ public sealed class ImportServiceTests } [TestMethod] - public async Task OpeningStock_IsOnlyChecked_UntilTheStockEntriesExist() + public async Task OpeningStock_LoadsTheWarehouse_WithAnOpeningMovement() { var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); await using (app) { var imports = app.Services.GetRequiredService(); var tables = app.Services.GetRequiredService(); + var stockService = app.Services.GetRequiredService(); await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" }); var items = Csv("codice;descrizione;categoria;tipo", "A-1;Valvola;VALV;merce", "S-1;Manodopera;VALV;servizio"); await imports.ImportAsync(Root, company, "articoli", items, ImportService.SuggestMapping(imports.Target("articoli"), items.Headers), new ImportOptions()); @@ -162,13 +163,16 @@ public sealed class ImportServiceTests var stock = Csv("articolo;deposito;quantita;costo_unitario", "A-1;;5;3,20", "S-1;;1;", "A-1;;0;", "B-9;;1;"); var mapping = ImportService.SuggestMapping(imports.Target("giacenze-iniziali"), stock.Headers); var preview = await imports.PreviewAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()); - Assert.IsFalse(preview.CanApply); + Assert.IsTrue(preview.CanApply); Assert.AreEqual(ImportOutcome.Ok, preview.Rows[0].Outcome, string.Join("; ", preview.Rows[0].Messages.Select(m => m.Field + ":" + m.Code))); Assert.AreEqual(ImportErrors.NotStocked, preview.Rows[1].Messages.Single().Code); CollectionAssert.Contains(preview.Rows[2].Messages.Select(m => m.Code).ToList(), ImportErrors.Positive); Assert.AreEqual(ImportErrors.CodeUnknown, preview.Rows[3].Messages.Single().Code); - var refused = await Assert.ThrowsExactlyAsync(() => imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions())); - Assert.AreEqual(ImportErrors.CheckOnly, refused.Code); + + var report = await imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()); + Assert.AreEqual(1, report.Created); + var row = (await stockService.StockAsync(Root, company, new Khaemhat.Application.Inventory.StockFilter())).Single(); + Assert.AreEqual((5m, 3.2m), (row.OnHand, row.AverageCost)); await app.StopAsync(); } } diff --git a/tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs b/tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs new file mode 100644 index 0000000..fd9f284 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs @@ -0,0 +1,74 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Purchases; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Security; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The demo purchases and warehouse (SPEC §14, issue #61): the opening stock, the orders, the receipts and the invoices +/// made through the engine, a self-invoice still to issue, items under their minimum and a stock take being counted. +/// +[TestClass] +public sealed class DemoPurchasesTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task DemoSeed_MakesPurchasesAndStock_Once() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await app.Services.GetRequiredService().RunAsync(company, SeedKind.Demo); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await app.Services.GetRequiredService().SeedAsync(company, context); + var seeder = app.Services.GetRequiredService(); + await seeder.SeedAsync(company, context); + + var editor = app.Services.GetRequiredService(); + var all = await AllAsync(editor, company); + int Count(DocumentKind kind, DocumentStatus status) => all.Count(r => r.Kind == kind && r.Status == status); + Assert.AreEqual(1, Count(DocumentKind.PurchaseOrder, DocumentStatus.Fulfilled), "One order received in full."); + Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.PurchaseOrder && r.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled), + "One order still partly on its way."); + Assert.AreEqual(2, all.Count(r => r.Kind == DocumentKind.PurchaseDeliveryNote)); + Assert.AreEqual(3, all.Count(r => r.Kind == DocumentKind.PurchaseInvoice && r.Status != DocumentStatus.Draft)); + Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.InventoryEntry)); + Assert.IsTrue(all.All(r => r.Date.Year == DateTime.Now.Year && r.Date <= DateOnly.FromDateTime(DateTime.Now)), "Dates of this year, never in the future."); + + // The German invoice waits for its self-invoice; the stock has items under the minimum to reorder. + var pending = await app.Services.GetRequiredService().PendingSelfInvoicesAsync(Root, company); + Assert.HasCount(1, pending); + var inventory = app.Services.GetRequiredService(); + Assert.IsNotEmpty(await inventory.StockAsync(Root, company, new StockFilter())); + Assert.IsNotEmpty(await app.Services.GetRequiredService().ProposalsAsync(Root, company)); + var take = (await app.Services.GetRequiredService().ListAsync(Root, company)).Single(); + Assert.AreEqual(StockTakeStatus.Open, take.Status); + + // Run again, nothing changes. + await seeder.SeedAsync(company, context); + Assert.HasCount(all.Count, await AllAsync(editor, company)); + await app.StopAsync(); + } + } + + private static async Task> AllAsync(DocumentEditor editor, string company) + { + var all = new List(); + foreach (var family in new[] { DocumentFamily.PurchaseOrder, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument }) + { + all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues()], new ListQuery { Limit = 200 })).Items); + } + + return all; + } +} diff --git a/tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs b/tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs new file mode 100644 index 0000000..9ab6512 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs @@ -0,0 +1,170 @@ +using System.IO.Compression; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Purchases; +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Files; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The import of supplier e-invoices on a real instance (issue #57): the supplier is added from the file, the items found +/// by code, the tax codes by rate and nature; the draft keeps the file; the same invoice is not registered twice; a ZIP +/// holds several files. +/// +[TestClass] +public sealed class PurchaseImportTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + private static string Invoice(string type, string number, string date, string lines, string summary, string total) => $""" + + + + + IT01234567897 + 00042FPR120000000 + + + + IT01234567897 + Ferramenta Piemontese S.r.l. + RF01 + + Via Roma1210121TorinoTOIT + + + + IT02987654304 + Azienda di prova + + Corso Milano20121MilanoMIIT + + + + + + {type}EUR{date}{number} + {total}Fornitura di marzo + + + {lines}{summary} + + + """; + + private const string Lines = """ + + 1 + SKUVALV-01 + Valvola a sfera 1/210.00PZ4.000000 + SC10.00 + 36.0022.00 + + + 2Spese di trasporto15.0015.0022.00 + + """; + + private const string Summary = """ + 22.0051.0011.22I + """; + + [TestMethod] + public async Task Import_AddsTheSupplier_MatchesItemsAndTaxes_AndRefusesTheSameInvoiceTwice() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var import = app.Services.GetRequiredService(); + var engine = app.Services.GetRequiredService(); + var attachments = app.Services.GetRequiredService(); + var parties = app.Services.GetRequiredService(); + var item = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null); + var year = DateTime.Now.Year; + var xml = Encoding.UTF8.GetBytes(Invoice("TD01", "FT/123", $"{year}-03-15", Lines, Summary, "62.22")); + + var reading = await import.ReadAsync(Root, company, [("IT01234567897_00042.xml", xml)]); + Assert.IsEmpty(reading.Rejected); + var candidate = reading.Invoices.Single(); + Assert.AreEqual(("FF", null, false, 62.22m), (candidate.DocumentTypeCode, candidate.SupplierId, candidate.Duplicate, candidate.ComputedTotal)); + Assert.IsEmpty(candidate.Problems); + + var done = (await import.ImportAsync(Root, company, reading.Invoices)).Single(); + Assert.IsNull(done.Error); + Assert.IsTrue(done.SupplierCreated); + Assert.IsEmpty(done.Warnings); + var record = done.Record!; + Assert.AreEqual((DocumentKind.PurchaseInvoice, DocumentStatus.Draft, "FT/123", new DateOnly(year, 3, 15)), + (record.Header.Kind, record.Header.Status, record.Header.ExternalReference, record.Header.ExternalDate)); + Assert.AreEqual(62.22m, record.Header.TotalAmount); + var valve = record.Lines.Single(l => l.Kind == DocumentLineKind.Item); + Assert.AreEqual((item, 10m, 4m, "10"), (valve.ItemId!.Value, valve.Quantity, valve.Price, valve.DiscountFormula)); + Assert.AreEqual(DocumentLineKind.Free, record.Lines.Single(l => l.Description == "Spese di trasporto").Kind); + var supplier = (await parties.GetAsync(Root, company, record.Header.PartyId!.Value))!.Party; + Assert.AreEqual(("Ferramenta Piemontese S.r.l.", "01234567897", PartyKind.Supplier, "Torino", "TO"), + (supplier.Name, supplier.VatNumber, supplier.Kind, supplier.City, supplier.Province)); + var files = await attachments.ListAsync(Root, company, DocumentPrintService.EntityOf(DocumentFamily.PurchaseDocument), record.Header.Id); + Assert.AreEqual((AttachmentKind.EInvoice, "IT01234567897_00042.xml"), (files.Single().Kind, files[0].FileName)); + + // The same file again: the supplier is known and the invoice is a duplicate. + var again = (await import.ReadAsync(Root, company, [("IT01234567897_00042.xml", xml)])).Invoices.Single(); + Assert.AreEqual((supplier.Id, true, false), (again.SupplierId!.Value, again.Duplicate, again.CanImport)); + CollectionAssert.Contains(again.Problems.ToArray(), PurchaseInvoiceImportService.DuplicateProblem); + + // A ZIP with a credit note, a self-invoice the company sent itself and a stray file. + var credit = Encoding.UTF8.GetBytes(Invoice("TD04", "NC/7", $"{year}-03-20", Lines, Summary, "62.22")); + var self = Encoding.UTF8.GetBytes(Invoice("TD17", "AF/1", $"{year}-03-21", Lines, Summary, "62.22")); + using var zip = new MemoryStream(); + using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) + { + await Add(archive, "nc.xml", credit); + await Add(archive, "af.xml", self); + await Add(archive, "leggimi.txt", Encoding.UTF8.GetBytes("nothing")); + } + + var zipped = await import.ReadAsync(Root, company, [("marzo.zip", zip.ToArray()), ("rotto.xml", Encoding.UTF8.GetBytes(""))]); + Assert.AreEqual("rotto.xml", zipped.Rejected.Single().FileName); + Assert.HasCount(2, zipped.Invoices); + var note = zipped.Invoices.Single(i => i.Invoice.Number == "NC/7"); + Assert.AreEqual(("NCF", supplier.Id), (note.DocumentTypeCode, note.SupplierId!.Value)); + var unsupported = zipped.Invoices.Single(i => i.Invoice.Number == "AF/1"); + Assert.IsFalse(unsupported.CanImport); + CollectionAssert.Contains(unsupported.Problems.ToArray(), PurchaseInvoiceImportService.UnsupportedType); + + var results = await import.ImportAsync(Root, company, zipped.Invoices); + Assert.AreEqual(DocumentKind.PurchaseCreditNote, results.Single(r => r.Candidate == note).Record!.Header.Kind); + Assert.AreEqual(PurchaseInvoiceImportService.UnsupportedType, results.Single(r => r.Candidate == unsupported).Error); + + // Confirmed, the imported invoice takes its protocol like one typed. + var confirmed = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, record.Header.Id); + Assert.IsNotNull(confirmed.Header.VatProtocol); + await app.StopAsync(); + } + } + + [TestMethod] + public void ItalianRules_RegisterInvoicesAndCreditNotes() + { + var rules = new Khaemhat.Fiscal.Italy.IncomingInvoiceRulesIt(); + Assert.AreEqual("FF", rules.DocumentTypeCode("TD01")); + Assert.AreEqual("FF", rules.DocumentTypeCode("td24")); + Assert.AreEqual("NCF", rules.DocumentTypeCode("TD04")); + Assert.IsNull(rules.DocumentTypeCode("TD17")); + Assert.IsInstanceOfType(rules); + } + + private static async Task Add(ZipArchive archive, string name, byte[] content) + { + await using var stream = archive.CreateEntry(name).Open(); + await stream.WriteAsync(content); + } +}