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
@@ -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 };
})();