Phase C: Add Manual Journal Entries (double-entry GL)

- JournalEntry + JournalEntryLine entities with Draft/Posted/Reversed lifecycle
- JournalEntryStatus enum (Draft, Posted, Reversed)
- Migration AddJournalEntries: two new tables with self-referencing reversal FK
- IUnitOfWork/UnitOfWork wired with JournalEntries + JournalEntryLines repos
- ApplicationDbContext: DbSets, tenant query filters, reversal FK config
- LedgerService: JE lines added as 10th source in GetAccountLedgerAsync and ComputePriorBalanceAsync
- JournalEntriesController: Index (All/Draft/Posted tabs), Create, Details, Post, Reverse, Delete
- Views: Index, Create (dynamic balanced line grid with running debit/credit totals), Details
- journal-entry-create.js: dynamic line management with balance indicator
- Nav: Journal Entries added to Finance section in _Layout

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-09 23:56:03 -04:00
parent 0afb474c3e
commit a33687f7bd
15 changed files with 11017 additions and 3 deletions
@@ -324,6 +324,11 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataPro
/// <summary>Ad-hoc expense records (non-bill spending); tenant-filtered with soft delete.</summary>
public DbSet<Expense> Expenses { get; set; }
/// <summary>Manual double-entry journal entries (Draft/Posted/Reversed lifecycle); tenant-filtered with soft delete.</summary>
public DbSet<JournalEntry> JournalEntries { get; set; }
/// <summary>Individual debit/credit lines within a journal entry; soft-delete only (access controlled through parent JournalEntry).</summary>
public DbSet<JournalEntryLine> JournalEntryLines { get; set; }
// Job Templates
/// <summary>Reusable job templates that pre-populate job items, coats, and prep services on job creation.</summary>
public DbSet<JobTemplate> JobTemplates { get; set; }
@@ -614,6 +619,11 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataPro
modelBuilder.Entity<Expense>().HasQueryFilter(e =>
!e.IsDeleted && (IsPlatformAdmin || e.CompanyId == CurrentCompanyId));
// Journal Entries: tenant-filtered; lines use soft-delete only (child rows)
modelBuilder.Entity<JournalEntry>().HasQueryFilter(e =>
!e.IsDeleted && (IsPlatformAdmin || e.CompanyId == CurrentCompanyId));
modelBuilder.Entity<JournalEntryLine>().HasQueryFilter(e => !e.IsDeleted);
// Purchase Orders
modelBuilder.Entity<PurchaseOrder>().HasQueryFilter(e =>
!e.IsDeleted && (IsPlatformAdmin || e.CompanyId == CurrentCompanyId));
@@ -633,6 +643,13 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataPro
.HasForeignKey(a => a.ParentAccountId)
.OnDelete(DeleteBehavior.Restrict);
// JournalEntry self-referencing reversal link
modelBuilder.Entity<JournalEntry>()
.HasOne(je => je.ReversalOf)
.WithMany()
.HasForeignKey(je => je.ReversalOfId)
.OnDelete(DeleteBehavior.Restrict);
// Vendor → DefaultExpenseAccount (no cascade)
modelBuilder.Entity<Vendor>()
.HasOne(s => s.DefaultExpenseAccount)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,155 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PowderCoating.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddJournalEntries : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "JournalEntries",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EntryNumber = table.Column<string>(type: "nvarchar(max)", nullable: false),
EntryDate = table.Column<DateTime>(type: "datetime2", nullable: false),
Reference = table.Column<string>(type: "nvarchar(max)", nullable: true),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Status = table.Column<int>(type: "int", nullable: false),
IsReversal = table.Column<bool>(type: "bit", nullable: false),
ReversalOfId = table.Column<int>(type: "int", nullable: true),
PostedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
PostedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
CompanyId = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_JournalEntries", x => x.Id);
table.ForeignKey(
name: "FK_JournalEntries_JournalEntries_ReversalOfId",
column: x => x.ReversalOfId,
principalTable: "JournalEntries",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "JournalEntryLines",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
JournalEntryId = table.Column<int>(type: "int", nullable: false),
AccountId = table.Column<int>(type: "int", nullable: false),
DebitAmount = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
CreditAmount = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
LineOrder = table.Column<int>(type: "int", nullable: false),
CompanyId = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_JournalEntryLines", x => x.Id);
table.ForeignKey(
name: "FK_JournalEntryLines_Accounts_AccountId",
column: x => x.AccountId,
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_JournalEntryLines_JournalEntries_JournalEntryId",
column: x => x.JournalEntryId,
principalTable: "JournalEntries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 1,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9350));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 2,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9357));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 3,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9359));
migrationBuilder.CreateIndex(
name: "IX_JournalEntries_ReversalOfId",
table: "JournalEntries",
column: "ReversalOfId");
migrationBuilder.CreateIndex(
name: "IX_JournalEntryLines_AccountId",
table: "JournalEntryLines",
column: "AccountId");
migrationBuilder.CreateIndex(
name: "IX_JournalEntryLines_JournalEntryId",
table: "JournalEntryLines",
column: "JournalEntryId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "JournalEntryLines");
migrationBuilder.DropTable(
name: "JournalEntries");
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 1,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 25, 9, 644, DateTimeKind.Utc).AddTicks(9957));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 2,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 25, 9, 644, DateTimeKind.Utc).AddTicks(9963));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 3,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 25, 9, 644, DateTimeKind.Utc).AddTicks(9965));
}
}
}
@@ -5073,6 +5073,132 @@ namespace PowderCoating.Infrastructure.Migrations
b.ToTable("JobTimeEntries");
});
modelBuilder.Entity("PowderCoating.Core.Entities.JournalEntry", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("datetime2");
b.Property<string>("DeletedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("EntryDate")
.HasColumnType("datetime2");
b.Property<string>("EntryNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsReversal")
.HasColumnType("bit");
b.Property<DateTime?>("PostedAt")
.HasColumnType("datetime2");
b.Property<string>("PostedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("Reference")
.HasColumnType("nvarchar(max)");
b.Property<int?>("ReversalOfId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("datetime2");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ReversalOfId");
b.ToTable("JournalEntries");
});
modelBuilder.Entity("PowderCoating.Core.Entities.JournalEntryLine", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("AccountId")
.HasColumnType("int");
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<decimal>("CreditAmount")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("DebitAmount")
.HasColumnType("decimal(18,2)");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("datetime2");
b.Property<string>("DeletedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("JournalEntryId")
.HasColumnType("int");
b.Property<int>("LineOrder")
.HasColumnType("int");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("datetime2");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("JournalEntryId");
b.ToTable("JournalEntryLines");
});
modelBuilder.Entity("PowderCoating.Core.Entities.MaintenanceRecord", b =>
{
b.Property<int>("Id")
@@ -6080,7 +6206,7 @@ namespace PowderCoating.Infrastructure.Migrations
{
Id = 1,
CompanyId = 0,
CreatedAt = new DateTime(2026, 5, 10, 3, 25, 9, 644, DateTimeKind.Utc).AddTicks(9957),
CreatedAt = new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9350),
Description = "Standard pricing for regular customers",
DiscountPercent = 0m,
IsActive = true,
@@ -6091,7 +6217,7 @@ namespace PowderCoating.Infrastructure.Migrations
{
Id = 2,
CompanyId = 0,
CreatedAt = new DateTime(2026, 5, 10, 3, 25, 9, 644, DateTimeKind.Utc).AddTicks(9963),
CreatedAt = new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9357),
Description = "5% discount for preferred customers",
DiscountPercent = 5m,
IsActive = true,
@@ -6102,7 +6228,7 @@ namespace PowderCoating.Infrastructure.Migrations
{
Id = 3,
CompanyId = 0,
CreatedAt = new DateTime(2026, 5, 10, 3, 25, 9, 644, DateTimeKind.Utc).AddTicks(9965),
CreatedAt = new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9359),
Description = "10% discount for premium customers",
DiscountPercent = 10m,
IsActive = true,
@@ -8762,6 +8888,35 @@ namespace PowderCoating.Infrastructure.Migrations
b.Navigation("Worker");
});
modelBuilder.Entity("PowderCoating.Core.Entities.JournalEntry", b =>
{
b.HasOne("PowderCoating.Core.Entities.JournalEntry", "ReversalOf")
.WithMany()
.HasForeignKey("ReversalOfId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("ReversalOf");
});
modelBuilder.Entity("PowderCoating.Core.Entities.JournalEntryLine", b =>
{
b.HasOne("PowderCoating.Core.Entities.Account", "Account")
.WithMany()
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PowderCoating.Core.Entities.JournalEntry", "JournalEntry")
.WithMany("Lines")
.HasForeignKey("JournalEntryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
b.Navigation("JournalEntry");
});
modelBuilder.Entity("PowderCoating.Core.Entities.MaintenanceRecord", b =>
{
b.HasOne("PowderCoating.Core.Entities.ApplicationUser", "AssignedUser")
@@ -9482,6 +9637,11 @@ namespace PowderCoating.Infrastructure.Migrations
b.Navigation("PrepServices");
});
modelBuilder.Entity("PowderCoating.Core.Entities.JournalEntry", b =>
{
b.Navigation("Lines");
});
modelBuilder.Entity("PowderCoating.Core.Entities.OvenBatch", b =>
{
b.Navigation("Items");
@@ -142,6 +142,10 @@ public class UnitOfWork : IUnitOfWork
private IRepository<BillPayment>? _billPayments;
private IRepository<Expense>? _expenses;
// Manual Journal Entries
private IRepository<JournalEntry>? _journalEntries;
private IRepository<JournalEntryLine>? _journalEntryLines;
/// <summary>
/// Initialises the unit of work with the scoped <paramref name="context"/>.
/// The context is shared across all repositories created by this instance so that
@@ -513,6 +517,15 @@ public class UnitOfWork : IUnitOfWork
public IRepository<Expense> Expenses =>
_expenses ??= new Repository<Expense>(_context);
// Manual Journal Entries
/// <summary>Repository for <see cref="JournalEntry"/> double-entry manual journal entries; tenant-filtered with soft delete.</summary>
public IRepository<JournalEntry> JournalEntries =>
_journalEntries ??= new Repository<JournalEntry>(_context);
/// <summary>Repository for <see cref="JournalEntryLine"/> individual debit/credit lines within a journal entry.</summary>
public IRepository<JournalEntryLine> JournalEntryLines =>
_journalEntryLines ??= new Repository<JournalEntryLine>(_context);
/// <summary>
/// Flushes all pending changes in the EF Core change tracker to the database.
/// Returns the number of state entries written.
@@ -298,6 +298,28 @@ public class LedgerService : ILedgerService
});
}
// ── 10. Journal Entry lines touching this account ──────────────────
var jeLines = await _context.JournalEntryLines
.Include(l => l.JournalEntry)
.Where(l => l.AccountId == accountId
&& l.JournalEntry.Status == JournalEntryStatus.Posted
&& l.JournalEntry.EntryDate >= fromDate
&& l.JournalEntry.EntryDate <= toDate)
.ToListAsync();
foreach (var line in jeLines)
entries.Add(new LedgerEntryDto
{
Date = line.JournalEntry.EntryDate,
Reference = line.JournalEntry.EntryNumber,
Source = "Journal Entry",
Description = line.Description ?? line.JournalEntry.Description,
Debit = line.DebitAmount,
Credit = line.CreditAmount,
LinkController = "JournalEntries",
LinkId = line.JournalEntry.Id
});
// ── Sort and compute running balance ──────────────────────────────────
entries = entries
.OrderBy(e => e.Date)
@@ -429,6 +451,19 @@ public class LedgerService : ILedgerService
.SumAsync(bp => (decimal?)bp.Amount) ?? 0;
}
// 10. Posted journal entry lines touching this account (prior to period)
debits += await _context.JournalEntryLines
.Where(l => l.AccountId == accountId
&& l.JournalEntry.Status == JournalEntryStatus.Posted
&& l.JournalEntry.EntryDate < beforeDate)
.SumAsync(l => (decimal?)l.DebitAmount) ?? 0;
credits += await _context.JournalEntryLines
.Where(l => l.AccountId == accountId
&& l.JournalEntry.Status == JournalEntryStatus.Posted
&& l.JournalEntry.EntryDate < beforeDate)
.SumAsync(l => (decimal?)l.CreditAmount) ?? 0;
decimal netActivity = normalDebitBalance ? debits - credits : credits - debits;
// Apply the opening balance if it was established on or before the end of the viewed period.