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
@@ -156,3 +156,47 @@ public class Expense : BaseEntity
public virtual Account PaymentAccount { get; set; } = null!;
public virtual Job? Job { get; set; }
}
/// <summary>
/// Manual double-entry journal entry. Lines must balance (sum of debits == sum of credits)
/// before posting. Once posted the entry is immutable — use Reverse to correct it.
/// Entry numbering follows the pattern JE-YYMM-#### scoped per company.
/// </summary>
public class JournalEntry : BaseEntity
{
public string EntryNumber { get; set; } = string.Empty;
public DateTime EntryDate { get; set; } = DateTime.UtcNow;
public string? Reference { get; set; }
public string? Description { get; set; }
public JournalEntryStatus Status { get; set; } = JournalEntryStatus.Draft;
/// <summary>True if this entry was machine-generated as a reversal of another entry.</summary>
public bool IsReversal { get; set; } = false;
/// <summary>FK to the original entry being reversed. Null for normal entries.</summary>
public int? ReversalOfId { get; set; }
public DateTime? PostedAt { get; set; }
public string? PostedBy { get; set; }
// Navigation
public virtual ICollection<JournalEntryLine> Lines { get; set; } = new List<JournalEntryLine>();
public virtual JournalEntry? ReversalOf { get; set; }
}
/// <summary>
/// One debit or credit line within a <see cref="JournalEntry"/>. Either DebitAmount or CreditAmount
/// should be non-zero per line (not both). LineOrder controls display sequence.
/// </summary>
public class JournalEntryLine : BaseEntity
{
public int JournalEntryId { get; set; }
public int AccountId { get; set; }
public decimal DebitAmount { get; set; }
public decimal CreditAmount { get; set; }
public string? Description { get; set; }
public int LineOrder { get; set; }
// Navigation
public virtual JournalEntry JournalEntry { get; set; } = null!;
public virtual Account Account { get; set; } = null!;
}
@@ -79,3 +79,14 @@ public enum AccountingMethod
/// <summary>Revenue and expenses recognised when earned/incurred (default).</summary>
Accrual = 1
}
/// <summary>Lifecycle state of a Manual Journal Entry.</summary>
public enum JournalEntryStatus
{
/// <summary>Not yet posted — can still be edited or deleted.</summary>
Draft = 0,
/// <summary>Posted to the GL — immutable; can only be reversed.</summary>
Posted = 1,
/// <summary>A reversal JE has been created and posted for this entry.</summary>
Reversed = 2
}
@@ -91,6 +91,10 @@ public interface IUnitOfWork : IDisposable
IRepository<BillPayment> BillPayments { get; }
IRepository<Expense> Expenses { get; }
// Manual Journal Entries
IRepository<JournalEntry> JournalEntries { get; }
IRepository<JournalEntryLine> JournalEntryLines { get; }
// Notifications — typed repository for IgnoreQueryFilters-based history lookups
INotificationLogRepository NotificationLogs { get; }
IRepository<NotificationTemplate> NotificationTemplates { get; }
@@ -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.
@@ -0,0 +1,372 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using PowderCoating.Application.Interfaces;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Enums;
using PowderCoating.Core.Interfaces;
using PowderCoating.Shared.Constants;
namespace PowderCoating.Web.Controllers;
[Authorize(Policy = AppConstants.Policies.CanViewData)]
public class JournalEntriesController : Controller
{
private readonly IUnitOfWork _unitOfWork;
private readonly ITenantContext _tenantContext;
private readonly IAccountBalanceService _accountBalanceService;
public JournalEntriesController(
IUnitOfWork unitOfWork,
ITenantContext tenantContext,
IAccountBalanceService accountBalanceService)
{
_unitOfWork = unitOfWork;
_tenantContext = tenantContext;
_accountBalanceService = accountBalanceService;
}
private bool AllowAccounting() =>
User.IsInRole("SuperAdmin") || User.IsInRole("Administrator") || User.IsInRole("Manager");
// ── Index ────────────────────────────────────────────────────────────────
public async Task<IActionResult> Index(string? status)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
var all = (await _unitOfWork.JournalEntries.FindAsync(
je => je.CompanyId == companyId))
.OrderByDescending(je => je.EntryDate)
.ThenByDescending(je => je.Id)
.ToList();
var displayed = status switch
{
"Draft" => all.Where(je => je.Status == JournalEntryStatus.Draft).ToList(),
"Posted" => all.Where(je => je.Status == JournalEntryStatus.Posted).ToList(),
_ => all
};
ViewBag.StatusFilter = status ?? "All";
ViewBag.TotalCount = all.Count;
ViewBag.DraftCount = all.Count(je => je.Status == JournalEntryStatus.Draft);
ViewBag.PostedCount = all.Count(je => je.Status == JournalEntryStatus.Posted);
return View(displayed);
}
// ── Create ───────────────────────────────────────────────────────────────
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
public async Task<IActionResult> Create()
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
await PopulateAccountDropdownAsync();
return View(new JournalEntry { EntryDate = DateTime.Today });
}
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
JournalEntry model,
int[] lineAccountIds,
decimal[] lineDebits,
decimal[] lineCreditAmounts,
string?[] lineDescriptions,
int[] lineOrders)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var lines = BuildLines(lineAccountIds, lineDebits, lineCreditAmounts, lineDescriptions, lineOrders);
if (!ValidateLines(lines, out string? error))
{
TempData["Error"] = error;
await PopulateAccountDropdownAsync();
return View(model);
}
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
model.EntryNumber = await GenerateEntryNumberAsync(companyId);
model.Status = JournalEntryStatus.Draft;
model.Lines = lines;
await _unitOfWork.JournalEntries.AddAsync(model);
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Journal entry {model.EntryNumber} created as draft.";
return RedirectToAction(nameof(Details), new { id = model.Id });
}
// ── Details ──────────────────────────────────────────────────────────────
public async Task<IActionResult> Details(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var je = (await _unitOfWork.JournalEntries.FindAsync(
e => e.Id == id,
false,
e => e.Lines))
.FirstOrDefault();
if (je == null) return NotFound();
// Load account names for lines
var accountIds = je.Lines.Select(l => l.AccountId).Distinct().ToList();
var accounts = await _unitOfWork.Accounts.FindAsync(a => accountIds.Contains(a.Id));
ViewBag.AccountMap = accounts.ToDictionary(a => a.Id, a => $"{a.AccountNumber} {a.Name}");
// Reversal metadata
if (je.ReversalOfId.HasValue)
{
var original = await _unitOfWork.JournalEntries.GetByIdAsync(je.ReversalOfId.Value);
ViewBag.ReversalOfNumber = original?.EntryNumber;
}
var reversal = (await _unitOfWork.JournalEntries.FindAsync(
r => r.ReversalOfId == je.Id && r.Status == JournalEntryStatus.Posted))
.FirstOrDefault();
ViewBag.ReversalEntryNumber = reversal?.EntryNumber;
ViewBag.ReversalEntryId = reversal?.Id;
return View(je);
}
// ── Post ─────────────────────────────────────────────────────────────────
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Post(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var entry = (await _unitOfWork.JournalEntries.FindAsync(
je => je.Id == id,
false,
je => je.Lines))
.FirstOrDefault();
if (entry == null) return NotFound();
if (entry.Status != JournalEntryStatus.Draft)
{
TempData["Error"] = "Only draft entries can be posted.";
return RedirectToAction(nameof(Details), new { id });
}
var totalDebits = entry.Lines.Sum(l => l.DebitAmount);
var totalCredits = entry.Lines.Sum(l => l.CreditAmount);
if (totalDebits != totalCredits)
{
TempData["Error"] = $"Entry does not balance — debits {totalDebits:C} ≠ credits {totalCredits:C}.";
return RedirectToAction(nameof(Details), new { id });
}
await _unitOfWork.ExecuteInTransactionAsync(async () =>
{
entry.Status = JournalEntryStatus.Posted;
entry.PostedAt = DateTime.UtcNow;
entry.PostedBy = User.Identity?.Name;
foreach (var line in entry.Lines)
{
if (line.DebitAmount > 0)
await _accountBalanceService.DebitAsync(line.AccountId, line.DebitAmount);
if (line.CreditAmount > 0)
await _accountBalanceService.CreditAsync(line.AccountId, line.CreditAmount);
}
await _unitOfWork.CompleteAsync();
});
TempData["Success"] = $"Journal entry {entry.EntryNumber} posted successfully.";
return RedirectToAction(nameof(Details), new { id });
}
// ── Reverse ──────────────────────────────────────────────────────────────
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Reverse(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var original = (await _unitOfWork.JournalEntries.FindAsync(
je => je.Id == id,
false,
je => je.Lines))
.FirstOrDefault();
if (original == null) return NotFound();
if (original.Status != JournalEntryStatus.Posted)
{
TempData["Error"] = "Only posted entries can be reversed.";
return RedirectToAction(nameof(Details), new { id });
}
var existingReversal = (await _unitOfWork.JournalEntries.FindAsync(
je => je.ReversalOfId == id))
.FirstOrDefault();
if (existingReversal != null)
{
TempData["Error"] = $"This entry was already reversed by {existingReversal.EntryNumber}.";
return RedirectToAction(nameof(Details), new { id });
}
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
int newEntryId = 0;
await _unitOfWork.ExecuteInTransactionAsync(async () =>
{
var reversal = new JournalEntry
{
EntryNumber = await GenerateEntryNumberAsync(companyId),
EntryDate = DateTime.Today,
Reference = $"Reversal of {original.EntryNumber}",
Description = $"Reversal of {original.EntryNumber}: {original.Description}",
Status = JournalEntryStatus.Posted,
IsReversal = true,
ReversalOfId = original.Id,
PostedAt = DateTime.UtcNow,
PostedBy = User.Identity?.Name,
Lines = original.Lines.Select((l, i) => new JournalEntryLine
{
AccountId = l.AccountId,
DebitAmount = l.CreditAmount,
CreditAmount = l.DebitAmount,
Description = l.Description,
LineOrder = l.LineOrder
}).ToList()
};
await _unitOfWork.JournalEntries.AddAsync(reversal);
original.Status = JournalEntryStatus.Reversed;
foreach (var line in reversal.Lines)
{
if (line.DebitAmount > 0)
await _accountBalanceService.DebitAsync(line.AccountId, line.DebitAmount);
if (line.CreditAmount > 0)
await _accountBalanceService.CreditAsync(line.AccountId, line.CreditAmount);
}
await _unitOfWork.CompleteAsync();
newEntryId = reversal.Id;
});
TempData["Success"] = "Reversal entry created and posted.";
return RedirectToAction(nameof(Details), new { id = newEntryId });
}
// ── Delete ───────────────────────────────────────────────────────────────
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CompanyAdminOnly)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var entry = await _unitOfWork.JournalEntries.GetByIdAsync(id);
if (entry == null) return NotFound();
if (entry.Status != JournalEntryStatus.Draft)
{
TempData["Error"] = "Only draft entries can be deleted. Posted entries must be reversed.";
return RedirectToAction(nameof(Details), new { id });
}
await _unitOfWork.JournalEntries.SoftDeleteAsync(id);
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Journal entry {entry.EntryNumber} deleted.";
return RedirectToAction(nameof(Index));
}
// ── Helpers ──────────────────────────────────────────────────────────────
private static List<JournalEntryLine> BuildLines(
int[] accountIds, decimal[] debits, decimal[] credits,
string?[] descriptions, int[] orders)
{
var lines = new List<JournalEntryLine>();
for (int i = 0; i < accountIds.Length; i++)
{
if (accountIds[i] == 0) continue;
lines.Add(new JournalEntryLine
{
AccountId = accountIds[i],
DebitAmount = i < debits.Length ? debits[i] : 0,
CreditAmount = i < credits.Length ? credits[i] : 0,
Description = i < descriptions.Length ? descriptions[i] : null,
LineOrder = i < orders.Length ? orders[i] : i
});
}
return lines;
}
private static bool ValidateLines(List<JournalEntryLine> lines, out string? error)
{
if (lines.Count < 2)
{
error = "A journal entry must have at least two lines.";
return false;
}
var totalDebits = lines.Sum(l => l.DebitAmount);
var totalCredits = lines.Sum(l => l.CreditAmount);
if (totalDebits == 0 && totalCredits == 0)
{
error = "At least one debit or credit amount must be non-zero.";
return false;
}
if (totalDebits != totalCredits)
{
error = $"Debits ({totalDebits:C}) must equal credits ({totalCredits:C}) before saving.";
return false;
}
error = null;
return true;
}
/// <summary>
/// Generates the next sequential entry number in the format JE-YYMM-####.
/// Queries across soft-deleted entries to prevent number reuse after deletion.
/// </summary>
private async Task<string> GenerateEntryNumberAsync(int companyId)
{
var prefix = $"JE-{DateTime.Now:yyMM}-";
var all = await _unitOfWork.JournalEntries.FindAsync(
je => je.CompanyId == companyId && je.EntryNumber.StartsWith(prefix),
ignoreQueryFilters: true);
int next = 1;
if (all.Any())
{
var nums = all
.Select(je => je.EntryNumber[prefix.Length..])
.Select(s => int.TryParse(s, out int n) ? n : 0);
next = nums.Max() + 1;
}
return $"{prefix}{next:D4}";
}
private async Task PopulateAccountDropdownAsync()
{
var accounts = await _unitOfWork.Accounts.FindAsync(a => a.IsActive);
ViewBag.AccountSelectList = accounts
.OrderBy(a => a.AccountNumber)
.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = $"{a.AccountNumber} {a.Name}"
})
.ToList();
}
}
@@ -0,0 +1,91 @@
@model PowderCoating.Core.Entities.JournalEntry
@{
ViewData["Title"] = "New Journal Entry";
var accounts = ViewBag.AccountSelectList as List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>
?? new List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>();
}
<div class="d-flex align-items-center mb-3 gap-2">
<a asp-action="Index" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-arrow-left me-1"></i>Back
</a>
<h4 class="mb-0 fw-semibold ms-2">New Journal Entry</h4>
</div>
@if (TempData["Error"] != null)
{
<div class="alert alert-danger alert-permanent alert-dismissible fade show">
@TempData["Error"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
<form asp-action="Create" method="post" id="jeForm">
@Html.AntiForgeryToken()
<div class="card shadow-sm mb-3">
<div class="card-header fw-semibold">Entry Details</div>
<div class="card-body">
<div class="row g-3">
<div class="col-md-3">
<label class="form-label fw-semibold">Date <span class="text-danger">*</span></label>
<input asp-for="EntryDate" type="date" class="form-control"
value="@Model.EntryDate.ToString("yyyy-MM-dd")" required />
</div>
<div class="col-md-3">
<label class="form-label fw-semibold">Reference</label>
<input asp-for="Reference" class="form-control" placeholder="e.g., Invoice #, memo" />
</div>
<div class="col-md-6">
<label class="form-label fw-semibold">Description</label>
<input asp-for="Description" class="form-control" placeholder="Brief purpose of this entry" />
</div>
</div>
</div>
</div>
<div class="card shadow-sm mb-3">
<div class="card-header d-flex align-items-center">
<span class="fw-semibold">Lines</span>
<div class="ms-auto d-flex gap-3 align-items-center small text-muted">
<span>Total Debits: <strong id="totalDebits" class="text-dark">$0.00</strong></span>
<span>Total Credits: <strong id="totalCredits" class="text-dark">$0.00</strong></span>
<span id="balanceStatus" class="badge bg-secondary">Unbalanced</span>
</div>
</div>
<div class="card-body p-0">
<table class="table table-sm mb-0" id="linesTable">
<thead class="table-light">
<tr>
<th style="width:40%">Account</th>
<th>Description</th>
<th class="text-end" style="width:130px">Debit</th>
<th class="text-end" style="width:130px">Credit</th>
<th style="width:40px"></th>
</tr>
</thead>
<tbody id="linesBody">
<!-- rows injected by JS -->
</tbody>
</table>
</div>
<div class="card-footer">
<button type="button" class="btn btn-sm btn-outline-secondary" id="addLineBtn">
<i class="bi bi-plus-lg me-1"></i>Add Line
</button>
</div>
</div>
<div class="d-flex gap-2">
<button type="submit" class="btn btn-primary" id="saveBtn">Save as Draft</button>
<a asp-action="Index" class="btn btn-outline-secondary">Cancel</a>
</div>
</form>
@section Scripts {
<script src="~/js/journal-entry-create.js" asp-append-version="true"></script>
<script>
JournalEntry.init(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(
accounts.Select(a => new { value = a.Value, text = a.Text }))));
</script>
}
@@ -0,0 +1,203 @@
@model PowderCoating.Core.Entities.JournalEntry
@using PowderCoating.Core.Enums
@{
ViewData["Title"] = $"Journal Entry {Model.EntryNumber}";
var accountMap = ViewBag.AccountMap as Dictionary<int, string> ?? new Dictionary<int, string>();
bool isPosted = Model.Status == JournalEntryStatus.Posted;
bool isDraft = Model.Status == JournalEntryStatus.Draft;
bool isReversed = Model.Status == JournalEntryStatus.Reversed;
bool alreadyReversed = ViewBag.ReversalEntryNumber != null;
}
<div class="d-flex align-items-center mb-3 gap-2 flex-wrap">
<a asp-action="Index" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-arrow-left me-1"></i>Back
</a>
<h4 class="mb-0 fw-semibold ms-2">@Model.EntryNumber</h4>
@if (isDraft)
{
<span class="badge bg-warning text-dark ms-1 fs-6">Draft</span>
}
else if (isPosted)
{
<span class="badge bg-success ms-1 fs-6">Posted</span>
}
else
{
<span class="badge bg-secondary ms-1 fs-6">Reversed</span>
}
@if (Model.IsReversal)
{
<span class="badge bg-secondary ms-1">Reversal of @ViewBag.ReversalOfNumber</span>
}
<div class="ms-auto d-flex gap-2">
@if (isDraft)
{
<form asp-action="Post" asp-route-id="@Model.Id" method="post" class="d-inline">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-success"
onclick="return confirm('Post this journal entry to the GL? This cannot be undone.')">
<i class="bi bi-check-circle me-1"></i>Post to GL
</button>
</form>
<form asp-action="Delete" asp-route-id="@Model.Id" method="post" class="d-inline">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger"
onclick="return confirm('Delete this draft entry?')">
<i class="bi bi-trash me-1"></i>Delete
</button>
</form>
}
@if (isPosted && !alreadyReversed)
{
<form asp-action="Reverse" asp-route-id="@Model.Id" method="post" class="d-inline">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-warning"
onclick="return confirm('Create a reversal entry for @Model.EntryNumber? This will immediately post the reversal.')">
<i class="bi bi-arrow-counterclockwise me-1"></i>Reverse
</button>
</form>
}
@if (alreadyReversed)
{
<a asp-action="Details" asp-route-id="@ViewBag.ReversalEntryId" class="btn btn-sm btn-outline-secondary">
View Reversal (@ViewBag.ReversalEntryNumber)
</a>
}
</div>
</div>
@if (TempData["Success"] != null)
{
<div class="alert alert-success alert-permanent alert-dismissible fade show">
@TempData["Success"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
@if (TempData["Error"] != null)
{
<div class="alert alert-danger alert-permanent alert-dismissible fade show">
@TempData["Error"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
<div class="row g-3 mb-3">
<div class="col-md-8">
<div class="card shadow-sm h-100">
<div class="card-body">
<dl class="row mb-0">
<dt class="col-4 text-muted">Entry Number</dt>
<dd class="col-8 fw-semibold">@Model.EntryNumber</dd>
<dt class="col-4 text-muted">Date</dt>
<dd class="col-8">@Model.EntryDate.ToString("MMMM d, yyyy")</dd>
@if (!string.IsNullOrWhiteSpace(Model.Reference))
{
<dt class="col-4 text-muted">Reference</dt>
<dd class="col-8">@Model.Reference</dd>
}
@if (!string.IsNullOrWhiteSpace(Model.Description))
{
<dt class="col-4 text-muted">Description</dt>
<dd class="col-8">@Model.Description</dd>
}
</dl>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card shadow-sm h-100">
<div class="card-body">
<dl class="row mb-0">
@if (isPosted && Model.PostedAt.HasValue)
{
<dt class="col-5 text-muted">Posted</dt>
<dd class="col-7 small">
@Model.PostedAt.Value.ToLocalTime().ToString("MMM d, yyyy h:mm tt")<br />
<span class="text-muted">by @(Model.PostedBy ?? "—")</span>
</dd>
}
<dt class="col-5 text-muted">Created</dt>
<dd class="col-7 small">@Model.CreatedAt.ToLocalTime().ToString("MMM d, yyyy")</dd>
</dl>
</div>
</div>
</div>
</div>
<div class="card shadow-sm">
<div class="card-header d-flex align-items-center">
<span class="fw-semibold">Lines</span>
@{
var totalDebits = Model.Lines.Sum(l => l.DebitAmount);
var totalCredits = Model.Lines.Sum(l => l.CreditAmount);
bool balanced = totalDebits == totalCredits;
}
<div class="ms-auto small">
<span class="me-3">Debits: <strong>@totalDebits.ToString("C")</strong></span>
<span class="me-3">Credits: <strong>@totalCredits.ToString("C")</strong></span>
@if (balanced)
{
<span class="badge bg-success">Balanced</span>
}
else
{
<span class="badge bg-danger">Out of Balance</span>
}
</div>
</div>
<div class="card-body p-0">
<table class="table table-sm mb-0">
<thead class="table-light">
<tr>
<th>Account</th>
<th>Description</th>
<th class="text-end">Debit</th>
<th class="text-end">Credit</th>
</tr>
</thead>
<tbody>
@foreach (var line in Model.Lines.OrderBy(l => l.LineOrder))
{
<tr>
<td>
@if (accountMap.TryGetValue(line.AccountId, out var accountName))
{
@accountName
}
else
{
<span class="text-muted">#@line.AccountId</span>
}
</td>
<td class="text-muted small">@line.Description</td>
<td class="text-end">
@if (line.DebitAmount > 0)
{
@line.DebitAmount.ToString("C")
}
</td>
<td class="text-end">
@if (line.CreditAmount > 0)
{
@line.CreditAmount.ToString("C")
}
</td>
</tr>
}
</tbody>
<tfoot class="table-light fw-semibold">
<tr>
<td colspan="2" class="text-end">Totals</td>
<td class="text-end">@totalDebits.ToString("C")</td>
<td class="text-end">@totalCredits.ToString("C")</td>
</tr>
</tfoot>
</table>
</div>
</div>
@@ -0,0 +1,112 @@
@model IEnumerable<PowderCoating.Core.Entities.JournalEntry>
@using PowderCoating.Core.Enums
@{
ViewData["Title"] = "Journal Entries";
var statusFilter = ViewBag.StatusFilter as string ?? "All";
}
<div class="d-flex align-items-center mb-3 gap-2">
<h4 class="mb-0 fw-semibold">Journal Entries</h4>
<a asp-action="Create" class="btn btn-sm btn-primary ms-auto">
<i class="bi bi-plus-lg me-1"></i>New Entry
</a>
</div>
@if (TempData["Success"] != null)
{
<div class="alert alert-success alert-permanent alert-dismissible fade show">
@TempData["Success"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
@if (TempData["Error"] != null)
{
<div class="alert alert-danger alert-permanent alert-dismissible fade show">
@TempData["Error"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<a class="nav-link @(statusFilter == "All" ? "active" : "")" asp-action="Index">
All <span class="badge bg-secondary ms-1">@ViewBag.TotalCount</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link @(statusFilter == "Draft" ? "active" : "")" asp-action="Index" asp-route-status="Draft">
Draft <span class="badge bg-warning text-dark ms-1">@ViewBag.DraftCount</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link @(statusFilter == "Posted" ? "active" : "")" asp-action="Index" asp-route-status="Posted">
Posted <span class="badge bg-success ms-1">@ViewBag.PostedCount</span>
</a>
</li>
</ul>
<div class="card shadow-sm">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Entry #</th>
<th>Date</th>
<th>Description</th>
<th>Reference</th>
<th>Status</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
@if (!Model.Any())
{
<tr>
<td colspan="6" class="text-center text-muted py-4">
No journal entries found.
<a asp-action="Create">Create the first one.</a>
</td>
</tr>
}
@foreach (var je in Model)
{
<tr>
<td>
<a asp-action="Details" asp-route-id="@je.Id" class="fw-semibold text-decoration-none">
@je.EntryNumber
</a>
@if (je.IsReversal)
{
<span class="badge bg-secondary ms-1" title="Reversal entry">REV</span>
}
</td>
<td>@je.EntryDate.ToString("MMM d, yyyy")</td>
<td class="text-truncate" style="max-width:280px">@je.Description</td>
<td class="text-muted small">@je.Reference</td>
<td>
@if (je.Status == JournalEntryStatus.Draft)
{
<span class="badge bg-warning text-dark">Draft</span>
}
else if (je.Status == JournalEntryStatus.Posted)
{
<span class="badge bg-success">Posted</span>
}
else
{
<span class="badge bg-secondary">Reversed</span>
}
</td>
<td class="text-end">
<a asp-action="Details" asp-route-id="@je.Id" class="btn btn-sm btn-outline-secondary">
View
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
@@ -1130,6 +1130,10 @@
<i class="bi bi-journal-bookmark"></i>
<span>Chart of Accounts</span>
</a>
<a asp-controller="JournalEntries" asp-action="Index" class="nav-link">
<i class="bi bi-journal-text"></i>
<span>Journal Entries</span>
</a>
if (hasReports)
{
<a asp-controller="AccountingExport" asp-action="Index" class="nav-link">
@@ -0,0 +1,78 @@
const JournalEntry = (() => {
let accounts = [];
let lineIndex = 0;
function init(accountList) {
accounts = accountList;
document.getElementById('addLineBtn').addEventListener('click', addLine);
addLine();
addLine();
}
function buildAccountOptions(selectedId) {
return accounts.map(a =>
`<option value="${a.value}" ${a.value == selectedId ? 'selected' : ''}>${escHtml(a.text)}</option>`
).join('');
}
function addLine(accountId, debit, credit, desc) {
const tbody = document.getElementById('linesBody');
const idx = lineIndex++;
const tr = document.createElement('tr');
tr.dataset.idx = idx;
tr.innerHTML = `
<td>
<select name="lineAccountIds" class="form-select form-select-sm line-account" required>
<option value="">— select account —</option>
${buildAccountOptions(accountId)}
</select>
</td>
<td><input name="lineDescriptions" type="text" class="form-control form-control-sm" placeholder="optional" value="${escHtml(desc || '')}" /></td>
<td>
<input name="lineDebits" type="number" step="0.01" min="0" class="form-control form-control-sm text-end line-debit" placeholder="0.00" value="${debit || ''}" />
</td>
<td>
<input name="lineCreditAmounts" type="number" step="0.01" min="0" class="form-control form-control-sm text-end line-credit" placeholder="0.00" value="${credit || ''}" />
</td>
<td>
<input name="lineOrders" type="hidden" value="${idx}" />
<button type="button" class="btn btn-sm btn-link text-danger p-0 remove-line-btn" title="Remove line">
<i class="bi bi-x-lg"></i>
</button>
</td>`;
tr.querySelector('.remove-line-btn').addEventListener('click', () => {
tr.remove();
updateTotals();
});
tr.querySelector('.line-debit').addEventListener('input', updateTotals);
tr.querySelector('.line-credit').addEventListener('input', updateTotals);
tbody.appendChild(tr);
updateTotals();
}
function updateTotals() {
let debits = 0, credits = 0;
document.querySelectorAll('.line-debit').forEach(el => {
debits += parseFloat(el.value) || 0;
});
document.querySelectorAll('.line-credit').forEach(el => {
credits += parseFloat(el.value) || 0;
});
document.getElementById('totalDebits').textContent = fmtCurrency(debits);
document.getElementById('totalCredits').textContent = fmtCurrency(credits);
const badge = document.getElementById('balanceStatus');
const balanced = Math.abs(debits - credits) < 0.001 && debits > 0;
badge.textContent = balanced ? 'Balanced' : 'Unbalanced';
badge.className = 'badge ' + (balanced ? 'bg-success' : 'bg-secondary');
}
function fmtCurrency(n) {
return n.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
function escHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
return { init };
})();