diff --git a/Backend/ERPCore/Controllers/AuditLogsController.cs b/Backend/ERPCore/Controllers/AuditLogsController.cs
new file mode 100644
index 0000000..a3f9750
--- /dev/null
+++ b/Backend/ERPCore/Controllers/AuditLogsController.cs
@@ -0,0 +1,26 @@
+using ERPCore.Dtos.Audit;
+using ERPCore.Dtos.Common;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+///
+/// Read-only audit trail (FR-X-02; auditor role). Extends the documented §11 API —
+/// the audit trail is required (AR-01 compensating control) and read access is the
+/// only way to consume it.
+///
+[Route("api/v1/audit-logs")]
+public sealed class AuditLogsController : ApiControllerBase
+{
+ private readonly IAuditService _audit;
+
+ public AuditLogsController(IAuditService audit) => _audit = audit;
+
+ [HttpGet]
+ [ProducesResponseType(typeof(PagedResponse), StatusCodes.Status200OK)]
+ public async Task>> List(
+ [FromQuery] string? entityType, [FromQuery] long? entityId, [FromQuery] long? userId,
+ [FromQuery] DateOnly? from, [FromQuery] DateOnly? to, [FromQuery] PageQuery query, CancellationToken ct)
+ => Ok(await _audit.ListLogsAsync(entityType, entityId, userId, from, to, query, ct));
+}
diff --git a/Backend/ERPCore/Controllers/GrnsController.cs b/Backend/ERPCore/Controllers/GrnsController.cs
new file mode 100644
index 0000000..0903a5a
--- /dev/null
+++ b/Backend/ERPCore/Controllers/GrnsController.cs
@@ -0,0 +1,52 @@
+using ERPCore.Dtos.Grn;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Goods-receipt endpoints (docs/11 §4).
+[Route("api/v1/grns")]
+public sealed class GrnsController : ApiControllerBase
+{
+ private readonly IGrnService _grns;
+
+ public GrnsController(IGrnService grns) => _grns = grns;
+
+ [HttpGet("{grnId:long}")]
+ [ProducesResponseType(typeof(GrnDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task> GetById(long grnId, CancellationToken ct)
+ {
+ var dto = await _grns.GetAsync(grnId, ct);
+ return dto is null ? NotFound() : Ok(dto);
+ }
+
+ /// Create a Draft GRN against a PO or direct. Cost is PO-derived for PO lines.
+ [HttpPost]
+ [ProducesResponseType(typeof(GrnDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> Create([FromBody] CreateGrnRequest request, CancellationToken ct)
+ {
+ var dto = await _grns.CreateAsync(request, ct);
+ return Created($"/api/v1/grns/{dto.GrnId}", dto);
+ }
+
+ /// Confirm: create FIFO layers + inbound ledger + update PO receipts (single UoW txn).
+ [HttpPost("{grnId:long}/confirm")]
+ [ProducesResponseType(typeof(GrnConfirmResultDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Confirm(
+ long grnId, [FromHeader(Name = "Idempotency-Key")] string? idempotencyKey, CancellationToken ct)
+ => Ok(await _grns.ConfirmAsync(grnId, idempotencyKey, ct));
+
+ /// Release or reject an inspection-hold line (FR-GRN-05).
+ [HttpPost("{grnId:long}/lines/{grnLineId:long}/release")]
+ [ProducesResponseType(typeof(ReleaseLineResultDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Release(
+ long grnId, long grnLineId, [FromBody] ReleaseLineRequest request, CancellationToken ct)
+ => Ok(await _grns.ReleaseLineAsync(grnId, grnLineId, request.Action, ct));
+}
diff --git a/Backend/ERPCore/Controllers/JournalEntriesController.cs b/Backend/ERPCore/Controllers/JournalEntriesController.cs
new file mode 100644
index 0000000..a2d500d
--- /dev/null
+++ b/Backend/ERPCore/Controllers/JournalEntriesController.cs
@@ -0,0 +1,24 @@
+using ERPCore.Dtos.Audit;
+using ERPCore.Dtos.Common;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+///
+/// Read-only GL-ready journal stubs (FR-STK-13; consumed by the Accounting phase).
+/// Data only — no posting in Phase 1.
+///
+[Route("api/v1/journal-entries")]
+public sealed class JournalEntriesController : ApiControllerBase
+{
+ private readonly IAuditService _audit;
+
+ public JournalEntriesController(IAuditService audit) => _audit = audit;
+
+ [HttpGet]
+ [ProducesResponseType(typeof(PagedResponse), StatusCodes.Status200OK)]
+ public async Task>> List(
+ [FromQuery] string? sourceDocType, [FromQuery] long? sourceDocId, [FromQuery] PageQuery query, CancellationToken ct)
+ => Ok(await _audit.ListJournalAsync(sourceDocType, sourceDocId, query, ct));
+}
diff --git a/Backend/ERPCore/Controllers/PurchaseReturnsController.cs b/Backend/ERPCore/Controllers/PurchaseReturnsController.cs
new file mode 100644
index 0000000..9f59a56
--- /dev/null
+++ b/Backend/ERPCore/Controllers/PurchaseReturnsController.cs
@@ -0,0 +1,26 @@
+using ERPCore.Dtos.Procurement;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Purchase-return endpoints (docs/11 §3.4).
+[Route("api/v1/purchase-returns")]
+public sealed class PurchaseReturnsController : ApiControllerBase
+{
+ private readonly IPurchaseReturnService _returns;
+
+ public PurchaseReturnsController(IPurchaseReturnService returns) => _returns = returns;
+
+ /// Create + auto-post a return (outbound movement). 409 if return exceeds available stock.
+ [HttpPost]
+ [ProducesResponseType(typeof(PurchaseReturnDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> Create([FromBody] CreatePurchaseReturnRequest request, CancellationToken ct)
+ {
+ var dto = await _returns.CreateAsync(request, ct);
+ return Created($"/api/v1/purchase-returns/{dto.ReturnId}", dto);
+ }
+}
diff --git a/Backend/ERPCore/Controllers/ReasonCodesController.cs b/Backend/ERPCore/Controllers/ReasonCodesController.cs
new file mode 100644
index 0000000..e67aa32
--- /dev/null
+++ b/Backend/ERPCore/Controllers/ReasonCodesController.cs
@@ -0,0 +1,31 @@
+using ERPCore.Domain.Enums;
+using ERPCore.Dtos.Common;
+using ERPCore.Dtos.Reference;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Reason-code reference endpoints (docs/11 §6).
+[Route("api/v1/reason-codes")]
+public sealed class ReasonCodesController : ApiControllerBase
+{
+ private readonly IReasonCodeService _codes;
+
+ public ReasonCodesController(IReasonCodeService codes) => _codes = codes;
+
+ [HttpGet]
+ [ProducesResponseType(typeof(PagedResponse), StatusCodes.Status200OK)]
+ public async Task>> List(
+ [FromQuery] ReasonContext? context, [FromQuery] PageQuery query, CancellationToken ct)
+ => Ok(await _codes.ListAsync(context, query, ct));
+
+ [HttpPost]
+ [ProducesResponseType(typeof(ReasonCodeDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Create([FromBody] CreateReasonCodeRequest request, CancellationToken ct)
+ {
+ var dto = await _codes.CreateAsync(request, ct);
+ return Created($"/api/v1/reason-codes/{dto.ReasonCodeId}", dto);
+ }
+}
diff --git a/Backend/ERPCore/Controllers/StockAdjustmentsController.cs b/Backend/ERPCore/Controllers/StockAdjustmentsController.cs
new file mode 100644
index 0000000..7952ba6
--- /dev/null
+++ b/Backend/ERPCore/Controllers/StockAdjustmentsController.cs
@@ -0,0 +1,26 @@
+using ERPCore.Dtos.Stock;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Stock-adjustment endpoints (docs/11 §5.5).
+[Route("api/v1/stock-adjustments")]
+public sealed class StockAdjustmentsController : ApiControllerBase
+{
+ private readonly IAdjustmentService _adjustments;
+
+ public StockAdjustmentsController(IAdjustmentService adjustments) => _adjustments = adjustments;
+
+ /// Create + auto-post an adjustment (mandatory reason code; decrease FIFO-consumes).
+ [HttpPost]
+ [ProducesResponseType(typeof(AdjustmentDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> Create([FromBody] CreateAdjustmentRequest request, CancellationToken ct)
+ {
+ var dto = await _adjustments.CreateAsync(request, ct);
+ return Created($"/api/v1/stock-adjustments/{dto.AdjustmentId}", dto);
+ }
+}
diff --git a/Backend/ERPCore/Controllers/StockController.cs b/Backend/ERPCore/Controllers/StockController.cs
new file mode 100644
index 0000000..3124bd3
--- /dev/null
+++ b/Backend/ERPCore/Controllers/StockController.cs
@@ -0,0 +1,56 @@
+using ERPCore.Dtos.Common;
+using ERPCore.Dtos.Procurement;
+using ERPCore.Dtos.Stock;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Stock enquiry, ledger, valuation and reorder-alert endpoints (docs/11 §5.1–5.3, §5.7).
+[Route("api/v1/stock")]
+public sealed class StockController : ApiControllerBase
+{
+ private readonly IStockService _stock;
+ private readonly IReorderService _reorder;
+
+ public StockController(IStockService stock, IReorderService reorder)
+ {
+ _stock = stock;
+ _reorder = reorder;
+ }
+
+ [HttpGet("on-hand")]
+ [ProducesResponseType(typeof(StockOnHandDto), StatusCodes.Status200OK)]
+ public async Task> OnHand([FromQuery] long itemId, [FromQuery] long warehouseId, CancellationToken ct)
+ => Ok(await _stock.GetOnHandAsync(itemId, warehouseId, ct));
+
+ [HttpGet("ledger")]
+ [ProducesResponseType(typeof(PagedResponse), StatusCodes.Status200OK)]
+ public async Task>> Ledger(
+ [FromQuery] long? itemId, [FromQuery] long? warehouseId,
+ [FromQuery] DateOnly? from, [FromQuery] DateOnly? to, [FromQuery] PageQuery query, CancellationToken ct)
+ => Ok(await _stock.GetLedgerAsync(itemId, warehouseId, from, to, query, ct));
+
+ [HttpGet("valuation")]
+ [ProducesResponseType(typeof(StockValuationDto), StatusCodes.Status200OK)]
+ public async Task> Valuation([FromQuery] long itemId, [FromQuery] long warehouseId, CancellationToken ct)
+ => Ok(await _stock.GetValuationAsync(itemId, warehouseId, ct));
+
+ /// Items at/below their reorder point (FR-STK-10), computed on read.
+ [HttpGet("reorder-alerts")]
+ [ProducesResponseType(typeof(PagedResponse), StatusCodes.Status200OK)]
+ public async Task>> ReorderAlerts(
+ [FromQuery] long? warehouseId, [FromQuery] PageQuery query, CancellationToken ct)
+ => Ok(await _reorder.GetAlertsAsync(warehouseId, query, ct));
+
+ /// Create a draft requisition for an item's suggested reorder quantity.
+ [HttpPost("reorder-alerts/{itemId:long}/requisition")]
+ [ProducesResponseType(typeof(RequisitionDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> SuggestRequisition(
+ long itemId, [FromQuery] long warehouseId, CancellationToken ct)
+ {
+ var dto = await _reorder.CreateSuggestedRequisitionAsync(itemId, warehouseId, ct);
+ return Created($"/api/v1/requisitions/{dto.RequisitionId}", dto);
+ }
+}
diff --git a/Backend/ERPCore/Controllers/StockCountsController.cs b/Backend/ERPCore/Controllers/StockCountsController.cs
new file mode 100644
index 0000000..e1c7bed
--- /dev/null
+++ b/Backend/ERPCore/Controllers/StockCountsController.cs
@@ -0,0 +1,49 @@
+using ERPCore.Dtos.Stock;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Stock-count endpoints (docs/11 §5.6).
+[Route("api/v1/stock-counts")]
+public sealed class StockCountsController : ApiControllerBase
+{
+ private readonly ICountService _counts;
+
+ public StockCountsController(ICountService counts) => _counts = counts;
+
+ [HttpGet("{countId:long}")]
+ [ProducesResponseType(typeof(CountDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task> GetById(long countId, CancellationToken ct)
+ {
+ var dto = await _counts.GetAsync(countId, ct);
+ return dto is null ? NotFound() : Ok(dto);
+ }
+
+ /// Create a count with system quantities snapshotted (immutable).
+ [HttpPost]
+ [ProducesResponseType(typeof(CountDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> Create([FromBody] CreateCountRequest request, CancellationToken ct)
+ {
+ var dto = await _counts.CreateAsync(request, ct);
+ return Created($"/api/v1/stock-counts/{dto.CountId}", dto);
+ }
+
+ /// Enter counted quantities; variance = counted − system.
+ [HttpPut("{countId:long}/counts")]
+ [ProducesResponseType(typeof(CountDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> EnterCounts(long countId, [FromBody] EnterCountsRequest request, CancellationToken ct)
+ => Ok(await _counts.EnterCountsAsync(countId, request, ct));
+
+ /// Post: emit a variance adjustment and close the count.
+ [HttpPost("{countId:long}/post")]
+ [ProducesResponseType(typeof(CountPostResultDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Post(long countId, CancellationToken ct)
+ => Ok(await _counts.PostAsync(countId, ct));
+}
diff --git a/Backend/ERPCore/Controllers/StockTransfersController.cs b/Backend/ERPCore/Controllers/StockTransfersController.cs
new file mode 100644
index 0000000..9d70733
--- /dev/null
+++ b/Backend/ERPCore/Controllers/StockTransfersController.cs
@@ -0,0 +1,49 @@
+using ERPCore.Dtos.Stock;
+using ERPCore.Services.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ERPCore.Controllers;
+
+/// Stock-transfer endpoints (docs/11 §5.4).
+[Route("api/v1/stock-transfers")]
+public sealed class StockTransfersController : ApiControllerBase
+{
+ private readonly ITransferService _transfers;
+
+ public StockTransfersController(ITransferService transfers) => _transfers = transfers;
+
+ [HttpGet("{transferId:long}")]
+ [ProducesResponseType(typeof(TransferDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ public async Task> GetById(long transferId, CancellationToken ct)
+ {
+ var dto = await _transfers.GetAsync(transferId, ct);
+ return dto is null ? NotFound() : Ok(dto);
+ }
+
+ [HttpPost]
+ [ProducesResponseType(typeof(TransferDto), StatusCodes.Status201Created)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> Create([FromBody] CreateTransferRequest request, CancellationToken ct)
+ {
+ var dto = await _transfers.CreateAsync(request, ct);
+ return Created($"/api/v1/stock-transfers/{dto.TransferId}", dto);
+ }
+
+ /// Dispatch: consume source FIFO layers into in-transit. 409 STOCK_NEGATIVE_BLOCKED if short.
+ [HttpPost("{transferId:long}/dispatch")]
+ [ProducesResponseType(typeof(DispatchResultDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task> Dispatch(long transferId, CancellationToken ct)
+ => Ok(await _transfers.DispatchAsync(transferId, ct));
+
+ /// Receive: create the destination layer at the inherited cost (cost-preserving).
+ [HttpPost("{transferId:long}/receive")]
+ [ProducesResponseType(typeof(ReceiveResultDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
+ public async Task> Receive(long transferId, [FromBody] ReceiveTransferRequest request, CancellationToken ct)
+ => Ok(await _transfers.ReceiveAsync(transferId, request, ct));
+}
diff --git a/Backend/ERPCore/Domain/Entities/AuditLog.cs b/Backend/ERPCore/Domain/Entities/AuditLog.cs
new file mode 100644
index 0000000..833a68c
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/AuditLog.cs
@@ -0,0 +1,23 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Immutable audit trail entry (FR-X-02) — the compensating control for the deferred
+/// RBAC (02-SECURITY AR-01/B.3). One row per create/update/delete of an audited
+/// entity, capturing who / when / what changed (old→new in ).
+/// Written automatically by ErpDbContext.SaveChangesAsync. Append-only at the
+/// app level; DB-role revocation of UPDATE/DELETE is deferred hardening (B.3).
+/// Model: docs/10 Part C.7.
+///
+public class AuditLog
+{
+ public long AuditId { get; set; }
+ public long UserId { get; set; }
+ public string EntityType { get; set; } = string.Empty;
+ public long EntityId { get; set; }
+ public AuditAction Action { get; set; }
+ /// JSON change set: field→value (create/delete) or field→{old,new} (update).
+ public string ChangeSet { get; set; } = "{}";
+ public DateTime CreatedAt { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/Batch.cs b/Backend/ERPCore/Domain/Entities/Batch.cs
new file mode 100644
index 0000000..cc51ae4
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/Batch.cs
@@ -0,0 +1,16 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// Batch/lot for a batch-tracked item (FR-GRN-04, FR-WH-03). Expiry drives FEFO
+/// picking of perishables. Model: docs/10 Part C.4.
+///
+public class Batch
+{
+ public long BatchId { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public string BatchNo { get; set; } = string.Empty;
+ public DateOnly? ExpiryDate { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/Grn.cs b/Backend/ERPCore/Domain/Entities/Grn.cs
new file mode 100644
index 0000000..9fc2516
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/Grn.cs
@@ -0,0 +1,37 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Goods Receipt Note header (FR-GRN-01/02). Raised against a PO or direct
+/// ( null). On confirm each line creates a FIFO layer and posts
+/// an inbound ledger entry. Mutable aggregate with an
+/// concurrency token (docs/10 C.10). Model: docs/10 Part C.3.
+///
+public class Grn
+{
+ public long GrnId { get; set; }
+ public string DocNo { get; set; } = string.Empty;
+
+ public long? PoId { get; set; }
+ public PurchaseOrder? PurchaseOrder { get; set; }
+
+ public long VendorId { get; set; }
+ public Vendor? Vendor { get; set; }
+
+ public long WarehouseId { get; set; }
+ public Warehouse? Warehouse { get; set; }
+
+ public GrnStatus Status { get; set; } = GrnStatus.Draft;
+
+ public long CreatedBy { get; set; }
+ public User? Creator { get; set; }
+
+ public DateTime CreatedAt { get; set; }
+ public DateTime? PostedAt { get; set; }
+
+ /// PostgreSQL xmin-backed optimistic concurrency token.
+ public uint RowVersion { get; set; }
+
+ public ICollection Lines { get; set; } = new List();
+}
diff --git a/Backend/ERPCore/Domain/Entities/GrnLine.cs b/Backend/ERPCore/Domain/Entities/GrnLine.cs
new file mode 100644
index 0000000..28dce48
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/GrnLine.cs
@@ -0,0 +1,37 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// GRN line (FR-GRN-04..08). is the PO-derived cost for
+/// PO-based receipts (client cost ignored — 02-SECURITY C.3) or the entered cost
+/// for direct receipts. = qty × unitCost.
+/// gates issuability. Model: docs/10 Part C.3.
+///
+public class GrnLine
+{
+ public long GrnLineId { get; set; }
+
+ public long GrnId { get; set; }
+ public Grn? Grn { get; set; }
+
+ public long? PoLineId { get; set; }
+ public PoLine? PoLine { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public long UomId { get; set; }
+ public Uom? Uom { get; set; }
+
+ public long? BinId { get; set; }
+ public Bin? Bin { get; set; }
+
+ public long? BatchId { get; set; }
+ public Batch? Batch { get; set; }
+
+ public decimal Qty { get; set; }
+ public decimal UnitCost { get; set; }
+ public decimal ReceivedValue { get; set; }
+ public HoldStatus HoldStatus { get; set; } = HoldStatus.Available;
+}
diff --git a/Backend/ERPCore/Domain/Entities/JournalEntryStub.cs b/Backend/ERPCore/Domain/Entities/JournalEntryStub.cs
new file mode 100644
index 0000000..7f458c7
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/JournalEntryStub.cs
@@ -0,0 +1,18 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// GL-ready journal entry emitted per stock movement (FR-STK-13) — data only, no
+/// posting in Phase 1 (the Accounting module consumes these later). One row per
+/// ledger entry, referencing the same source document polymorphically. Account
+/// codes are Phase-1 placeholders until a chart of accounts exists.
+/// Model: docs/10 Part C.7.
+///
+public class JournalEntryStub
+{
+ public long JournalId { get; set; }
+ public string SourceDocType { get; set; } = string.Empty;
+ public long SourceDocId { get; set; }
+ public string DebitAccount { get; set; } = string.Empty;
+ public string CreditAccount { get; set; } = string.Empty;
+ public decimal Amount { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/PurchaseReturn.cs b/Backend/ERPCore/Domain/Entities/PurchaseReturn.cs
new file mode 100644
index 0000000..1acd501
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/PurchaseReturn.cs
@@ -0,0 +1,32 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Purchase return header (FR-PROC-08) — returns received goods to a vendor,
+/// generating an outbound stock movement. Auto-posts with a mandatory reason code.
+/// Model: docs/10 Part C.2.
+///
+public class PurchaseReturn
+{
+ public long ReturnId { get; set; }
+ public string DocNo { get; set; } = string.Empty;
+
+ public long VendorId { get; set; }
+ public Vendor? Vendor { get; set; }
+
+ public long WarehouseId { get; set; }
+ public Warehouse? Warehouse { get; set; }
+
+ public long ReasonCodeId { get; set; }
+ public ReasonCode? ReasonCode { get; set; }
+
+ public ReturnStatus Status { get; set; } = ReturnStatus.Posted;
+
+ public long CreatedBy { get; set; }
+ public User? Creator { get; set; }
+
+ public DateTime CreatedAt { get; set; }
+
+ public ICollection Lines { get; set; } = new List();
+}
diff --git a/Backend/ERPCore/Domain/Entities/PurchaseReturnLine.cs b/Backend/ERPCore/Domain/Entities/PurchaseReturnLine.cs
new file mode 100644
index 0000000..f42c0e0
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/PurchaseReturnLine.cs
@@ -0,0 +1,21 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// Purchase-return line (FR-PROC-08) referencing the original GRN line for
+/// traceability. is in base UOM. Model: docs/10 Part C.2.
+///
+public class PurchaseReturnLine
+{
+ public long ReturnLineId { get; set; }
+
+ public long ReturnId { get; set; }
+ public PurchaseReturn? Return { get; set; }
+
+ public long? GrnLineId { get; set; }
+ public GrnLine? GrnLine { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public decimal Qty { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/ReasonCode.cs b/Backend/ERPCore/Domain/Entities/ReasonCode.cs
new file mode 100644
index 0000000..662bb49
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/ReasonCode.cs
@@ -0,0 +1,15 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Configurable reason code for adjustments, returns and count variances
+/// (FR-X-04). Model: docs/10 Part C.7.
+///
+public class ReasonCode
+{
+ public long ReasonCodeId { get; set; }
+ public string Code { get; set; } = string.Empty;
+ public string Description { get; set; } = string.Empty;
+ public ReasonContext Context { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/Serial.cs b/Backend/ERPCore/Domain/Entities/Serial.cs
new file mode 100644
index 0000000..2fdd5a4
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/Serial.cs
@@ -0,0 +1,16 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// Serial number for a serial-tracked item across its lifecycle (FR-WH-04).
+/// Model: docs/10 Part C.4.
+///
+public class Serial
+{
+ public long SerialId { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public string SerialNo { get; set; } = string.Empty;
+ public string Status { get; set; } = "InStock";
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockAdjustment.cs b/Backend/ERPCore/Domain/Entities/StockAdjustment.cs
new file mode 100644
index 0000000..3b47f1a
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockAdjustment.cs
@@ -0,0 +1,31 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Stock adjustment header (FR-STK-07) — the highest-risk feature in the phase
+/// (02-SECURITY C.5). Auto-posts in Phase 1 with a mandatory reason code and user
+/// stamp. Mutable aggregate with an token (docs/10 C.10).
+/// Model: docs/10 Part C.6.
+///
+public class StockAdjustment
+{
+ public long AdjustmentId { get; set; }
+ public string DocNo { get; set; } = string.Empty;
+
+ public long WarehouseId { get; set; }
+ public Warehouse? Warehouse { get; set; }
+
+ public long ReasonCodeId { get; set; }
+ public ReasonCode? ReasonCode { get; set; }
+
+ public AdjustmentStatus Status { get; set; } = AdjustmentStatus.Posted;
+
+ public long CreatedBy { get; set; }
+ public User? Creator { get; set; }
+
+ public DateTime CreatedAt { get; set; }
+ public uint RowVersion { get; set; }
+
+ public ICollection Lines { get; set; } = new List();
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockAdjustmentLine.cs b/Backend/ERPCore/Domain/Entities/StockAdjustmentLine.cs
new file mode 100644
index 0000000..dbdae9b
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockAdjustmentLine.cs
@@ -0,0 +1,23 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// Adjustment line (FR-STK-07). is a signed base-UOM
+/// quantity: negative consumes FIFO layers, positive creates a layer at last cost.
+/// Model: docs/10 Part C.6.
+///
+public class StockAdjustmentLine
+{
+ public long AdjLineId { get; set; }
+
+ public long AdjustmentId { get; set; }
+ public StockAdjustment? Adjustment { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public long? BinId { get; set; }
+ public long? BatchId { get; set; }
+ public long? SerialId { get; set; }
+
+ public decimal QtyDelta { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockCount.cs b/Backend/ERPCore/Domain/Entities/StockCount.cs
new file mode 100644
index 0000000..5d652d8
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockCount.cs
@@ -0,0 +1,29 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Cycle/full physical count header (FR-STK-08). System quantities are snapshotted
+/// at creation and are immutable once opened (02-SECURITY C.7); posting emits a
+/// variance adjustment. Mutable aggregate with an token.
+/// Model: docs/10 Part C.6.
+///
+public class StockCount
+{
+ public long CountId { get; set; }
+ public string DocNo { get; set; } = string.Empty;
+
+ public long WarehouseId { get; set; }
+ public Warehouse? Warehouse { get; set; }
+
+ public CountType CountType { get; set; }
+ public CountStatus Status { get; set; } = CountStatus.Draft;
+
+ public long CreatedBy { get; set; }
+ public User? Creator { get; set; }
+
+ public DateTime CreatedAt { get; set; }
+ public uint RowVersion { get; set; }
+
+ public ICollection Lines { get; set; } = new List();
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockCountLine.cs b/Backend/ERPCore/Domain/Entities/StockCountLine.cs
new file mode 100644
index 0000000..2a8ef40
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockCountLine.cs
@@ -0,0 +1,22 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// Count line (FR-STK-08). is the immutable snapshot;
+/// = counted − system (in base UOM). Model: docs/10 Part C.6.
+///
+public class StockCountLine
+{
+ public long CountLineId { get; set; }
+
+ public long CountId { get; set; }
+ public StockCount? Count { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public long? BinId { get; set; }
+
+ public decimal SystemQty { get; set; }
+ public decimal? CountedQty { get; set; }
+ public decimal? Variance { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockLayer.cs b/Backend/ERPCore/Domain/Entities/StockLayer.cs
new file mode 100644
index 0000000..de686c1
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockLayer.cs
@@ -0,0 +1,33 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// FIFO cost layer — a quantity received at a specific unit cost, consumed
+/// oldest-first (FR-STK-02). Keyed per item **per warehouse**; quantities and
+/// are in the item's base UOM. Answers valuation
+/// ("what's on hand and at what cost"). Model: docs/10 Part C.5.
+///
+public class StockLayer
+{
+ public long LayerId { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public long WarehouseId { get; set; }
+ public Warehouse? Warehouse { get; set; }
+
+ public long? BatchId { get; set; }
+ public Batch? Batch { get; set; }
+
+ public long? SerialId { get; set; }
+ public Serial? Serial { get; set; }
+
+ /// Originating GRN line — carries the inspection hold status for this stock.
+ public long? GrnLineId { get; set; }
+ public GrnLine? GrnLine { get; set; }
+
+ public decimal QtyReceived { get; set; }
+ public decimal QtyRemaining { get; set; }
+ public decimal UnitCost { get; set; }
+ public DateTime ReceiptDate { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockLedger.cs b/Backend/ERPCore/Domain/Entities/StockLedger.cs
new file mode 100644
index 0000000..cbffbf7
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockLedger.cs
@@ -0,0 +1,32 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Immutable, append-only stock ledger (FR-STK-01, FR-X-05). One row per costed
+/// movement; answers history ("what moved, when, by whom"). The originating
+/// document is referenced polymorphically via
+/// / (no hard FK per type) so
+/// new transaction types write here without a schema change. Model: docs/10 Part C.5.
+///
+public class StockLedger
+{
+ public long LedgerId { get; set; }
+
+ public long ItemId { get; set; }
+ public long WarehouseId { get; set; }
+ public long? BinId { get; set; }
+ public long? BatchId { get; set; }
+ public long? SerialId { get; set; }
+ public long UserId { get; set; }
+
+ public Direction Direction { get; set; }
+ public decimal QtyBase { get; set; }
+ public decimal UnitCost { get; set; }
+ public decimal Value { get; set; }
+ public decimal RunningBalance { get; set; }
+
+ public string SourceDocType { get; set; } = string.Empty;
+ public long SourceDocId { get; set; }
+ public DateTime CreatedAt { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockTransfer.cs b/Backend/ERPCore/Domain/Entities/StockTransfer.cs
new file mode 100644
index 0000000..7bfc244
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockTransfer.cs
@@ -0,0 +1,31 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Domain.Entities;
+
+///
+/// Inter-warehouse stock transfer header (FR-STK-05/06). Dispatch consumes source
+/// FIFO layers into in-transit; receive creates the destination layer at the
+/// inherited cost (cost-preserving). Mutable aggregate with an
+/// token (docs/10 C.10). Model: docs/10 Part C.6.
+///
+public class StockTransfer
+{
+ public long TransferId { get; set; }
+ public string DocNo { get; set; } = string.Empty;
+
+ public long SrcWarehouseId { get; set; }
+ public Warehouse? SrcWarehouse { get; set; }
+
+ public long DestWarehouseId { get; set; }
+ public Warehouse? DestWarehouse { get; set; }
+
+ public TransferStatus Status { get; set; } = TransferStatus.Draft;
+
+ public long CreatedBy { get; set; }
+ public User? Creator { get; set; }
+
+ public DateTime CreatedAt { get; set; }
+ public uint RowVersion { get; set; }
+
+ public ICollection Lines { get; set; } = new List();
+}
diff --git a/Backend/ERPCore/Domain/Entities/StockTransferLine.cs b/Backend/ERPCore/Domain/Entities/StockTransferLine.cs
new file mode 100644
index 0000000..3959676
--- /dev/null
+++ b/Backend/ERPCore/Domain/Entities/StockTransferLine.cs
@@ -0,0 +1,35 @@
+namespace ERPCore.Domain.Entities;
+
+///
+/// Transfer line (FR-STK-05/06). is in base UOM.
+///
+/// Deviation note: and extend
+/// docs/10 Part C.6's STOCK_TRANSFER_LINE to make the transfer
+/// cost-preserving: at dispatch the value-weighted cost of the consumed source
+/// layers is stored here, and receive recreates the destination layer at that cost
+/// (supports partial receive via ).
+///
+///
+public class StockTransferLine
+{
+ public long TransferLineId { get; set; }
+
+ public long TransferId { get; set; }
+ public StockTransfer? Transfer { get; set; }
+
+ public long ItemId { get; set; }
+ public Item? Item { get; set; }
+
+ public long? SrcBinId { get; set; }
+ public long? DestBinId { get; set; }
+ public long? BatchId { get; set; }
+ public long? SerialId { get; set; }
+
+ public decimal Qty { get; set; }
+
+ /// Value-weighted unit cost of the consumed source layers (set at dispatch).
+ public decimal? UnitCost { get; set; }
+
+ /// Quantity already received at the destination (partial-receive support).
+ public decimal QtyReceived { get; set; }
+}
diff --git a/Backend/ERPCore/Domain/Enums/AdjustmentStatus.cs b/Backend/ERPCore/Domain/Enums/AdjustmentStatus.cs
new file mode 100644
index 0000000..7d56708
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/AdjustmentStatus.cs
@@ -0,0 +1,13 @@
+namespace ERPCore.Domain.Enums;
+
+///
+/// Stock-adjustment lifecycle (docs/10 §B.8.1). Phase 1 auto-posts, so
+/// is reserved for the future threshold-approval
+/// workflow (FR-STK-07). Stored as a string.
+///
+public enum AdjustmentStatus
+{
+ Draft,
+ PendingApproval,
+ Posted
+}
diff --git a/Backend/ERPCore/Domain/Enums/AuditAction.cs b/Backend/ERPCore/Domain/Enums/AuditAction.cs
new file mode 100644
index 0000000..f7644e8
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/AuditAction.cs
@@ -0,0 +1,9 @@
+namespace ERPCore.Domain.Enums;
+
+/// Kind of mutation recorded in the audit trail (FR-X-02). Stored as a string.
+public enum AuditAction
+{
+ Create,
+ Update,
+ Delete
+}
diff --git a/Backend/ERPCore/Domain/Enums/CountStatus.cs b/Backend/ERPCore/Domain/Enums/CountStatus.cs
new file mode 100644
index 0000000..8e3e958
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/CountStatus.cs
@@ -0,0 +1,9 @@
+namespace ERPCore.Domain.Enums;
+
+/// Stock-count lifecycle (docs/11 §8; docs/10 §B.8.1). Stored as a string.
+public enum CountStatus
+{
+ Draft,
+ Counted,
+ Posted
+}
diff --git a/Backend/ERPCore/Domain/Enums/CountType.cs b/Backend/ERPCore/Domain/Enums/CountType.cs
new file mode 100644
index 0000000..29015d8
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/CountType.cs
@@ -0,0 +1,8 @@
+namespace ERPCore.Domain.Enums;
+
+/// Physical-count scope (docs/11 §8; FR-STK-08). Stored as a string.
+public enum CountType
+{
+ Cycle,
+ Full
+}
diff --git a/Backend/ERPCore/Domain/Enums/Direction.cs b/Backend/ERPCore/Domain/Enums/Direction.cs
new file mode 100644
index 0000000..afee991
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/Direction.cs
@@ -0,0 +1,8 @@
+namespace ERPCore.Domain.Enums;
+
+/// Stock-ledger movement direction (docs/11 §8). Stored as a string.
+public enum Direction
+{
+ In,
+ Out
+}
diff --git a/Backend/ERPCore/Domain/Enums/GrnStatus.cs b/Backend/ERPCore/Domain/Enums/GrnStatus.cs
new file mode 100644
index 0000000..550cca2
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/GrnStatus.cs
@@ -0,0 +1,9 @@
+namespace ERPCore.Domain.Enums;
+
+/// Goods-receipt-note lifecycle (docs/11 §8; docs/10 §B.8.1). Stored as a string.
+public enum GrnStatus
+{
+ Draft,
+ Confirmed,
+ Closed
+}
diff --git a/Backend/ERPCore/Domain/Enums/HoldStatus.cs b/Backend/ERPCore/Domain/Enums/HoldStatus.cs
new file mode 100644
index 0000000..e38dd1d
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/HoldStatus.cs
@@ -0,0 +1,12 @@
+namespace ERPCore.Domain.Enums;
+
+///
+/// Inspection-hold state of received stock (docs/11 §8; FR-GRN-05).
+/// stock is on-hand but not issuable until released (FR-WH-07). Stored as a string.
+///
+public enum HoldStatus
+{
+ Available,
+ OnHold,
+ Rejected
+}
diff --git a/Backend/ERPCore/Domain/Enums/ReasonContext.cs b/Backend/ERPCore/Domain/Enums/ReasonContext.cs
new file mode 100644
index 0000000..b569040
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/ReasonContext.cs
@@ -0,0 +1,9 @@
+namespace ERPCore.Domain.Enums;
+
+/// Where a reason code applies (FR-X-04; docs/10 §B.8.3). Stored as a string.
+public enum ReasonContext
+{
+ Adjustment,
+ Return,
+ Count
+}
diff --git a/Backend/ERPCore/Domain/Enums/ReturnStatus.cs b/Backend/ERPCore/Domain/Enums/ReturnStatus.cs
new file mode 100644
index 0000000..6214b0b
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/ReturnStatus.cs
@@ -0,0 +1,8 @@
+namespace ERPCore.Domain.Enums;
+
+/// Purchase-return lifecycle (docs/11 §3.4). Auto-posts in Phase 1. Stored as a string.
+public enum ReturnStatus
+{
+ Draft,
+ Posted
+}
diff --git a/Backend/ERPCore/Domain/Enums/TransferStatus.cs b/Backend/ERPCore/Domain/Enums/TransferStatus.cs
new file mode 100644
index 0000000..0f96724
--- /dev/null
+++ b/Backend/ERPCore/Domain/Enums/TransferStatus.cs
@@ -0,0 +1,10 @@
+namespace ERPCore.Domain.Enums;
+
+/// Stock-transfer lifecycle (docs/11 §8; docs/10 §B.8.1). Stored as a string.
+public enum TransferStatus
+{
+ Draft,
+ InTransit,
+ Received,
+ Closed
+}
diff --git a/Backend/ERPCore/Dtos/Audit/AuditDtos.cs b/Backend/ERPCore/Dtos/Audit/AuditDtos.cs
new file mode 100644
index 0000000..4870725
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Audit/AuditDtos.cs
@@ -0,0 +1,12 @@
+using System.Text.Json;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Audit;
+
+/// An audit-trail entry (FR-X-02). ChangeSet is the stored JSON, inlined.
+public sealed record AuditLogDto(
+ long AuditId, long UserId, string EntityType, long EntityId, AuditAction Action, JsonElement ChangeSet, DateTime CreatedAt);
+
+/// A GL-ready journal stub emitted per stock movement (FR-STK-13).
+public sealed record JournalEntryStubDto(
+ long JournalId, string SourceDocType, long SourceDocId, string DebitAccount, string CreditAccount, decimal Amount);
diff --git a/Backend/ERPCore/Dtos/Grn/GrnDtos.cs b/Backend/ERPCore/Dtos/Grn/GrnDtos.cs
new file mode 100644
index 0000000..72582ed
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Grn/GrnDtos.cs
@@ -0,0 +1,63 @@
+using System.ComponentModel.DataAnnotations;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Grn;
+
+// Responses (docs/11 §4) --------------------------------------------------------
+
+public sealed record GrnLineDto(
+ long GrnLineId, long? PoLineId, long ItemId, long UomId, long? BinId,
+ decimal Qty, decimal UnitCost, decimal ReceivedValue, HoldStatus HoldStatus, long? BatchId);
+
+public sealed record GrnDto(
+ long GrnId, string DocNo, long? PoId, long VendorId, long WarehouseId, GrnStatus Status,
+ long CreatedBy, DateTime CreatedAt, DateTime? PostedAt, IReadOnlyList Lines);
+
+public sealed record CreatedLayerDto(
+ long LayerId, long ItemId, long WarehouseId, long? BatchId,
+ decimal QtyReceived, decimal QtyRemaining, decimal UnitCost, DateTime ReceiptDate);
+
+public sealed record GrnConfirmResultDto(
+ long GrnId, GrnStatus Status, DateTime PostedAt,
+ IReadOnlyList CreatedLayers, IReadOnlyList LedgerRefs, PurchaseOrderStatus? PoStatus);
+
+public sealed record ReleaseLineResultDto(long GrnLineId, HoldStatus HoldStatus);
+
+// Requests ----------------------------------------------------------------------
+
+public sealed class BatchInput
+{
+ [Required, StringLength(50)] public string BatchNo { get; set; } = string.Empty;
+ public DateOnly? ExpiryDate { get; set; }
+}
+
+public sealed class CreateGrnLineInput
+{
+ /// Set for a PO-based receipt; cost is then derived from the PO line (02-SECURITY C.3).
+ public long? PoLineId { get; set; }
+ [Required] public long ItemId { get; set; }
+ [Required] public long UomId { get; set; }
+ public long? BinId { get; set; }
+ [Range(0.0001, double.MaxValue)] public decimal Qty { get; set; }
+ /// Used only for direct (no-PO) receipts; ignored when is set.
+ [Range(0, double.MaxValue)] public decimal UnitCost { get; set; }
+ [EnumDataType(typeof(HoldStatus))] public HoldStatus HoldStatus { get; set; } = HoldStatus.Available;
+ public BatchInput? Batch { get; set; }
+}
+
+public sealed class CreateGrnRequest
+{
+ /// PO to receive against; null for a direct/emergency receipt (FR-GRN-02).
+ public long? PoId { get; set; }
+ /// Required for a direct receipt (no PO); ignored otherwise (vendor derives from the PO).
+ public long? VendorId { get; set; }
+ [Required] public long WarehouseId { get; set; }
+ [Required, MinLength(1)] public List Lines { get; set; } = new();
+}
+
+public sealed class ReleaseLineRequest
+{
+ /// Release makes the stock available; Reject removes it from on-hand.
+ [Required, RegularExpression("Release|Reject")]
+ public string Action { get; set; } = "Release";
+}
diff --git a/Backend/ERPCore/Dtos/Procurement/PurchaseReturnDtos.cs b/Backend/ERPCore/Dtos/Procurement/PurchaseReturnDtos.cs
new file mode 100644
index 0000000..85328ed
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Procurement/PurchaseReturnDtos.cs
@@ -0,0 +1,31 @@
+using System.ComponentModel.DataAnnotations;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Procurement;
+
+// Responses (docs/11 §3.4) ------------------------------------------------------
+
+public sealed record PurchaseReturnLineDto(long ReturnLineId, long? GrnLineId, long ItemId, decimal Qty);
+
+public sealed record PurchaseReturnDto(
+ long ReturnId, string DocNo, long VendorId, long WarehouseId, long ReasonCodeId, ReturnStatus Status,
+ long CreatedBy, IReadOnlyList Lines, IReadOnlyList LedgerRefs);
+
+// Requests ----------------------------------------------------------------------
+
+public sealed class CreatePurchaseReturnLineInput
+{
+ /// Original GRN line, for traceability against the receipt.
+ public long? GrnLineId { get; set; }
+ [Required] public long ItemId { get; set; }
+ [Range(0.0001, double.MaxValue)] public decimal Qty { get; set; }
+}
+
+public sealed class CreatePurchaseReturnRequest
+{
+ [Required] public long VendorId { get; set; }
+ [Required] public long WarehouseId { get; set; }
+ /// Nullable so an omitted value is a distinct REASON_CODE_REQUIRED error.
+ public long? ReasonCodeId { get; set; }
+ [Required, MinLength(1)] public List Lines { get; set; } = new();
+}
diff --git a/Backend/ERPCore/Dtos/Reference/ReasonCodeDtos.cs b/Backend/ERPCore/Dtos/Reference/ReasonCodeDtos.cs
new file mode 100644
index 0000000..60080f2
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Reference/ReasonCodeDtos.cs
@@ -0,0 +1,14 @@
+using System.ComponentModel.DataAnnotations;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Reference;
+
+/// Reason code (docs/11 §6).
+public sealed record ReasonCodeDto(long ReasonCodeId, string Code, string Description, ReasonContext Context);
+
+public sealed class CreateReasonCodeRequest
+{
+ [Required, StringLength(20)] public string Code { get; set; } = string.Empty;
+ [Required, StringLength(200)] public string Description { get; set; } = string.Empty;
+ [Required, EnumDataType(typeof(ReasonContext))] public ReasonContext Context { get; set; }
+}
diff --git a/Backend/ERPCore/Dtos/Stock/AdjustmentDtos.cs b/Backend/ERPCore/Dtos/Stock/AdjustmentDtos.cs
new file mode 100644
index 0000000..57d41a3
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Stock/AdjustmentDtos.cs
@@ -0,0 +1,31 @@
+using System.ComponentModel.DataAnnotations;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Stock;
+
+// Responses (docs/11 §5.5) ------------------------------------------------------
+
+public sealed record AdjustmentLineDto(long AdjLineId, long ItemId, long? BinId, long? BatchId, decimal QtyDelta);
+
+public sealed record AdjustmentDto(
+ long AdjustmentId, string DocNo, long WarehouseId, long ReasonCodeId, AdjustmentStatus Status,
+ long CreatedBy, DateTime CreatedAt, IReadOnlyList Lines, IReadOnlyList LedgerRefs);
+
+// Requests ----------------------------------------------------------------------
+
+public sealed class CreateAdjustmentLineInput
+{
+ [Required] public long ItemId { get; set; }
+ public long? BinId { get; set; }
+ public long? BatchId { get; set; }
+ /// Signed base-UOM delta: negative consumes FIFO layers, positive adds stock.
+ public decimal QtyDelta { get; set; }
+}
+
+public sealed class CreateAdjustmentRequest
+{
+ [Required] public long WarehouseId { get; set; }
+ /// Nullable so an omitted value is a distinct REASON_CODE_REQUIRED error, not 0.
+ public long? ReasonCodeId { get; set; }
+ [Required, MinLength(1)] public List Lines { get; set; } = new();
+}
diff --git a/Backend/ERPCore/Dtos/Stock/CountDtos.cs b/Backend/ERPCore/Dtos/Stock/CountDtos.cs
new file mode 100644
index 0000000..79a4b73
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Stock/CountDtos.cs
@@ -0,0 +1,33 @@
+using System.ComponentModel.DataAnnotations;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Stock;
+
+// Responses (docs/11 §5.6) ------------------------------------------------------
+
+public sealed record CountLineDto(long CountLineId, long ItemId, long? BinId, decimal SystemQty, decimal? CountedQty, decimal? Variance);
+
+public sealed record CountDto(
+ long CountId, string DocNo, long WarehouseId, CountType CountType, CountStatus Status, IReadOnlyList Lines);
+
+public sealed record CountPostResultDto(long CountId, CountStatus Status, long? AdjustmentId, IReadOnlyList LedgerRefs);
+
+// Requests ----------------------------------------------------------------------
+
+public sealed class CreateCountRequest
+{
+ [Required] public long WarehouseId { get; set; }
+ [Required, EnumDataType(typeof(CountType))] public CountType CountType { get; set; }
+ [Required, MinLength(1)] public List ItemIds { get; set; } = new();
+}
+
+public sealed class EnterCountLineInput
+{
+ [Required] public long CountLineId { get; set; }
+ [Range(0, double.MaxValue)] public decimal CountedQty { get; set; }
+}
+
+public sealed class EnterCountsRequest
+{
+ [Required, MinLength(1)] public List Lines { get; set; } = new();
+}
diff --git a/Backend/ERPCore/Dtos/Stock/ReorderDtos.cs b/Backend/ERPCore/Dtos/Stock/ReorderDtos.cs
new file mode 100644
index 0000000..48d1b7c
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Stock/ReorderDtos.cs
@@ -0,0 +1,6 @@
+namespace ERPCore.Dtos.Stock;
+
+/// An item at/below its reorder point (docs/11 §5.7; FR-STK-10). Computed on read.
+public sealed record ReorderAlertDto(
+ long ItemId, long WarehouseId, decimal Available,
+ decimal ReorderPoint, decimal ReorderQty, decimal SuggestedRequisitionQty);
diff --git a/Backend/ERPCore/Dtos/Stock/StockDtos.cs b/Backend/ERPCore/Dtos/Stock/StockDtos.cs
new file mode 100644
index 0000000..a1663e8
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Stock/StockDtos.cs
@@ -0,0 +1,22 @@
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Stock;
+
+/// Stock enquiry (docs/11 §5.1). available = onHand − onHold − reserved − inTransit(out).
+public sealed record StockOnHandDto(
+ long ItemId, long WarehouseId, decimal OnHand, decimal Available,
+ decimal OnHold, decimal InTransit, decimal Reserved, DateTime AsOf);
+
+/// A stock-ledger row (docs/11 §5.2).
+public sealed record StockLedgerRowDto(
+ long LedgerId, long ItemId, long WarehouseId, long? BinId, long? BatchId, long? SerialId,
+ Direction Direction, decimal QtyBase, decimal UnitCost, decimal Value, decimal RunningBalance,
+ string SourceDocType, long SourceDocId, long UserId, DateTime CreatedAt);
+
+/// An open FIFO layer in a valuation (docs/11 §5.3).
+public sealed record StockValuationLayerDto(long LayerId, decimal QtyRemaining, decimal UnitCost, decimal Value, DateTime ReceiptDate);
+
+/// Valuation of on-hand stock from open FIFO layers (docs/11 §5.3).
+public sealed record StockValuationDto(
+ long ItemId, long WarehouseId, IReadOnlyList Layers,
+ decimal TotalQty, decimal TotalValue, string Currency, string CostingMethod);
diff --git a/Backend/ERPCore/Dtos/Stock/TransferDtos.cs b/Backend/ERPCore/Dtos/Stock/TransferDtos.cs
new file mode 100644
index 0000000..3974852
--- /dev/null
+++ b/Backend/ERPCore/Dtos/Stock/TransferDtos.cs
@@ -0,0 +1,52 @@
+using System.ComponentModel.DataAnnotations;
+using ERPCore.Domain.Enums;
+
+namespace ERPCore.Dtos.Stock;
+
+// Responses (docs/11 §5.4) ------------------------------------------------------
+
+public sealed record TransferLineDto(
+ long TransferLineId, long ItemId, long? SrcBinId, long? DestBinId, long? BatchId, decimal Qty, decimal QtyReceived);
+
+public sealed record TransferDto(
+ long TransferId, string DocNo, long SrcWarehouseId, long DestWarehouseId,
+ TransferStatus Status, IReadOnlyList Lines);
+
+public sealed record ConsumedLayerDto(long LayerId, decimal QtyConsumed, decimal UnitCost);
+
+public sealed record DispatchResultDto(
+ long TransferId, TransferStatus Status, IReadOnlyList ConsumedLayers, IReadOnlyList LedgerRefs);
+
+public sealed record TransferCreatedLayerDto(long LayerId, long WarehouseId, decimal QtyReceived, decimal UnitCost);
+
+public sealed record ReceiveResultDto(
+ long TransferId, TransferStatus Status, IReadOnlyList CreatedLayers, IReadOnlyList LedgerRefs);
+
+// Requests ----------------------------------------------------------------------
+
+public sealed class CreateTransferLineInput
+{
+ [Required] public long ItemId { get; set; }
+ public long? SrcBinId { get; set; }
+ public long? DestBinId { get; set; }
+ public long? BatchId { get; set; }
+ [Range(0.0001, double.MaxValue)] public decimal Qty { get; set; }
+}
+
+public sealed class CreateTransferRequest
+{
+ [Required] public long SrcWarehouseId { get; set; }
+ [Required] public long DestWarehouseId { get; set; }
+ [Required, MinLength(1)] public List Lines { get; set; } = new();
+}
+
+public sealed class ReceiveTransferLineInput
+{
+ [Required] public long TransferLineId { get; set; }
+ [Range(0.0001, double.MaxValue)] public decimal Qty { get; set; }
+}
+
+public sealed class ReceiveTransferRequest
+{
+ [Required, MinLength(1)] public List Lines { get; set; } = new();
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Auditing/AuditScribe.cs b/Backend/ERPCore/Infra/Persistence/Auditing/AuditScribe.cs
new file mode 100644
index 0000000..a65e413
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Auditing/AuditScribe.cs
@@ -0,0 +1,98 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using ERPCore.Domain.Entities;
+using ERPCore.Domain.Enums;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.ChangeTracking;
+
+namespace ERPCore.Infra.Persistence.Auditing;
+
+/// A mutation captured before save, awaiting its (possibly generated) key.
+public sealed record PendingAudit(EntityEntry Entry, string EntityType, AuditAction Action, string ChangeSet, long CapturedId, bool IsAdded);
+
+///
+/// Builds audit-trail rows from the EF change tracker (FR-X-02). High-volume /
+/// derived / self-referential tables are excluded (the stock ledger is itself the
+/// stock movement audit). Change sets are captured before save so old→new is
+/// accurate; generated keys for inserts are read after save.
+///
+public static class AuditScribe
+{
+ private static readonly HashSet Excluded =
+ [
+ typeof(AuditLog), typeof(JournalEntryStub), typeof(NumberSequence),
+ typeof(StockLedger), typeof(StockLayer),
+ ];
+
+ private static readonly JsonSerializerOptions Json = new()
+ {
+ Converters = { new JsonStringEnumConverter() },
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ };
+
+ public static List Capture(ChangeTracker tracker)
+ {
+ var pending = new List();
+ foreach (var entry in tracker.Entries())
+ {
+ if (entry.State is not (EntityState.Added or EntityState.Modified or EntityState.Deleted)) continue;
+ if (Excluded.Contains(entry.Entity.GetType())) continue;
+
+ var action = entry.State switch
+ {
+ EntityState.Added => AuditAction.Create,
+ EntityState.Deleted => AuditAction.Delete,
+ _ => AuditAction.Update,
+ };
+
+ var changeSet = BuildChangeSet(entry, action);
+ if (action == AuditAction.Update && changeSet == "{}") continue; // only concurrency token touched, etc.
+
+ var isAdded = entry.State == EntityState.Added;
+ pending.Add(new PendingAudit(entry, entry.Entity.GetType().Name, action, changeSet, isAdded ? 0 : ReadKey(entry), isAdded));
+ }
+ return pending;
+ }
+
+ public static AuditLog ToLog(PendingAudit p, long userId, DateTime now) => new()
+ {
+ UserId = userId,
+ EntityType = p.EntityType,
+ EntityId = p.IsAdded ? ReadKey(p.Entry) : p.CapturedId,
+ Action = p.Action,
+ ChangeSet = p.ChangeSet,
+ CreatedAt = now,
+ };
+
+ private static long ReadKey(EntityEntry entry)
+ {
+ var pk = entry.Metadata.FindPrimaryKey();
+ if (pk is null || pk.Properties.Count != 1) return 0;
+ var value = entry.Property(pk.Properties[0].Name).CurrentValue;
+ return value is null ? 0 : Convert.ToInt64(value);
+ }
+
+ private static string BuildChangeSet(EntityEntry entry, AuditAction action)
+ {
+ var set = new Dictionary();
+ foreach (var p in entry.Properties)
+ {
+ if (p.Metadata.IsPrimaryKey()) continue;
+ if (p.Metadata.Name == nameof(Item.RowVersion)) continue;
+
+ switch (action)
+ {
+ case AuditAction.Create when p.CurrentValue is not null:
+ set[p.Metadata.Name] = p.CurrentValue;
+ break;
+ case AuditAction.Delete:
+ set[p.Metadata.Name] = p.OriginalValue;
+ break;
+ case AuditAction.Update when p.IsModified && !Equals(p.OriginalValue, p.CurrentValue):
+ set[p.Metadata.Name] = new Dictionary { ["old"] = p.OriginalValue, ["new"] = p.CurrentValue };
+ break;
+ }
+ }
+ return JsonSerializer.Serialize(set, Json);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/AuditConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/AuditConfiguration.cs
new file mode 100644
index 0000000..a93681c
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/AuditConfiguration.cs
@@ -0,0 +1,41 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class AuditLogConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("audit_logs");
+ builder.HasKey(a => a.AuditId);
+
+ builder.Property(a => a.EntityType).IsRequired().HasMaxLength(80);
+ builder.Property(a => a.Action).HasConversion().HasMaxLength(10).IsRequired();
+ builder.Property(a => a.ChangeSet).IsRequired().HasColumnType("jsonb");
+ builder.Property(a => a.CreatedAt).IsRequired();
+
+ builder.HasOne().WithMany().HasForeignKey(a => a.UserId).OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasIndex(a => new { a.EntityType, a.EntityId });
+ builder.HasIndex(a => a.CreatedAt);
+ builder.HasIndex(a => a.UserId);
+ }
+}
+
+public sealed class JournalEntryStubConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("journal_entry_stubs");
+ builder.HasKey(j => j.JournalId);
+
+ builder.Property(j => j.SourceDocType).IsRequired().HasMaxLength(10);
+ builder.Property(j => j.DebitAccount).IsRequired().HasMaxLength(20);
+ builder.Property(j => j.CreditAccount).IsRequired().HasMaxLength(20);
+ builder.Property(j => j.Amount).HasPrecision(18, 4);
+
+ builder.HasIndex(j => new { j.SourceDocType, j.SourceDocId });
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/BatchSerialConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/BatchSerialConfiguration.cs
new file mode 100644
index 0000000..8de6adf
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/BatchSerialConfiguration.cs
@@ -0,0 +1,43 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class BatchConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("batches");
+ builder.HasKey(b => b.BatchId);
+
+ builder.Property(b => b.BatchNo).IsRequired().HasMaxLength(50);
+
+ builder.HasOne(b => b.Item)
+ .WithMany()
+ .HasForeignKey(b => b.ItemId)
+ .OnDelete(DeleteBehavior.Restrict);
+
+ // Batch number unique within an item.
+ builder.HasIndex(b => new { b.ItemId, b.BatchNo }).IsUnique();
+ }
+}
+
+public sealed class SerialConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("serials");
+ builder.HasKey(s => s.SerialId);
+
+ builder.Property(s => s.SerialNo).IsRequired().HasMaxLength(100);
+ builder.Property(s => s.Status).IsRequired().HasMaxLength(20);
+
+ builder.HasOne(s => s.Item)
+ .WithMany()
+ .HasForeignKey(s => s.ItemId)
+ .OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasIndex(s => new { s.ItemId, s.SerialNo }).IsUnique();
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/GrnConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/GrnConfiguration.cs
new file mode 100644
index 0000000..087ea19
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/GrnConfiguration.cs
@@ -0,0 +1,50 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class GrnConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("grns");
+ builder.HasKey(g => g.GrnId);
+
+ builder.Property(g => g.DocNo).IsRequired().HasMaxLength(30);
+ builder.HasIndex(g => g.DocNo).IsUnique();
+
+ builder.Property(g => g.Status).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(g => g.CreatedAt).IsRequired();
+ builder.Property(g => g.RowVersion).IsRowVersion();
+
+ builder.HasOne(g => g.PurchaseOrder).WithMany().HasForeignKey(g => g.PoId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(g => g.Vendor).WithMany().HasForeignKey(g => g.VendorId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(g => g.Warehouse).WithMany().HasForeignKey(g => g.WarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(g => g.Creator).WithMany().HasForeignKey(g => g.CreatedBy).OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasIndex(g => g.Status);
+ builder.HasIndex(g => g.PoId);
+ }
+}
+
+public sealed class GrnLineConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("grn_lines");
+ builder.HasKey(l => l.GrnLineId);
+
+ builder.Property(l => l.Qty).HasPrecision(18, 4);
+ builder.Property(l => l.UnitCost).HasPrecision(18, 6);
+ builder.Property(l => l.ReceivedValue).HasPrecision(18, 4);
+ builder.Property(l => l.HoldStatus).HasConversion().HasMaxLength(20).IsRequired();
+
+ builder.HasOne(l => l.Grn).WithMany(g => g.Lines).HasForeignKey(l => l.GrnId).OnDelete(DeleteBehavior.Cascade);
+ builder.HasOne(l => l.PoLine).WithMany().HasForeignKey(l => l.PoLineId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Uom).WithMany().HasForeignKey(l => l.UomId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Bin).WithMany().HasForeignKey(l => l.BinId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Batch).WithMany().HasForeignKey(l => l.BatchId).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/PurchaseReturnConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/PurchaseReturnConfiguration.cs
new file mode 100644
index 0000000..00add0a
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/PurchaseReturnConfiguration.cs
@@ -0,0 +1,40 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class PurchaseReturnConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("purchase_returns");
+ builder.HasKey(r => r.ReturnId);
+
+ builder.Property(r => r.DocNo).IsRequired().HasMaxLength(30);
+ builder.HasIndex(r => r.DocNo).IsUnique();
+
+ builder.Property(r => r.Status).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(r => r.CreatedAt).IsRequired();
+
+ builder.HasOne(r => r.Vendor).WithMany().HasForeignKey(r => r.VendorId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(r => r.Warehouse).WithMany().HasForeignKey(r => r.WarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(r => r.ReasonCode).WithMany().HasForeignKey(r => r.ReasonCodeId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(r => r.Creator).WithMany().HasForeignKey(r => r.CreatedBy).OnDelete(DeleteBehavior.Restrict);
+ }
+}
+
+public sealed class PurchaseReturnLineConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("purchase_return_lines");
+ builder.HasKey(l => l.ReturnLineId);
+
+ builder.Property(l => l.Qty).HasPrecision(18, 4);
+
+ builder.HasOne(l => l.Return).WithMany(r => r.Lines).HasForeignKey(l => l.ReturnId).OnDelete(DeleteBehavior.Cascade);
+ builder.HasOne(l => l.GrnLine).WithMany().HasForeignKey(l => l.GrnLineId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/ReasonCodeConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/ReasonCodeConfiguration.cs
new file mode 100644
index 0000000..4746889
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/ReasonCodeConfiguration.cs
@@ -0,0 +1,20 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class ReasonCodeConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("reason_codes");
+ builder.HasKey(r => r.ReasonCodeId);
+
+ builder.Property(r => r.Code).IsRequired().HasMaxLength(20);
+ builder.Property(r => r.Description).IsRequired().HasMaxLength(200);
+ builder.Property(r => r.Context).HasConversion().HasMaxLength(20).IsRequired();
+
+ builder.HasIndex(r => new { r.Context, r.Code }).IsUnique();
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/StockAdjustmentConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/StockAdjustmentConfiguration.cs
new file mode 100644
index 0000000..d50a0e6
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/StockAdjustmentConfiguration.cs
@@ -0,0 +1,42 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class StockAdjustmentConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_adjustments");
+ builder.HasKey(a => a.AdjustmentId);
+
+ builder.Property(a => a.DocNo).IsRequired().HasMaxLength(30);
+ builder.HasIndex(a => a.DocNo).IsUnique();
+
+ builder.Property(a => a.Status).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(a => a.CreatedAt).IsRequired();
+ builder.Property(a => a.RowVersion).IsRowVersion();
+
+ builder.HasOne(a => a.Warehouse).WithMany().HasForeignKey(a => a.WarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(a => a.ReasonCode).WithMany().HasForeignKey(a => a.ReasonCodeId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(a => a.Creator).WithMany().HasForeignKey(a => a.CreatedBy).OnDelete(DeleteBehavior.Restrict);
+ }
+}
+
+public sealed class StockAdjustmentLineConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_adjustment_lines");
+ builder.HasKey(l => l.AdjLineId);
+
+ builder.Property(l => l.QtyDelta).HasPrecision(18, 4);
+
+ builder.HasOne(l => l.Adjustment).WithMany(a => a.Lines).HasForeignKey(l => l.AdjustmentId).OnDelete(DeleteBehavior.Cascade);
+ builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.BinId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.BatchId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.SerialId).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/StockConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/StockConfiguration.cs
new file mode 100644
index 0000000..57d51a6
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/StockConfiguration.cs
@@ -0,0 +1,60 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class StockLayerConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_layers");
+ builder.HasKey(l => l.LayerId);
+
+ builder.Property(l => l.QtyReceived).HasPrecision(18, 4);
+ builder.Property(l => l.QtyRemaining).HasPrecision(18, 4);
+ builder.Property(l => l.UnitCost).HasPrecision(18, 6);
+ builder.Property(l => l.ReceiptDate).IsRequired();
+
+ builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Warehouse).WithMany().HasForeignKey(l => l.WarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Batch).WithMany().HasForeignKey(l => l.BatchId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.Serial).WithMany().HasForeignKey(l => l.SerialId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(l => l.GrnLine).WithMany().HasForeignKey(l => l.GrnLineId).OnDelete(DeleteBehavior.Restrict);
+
+ // FIFO consumption orders by receipt date then layer id, scoped per item+warehouse.
+ builder.HasIndex(l => new { l.ItemId, l.WarehouseId, l.ReceiptDate, l.LayerId });
+ builder.HasIndex(l => l.GrnLineId);
+ }
+}
+
+public sealed class StockLedgerConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ // Append-only (FR-STK-01/FR-X-05): the app never updates/deletes ledger rows.
+ // DB-level revocation of UPDATE/DELETE is a deferred hardening step (02-SECURITY B.3).
+ builder.ToTable("stock_ledger");
+ builder.HasKey(l => l.LedgerId);
+
+ builder.Property(l => l.Direction).HasConversion().HasMaxLength(5).IsRequired();
+ builder.Property(l => l.QtyBase).HasPrecision(18, 4);
+ builder.Property(l => l.UnitCost).HasPrecision(18, 6);
+ builder.Property(l => l.Value).HasPrecision(18, 4);
+ builder.Property(l => l.RunningBalance).HasPrecision(18, 4);
+ builder.Property(l => l.SourceDocType).IsRequired().HasMaxLength(10);
+ builder.Property(l => l.CreatedAt).IsRequired();
+
+ builder.HasOne- ().WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.WarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.UserId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.BinId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.BatchId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.SerialId).OnDelete(DeleteBehavior.Restrict);
+
+ // Time-series query paths (NFR-06) and polymorphic source tracing.
+ builder.HasIndex(l => new { l.ItemId, l.WarehouseId, l.LedgerId });
+ builder.HasIndex(l => new { l.ItemId, l.WarehouseId, l.CreatedAt });
+ builder.HasIndex(l => new { l.SourceDocType, l.SourceDocId });
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/StockCountConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/StockCountConfiguration.cs
new file mode 100644
index 0000000..fa44f42
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/StockCountConfiguration.cs
@@ -0,0 +1,44 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class StockCountConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_counts");
+ builder.HasKey(c => c.CountId);
+
+ builder.Property(c => c.DocNo).IsRequired().HasMaxLength(30);
+ builder.HasIndex(c => c.DocNo).IsUnique();
+
+ builder.Property(c => c.CountType).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(c => c.Status).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(c => c.CreatedAt).IsRequired();
+ builder.Property(c => c.RowVersion).IsRowVersion();
+
+ builder.HasOne(c => c.Warehouse).WithMany().HasForeignKey(c => c.WarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(c => c.Creator).WithMany().HasForeignKey(c => c.CreatedBy).OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasIndex(c => c.Status);
+ }
+}
+
+public sealed class StockCountLineConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_count_lines");
+ builder.HasKey(l => l.CountLineId);
+
+ builder.Property(l => l.SystemQty).HasPrecision(18, 4);
+ builder.Property(l => l.CountedQty).HasPrecision(18, 4);
+ builder.Property(l => l.Variance).HasPrecision(18, 4);
+
+ builder.HasOne(l => l.Count).WithMany(c => c.Lines).HasForeignKey(l => l.CountId).OnDelete(DeleteBehavior.Cascade);
+ builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.BinId).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/StockTransferConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/StockTransferConfiguration.cs
new file mode 100644
index 0000000..2aae8bb
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Configurations/StockTransferConfiguration.cs
@@ -0,0 +1,47 @@
+using ERPCore.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace ERPCore.Infra.Persistence.Configurations;
+
+public sealed class StockTransferConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_transfers");
+ builder.HasKey(t => t.TransferId);
+
+ builder.Property(t => t.DocNo).IsRequired().HasMaxLength(30);
+ builder.HasIndex(t => t.DocNo).IsUnique();
+
+ builder.Property(t => t.Status).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(t => t.CreatedAt).IsRequired();
+ builder.Property(t => t.RowVersion).IsRowVersion();
+
+ builder.HasOne(t => t.SrcWarehouse).WithMany().HasForeignKey(t => t.SrcWarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(t => t.DestWarehouse).WithMany().HasForeignKey(t => t.DestWarehouseId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne(t => t.Creator).WithMany().HasForeignKey(t => t.CreatedBy).OnDelete(DeleteBehavior.Restrict);
+
+ builder.HasIndex(t => t.Status);
+ }
+}
+
+public sealed class StockTransferLineConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("stock_transfer_lines");
+ builder.HasKey(l => l.TransferLineId);
+
+ builder.Property(l => l.Qty).HasPrecision(18, 4);
+ builder.Property(l => l.UnitCost).HasPrecision(18, 6);
+ builder.Property(l => l.QtyReceived).HasPrecision(18, 4);
+
+ builder.HasOne(l => l.Transfer).WithMany(t => t.Lines).HasForeignKey(l => l.TransferId).OnDelete(DeleteBehavior.Cascade);
+ builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.SrcBinId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.DestBinId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.BatchId).OnDelete(DeleteBehavior.Restrict);
+ builder.HasOne().WithMany().HasForeignKey(l => l.SerialId).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/DataSeeder.cs b/Backend/ERPCore/Infra/Persistence/DataSeeder.cs
new file mode 100644
index 0000000..59a8803
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/DataSeeder.cs
@@ -0,0 +1,45 @@
+using ERPCore.Domain.Entities;
+using ERPCore.Domain.Enums;
+using Microsoft.EntityFrameworkCore;
+
+namespace ERPCore.Infra.Persistence;
+
+///
+/// Idempotent startup seeding of configurable reference data (docs/10 §B.8.3).
+/// Reason codes are seeded at runtime (not via HasData) so the identity
+/// sequence advances normally and later admin POST /reason-codes calls
+/// cannot collide with seeded ids.
+///
+public static class DataSeeder
+{
+ private static readonly (string Code, string Description, ReasonContext Context)[] StandardReasonCodes =
+ [
+ ("DMG", "Damage", ReasonContext.Adjustment),
+ ("THEFT", "Theft/Loss", ReasonContext.Adjustment),
+ ("VAR", "Count Variance", ReasonContext.Adjustment),
+ ("EXP", "Expiry Write-off", ReasonContext.Adjustment),
+ ("SYS", "System Correction", ReasonContext.Adjustment),
+ ("DEF", "Defective", ReasonContext.Return),
+ ("WRONG", "Wrong Item", ReasonContext.Return),
+ ("OVER", "Over-supply", ReasonContext.Return),
+ ("QREJ", "Quality Reject", ReasonContext.Return),
+ ];
+
+ public static async Task SeedAsync(ErpDbContext db, CancellationToken ct = default)
+ {
+ var existing = await db.ReasonCodes
+ .Select(r => new { r.Context, r.Code })
+ .ToListAsync(ct);
+ var have = existing.Select(x => (x.Context, x.Code)).ToHashSet();
+
+ var toAdd = StandardReasonCodes
+ .Where(r => !have.Contains((r.Context, r.Code)))
+ .Select(r => new ReasonCode { Code = r.Code, Description = r.Description, Context = r.Context })
+ .ToList();
+
+ if (toAdd.Count == 0) return;
+
+ db.ReasonCodes.AddRange(toAdd);
+ await db.SaveChangesAsync(ct);
+ }
+}
diff --git a/Backend/ERPCore/Infra/Persistence/ErpDbContext.cs b/Backend/ERPCore/Infra/Persistence/ErpDbContext.cs
index d8bf5d5..6a7d7e6 100644
--- a/Backend/ERPCore/Infra/Persistence/ErpDbContext.cs
+++ b/Backend/ERPCore/Infra/Persistence/ErpDbContext.cs
@@ -1,4 +1,6 @@
using ERPCore.Domain.Entities;
+using ERPCore.Infra.Auth;
+using ERPCore.Infra.Persistence.Auditing;
using Microsoft.EntityFrameworkCore;
namespace ERPCore.Infra.Persistence;
@@ -8,11 +10,15 @@ namespace ERPCore.Infra.Persistence;
/// configurations are added under
/// Domain/Entities and Infra/Persistence/Configurations as they are implemented.
/// The authoritative schema lives in docs/10-BACKEND-PHASE1.md — do not invent it here.
+/// Every save writes an immutable audit trail (FR-X-02) via .
///
public class ErpDbContext : DbContext
{
- public ErpDbContext(DbContextOptions options) : base(options)
+ private readonly ICurrentUser _currentUser;
+
+ public ErpDbContext(DbContextOptions options, ICurrentUser currentUser) : base(options)
{
+ _currentUser = currentUser;
}
// --- Master Data (docs/10 Part C.1) ---
@@ -39,6 +45,37 @@ public class ErpDbContext : DbContext
public DbSet PurchaseOrders => Set();
public DbSet PoLines => Set();
+ // --- Goods Receipt (docs/10 Part C.3) ---
+ public DbSet Grns => Set();
+ public DbSet GrnLines => Set();
+
+ // --- Batch / Serial (docs/10 Part C.4) ---
+ public DbSet Batches => Set();
+ public DbSet Serials => Set();
+
+ // --- Stock core: FIFO layers + immutable ledger (docs/10 Part C.5) ---
+ public DbSet StockLayers => Set();
+ public DbSet StockLedger => Set();
+
+ // --- Stock transactions (docs/10 Part C.6) ---
+ public DbSet StockTransfers => Set();
+ public DbSet StockTransferLines => Set();
+ public DbSet StockAdjustments => Set();
+ public DbSet StockAdjustmentLines => Set();
+ public DbSet StockCounts => Set();
+ public DbSet StockCountLines => Set();
+
+ // --- Purchase returns (docs/10 Part C.2) ---
+ public DbSet PurchaseReturns => Set();
+ public DbSet PurchaseReturnLines => Set();
+
+ // --- Reference data (docs/10 Part C.7) ---
+ public DbSet ReasonCodes => Set();
+
+ // --- Cross-cutting: audit trail + GL-ready journal (docs/10 Part C.7) ---
+ public DbSet AuditLogs => Set();
+ public DbSet JournalEntryStubs => Set();
+
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
@@ -47,4 +84,39 @@ public class ErpDbContext : DbContext
// (Infra/Persistence/Configurations/*).
modelBuilder.ApplyConfigurationsFromAssembly(typeof(ErpDbContext).Assembly);
}
+
+ // Audit trail (FR-X-02): capture mutations before save (accurate old→new), then
+ // write the log rows once inserts have their generated keys. A second base save
+ // persists the logs without re-auditing them.
+ public override async Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken ct = default)
+ {
+ var pending = AuditScribe.Capture(ChangeTracker);
+ var result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, ct);
+ if (pending.Count > 0)
+ {
+ WriteAuditLogs(pending);
+ await base.SaveChangesAsync(acceptAllChangesOnSuccess, ct);
+ }
+ return result;
+ }
+
+ public override int SaveChanges(bool acceptAllChangesOnSuccess)
+ {
+ var pending = AuditScribe.Capture(ChangeTracker);
+ var result = base.SaveChanges(acceptAllChangesOnSuccess);
+ if (pending.Count > 0)
+ {
+ WriteAuditLogs(pending);
+ base.SaveChanges(acceptAllChangesOnSuccess);
+ }
+ return result;
+ }
+
+ private void WriteAuditLogs(IReadOnlyList pending)
+ {
+ var now = DateTime.UtcNow;
+ var userId = _currentUser.AuditUserId;
+ foreach (var p in pending)
+ AuditLogs.Add(AuditScribe.ToLog(p, userId, now));
+ }
}
diff --git a/Backend/ERPCore/Infra/Persistence/Migrations/20260713054124_AddStockAndGrn.Designer.cs b/Backend/ERPCore/Infra/Persistence/Migrations/20260713054124_AddStockAndGrn.Designer.cs
new file mode 100644
index 0000000..d10be22
--- /dev/null
+++ b/Backend/ERPCore/Infra/Persistence/Migrations/20260713054124_AddStockAndGrn.Designer.cs
@@ -0,0 +1,1480 @@
+//
+using System;
+using ERPCore.Infra.Persistence;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+
+#nullable disable
+
+namespace ERPCore.Infra.Persistence.Migrations
+{
+ [DbContext(typeof(ErpDbContext))]
+ [Migration("20260713054124_AddStockAndGrn")]
+ partial class AddStockAndGrn
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.9")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.Batch", b =>
+ {
+ b.Property("BatchId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("BatchId"));
+
+ b.Property("BatchNo")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property("ExpiryDate")
+ .HasColumnType("date");
+
+ b.Property("ItemId")
+ .HasColumnType("bigint");
+
+ b.HasKey("BatchId");
+
+ b.HasIndex("ItemId", "BatchNo")
+ .IsUnique();
+
+ b.ToTable("batches", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.Bin", b =>
+ {
+ b.Property("BinId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("BinId"));
+
+ b.Property("BinType")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property("WarehouseId")
+ .HasColumnType("bigint");
+
+ b.HasKey("BinId");
+
+ b.HasIndex("WarehouseId", "Code")
+ .IsUnique();
+
+ b.ToTable("bins", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.Category", b =>
+ {
+ b.Property("CategoryId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("CategoryId"));
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)");
+
+ b.Property("ParentId")
+ .HasColumnType("bigint");
+
+ b.HasKey("CategoryId");
+
+ b.HasIndex("ParentId");
+
+ b.ToTable("categories", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.Grn", b =>
+ {
+ b.Property("GrnId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("GrnId"));
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CreatedBy")
+ .HasColumnType("bigint");
+
+ b.Property("DocNo")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property("PoId")
+ .HasColumnType("bigint");
+
+ b.Property("PostedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("xid")
+ .HasColumnName("xmin");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("VendorId")
+ .HasColumnType("bigint");
+
+ b.Property("WarehouseId")
+ .HasColumnType("bigint");
+
+ b.HasKey("GrnId");
+
+ b.HasIndex("CreatedBy");
+
+ b.HasIndex("DocNo")
+ .IsUnique();
+
+ b.HasIndex("PoId");
+
+ b.HasIndex("Status");
+
+ b.HasIndex("VendorId");
+
+ b.HasIndex("WarehouseId");
+
+ b.ToTable("grns", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.GrnLine", b =>
+ {
+ b.Property("GrnLineId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("GrnLineId"));
+
+ b.Property("BatchId")
+ .HasColumnType("bigint");
+
+ b.Property("BinId")
+ .HasColumnType("bigint");
+
+ b.Property("GrnId")
+ .HasColumnType("bigint");
+
+ b.Property("HoldStatus")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("ItemId")
+ .HasColumnType("bigint");
+
+ b.Property("PoLineId")
+ .HasColumnType("bigint");
+
+ b.Property("Qty")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("ReceivedValue")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("UnitCost")
+ .HasPrecision(18, 6)
+ .HasColumnType("numeric(18,6)");
+
+ b.Property("UomId")
+ .HasColumnType("bigint");
+
+ b.HasKey("GrnLineId");
+
+ b.HasIndex("BatchId");
+
+ b.HasIndex("BinId");
+
+ b.HasIndex("GrnId");
+
+ b.HasIndex("ItemId");
+
+ b.HasIndex("PoLineId");
+
+ b.HasIndex("UomId");
+
+ b.ToTable("grn_lines", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.Item", b =>
+ {
+ b.Property("ItemId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("ItemId"));
+
+ b.Property("BaseUomId")
+ .HasColumnType("bigint");
+
+ b.Property("CategoryId")
+ .HasColumnType("bigint");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DefaultVendorId")
+ .HasColumnType("bigint");
+
+ b.Property("Description")
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("ItemType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)");
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("xid")
+ .HasColumnName("xmin");
+
+ b.Property("Sku")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)")
+ .HasDefaultValue("Active");
+
+ b.Property("TaxClass")
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("TrackingMode")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("ItemId");
+
+ b.HasIndex("BaseUomId");
+
+ b.HasIndex("CategoryId");
+
+ b.HasIndex("DefaultVendorId");
+
+ b.HasIndex("Sku")
+ .IsUnique();
+
+ b.HasIndex("Status");
+
+ b.ToTable("items", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.ItemReorder", b =>
+ {
+ b.Property("ReorderId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("ReorderId"));
+
+ b.Property("ItemId")
+ .HasColumnType("bigint");
+
+ b.Property("ReorderPoint")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("ReorderQty")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("WarehouseId")
+ .HasColumnType("bigint");
+
+ b.HasKey("ReorderId");
+
+ b.HasIndex("WarehouseId");
+
+ b.HasIndex("ItemId", "WarehouseId")
+ .IsUnique();
+
+ b.ToTable("item_reorders", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.NumberSequence", b =>
+ {
+ b.Property("SequenceId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("SequenceId"));
+
+ b.Property("DocType")
+ .IsRequired()
+ .HasMaxLength(10)
+ .HasColumnType("character varying(10)")
+ .HasColumnName("doc_type");
+
+ b.Property("LastNumber")
+ .HasColumnType("bigint")
+ .HasColumnName("last_number");
+
+ b.Property("Year")
+ .HasColumnType("integer")
+ .HasColumnName("year");
+
+ b.HasKey("SequenceId");
+
+ b.HasIndex("DocType", "Year")
+ .IsUnique();
+
+ b.ToTable("number_sequences", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.PoLine", b =>
+ {
+ b.Property("PoLineId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("PoLineId"));
+
+ b.Property("ItemId")
+ .HasColumnType("bigint");
+
+ b.Property("PoId")
+ .HasColumnType("bigint");
+
+ b.Property("Qty")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("QtyReceived")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("Tax")
+ .HasPrecision(9, 4)
+ .HasColumnType("numeric(9,4)");
+
+ b.Property("UnitPrice")
+ .HasPrecision(18, 4)
+ .HasColumnType("numeric(18,4)");
+
+ b.Property("UomId")
+ .HasColumnType("bigint");
+
+ b.Property("WarehouseId")
+ .HasColumnType("bigint");
+
+ b.HasKey("PoLineId");
+
+ b.HasIndex("ItemId");
+
+ b.HasIndex("PoId");
+
+ b.HasIndex("UomId");
+
+ b.HasIndex("WarehouseId");
+
+ b.ToTable("po_lines", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.PurchaseOrder", b =>
+ {
+ b.Property("PoId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("PoId"));
+
+ b.Property("ApprovalRequired")
+ .HasColumnType("boolean");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CreatedBy")
+ .HasColumnType("bigint");
+
+ b.Property("DocNo")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property("RequisitionId")
+ .HasColumnType("bigint");
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("xid")
+ .HasColumnName("xmin");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("VendorId")
+ .HasColumnType("bigint");
+
+ b.HasKey("PoId");
+
+ b.HasIndex("CreatedBy");
+
+ b.HasIndex("DocNo")
+ .IsUnique();
+
+ b.HasIndex("RequisitionId");
+
+ b.HasIndex("Status");
+
+ b.HasIndex("VendorId");
+
+ b.ToTable("purchase_orders", (string)null);
+ });
+
+ modelBuilder.Entity("ERPCore.Domain.Entities.Requisition", b =>
+ {
+ b.Property("RequisitionId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("RequisitionId"));
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DocNo")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property