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 <noreply@anthropic.com>
This commit is contained in:
1 parent
eb301fa570
commit
ced689b297
31 files changed
+3478
-110
No files matched your search
@@ -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 |
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>): 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.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
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"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> 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<Item, long>().ListAsync(Query.For<Item>(), 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<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var seen = new HashSet<(long, long)>();
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted
|
||||
/// become one warehouse movement per warehouse with the reason <c>APE</c> (opening stock), confirmed at the day of the
|
||||
/// import: the stock and the average cost start from there.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
/// <param name="engine">Writes the movements.</param>
|
||||
/// <param name="clock">The day of the movements.</param>
|
||||
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget
|
||||
{
|
||||
/// <summary>The reason of the opening stock.</summary>
|
||||
public const string OpeningReason = "APE";
|
||||
|
||||
/// <summary>Error: the reason APE is missing.</summary>
|
||||
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"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
[.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> 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<InventoryReason, long>().FindAsync(Query.For<InventoryReason>().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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
|
||||
private async Task<List<(ImportRowResult Result, (Item Item, long WarehouseId, decimal Quantity, decimal Cost)? Stock)>> ReadAsync(
|
||||
ImportContext context, IReadOnlyList<ImportRow> 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<Item, long>().ListAsync(Query.For<Item>(), 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<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var fallback = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().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<ImportMessage>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>An invoice found in a received file, as the import screen shows it before registering (mockup 034).</summary>
|
||||
/// <param name="FileName">The file (inside a ZIP, its entry).</param>
|
||||
/// <param name="File">The file as read.</param>
|
||||
/// <param name="Invoice">The invoice (a file may hold several).</param>
|
||||
/// <param name="DocumentTypeCode">The purchase document type that registers it, or none.</param>
|
||||
/// <param name="SupplierId">The supplier already in the archive, by VAT number or tax code.</param>
|
||||
/// <param name="Duplicate">Whether the supplier already has a document with this number in this year.</param>
|
||||
/// <param name="ComputedTotal">Taxable plus tax of the summary, plus rounding: what the total should be.</param>
|
||||
/// <param name="Problems">What stops or warns (resource codes).</param>
|
||||
public sealed record IncomingCandidate(
|
||||
string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
|
||||
IReadOnlyList<string> Problems)
|
||||
{
|
||||
/// <summary>Whether it can be registered.</summary>
|
||||
public bool CanImport => DocumentTypeCode is not null && !Duplicate;
|
||||
|
||||
/// <summary>The total in the file, or the computed one.</summary>
|
||||
public decimal Total => Invoice.Total ?? ComputedTotal;
|
||||
}
|
||||
|
||||
/// <summary>A file that could not be read.</summary>
|
||||
/// <param name="FileName">The file.</param>
|
||||
/// <param name="Error">Why (resource code).</param>
|
||||
public sealed record IncomingRejected(string FileName, string Error);
|
||||
|
||||
/// <summary>What the files hold.</summary>
|
||||
/// <param name="Invoices">The invoices found.</param>
|
||||
/// <param name="Rejected">The files not read.</param>
|
||||
public sealed record IncomingReading(IReadOnlyList<IncomingCandidate> Invoices, IReadOnlyList<IncomingRejected> Rejected);
|
||||
|
||||
/// <summary>An invoice registered, or why not.</summary>
|
||||
/// <param name="Candidate">The invoice.</param>
|
||||
/// <param name="Record">The draft document.</param>
|
||||
/// <param name="SupplierCreated">Whether the supplier was added to the archive.</param>
|
||||
/// <param name="Error">Why it was not registered (resource code).</param>
|
||||
/// <param name="Warnings">What to check on the draft (resource codes).</param>
|
||||
public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList<string> Warnings);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class PurchaseInvoiceImportService
|
||||
{
|
||||
/// <summary>The largest file accepted, ZIP included.</summary>
|
||||
public const int MaxFileSize = 50 * 1024 * 1024;
|
||||
|
||||
/// <summary>Problem: the type of the invoice is not a purchase (a self-invoice).</summary>
|
||||
public const string UnsupportedType = "purchase.import.unsupported-type";
|
||||
|
||||
/// <summary>Problem: already registered.</summary>
|
||||
public const string DuplicateProblem = "purchase.import.duplicate";
|
||||
|
||||
/// <summary>Warning: the total in the file differs from the lines.</summary>
|
||||
public const string TotalMismatch = "purchase.import.total-mismatch";
|
||||
|
||||
/// <summary>Warning: the signature of the file could not be verified.</summary>
|
||||
public const string SignatureNotVerified = "purchase.import.signature";
|
||||
|
||||
/// <summary>Warning: the discounts of the whole document are not carried to the lines.</summary>
|
||||
public const string DocumentDiscount = "purchase.import.document-discount";
|
||||
|
||||
/// <summary>Error: no tax code of the company has the rate and nature of a line.</summary>
|
||||
public const string TaxCodeMissing = "purchase.import.tax-code";
|
||||
|
||||
/// <summary>Error: the archive is empty of invoices.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The editor (terms of the supplier).</param>
|
||||
/// <param name="parties">The parties (new suppliers).</param>
|
||||
/// <param name="attachments">The attachments (the file).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Reads files: each XML or P7M, and those inside a ZIP.</summary>
|
||||
/// <param name="actor">Who imports: needs <c>purchases.invoice.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="files">The files, by name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The invoices found and the files not read.</returns>
|
||||
public async Task<IncomingReading> 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<IIncomingInvoiceReader>();
|
||||
var rules = pack.GetFeature<IIncomingInvoiceRules>();
|
||||
var found = new List<(string Name, IncomingInvoiceFile File)>();
|
||||
var rejected = new List<IncomingRejected>();
|
||||
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<IncomingCandidate>();
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="candidates">The invoices to register.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened to each.</returns>
|
||||
public async Task<IReadOnlyList<IncomingImported>> ImportAsync(
|
||||
Actor actor, string companyCode, IReadOnlyList<IncomingCandidate> 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<string, long>(StringComparer.OrdinalIgnoreCase);
|
||||
var result = new List<IncomingImported>();
|
||||
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<IncomingRejected> 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<long?> FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
|
||||
{
|
||||
var parties = uow.Repository<Party, long>();
|
||||
if (VatOf(party) is { } vat)
|
||||
{
|
||||
var bare = party.VatNumber!;
|
||||
var byVat = (await parties.ListAsync(Query.For<Party>().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<Party>().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<Party> 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<bool> 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<PurchaseDocument, long>().CountAsync(
|
||||
Query.For<PurchaseDocument>().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<long> 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<Country, long>().FindAsync(Query.For<Country>().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<string> 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<TaxCode, long>().ListAsync(Query.For<TaxCode>().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<ItemSupplier, long>().ListAsync(
|
||||
Query.For<ItemSupplier>().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<ItemBarcode, long>().ListAsync(
|
||||
Query.For<ItemBarcode>().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<Item, long>().ListAsync(
|
||||
Query.For<Item>().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<Item, long>().ListAsync(Query.For<Item>().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<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> 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<TaxCode> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The document editor (supplier terms, item costs).</param>
|
||||
/// <param name="copies">The transformations between documents.</param>
|
||||
/// <param name="stockTakes">The stock takes.</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 30;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<DemoData?> ReadAsync(string companyCode, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
if (await uow.Repository<PurchaseOrder, long>().CountAsync(Query.For<PurchaseOrder>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<PurchaseDocument, long>().CountAsync(Query.For<PurchaseDocument>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<InventoryDocument, long>().CountAsync(Query.For<InventoryDocument>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().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<Item, long>().ListAsync(Query.For<Item>().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<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => goodIds.Contains(s.ItemId)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.GroupBy(s => s.PartyId).ToDictionary(g => g.Key, g => (IReadOnlyList<long>)[.. g.Select(s => s.ItemId).Distinct()]);
|
||||
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(r => r.Code, r => r.Id, StringComparer.Ordinal);
|
||||
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var warehouse = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().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<string, long> Parties, IReadOnlyList<Item> Goods, IReadOnlyDictionary<long, IReadOnlyList<long>> 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<Item> 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<long, decimal?>();
|
||||
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<DocumentRecord> 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<DocumentRecord> ReceiveAsync(DocumentRecord order, DateOnly date, string reference, IReadOnlyCollection<long>? 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<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? 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<DocumentRecord> SaveAsync(DocumentRecord record)
|
||||
{
|
||||
record.Header.IsDemo = true;
|
||||
return owner.Engine.SaveAsync(Seed, company, record, cancellationToken);
|
||||
}
|
||||
|
||||
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
|
||||
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -267,3 +267,15 @@ public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal A
|
||||
/// <param name="Description">The description, if any.</param>
|
||||
/// <param name="Content">The decoded content.</param>
|
||||
public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public interface IIncomingInvoiceRules
|
||||
{
|
||||
/// <summary>The code of the document type that registers an invoice of this type of the format.</summary>
|
||||
/// <param name="formatType">The type in the file (TD01...).</param>
|
||||
/// <returns>The document type code, or none when the type is not registered as a purchase (a self-invoice).</returns>
|
||||
string? DocumentTypeCode(string formatType);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class IncomingInvoiceRulesIt : IIncomingInvoiceRules
|
||||
{
|
||||
private static readonly HashSet<string> Invoices = new(StringComparer.Ordinal) { "TD01", "TD02", "TD03", "TD05", "TD06", "TD24", "TD25", "TD26", "TD27" };
|
||||
private static readonly HashSet<string> CreditNotes = new(StringComparer.Ordinal) { "TD04", "TD08" };
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? DocumentTypeCode(string formatType)
|
||||
{
|
||||
var type = formatType?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||
return Invoices.Contains(type) ? "FF" : CreditNotes.Contains(type) ? "NCF" : null;
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
|
||||
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
|
||||
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
case WidgetIds.SystemStatus:
|
||||
<SystemStatusWidget Definition="Definition" />
|
||||
break;
|
||||
case WidgetIds.Understock:
|
||||
<UnderstockWidget Definition="Definition" />
|
||||
break;
|
||||
default:
|
||||
<ComingWidget Definition="Definition" />
|
||||
break;
|
||||
|
||||
@@ -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. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
|
||||
<Actions>
|
||||
@if (_rows is { Count: > 0 })
|
||||
{
|
||||
<span class="badge @(_rows.Any(r => r.Level == StockLevel.Out) ? "red" : "amber")">@T.Number(_rows.Count)</span>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_failed)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
|
||||
}
|
||||
else if (_rows is null)
|
||||
{
|
||||
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
|
||||
}
|
||||
else if (_rows.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Dashboard.Widgets.Understock.Empty"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list kh-wlist">
|
||||
@foreach (var row in _rows)
|
||||
{
|
||||
<a class="li" href="magazzino/giacenze?articolo=@row.ItemId">
|
||||
<span class="kh-tone @(row.Level == StockLevel.Out ? "err" : "warn")" aria-hidden="true"></span>
|
||||
<div class="grow">
|
||||
<div class="t"><span class="code">@row.Code</span> @row.Description</div>
|
||||
<div class="s">@T.Format("Dashboard.Widgets.Understock.Line", T.Number(row.Available), T.Number(row.MinimumStock ?? row.ReorderPoint ?? 0m))</div>
|
||||
</div>
|
||||
<span class="badge @(row.Level == StockLevel.Out ? "red" : "amber")">@T["Inventory.Levels." + row.Level]</span>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
<div class="kh-wfoot"><a href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Dashboard.Widgets.Understock.Reorder"]</a></div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhWidget>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<StockRow>? _rows;
|
||||
private bool _failed;
|
||||
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<KhOption<string>> TargetChoices => [.. Targets.Select(t => new KhOption<string>(t.Key, TargetName(t.Key)))];
|
||||
|
||||
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Inventory.Reorder.Title"]" Icon="refresh" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(InventoryService.StockPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhStrip Items="Stats" Label="@T["Inventory.Reorder.Title"]" />
|
||||
|
||||
@if (_orders.Count > 0)
|
||||
{
|
||||
<div class="callout ok kh-pad" role="status">
|
||||
<KhIcon Name="check-circle" />
|
||||
<span>
|
||||
@T.Format("Inventory.Reorder.Created", _orders.Count)
|
||||
@foreach (var order in _orders)
|
||||
{
|
||||
<span> </span><a href="@SalesScreens.RecordUrl(order.Record.Header.Kind, order.Record.Header.Id)">@order.Supplier</a>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<KhPanel Title="@T["Inventory.Reorder.Lines"]" Icon="list">
|
||||
<Actions>
|
||||
<span class="muted sm">@T.Format("Inventory.Reorder.Selected", Chosen.Count(), T.Money(ChosenValue))</span>
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="LoadAsync"><KhIcon Name="refresh" /> @T["Inventory.Reorder.Refresh"]</button>
|
||||
@if (CanOrder)
|
||||
{
|
||||
<button type="button" class="btn primary" disabled="@(_busy || !Chosen.Any())" @onclick="CreateAsync"><KhIcon Name="truck" /> @T["Inventory.Reorder.Create"]</button>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_lines.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Inventory.Reorder.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Inventory.Reorder.Lines"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" class="kh-check"><input type="checkbox" checked="@_lines.All(l => l.Chosen)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col">@T["Items.Radar.Unit"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.Available"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.OrderedColumn"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.Minimum"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.ReorderPoint"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Reorder.Quantity"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Reorder.Price"]</th>
|
||||
<th scope="col">@T["Inventory.Reorder.Expected"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in _lines)
|
||||
{
|
||||
var row = line.Proposal;
|
||||
<tr class="@(line.Chosen ? "sel" : null)">
|
||||
<td class="kh-check"><input type="checkbox" checked="@line.Chosen" aria-label="@row.Code" @onchange="e => line.Chosen = e.Value is true" /></td>
|
||||
<td class="code">@row.Code</td>
|
||||
<td>@row.Description</td>
|
||||
<td>@PartyScreens.Describe(_lookups.Units, row.UnitOfMeasureId)</td>
|
||||
<td class="num @(row.Available < 0m ? "err" : null)">@Qty(row.Available)</td>
|
||||
<td class="num">@Qty(row.Ordered)</td>
|
||||
<td class="num">@(row.MinimumStock is { } m ? Qty(m) : null)</td>
|
||||
<td class="num">@(row.ReorderPoint is { } p ? Qty(p) : null)</td>
|
||||
<td class="num">
|
||||
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.Reorder.Quantity"] + " " + row.Code)"
|
||||
value="@Qty(line.Quantity)" @onchange="e => SetQuantity(line, e.Value?.ToString())" />
|
||||
</td>
|
||||
<td class="kh-cellpick">
|
||||
<KhHotlink TItem="PartyRow" Name="@("Supplier" + row.ItemId)" Value="line.Supplier" ValueChanged="v => line.Supplier = v" Span="12"
|
||||
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Placeholder="@T["Inventory.Reorder.ChooseSupplier"]" />
|
||||
</td>
|
||||
<td class="num">@(row.Price is { } price ? T.Money(price) : null)</td>
|
||||
<td>@(row.ExpectedDate is { } date ? T.Date(date) : null)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
<p class="muted sm kh-pad">@T["Inventory.Reorder.Hint"]</p>
|
||||
}
|
||||
|
||||
@code {
|
||||
private List<Line> _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<Line> 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<KhStat> 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),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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<IReadOnlyList<PartyRow>> 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; }
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Inventory.Stock.Title"]" Icon="box" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(InventoryService.StockPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhStrip Items="Stats" Label="@T["Inventory.Stock.Title"]" />
|
||||
<KhForm Layout="KhFormLayout.Grid" Class="kh-pagefilters">
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="Warehouse" Options="_warehouses" Empty="@T["Inventory.Stock.AllWarehouses"]"
|
||||
Value="@PartyScreens.Text(_warehouse)" ValueChanged="SetWarehouseAsync" Span="4" />
|
||||
<KhCheck Label="@T["Inventory.Stock.IncludeEmpty"]" Name="IncludeEmpty" Value="_includeEmpty" ValueChanged="SetIncludeEmptyAsync" Span="4" />
|
||||
</KhForm>
|
||||
|
||||
<KhRadar TItem="StockRow" @ref="_radar" Id="stock" Columns="Columns" Source="ListAsync" KeyOf="r => r.ItemId" Selectable="false" OnOpen="OpenMovementsAsync"
|
||||
QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Inventory.Stock.Search"]" ExportName="giacenze" Label="@T["Inventory.Stock.Title"]">
|
||||
<Toolbar>
|
||||
<a class="btn" href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Shell.Menu.Inventory.Reorder"]</a>
|
||||
<a class="btn" href="magazzino/inventario"><KhIcon Name="file-check" /> @T["Shell.Menu.Inventory.StockTake"]</a>
|
||||
@if (_costs)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="OpenValuation"><KhIcon Name="euro" /> @T["Inventory.Valuation.Title"]</button>
|
||||
}
|
||||
@if (Session.Permissions.Allows(InventoryService.PostPermission))
|
||||
{
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="RebuildAsync"><KhIcon Name="layers" /> @T["Inventory.Rebuild.Action"]</button>
|
||||
}
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
|
||||
@if (_rebuild is { } progress)
|
||||
{
|
||||
<div class="callout info kh-pad" role="status">
|
||||
<KhIcon Name="layers" />
|
||||
<span>@T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total))</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<KhDialog Open="_item is not null" Title="@MovementsTitle" Icon="layers" Size="lg" OnClose="() => _item = null">
|
||||
<ChildContent>
|
||||
@if (_balances is { Count: > 1 })
|
||||
{
|
||||
<KhStrip Items="BalanceStats" Label="@T["Inventory.Movements.ByWarehouse"]" />
|
||||
}
|
||||
@if (_movements is null)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (_movements.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Inventory.Movements.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap kh-dialoggrid">
|
||||
<table class="grid" aria-label="@T["Inventory.Movements.Title"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Inventory.Movements.Date"]</th>
|
||||
<th scope="col">@T["Inventory.Movements.Document"]</th>
|
||||
<th scope="col">@T["Inventory.Fields.Reason"]</th>
|
||||
<th scope="col">@T["Inventory.Movements.Party"]</th>
|
||||
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
|
||||
@if (_costs)
|
||||
{
|
||||
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
|
||||
}
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Balance"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var move in _movements)
|
||||
{
|
||||
<tr>
|
||||
<td>@T.Date(move.Date)</td>
|
||||
<td class="code">
|
||||
@if (move.Kind is { } kind && move.DocumentId is { } document)
|
||||
{
|
||||
<a href="@SalesScreens.RecordUrl(kind, document)">@T["Sales.Kinds." + kind] @move.Number</a>
|
||||
}
|
||||
</td>
|
||||
<td class="code">@move.ReasonCode</td>
|
||||
<td>@move.PartyName</td>
|
||||
<td>@PartyScreens.Describe(_warehouses, move.WarehouseId)</td>
|
||||
<td class="num @(move.Quantity < 0m ? "err" : "ok")">@Qty(move.Quantity)</td>
|
||||
@if (_costs)
|
||||
{
|
||||
<td class="num">@Cost(move.UnitCost)</td>
|
||||
}
|
||||
<td class="num"><b>@Qty(move.Balance)</b></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
@if (_item is { } item)
|
||||
{
|
||||
<a class="btn" href="@ItemScreens.RecordUrl(item.ItemId)"><KhIcon Name="box" /> @T["Inventory.Movements.OpenItem"]</a>
|
||||
}
|
||||
<button type="button" class="btn primary" @onclick="() => _item = null">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
<KhDialog Open="_valuationOpen" Title="@T["Inventory.Valuation.Title"]" Icon="euro" Size="lg" OnClose="() => _valuationOpen = false">
|
||||
<ChildContent>
|
||||
<KhForm Layout="KhFormLayout.Grid">
|
||||
<KhDateBox Label="@T["Inventory.Valuation.Date"]" Name="ValuationDate" Value="_valuationDate" ValueChanged="v => _valuationDate = v" Span="4" Required="true" />
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Valuation.Method"]" Name="Method" Options="Methods" Value="@_method.ToString()" Span="4"
|
||||
ValueChanged="SetMethod" />
|
||||
<div class="c4 kh-endrow">
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="ValueAsync"><KhIcon Name="chart" /> @T["Inventory.Valuation.Compute"]</button>
|
||||
</div>
|
||||
</KhForm>
|
||||
@if (_valuation is { } rows)
|
||||
{
|
||||
<KhStrip Items="ValuationStats" Label="@T["Inventory.Valuation.Title"]" />
|
||||
<div class="gridwrap kh-dialoggrid">
|
||||
<table class="grid" aria-label="@T["Inventory.Valuation.Title"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.Value"]</th>
|
||||
<th scope="col">@T["Inventory.Valuation.Class"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var row in rows)
|
||||
{
|
||||
<tr>
|
||||
<td class="code">@row.Code</td>
|
||||
<td>@row.Description</td>
|
||||
<td class="num">@Qty(row.Quantity)</td>
|
||||
<td class="num">@T.Money(row.UnitCost)</td>
|
||||
<td class="num">@T.Money(row.Value)</td>
|
||||
<td><KhBadge Tone="@(row.AbcClass switch { 'A' => KhTone.Ok, 'B' => KhTone.Info, _ => KhTone.Neutral })">@row.AbcClass</KhBadge></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
<p class="muted sm">@T["Inventory.Valuation.Hint"]</p>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn primary" @onclick="() => _valuationOpen = false">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private static readonly ListFields<StockRow> Fields = new ListFields<StockRow>()
|
||||
.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<StockRow> _source = new([], Fields);
|
||||
private IReadOnlyList<StockRow> _rows = [];
|
||||
private ItemLookups _lookups = ItemLookups.Empty;
|
||||
private IReadOnlyList<KhOption<string>> _warehouses = [];
|
||||
private KhRadar<StockRow>? _radar;
|
||||
private long? _warehouse;
|
||||
private bool _includeEmpty;
|
||||
private bool _costs;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
private RebuildProgress? _rebuild;
|
||||
|
||||
private StockRow? _item;
|
||||
private IReadOnlyList<MovementRow>? _movements;
|
||||
private IReadOnlyList<ItemBalance>? _balances;
|
||||
|
||||
private bool _valuationOpen;
|
||||
private DateOnly? _valuationDate;
|
||||
private StockValuationMethod _method = StockValuationMethod.WeightedAverage;
|
||||
private IReadOnlyList<ValuationRow>? _valuation;
|
||||
|
||||
/// <summary>An item to open at once, from the dashboard.</summary>
|
||||
[SupplyParameterFromQuery(Name = "articolo")]
|
||||
public long? ItemId { get; set; }
|
||||
|
||||
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
|
||||
private IReadOnlyList<KhStat> 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<KhStat>(),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhStat> BalanceStats => _balances is null ? [] :
|
||||
[.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))];
|
||||
|
||||
private IReadOnlyList<KhStat> 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<KhOption<string>> 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<KhColumn<StockRow>> 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 => @<KhBadge Tone="ToneOf(r.Level)">@T["Inventory.Levels." + r.Level]</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> 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<StockLevel>().Select(l => new KhOption<string>(l.ToString(), T["Inventory.Levels." + l])),
|
||||
]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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<Warehouse>(actor, company)).Select(w => new KhOption<string>(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<StockRow>(_rows, Fields);
|
||||
}
|
||||
|
||||
private Task<ListPage<StockRow>> 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<StockValuationMethod>(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<RebuildProgress>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@Title" Icon="file-check" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(InventoryService.EntryReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else if (Id is null)
|
||||
{
|
||||
<div class="kh-import">
|
||||
<div class="kh-import-side">
|
||||
<KhPanel Title="@T["Inventory.StockTake.New"]" Icon="plus">
|
||||
@if (CanWrite)
|
||||
{
|
||||
<KhForm Layout="KhFormLayout.Grid" Validation="_validation" Class="kh-import-options">
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="WarehouseId" Options="_warehouses" Value="@PartyScreens.Text(_warehouse)"
|
||||
ValueChanged="v => _warehouse = PartyScreens.Id(v)" Span="12" Required="true" />
|
||||
<KhDateBox Label="@T["Inventory.StockTake.Date"]" Name="TakeDate" Value="_date" ValueChanged="v => _date = v" Span="6" Required="true" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Radar.Category"]" Name="CategoryId" Options="_lookups.Categories" Empty="@T["Inventory.StockTake.AllCategories"]"
|
||||
Value="@PartyScreens.Text(_category)" ValueChanged="v => _category = PartyScreens.Id(v)" Span="6" />
|
||||
<KhTextBox Label="@T["Inventory.StockTake.Description"]" Name="Description" Value="@_description" ValueChanged="v => _description = v" Span="12"
|
||||
Hint="@T["Inventory.StockTake.DescriptionHint"]" />
|
||||
<div class="c12 kh-endrow">
|
||||
<button type="button" class="btn primary" disabled="@(_busy || _warehouse is null || _date is null)" @onclick="CreateAsync">
|
||||
<KhIcon Name="file-check" /> @T["Inventory.StockTake.Open"]
|
||||
</button>
|
||||
</div>
|
||||
</KhForm>
|
||||
}
|
||||
<p class="muted sm kh-pad">@T["Inventory.StockTake.Hint"]</p>
|
||||
</KhPanel>
|
||||
</div>
|
||||
<div class="kh-import-main">
|
||||
<KhPanel Title="@T["Inventory.StockTake.List"]" Icon="list">
|
||||
@if (_takes.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Inventory.StockTake.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Inventory.StockTake.List"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Inventory.StockTake.Date"]</th>
|
||||
<th scope="col">@T["Inventory.StockTake.Description"]</th>
|
||||
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
|
||||
<th scope="col">@T["Items.Radar.State"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var take in _takes)
|
||||
{
|
||||
<tr>
|
||||
<td>@T.Date(take.TakeDate)</td>
|
||||
<td><a href="magazzino/inventario/@take.Id">@take.Description</a></td>
|
||||
<td>@PartyScreens.Describe(_warehouses, take.WarehouseId)</td>
|
||||
<td><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</KhPanel>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
else if (_view is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Inventory.StockTake.Missing"]</h1><p><a href="magazzino/inventario">@T["Inventory.StockTake.List"]</a></p></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
var take = _view.Take;
|
||||
<div class="kh-import">
|
||||
<div class="kh-import-side">
|
||||
<KhPanel Title="@take.Description" Icon="file-check">
|
||||
<KhVSteps Items="Steps" Current="Step" Label="@T["Inventory.StockTake.Procedure"]" />
|
||||
<dl class="kh-facts">
|
||||
<dt>@T["Inventory.Fields.Warehouse"]</dt><dd>@PartyScreens.Describe(_warehouses, take.WarehouseId)</dd>
|
||||
<dt>@T["Inventory.StockTake.Date"]</dt><dd>@T.Date(take.TakeDate)</dd>
|
||||
<dt>@T["Items.Radar.Category"]</dt><dd>@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])</dd>
|
||||
<dt>@T["Items.Radar.State"]</dt><dd><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></dd>
|
||||
@if (take.Status == StockTakeStatus.Posted)
|
||||
{
|
||||
<dt>@T["Inventory.StockTake.Movements"]</dt>
|
||||
<dd>
|
||||
@if (take.AdjustmentDocumentId is { } gain)
|
||||
{
|
||||
<a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, gain)">@StockTakeService.GainReason</a>
|
||||
}
|
||||
@if (take.LossDocumentId is { } loss)
|
||||
{
|
||||
<span> </span><a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, loss)">@StockTakeService.LossReason</a>
|
||||
}
|
||||
</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (IsOpen && CanWrite)
|
||||
{
|
||||
<div class="kh-endrow kh-pad">
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="CancelAsync"><KhIcon Name="x-circle" /> @T["Inventory.StockTake.Cancel"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhPanel>
|
||||
</div>
|
||||
<div class="kh-import-main">
|
||||
<KhStrip Items="Stats" Label="@T["Inventory.StockTake.Procedure"]" />
|
||||
<KhPanel Title="@T["Inventory.StockTake.Lines"]" Icon="list">
|
||||
<Actions>
|
||||
<input type="search" class="in kh-searchbox" placeholder="@T["Inventory.Stock.Search"]" aria-label="@T["Inventory.Stock.Search"]"
|
||||
value="@_search" @oninput="e => _search = e.Value?.ToString()" />
|
||||
<select class="in" aria-label="@T["Inventory.StockTake.Show"]" @onchange="e => _show = e.Value?.ToString() ?? string.Empty">
|
||||
<option value="" selected="@(_show.Length == 0)">@T["Inventory.StockTake.ShowAll"]</option>
|
||||
<option value="todo" selected="@(_show == "todo")">@T["Inventory.StockTake.ShowToCount"]</option>
|
||||
<option value="diff" selected="@(_show == "diff")">@T["Inventory.StockTake.ShowDifferences"]</option>
|
||||
</select>
|
||||
@if (IsOpen && CanWrite)
|
||||
{
|
||||
<label class="btn kh-filebtn">
|
||||
<KhIcon Name="upload" /> @T["Inventory.StockTake.Import"]
|
||||
<InputFile OnChange="ImportAsync" accept=".csv,.txt,text/csv,text/plain" disabled="@_busy" />
|
||||
</label>
|
||||
<button type="button" class="btn" disabled="@(_busy || _counts.Count == 0)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Inventory.StockTake.Save"]</button>
|
||||
@if (Session.Permissions.Allows(InventoryService.PostPermission))
|
||||
{
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="PostAsync"><KhIcon Name="check-circle" /> @T["Inventory.StockTake.Post"]</button>
|
||||
}
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
<div class="gridwrap kh-taketable">
|
||||
<table class="grid" aria-label="@T["Inventory.StockTake.Lines"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col">@T["Items.Radar.Unit"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.Book"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.Counted"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.Difference"]</th>
|
||||
@if (_costs)
|
||||
{
|
||||
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.DifferenceValue"]</th>
|
||||
}
|
||||
<th scope="col">@T["Items.Radar.State"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in Shown)
|
||||
{
|
||||
var id = line.Line.Id;
|
||||
var counted = CountOf(line);
|
||||
var difference = counted is { } c ? c - line.Line.BookQuantity : 0m;
|
||||
<tr class="@(counted is not null && difference != 0m ? "hl" : null)">
|
||||
<td class="code">@line.Code</td>
|
||||
<td>@line.Description</td>
|
||||
<td>@PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId)</td>
|
||||
<td class="num">@Qty(line.Line.BookQuantity)</td>
|
||||
<td class="num">
|
||||
@if (IsOpen && CanWrite)
|
||||
{
|
||||
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.StockTake.Counted"] + " " + line.Code)"
|
||||
value="@(counted is { } v ? Qty(v) : null)" @onchange="e => SetCount(id, e.Value?.ToString())" />
|
||||
}
|
||||
else
|
||||
{
|
||||
@(counted is { } v ? Qty(v) : "—")
|
||||
}
|
||||
</td>
|
||||
<td class="num @(difference < 0m ? "err" : difference > 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))</td>
|
||||
@if (_costs)
|
||||
{
|
||||
<td class="num">@T.Money(line.Line.UnitCost)</td>
|
||||
<td class="num">@(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2)))</td>
|
||||
}
|
||||
<td>
|
||||
@if (counted is null)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Neutral">@T["Inventory.StockTake.ToCount"]</KhBadge>
|
||||
}
|
||||
else if (difference == 0m)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Ok">@T["Inventory.StockTake.Matches"]</KhBadge>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["Inventory.StockTake.Differs"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private readonly Dictionary<long, decimal?> _counts = [];
|
||||
private IReadOnlyList<StockTake> _takes = [];
|
||||
private IReadOnlyList<KhOption<string>> _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;
|
||||
|
||||
/// <summary>The stock take shown, or none for the list.</summary>
|
||||
[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<KhStep> 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<KhStat> 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<KhStat>(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<StockTakeLineView> 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,
|
||||
});
|
||||
|
||||
/// <inheritdoc />
|
||||
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<Warehouse>(actor, company)).Select(w => new KhOption<string>(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<long?> DefaultWarehouseAsync(Actor actor, string company) =>
|
||||
(await Tables.ActiveAsync<Warehouse>(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)));
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Purchases.Import.Title"]" Icon="upload" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(PurchaseService.WritePermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kh-import">
|
||||
<div class="kh-import-side">
|
||||
<KhPanel Title="@T["Purchases.Import.Procedure"]" Icon="upload">
|
||||
<KhVSteps Items="Steps" Current="_step" Label="@T["Purchases.Import.Procedure"]" />
|
||||
<div class="kh-import-options">
|
||||
<div class="f c12">
|
||||
<label for="kh-incoming-files">@T["Purchases.Import.Files"]</label>
|
||||
<InputFile id="kh-incoming-files" class="in" OnChange="ReadAsync" multiple accept=".xml,.p7m,.zip" disabled="@_busy" />
|
||||
<span class="muted sm">@T["Purchases.Import.FilesHint"]</span>
|
||||
</div>
|
||||
</div>
|
||||
</KhPanel>
|
||||
</div>
|
||||
<div class="kh-import-main">
|
||||
@if (_results.Count > 0)
|
||||
{
|
||||
<KhPanel Title="@T["Purchases.Import.Results"]" Icon="check-circle">
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Purchases.Import.Results"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.SupplierNumber"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Draft"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Check"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var result in _results)
|
||||
{
|
||||
<tr>
|
||||
<td>
|
||||
@result.Candidate.File.Supplier.DisplayName
|
||||
@if (result.SupplierCreated)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Purchases.Import.NewSupplier"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
<td class="code">@result.Candidate.Invoice.Number</td>
|
||||
@if (result.Record is { } record)
|
||||
{
|
||||
<td><a href="@SalesScreens.RecordUrl(record.Header.Kind, record.Header.Id)">@T["Sales.Kinds." + record.Header.Kind] · @T.Money(record.Header.TotalAmount)</a></td>
|
||||
<td>@string.Join(" ", result.Warnings.Select(w => T[w]))</td>
|
||||
}
|
||||
else
|
||||
{
|
||||
<td colspan="2" class="err"><KhIcon Name="alert-circle" /> @(T.Contains(result.Error ?? string.Empty) ? T[result.Error!] : result.Error)</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="kh-endrow kh-pad">
|
||||
<a class="btn" href="acquisti/fatture"><KhIcon Name="euro" /> @T["Sales.Sections.PurchaseInvoices.Title"]</a>
|
||||
<button type="button" class="btn" @onclick="Restart"><KhIcon Name="refresh" /> @T["Purchases.Import.Again"]</button>
|
||||
</div>
|
||||
</KhPanel>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_rejected.Count > 0)
|
||||
{
|
||||
<div class="callout warn kh-pad" role="alert">
|
||||
<KhIcon Name="alert" />
|
||||
<div>
|
||||
<b>@T.Format("Purchases.Import.Rejected", _rejected.Count)</b>
|
||||
<ul class="kh-plainlist">
|
||||
@foreach (var file in _rejected)
|
||||
{
|
||||
<li><span class="code">@file.FileName</span> · @(T.Contains(file.Error) ? T[file.Error] : file.Error)</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<KhPanel Title="@T["Purchases.Import.Invoices"]" Icon="file">
|
||||
<Actions>
|
||||
<span class="muted sm">@T.Format("Purchases.Import.Selected", _selected.Count, T.Money(SelectedTotal))</span>
|
||||
<button type="button" class="btn primary" disabled="@(_selected.Count == 0 || _busy)" @onclick="ImportAsync">
|
||||
<KhIcon Name="download" /> @T["Purchases.Import.Register"]
|
||||
</button>
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_invoices.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Purchases.Import.Start"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Purchases.Import.Invoices"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" class="kh-check"><input type="checkbox" checked="@(_selected.Count == Importable.Count() && _selected.Count > 0)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col">@T["Purchases.Import.VatNumber"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Type"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.SupplierNumber"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.SupplierDate"]</th>
|
||||
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Check"]</th>
|
||||
<th scope="col"><span class="sr-only">@T["Purchases.Import.View"]</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (var i = 0; i < _invoices.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var invoice = _invoices[i];
|
||||
<tr class="@(invoice.CanImport ? null : "muted")">
|
||||
<td class="kh-check">
|
||||
<input type="checkbox" checked="@_selected.Contains(index)" disabled="@(!invoice.CanImport)" aria-label="@invoice.Invoice.Number"
|
||||
@onchange="e => Toggle(index, e.Value is true)" />
|
||||
</td>
|
||||
<td>
|
||||
@invoice.File.Supplier.DisplayName
|
||||
@if (invoice.SupplierId is null)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Purchases.Import.NewSupplier"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
<td class="code">@(invoice.File.Supplier.CountryCode)@invoice.File.Supplier.VatNumber</td>
|
||||
<td><span class="code">@invoice.Invoice.DocumentType</span> @(invoice.DocumentTypeCode is { } code ? "→ " + code : null)</td>
|
||||
<td class="code">@invoice.Invoice.Number</td>
|
||||
<td>@T.Date(invoice.Invoice.Date)</td>
|
||||
<td class="num">@T.Money(invoice.Total)</td>
|
||||
<td>
|
||||
@if (invoice.Problems.Count == 0)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Ok">@T["Purchases.Import.Ready"]</KhBadge>
|
||||
}
|
||||
@foreach (var problem in invoice.Problems)
|
||||
{
|
||||
<KhBadge Tone="@(invoice.CanImport ? KhTone.Warning : KhTone.Error)">@T[problem + ".short"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
<td><button type="button" class="btn sm" @onclick="() => _shown = invoice"><KhIcon Name="eye" /> @T["Purchases.Import.View"]</button></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<KhDialog Open="_shown is not null" Title="@ShownTitle" Icon="file" Size="lg" OnClose="() => _shown = null">
|
||||
<ChildContent>
|
||||
@if (_shown is { } shown)
|
||||
{
|
||||
var supplier = shown.File.Supplier;
|
||||
var invoice = shown.Invoice;
|
||||
<div class="kh-einvoice">
|
||||
<dl class="kh-facts">
|
||||
<dt>@T["Purchases.Fields.Supplier"]</dt>
|
||||
<dd><b>@supplier.DisplayName</b><br />@supplier.Address @supplier.StreetNumber, @supplier.PostalCode @supplier.City @(supplier.Province is null ? null : "(" + supplier.Province + ")")</dd>
|
||||
<dt>@T["Purchases.Import.VatNumber"]</dt><dd class="code">@supplier.CountryCode@supplier.VatNumber @(supplier.TaxCode is null ? null : " · " + supplier.TaxCode)</dd>
|
||||
<dt>@T["Purchases.Import.Type"]</dt><dd><span class="code">@invoice.DocumentType</span> · @invoice.Currency</dd>
|
||||
<dt>@T["Purchases.Fields.SupplierNumber"]</dt><dd>@invoice.Number · @T.Date(invoice.Date)</dd>
|
||||
@if (invoice.Causals.Count > 0)
|
||||
{
|
||||
<dt>@T["Purchases.Import.Causal"]</dt><dd>@string.Join(" ", invoice.Causals)</dd>
|
||||
}
|
||||
@if (shown.File.Signature is { } signature)
|
||||
{
|
||||
<dt>@T["Purchases.Import.Signature"]</dt>
|
||||
<dd>
|
||||
<KhBadge Tone="@(signature.Verified ? KhTone.Ok : KhTone.Warning)">@T[signature.Verified ? "Purchases.Import.SignatureOk" : "Purchases.Import.SignatureKo"]</KhBadge>
|
||||
@signature.Signer
|
||||
</dd>
|
||||
}
|
||||
</dl>
|
||||
<div class="gridwrap kh-dialoggrid">
|
||||
<table class="grid" aria-label="@T["Purchases.Import.Lines"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Reorder.Price"]</th>
|
||||
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
|
||||
<th scope="col" class="num">@T["Purchases.Import.Rate"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in invoice.Lines)
|
||||
{
|
||||
<tr>
|
||||
<td>@line.Number</td>
|
||||
<td class="code">@string.Join(" ", line.Codes.Select(c => c.Value))</td>
|
||||
<td>@line.Description</td>
|
||||
<td class="num">@(line.Quantity is { } q ? q.ToString("#,##0.###", T.Culture) + " " + line.Unit : null)</td>
|
||||
<td class="num">@T.Money(line.UnitPrice)</td>
|
||||
<td class="num">@T.Money(line.TotalPrice)</td>
|
||||
<td class="num">@(line.Nature ?? line.TaxRate.ToString("0.##", T.Culture) + "%")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<KhStrip Items="SummaryOf(invoice)" Label="@T["Purchases.Import.Summary"]" />
|
||||
@if (invoice.Payments.Count > 0)
|
||||
{
|
||||
<ul class="kh-plainlist muted sm">
|
||||
@foreach (var payment in invoice.Payments)
|
||||
{
|
||||
<li>@T["Purchases.Import.Payment"] @(payment.DueDate is { } due ? T.Date(due) : null) · @T.Money(payment.Amount) @(payment.Iban is null ? null : " · " + payment.Iban)</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn primary" @onclick="() => _shown = null">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly HashSet<int> _selected = [];
|
||||
private List<IncomingCandidate> _invoices = [];
|
||||
private List<IncomingRejected> _rejected = [];
|
||||
private List<IncomingImported> _results = [];
|
||||
private IncomingCandidate? _shown;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
private int _step;
|
||||
|
||||
private IReadOnlyList<KhStep> 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<int> 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<KhStat> 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))),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
@page "/magazzino/{Segment}/{Id:long}"
|
||||
@attribute [Authorize]
|
||||
@inherits DocumentPage<DocumentRecord, DocumentLine>
|
||||
@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)
|
||||
{
|
||||
<div class="callout warn kh-doc-callout"><KhIcon Name="alert" />
|
||||
<span>@T.Format("Purchases.PriceDifferences.Summary", _differences.Count, T.Money(_differences.Sum(d => d.Amount)))
|
||||
@foreach (var difference in _differences.Take(5))
|
||||
{
|
||||
<br /><span class="sm">@T.Format("Purchases.PriceDifferences.Line", difference.LineNumber, difference.Description, difference.SourceNumber ?? string.Empty,
|
||||
T.Money(difference.SourcePrice), T.Money(difference.InvoicePrice))</span>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
@if (_selfAdvice is { } advice)
|
||||
{
|
||||
<div class="callout info kh-doc-callout"><KhIcon Name="refresh" />
|
||||
<span>@T.Format("Purchases.SelfInvoices.Advice", advice.DocumentTypeCode, advice.Reason, T.Date(advice.Deadline))</span>
|
||||
@if (Session.Permissions.Allows(PurchaseService.WritePermission) && DocumentStateMachine.IsInForce(h.Status))
|
||||
{
|
||||
<button type="button" class="btn" @onclick="CreateSelfInvoiceAsync"><KhIcon Name="plus" /> @T["Purchases.SelfInvoices.Create"]</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (h.PartyId is null && !IsReadOnly && !IsInternal)
|
||||
{
|
||||
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
|
||||
|
||||
@@ -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<DocumentAction> _actions = [];
|
||||
private IReadOnlyList<LinkedDocument> _links = [];
|
||||
private IReadOnlyList<PriceDifference> _differences = [];
|
||||
private SelfInvoiceAdvice? _selfAdvice;
|
||||
private IReadOnlyList<AuditItem> _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<string> PartyLines
|
||||
|
||||
@@ -39,6 +39,10 @@ else if (!CanRead)
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "autofatture")
|
||||
{
|
||||
<Khaemhat.Web.Components.Purchases.PendingSelfInvoicesPanel />
|
||||
}
|
||||
<KhRadar TItem="DocumentRow" @key="_section.Area + _section.Segment" Id="@(_section.Area == SalesScreens.BasePath ? "sales." + _section.Segment : _section.Area + "." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
|
||||
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
|
||||
Label="@Title">
|
||||
@@ -51,6 +55,10 @@ else
|
||||
{
|
||||
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
|
||||
}
|
||||
@if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "fatture" && Session.Permissions.Allows("purchases.invoice.write"))
|
||||
{
|
||||
<a class="btn" href="acquisti/importa-fatture"><KhIcon Name="upload" /> @T["Shell.Menu.Purchases.Import"]</a>
|
||||
}
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
<KhPanel Title="@T["Purchases.SelfInvoices.Pending"]" Icon="refresh" Class="kh-pendingself">
|
||||
<Actions><span class="badge @(pending.Any(p => p.Advice.Deadline < Today) ? "red" : "amber")">@T.Number(pending.Count)</span></Actions>
|
||||
<ChildContent>
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Purchases.SelfInvoices.Pending"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Invoice"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Type"]</th>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Reason"]</th>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Deadline"]</th>
|
||||
<th scope="col"><span class="sr-only">@T["Purchases.SelfInvoices.Create"]</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var item in pending)
|
||||
{
|
||||
var row = item.Invoice;
|
||||
<tr>
|
||||
<td class="code"><a href="@SalesScreens.RecordUrl(row.Kind, row.Id)">@row.DocumentNumber</a> · @T.Date(row.Date)</td>
|
||||
<td>@row.PartyName</td>
|
||||
<td class="num">@T.Money(row.Taxable)</td>
|
||||
<td class="code">@item.Advice.DocumentTypeCode</td>
|
||||
<td>@item.Advice.Reason</td>
|
||||
<td><KhBadge Tone="@(item.Advice.Deadline < Today ? KhTone.Error : item.Advice.Deadline <= Today.AddDays(5) ? KhTone.Warning : KhTone.Neutral)">@T.Date(item.Advice.Deadline)</KhBadge></td>
|
||||
<td>
|
||||
@if (CanWrite)
|
||||
{
|
||||
<button type="button" class="btn sm primary" disabled="@_busy" @onclick="() => CreateAsync(item)"><KhIcon Name="plus" /> @T["Purchases.SelfInvoices.Create"]</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
}
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<PendingSelfInvoice>? _pending;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(PurchaseService.WritePermission);
|
||||
|
||||
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,7 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.InventoryService>();
|
||||
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseService>();
|
||||
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseInvoiceImportService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.StockTakeService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.ReorderService>();
|
||||
services.AddSingleton<IScheduledJob, Khaemhat.Application.Inventory.InventoryRebuildJob>();
|
||||
@@ -183,6 +184,8 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
|
||||
services.AddSingleton<DemoSalesSeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
|
||||
services.AddSingleton<DemoPurchasesSeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoPurchasesSeeder>());
|
||||
services.AddSingleton<CompanyService>();
|
||||
services.AddSingleton<CompanyContextResolver>();
|
||||
services.AddScoped<ICompanyContext, WebCompanyContext>();
|
||||
|
||||
@@ -132,6 +132,7 @@ public static class SeedCommand
|
||||
|
||||
// The demo documents go through the document engine, after the masters they use.
|
||||
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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."
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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; }
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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<ImportService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
var stockService = app.Services.GetRequiredService<Khaemhat.Application.Inventory.InventoryService>();
|
||||
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<ImportFileException>(() => 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<SeedRunner>().RunAsync(company, SeedKind.Demo);
|
||||
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
|
||||
await app.Services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, context);
|
||||
var seeder = app.Services.GetRequiredService<DemoPurchasesSeeder>();
|
||||
await seeder.SeedAsync(company, context);
|
||||
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
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<PurchaseService>().PendingSelfInvoicesAsync(Root, company);
|
||||
Assert.HasCount(1, pending);
|
||||
var inventory = app.Services.GetRequiredService<InventoryService>();
|
||||
Assert.IsNotEmpty(await inventory.StockAsync(Root, company, new StockFilter()));
|
||||
Assert.IsNotEmpty(await app.Services.GetRequiredService<ReorderService>().ProposalsAsync(Root, company));
|
||||
var take = (await app.Services.GetRequiredService<StockTakeService>().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<List<DocumentRow>> AllAsync(DocumentEditor editor, string company)
|
||||
{
|
||||
var all = new List<DocumentRow>();
|
||||
foreach (var family in new[] { DocumentFamily.PurchaseOrder, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
|
||||
{
|
||||
all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues<DocumentKind>()], new ListQuery { Limit = 200 })).Items);
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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) => $"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<p:FatturaElettronica versione="FPR12" xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2">
|
||||
<FatturaElettronicaHeader>
|
||||
<DatiTrasmissione>
|
||||
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567897</IdCodice></IdTrasmittente>
|
||||
<ProgressivoInvio>00042</ProgressivoInvio><FormatoTrasmissione>FPR12</FormatoTrasmissione><CodiceDestinatario>0000000</CodiceDestinatario>
|
||||
</DatiTrasmissione>
|
||||
<CedentePrestatore>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567897</IdCodice></IdFiscaleIVA>
|
||||
<Anagrafica><Denominazione>Ferramenta Piemontese S.r.l.</Denominazione></Anagrafica>
|
||||
<RegimeFiscale>RF01</RegimeFiscale>
|
||||
</DatiAnagrafici>
|
||||
<Sede><Indirizzo>Via Roma</Indirizzo><NumeroCivico>12</NumeroCivico><CAP>10121</CAP><Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</CedentePrestatore>
|
||||
<CessionarioCommittente>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>02987654304</IdCodice></IdFiscaleIVA>
|
||||
<Anagrafica><Denominazione>Azienda di prova</Denominazione></Anagrafica>
|
||||
</DatiAnagrafici>
|
||||
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</CessionarioCommittente>
|
||||
</FatturaElettronicaHeader>
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento>
|
||||
<TipoDocumento>{type}</TipoDocumento><Divisa>EUR</Divisa><Data>{date}</Data><Numero>{number}</Numero>
|
||||
<ImportoTotaleDocumento>{total}</ImportoTotaleDocumento><Causale>Fornitura di marzo</Causale>
|
||||
</DatiGeneraliDocumento>
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi>{lines}{summary}</DatiBeniServizi>
|
||||
</FatturaElettronicaBody>
|
||||
</p:FatturaElettronica>
|
||||
""";
|
||||
|
||||
private const string Lines = """
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>1</NumeroLinea>
|
||||
<CodiceArticolo><CodiceTipo>SKU</CodiceTipo><CodiceValore>VALV-01</CodiceValore></CodiceArticolo>
|
||||
<Descrizione>Valvola a sfera 1/2</Descrizione><Quantita>10.00</Quantita><UnitaMisura>PZ</UnitaMisura><PrezzoUnitario>4.000000</PrezzoUnitario>
|
||||
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>10.00</Percentuale></ScontoMaggiorazione>
|
||||
<PrezzoTotale>36.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>2</NumeroLinea><Descrizione>Spese di trasporto</Descrizione><PrezzoUnitario>15.00</PrezzoUnitario><PrezzoTotale>15.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
""";
|
||||
|
||||
private const string Summary = """
|
||||
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>51.00</ImponibileImporto><Imposta>11.22</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
|
||||
""";
|
||||
|
||||
[TestMethod]
|
||||
public async Task Import_AddsTheSupplier_MatchesItemsAndTaxes_AndRefusesTheSameInvoiceTwice()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var import = app.Services.GetRequiredService<PurchaseInvoiceImportService>();
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var attachments = app.Services.GetRequiredService<AttachmentService>();
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
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("<FatturaElettronica>"))]);
|
||||
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<IIncomingInvoiceRules>(rules);
|
||||
}
|
||||
|
||||
private static async Task Add(ZipArchive archive, string name, byte[] content)
|
||||
{
|
||||
await using var stream = archive.CreateEntry(name).Open();
|
||||
await stream.WriteAsync(content);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user