From 22657f0910235044f1501dd09bb051d61bd4d759 Mon Sep 17 00:00:00 2001 From: Haritha Randunu Date: Fri, 31 Jul 2026 17:57:55 +0530 Subject: [PATCH 1/2] feat: Implement new General Ledger frontend section with comprehensive report screens and cash/bank account management - Added a new Ledgers sidebar section for statutory-format financial reports and cash/bank-account management. - Introduced dedicated GL client for API interactions, handling response envelopes and error management. - Developed report screens for Trial Balance, Balance Sheet, General Ledger, Profit & Loss, Cash Flow, Budget vs Actual, and a new Tax Report. - Implemented CSV download functionality alongside existing PDF downloads for all report screens. - Separated Cash and Bank accounts into distinct tables/endpoints, with updated create forms and unified list view. - Created a new Accounts section for Cheque Management, moving Cash/Bank Accounts from the Ledgers section. - Updated RBAC navigation to include new permissions and sub-navigation items for the added features. - Ensured compliance with GL's updated API contract, including renaming fields and adjusting response shapes. - Addressed various bugs and presentation issues, enhancing user experience across the new module. --- .../Controllers/GeneralLedgerController.cs | 43 ++ .../ERPCore/Infra/Gl/GeneralLedgerClient.cs | 55 ++ .../ERPCore/Infra/Gl/GeneralLedgerResponse.cs | 15 + .../ERPCore/Infra/Gl/IGeneralLedgerClient.cs | 13 + .../Configurations/NavItemConfiguration.cs | 4 +- .../Configurations/PermissionConfiguration.cs | 24 +- .../Configurations/SubNavItemConfiguration.cs | 23 +- .../Migrations/ErpDbContextModelSnapshot.cs | 212 ++++++- Backend/ERPCore/Program.cs | 10 + .../ERPCore/Services/GeneralLedgerService.cs | 16 + .../Interfaces/IGeneralLedgerService.cs | 16 + Backend/ERPCore/System/Errors/ErrorCodes.cs | 3 + Backend/ERPCore/appsettings.Development.json | 2 +- Backend/ERPCore/appsettings.json | 4 + Backend/PROGRESS.md | 25 + Frontend/PROGRESS.md | 40 ++ .../accounts/bank-accounts/new/page.tsx | 204 +++++++ .../dashboard/accounts/bank-accounts/page.tsx | 192 ++++++ .../cheque-books/[chequeBookNo]/page.tsx | 159 +++++ .../accounts/cheque-books/new/page.tsx | 216 +++++++ .../dashboard/accounts/cheque-books/page.tsx | 154 +++++ .../app/dashboard/accounts/page.tsx | 58 ++ .../accounts/received-cheques/new/page.tsx | 215 +++++++ .../accounts/received-cheques/page.tsx | 151 +++++ .../dashboard/ledgers/balance-sheet/page.tsx | 156 +++++ .../ledgers/budget-vs-actual/page.tsx | 179 ++++++ .../app/dashboard/ledgers/cash-flow/page.tsx | 184 ++++++ .../dashboard/ledgers/general-ledger/page.tsx | 148 +++++ .../erp-system/app/dashboard/ledgers/page.tsx | 91 +++ .../ledgers/profit-and-loss/page.tsx | 166 ++++++ .../app/dashboard/ledgers/tax-report/page.tsx | 284 +++++++++ .../dashboard/ledgers/trial-balance/page.tsx | 134 +++++ .../components/Layouts/AppSidebar.tsx | 49 +- .../erp-system/components/Layouts/Header.tsx | 31 +- .../components/accounts/ChequePageDialog.tsx | 381 ++++++++++++ .../accounts/ReceivedChequeDialog.tsx | 236 ++++++++ .../components/reports/DownloadCsvButton.tsx | 42 ++ .../components/reports/DownloadPdfButton.tsx | 41 ++ .../components/reports/ReportHeader.tsx | 27 + .../components/reports/ReportSection.tsx | 42 ++ .../components/reports/ReportSubtotal.tsx | 23 + Frontend/erp-system/lib/api/general-ledger.ts | 322 ++++++++++ Frontend/erp-system/lib/format.ts | 35 ++ .../lib/validations/general-ledger.ts | 55 ++ Frontend/erp-system/types/general-ledger.ts | 558 ++++++++++++++++++ docs/00-CORE.md | 6 +- docs/01-DOC-GUIDE.md | 2 + docs/12-GENERAL-LEDGER-INTEGRATION.md | 156 +++++ docs/21-GENERAL-LEDGER-FRONTEND.md | 532 +++++++++++++++++ 49 files changed, 5707 insertions(+), 27 deletions(-) create mode 100644 Backend/ERPCore/Controllers/GeneralLedgerController.cs create mode 100644 Backend/ERPCore/Infra/Gl/GeneralLedgerClient.cs create mode 100644 Backend/ERPCore/Infra/Gl/GeneralLedgerResponse.cs create mode 100644 Backend/ERPCore/Infra/Gl/IGeneralLedgerClient.cs create mode 100644 Backend/ERPCore/Services/GeneralLedgerService.cs create mode 100644 Backend/ERPCore/Services/Interfaces/IGeneralLedgerService.cs create mode 100644 Frontend/erp-system/app/dashboard/accounts/bank-accounts/new/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/bank-accounts/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/cheque-books/[chequeBookNo]/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/cheque-books/new/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/cheque-books/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/received-cheques/new/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/accounts/received-cheques/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/balance-sheet/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/budget-vs-actual/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/cash-flow/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/general-ledger/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/profit-and-loss/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/tax-report/page.tsx create mode 100644 Frontend/erp-system/app/dashboard/ledgers/trial-balance/page.tsx create mode 100644 Frontend/erp-system/components/accounts/ChequePageDialog.tsx create mode 100644 Frontend/erp-system/components/accounts/ReceivedChequeDialog.tsx create mode 100644 Frontend/erp-system/components/reports/DownloadCsvButton.tsx create mode 100644 Frontend/erp-system/components/reports/DownloadPdfButton.tsx create mode 100644 Frontend/erp-system/components/reports/ReportHeader.tsx create mode 100644 Frontend/erp-system/components/reports/ReportSection.tsx create mode 100644 Frontend/erp-system/components/reports/ReportSubtotal.tsx create mode 100644 Frontend/erp-system/lib/api/general-ledger.ts create mode 100644 Frontend/erp-system/lib/format.ts create mode 100644 Frontend/erp-system/lib/validations/general-ledger.ts create mode 100644 Frontend/erp-system/types/general-ledger.ts create mode 100644 docs/12-GENERAL-LEDGER-INTEGRATION.md create mode 100644 docs/21-GENERAL-LEDGER-FRONTEND.md diff --git a/Backend/ERPCore/Controllers/GeneralLedgerController.cs b/Backend/ERPCore/Controllers/GeneralLedgerController.cs new file mode 100644 index 0000000..2f0bf12 --- /dev/null +++ b/Backend/ERPCore/Controllers/GeneralLedgerController.cs @@ -0,0 +1,43 @@ +using ERPCore.Services.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace ERPCore.Controllers; + +/// +/// Generic reverse proxy into the external General Ledger service — forwards every +/// method/path/query/body under this prefix verbatim via +/// and returns GL's response (status, content-type, +/// body) unchanged. No endpoint-specific shape lives here; see +/// docs/12-GENERAL-LEDGER-INTEGRATION.md for the full GL contract and what this proxy +/// does and doesn't do. Gated by the same ERP door policy as every other v1 endpoint +/// () — the shared GL API key is attached server-side +/// only and is never exposed to the frontend. +/// +[Route("api/v1/gl")] +public sealed class GeneralLedgerController : ApiControllerBase +{ + private readonly IGeneralLedgerService _gl; + + public GeneralLedgerController(IGeneralLedgerService gl) => _gl = gl; + + [HttpGet("{**path}")] + public Task Get(string path, CancellationToken ct) => ForwardAsync(HttpMethod.Get, path, ct); + + [HttpPost("{**path}")] + public Task Post(string path, CancellationToken ct) => ForwardAsync(HttpMethod.Post, path, ct); + + [HttpPut("{**path}")] + public Task Put(string path, CancellationToken ct) => ForwardAsync(HttpMethod.Put, path, ct); + + private async Task ForwardAsync(HttpMethod method, string path, CancellationToken ct) + { + var body = method == HttpMethod.Get ? null : Request.Body; + var result = await _gl.ForwardAsync(method, path, Request.QueryString.Value, Request.ContentType, body, ct); + return new ContentResult + { + StatusCode = result.StatusCode, + Content = result.Body, + ContentType = result.ContentType ?? "application/json" + }; + } +} diff --git a/Backend/ERPCore/Infra/Gl/GeneralLedgerClient.cs b/Backend/ERPCore/Infra/Gl/GeneralLedgerClient.cs new file mode 100644 index 0000000..170879f --- /dev/null +++ b/Backend/ERPCore/Infra/Gl/GeneralLedgerClient.cs @@ -0,0 +1,55 @@ +using ERPCore.System.Errors; + +namespace ERPCore.Infra.Gl; + +/// +/// HTTP implementation of . Registered as a typed +/// client (`AddHttpClient<IGeneralLedgerClient, GeneralLedgerClient>`) with its +/// `BaseAddress` bound from `GeneralLedgerService:BaseUrl`. Every call attaches the +/// shared `GeneralLedgerService:ApiKey` as `X-Api-Key` and streams the request/response +/// body straight through, unparsed — GL's own response (status, content-type, body) is +/// returned exactly as received; nothing here reshapes it. +/// +public sealed class GeneralLedgerClient(HttpClient http, IConfiguration configuration) : IGeneralLedgerClient +{ + private readonly HttpClient _http = http; + private readonly string _apiKey = configuration["GeneralLedgerService:ApiKey"] ?? string.Empty; + + public async Task SendAsync( + HttpMethod method, string path, string? queryString, string? contentType, Stream? body, CancellationToken ct) + { + var relativeUri = path.TrimStart('/') + queryString; + using var request = new HttpRequestMessage(method, relativeUri); + request.Headers.TryAddWithoutValidation("X-Api-Key", _apiKey); + + if (body is not null && method != HttpMethod.Get) + { + var content = new StreamContent(body); + if (!string.IsNullOrEmpty(contentType)) + content.Headers.TryAddWithoutValidation("Content-Type", contentType); + request.Content = content; + } + + HttpResponseMessage response; + try + { + response = await _http.SendAsync(request, ct); + } + catch (HttpRequestException) + { + throw new DomainException(ErrorCodes.GlServiceUnavailable, "The General Ledger service is unreachable.", 503); + } + catch (TaskCanceledException) when (!ct.IsCancellationRequested) + { + throw new DomainException(ErrorCodes.GlServiceUnavailable, "The General Ledger service timed out.", 503); + } + + var responseBody = await response.Content.ReadAsStringAsync(ct); + return new GeneralLedgerResponse + { + StatusCode = (int)response.StatusCode, + ContentType = response.Content.Headers.ContentType?.ToString(), + Body = responseBody + }; + } +} diff --git a/Backend/ERPCore/Infra/Gl/GeneralLedgerResponse.cs b/Backend/ERPCore/Infra/Gl/GeneralLedgerResponse.cs new file mode 100644 index 0000000..bfaec0c --- /dev/null +++ b/Backend/ERPCore/Infra/Gl/GeneralLedgerResponse.cs @@ -0,0 +1,15 @@ +namespace ERPCore.Infra.Gl; + +/// +/// Raw HTTP result from the external General Ledger service — status code, content +/// type, and body exactly as GL returned them. Deliberately un-reshaped: GL's own +/// envelope (see the GL service's own API reference) is passed through byte-for-byte +/// so its camelCase-success/PascalCase-error inconsistency and full decimal precision +/// survive the hop unchanged (docs/12-GENERAL-LEDGER-INTEGRATION.md). +/// +public sealed class GeneralLedgerResponse +{ + public int StatusCode { get; init; } + public string? ContentType { get; init; } + public string Body { get; init; } = string.Empty; +} diff --git a/Backend/ERPCore/Infra/Gl/IGeneralLedgerClient.cs b/Backend/ERPCore/Infra/Gl/IGeneralLedgerClient.cs new file mode 100644 index 0000000..962c0eb --- /dev/null +++ b/Backend/ERPCore/Infra/Gl/IGeneralLedgerClient.cs @@ -0,0 +1,13 @@ +namespace ERPCore.Infra.Gl; + +/// +/// Typed HTTP transport to the external General Ledger service. Injects the shared +/// `X-Api-Key` secret and forwards method/path/query/body/content-type verbatim — +/// see docs/12-GENERAL-LEDGER-INTEGRATION.md. Internal: only +/// consumes this. +/// +public interface IGeneralLedgerClient +{ + Task SendAsync( + HttpMethod method, string path, string? queryString, string? contentType, Stream? body, CancellationToken ct); +} diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/NavItemConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/NavItemConfiguration.cs index 0a89d0a..4db1434 100644 --- a/Backend/ERPCore/Infra/Persistence/Configurations/NavItemConfiguration.cs +++ b/Backend/ERPCore/Infra/Persistence/Configurations/NavItemConfiguration.cs @@ -36,7 +36,9 @@ public sealed class NavItemConfiguration : IEntityTypeConfiguration new NavItem { NavItemId = 7, Code = "warehouses", Label = "Warehouses", Href = "/dashboard/warehouse", SortOrder = 7 }, new NavItem { NavItemId = 8, Code = "orders", Label = "Orders", Href = "/dashboard/orders", SortOrder = 8 }, new NavItem { NavItemId = 9, Code = "settings", Label = "Settings", Href = "/dashboard/settings", SortOrder = 9 }, - new NavItem { NavItemId = 10, Code = "help", Label = "Help", Href = "/dashboard/help", SortOrder = 10 } + new NavItem { NavItemId = 10, Code = "help", Label = "Help", Href = "/dashboard/help", SortOrder = 10 }, + new NavItem { NavItemId = 11, Code = "ledgers", Label = "Ledgers", Href = "/dashboard/ledgers", SortOrder = 11 }, + new NavItem { NavItemId = 12, Code = "accounts", Label = "Accounts", Href = "/dashboard/accounts", SortOrder = 12 } ); } } diff --git a/Backend/ERPCore/Infra/Persistence/Configurations/PermissionConfiguration.cs b/Backend/ERPCore/Infra/Persistence/Configurations/PermissionConfiguration.cs index 065f5b8..47bec28 100644 --- a/Backend/ERPCore/Infra/Persistence/Configurations/PermissionConfiguration.cs +++ b/Backend/ERPCore/Infra/Persistence/Configurations/PermissionConfiguration.cs @@ -42,10 +42,26 @@ public sealed class PermissionConfiguration : IEntityTypeConfiguration(); builder.Services.AddScoped(); builder.Services.AddScoped(); +// General Ledger service proxy → external GL microservice (docs/12-GENERAL-LEDGER-INTEGRATION.md) +builder.Services.AddHttpClient(c => +{ + var baseUrl = builder.Configuration["GeneralLedgerService:BaseUrl"] + ?? throw new InvalidOperationException("GeneralLedgerService:BaseUrl is not configured."); + c.BaseAddress = new Uri(baseUrl); +}); +builder.Services.AddScoped(); + // Current-user (audit actor). AuthHex has no sub/nameid → a claims transformation // JIT-provisions a local shadow user and injects the local `int` id as `nameid`. builder.Services.AddHttpContextAccessor(); diff --git a/Backend/ERPCore/Services/GeneralLedgerService.cs b/Backend/ERPCore/Services/GeneralLedgerService.cs new file mode 100644 index 0000000..4b70e23 --- /dev/null +++ b/Backend/ERPCore/Services/GeneralLedgerService.cs @@ -0,0 +1,16 @@ +using ERPCore.Infra.Gl; +using ERPCore.Services.Interfaces; + +namespace ERPCore.Services; + +/// +public sealed class GeneralLedgerService : IGeneralLedgerService +{ + private readonly IGeneralLedgerClient _client; + + public GeneralLedgerService(IGeneralLedgerClient client) => _client = client; + + public Task ForwardAsync( + HttpMethod method, string path, string? queryString, string? contentType, Stream? body, CancellationToken ct) + => _client.SendAsync(method, path, queryString, contentType, body, ct); +} diff --git a/Backend/ERPCore/Services/Interfaces/IGeneralLedgerService.cs b/Backend/ERPCore/Services/Interfaces/IGeneralLedgerService.cs new file mode 100644 index 0000000..eeff07b --- /dev/null +++ b/Backend/ERPCore/Services/Interfaces/IGeneralLedgerService.cs @@ -0,0 +1,16 @@ +using ERPCore.Infra.Gl; + +namespace ERPCore.Services.Interfaces; + +/// +/// Single entry point into the external General Ledger service — the one function +/// used both by (frontend +/// requests, forwarded verbatim) and, once wired, other ERPCore services that need to +/// post directly to GL (e.g. GRN confirm, adjustments — docs/12-GENERAL-LEDGER-INTEGRATION.md). +/// No business logic lives here yet; this pass only connects the transport. +/// +public interface IGeneralLedgerService +{ + Task ForwardAsync( + HttpMethod method, string path, string? queryString, string? contentType, Stream? body, CancellationToken ct); +} diff --git a/Backend/ERPCore/System/Errors/ErrorCodes.cs b/Backend/ERPCore/System/Errors/ErrorCodes.cs index 903af82..bc439f3 100644 --- a/Backend/ERPCore/System/Errors/ErrorCodes.cs +++ b/Backend/ERPCore/System/Errors/ErrorCodes.cs @@ -66,4 +66,7 @@ public static class ErrorCodes public const string LeftoverExceedsConsumed = "LEFTOVER_EXCEEDS_CONSUMED"; public const string RunCostClosed = "RUN_COST_CLOSED"; public const string RunNotCancellable = "RUN_NOT_CANCELLABLE"; + + // General Ledger service proxy (GeneralLedgerController → external GL service, docs/12) + public const string GlServiceUnavailable = "GL_SERVICE_UNAVAILABLE"; } diff --git a/Backend/ERPCore/appsettings.Development.json b/Backend/ERPCore/appsettings.Development.json index 28ac658..6d40007 100644 --- a/Backend/ERPCore/appsettings.Development.json +++ b/Backend/ERPCore/appsettings.Development.json @@ -6,7 +6,7 @@ } }, "ConnectionStrings": { - "DefaultConnection": "Host=localhost;Port=5432;Database=ERPCore;Username=postgres;Password=root" + "DefaultConnection": "Host=localhost;Port=5432;Database=ERPCore;Username=postgres;Password=dbuser" }, "AuthHex": { "BaseUrl": "http://localhost:5011" diff --git a/Backend/ERPCore/appsettings.json b/Backend/ERPCore/appsettings.json index ee6e372..9d07a93 100644 --- a/Backend/ERPCore/appsettings.json +++ b/Backend/ERPCore/appsettings.json @@ -22,5 +22,9 @@ "RootPath": "App_Data/hr-documents", "MaxSizeBytes": 10485760 }, + "GeneralLedgerService": { + "BaseUrl": "https://localhost:7024/api/v1/", + "ApiKey": "1A5FE0E389C029B1FBCD2A94650CEBF0656083BF06FF48E5E11987040ABA262D" + }, "AllowedHosts": "*" } diff --git a/Backend/PROGRESS.md b/Backend/PROGRESS.md index f9431cf..4e6884f 100644 --- a/Backend/PROGRESS.md +++ b/Backend/PROGRESS.md @@ -105,6 +105,31 @@ Convention: `docs/01-DOC-GUIDE.md §6`. Update this file in the **same commit** - [~] FEFO picking for perishables; block expired / on-hold issue — **issue-block done + verified** (`ONHOLD_NOT_ISSUABLE`, `EXPIRED_BATCH_BLOCKED`; on-hold/expired layers excluded from consume). FEFO *pick ordering* (oldest-expiry first) not yet built. - [x] Reason codes (FR-X-04) — `ReasonCode` entity + `GET/POST /reason-codes`; standard set (docs/10 §B.8.3) seeded idempotently at startup (`DataSeeder`). Verified. +## 7. External Integrations +> **General Ledger service** (separate microservice, own repo/DB) — connected 2026-07-20 as a generic reverse-proxy only; no ERPCore business logic posts to it yet. Full contract + progress detail: `docs/12-GENERAL-LEDGER-INTEGRATION.md`. +- [~] Generic proxy `GET|POST|PUT /api/v1/gl/{**path}` (`GeneralLedgerController` → `IGeneralLedgerService` → `IGeneralLedgerClient`) — forwards method/path/query/body/content-type verbatim to the GL service with a server-attached `X-Api-Key`; GL's response (status + body) returned unchanged. ErpAccess-door-policy-gated like every other v1 endpoint. Config: `GeneralLedgerService:BaseUrl`/`ApiKey` in `appsettings.json`. Build verified clean; **not yet live-smoke-tested** (no running GL instance this pass). +- [ ] Internal wiring — ERPCore services (GRN confirm, adjustments, etc.) calling `IGeneralLedgerService` directly to post real journal entries. Deliberately deferred. + +> ### 2026-07-20 — RBAC nav seed for the frontend's new "Ledgers" section +> The `Frontend/PROGRESS.md` §8 "Ledgers" sidebar section (docs/21-GENERAL-LEDGER-FRONTEND.md) needs a matching `NavItem`/`SubNavItem`/`Permission` row for every entry, or the sidebar filters it out for every role regardless of the frontend change (docs/10 C.8, `GET /auth/me`'s `navCodes`). Added via `NavItemConfiguration.cs`/`SubNavItemConfiguration.cs`/`PermissionConfiguration.cs` `HasData`: `NavItem` `ledgers` (id 11), 7 `SubNavItem` rows (ids 9–15, `ledgers.trial-balance` … `ledgers.bank-accounts`), 8 `Permission` rows (ids 19–26) — same one-`Permission`-per-nav-entry convention as every existing nav row. Migration `AddLedgersNavSeed`. +> **Build note:** a locally running `ERPCore.exe` (PID 29692) held the default `bin/Debug` output locked for the whole session, so `dotnet ef migrations add` twice produced an empty no-op migration off a stale assembly (`--no-build` silently reused pre-edit code) before the real cause was found. Fixed by building to a scratch output directory (unaffected by the lock), copying the fresh `ERPCore.dll` over the locked `bin/Debug` copy (the running process only locks the `.exe`, not the `.dll`), then re-scaffolding — the resulting migration's `Up`/`Down` were verified by inspection against the identical, already-applied `AddRolesNavPermissions` migration's `InsertData`/`DeleteData` shape. The stray process was left running rather than killed, since it wasn't started by this work and may be in active use elsewhere. +> **Not yet applied to a live database** — no Postgres instance was available in this pass to run `dotnet ef database update` against. `dotnet build` is clean (0 warnings/0 errors). +> **Operational step still needed post-deploy (not code):** a new `NavItem`/`SubNavItem` carries no `RolePermission` grants by default — an administrator must check the new Ledgers permissions for the relevant role(s) via **Settings → Roles** before anyone sees the sidebar entry, same as every previous nav addition. + +> ### 2026-07-30 — RBAC nav seed: 8th sub-item for the new "Tax Report" screen +> The frontend's GL-revision pass (`docs/21-GENERAL-LEDGER-FRONTEND.md`, Frontend/PROGRESS.md §8) added a Tax Report screen to the Ledgers sidebar section — needs the same nav-seed treatment as every other entry (docs/10 C.8). Added `SubNavItem` id 16 (`ledgers.tax-report`, `/dashboard/ledgers/tax-report`, sort order 7) and `Permission` id 27 (`NAV:ledgers.tax-report`); re-sequenced the existing `ledgers.bank-accounts` row's `SortOrder` from 7→8 so Tax Report sits before it, matching the sidebar array's actual order. Migration `AddTaxReportNavSeed` — no locked-process issue this time (confirmed no stray `ERPCore.exe` running before scaffolding), generated cleanly on the first attempt with real `InsertData`/`UpdateData`/`DeleteData` (`Down()` correctly restores `bank-accounts`' `SortOrder` to 7). `dotnet build` clean (0 warnings/0 errors). **Not yet applied to a live database** — same open item as the original `AddLedgersNavSeed` migration; both are still pending `dotnet ef database update` against a real Postgres instance. + +> ### 2026-07-30 (2) — Fixed a real `SubNavItemId`/`PermissionId` collision between Procurement and Ledgers seed data +> **Root cause:** when the 2026-07-20 `AddLedgersNavSeed` migration was authored, its `SubNavItem`/`Permission` IDs were picked by looking at the *actual DB row count*, not the config source — but `SubNavItemConfiguration.cs`/`PermissionConfiguration.cs` already had `HasData` entries for Procurement's 4 sub-items (`procurement.requisitions`/`.rfqs`/`.purchase-orders`/`.purchase-returns`, ids 9–12/19–22) that **had never actually been migrated into any database** (no migration `Up()` anywhere ever inserts them — confirmed by grep across every migration file). Ledgers then claimed the same ids (9–12 sub-nav, 19–22 permission) for its own rows, so the config ended up with two `HasData` entries sharing the same primary key per table. `ErpDbContextModelSnapshot.cs` had silently absorbed both (`dotnet ef migrations add` doesn't hard-fail on this at scaffold time), but **EF's runtime model validator does** — `dotnet ef migrations add` for anything touching these tables, and by extension normal app startup/first `DbContext` use, throws `InvalidOperationException: A seed entity ... has the same key value as another seed entity mapped to the same table`. This is very likely the crash the user was hitting. +> **Fix:** moved Procurement's 4 sub-nav rows off the colliding ids onto **17–20** (`SubNavItemId`) and **28–31** (`PermissionId`), past every id already claimed by Ledgers/Tax-Report (max 16/27). Removed the phantom duplicate Procurement entries from `ErpDbContextModelSnapshot.cs` (they never reflected real DB state) so the differ could compute a clean diff, then generated migration **`FixProcurementNavIdCollision`** — pure `InsertData` for the 4 sub-nav rows + 4 permission rows at their new ids (this is also the *first* migration that actually creates Procurement's sub-nav-item/permission rows in the database at all). `Down()` is a clean `DeleteData` reversal. +> **Verified:** running `dotnet ef migrations add` against the pre-fix config reproduced the exact `InvalidOperationException` above (scaffold failed outright, no migration file produced), confirming this was a real, reproducible crash and not a false alarm; after the fix, the same command succeeded and `dotnet ef migrations list` builds the full model with no error, listing all 7 migrations (the last 2 — `AddTaxReportNavSeed`, `FixProcurementNavIdCollision` — still `(Pending)`, no Postgres instance available this session); `dotnet build` clean (0 warnings/0 errors). **Not yet applied to a live database** — same standing blocker as the two prior nav-seed migrations. +> Also fixed, same pass: `Frontend/erp-system/components/Layouts/AppSidebar.tsx`'s auto-expand-active-parent logic tripped `react-hooks/set-state-in-effect` (`setExpanded` called synchronously inside a `useEffect`) — converted to the same "adjust state during render" pattern used for the Ledgers report pages, keyed on a `pathname + item-codes` composite key (tracked via a `lastAutoExpandKey` state var) so it still re-fires once `items` populates after the RBAC `navCodes` fetch resolves. `npx eslint components/Layouts/AppSidebar.tsx` clean. + +> ### 2026-07-31 — RBAC nav seed: new "Accounts" nav item (Cheque Management screens + Cash/Bank Accounts moved off Ledgers) +> The frontend added a new "Accounts" sidebar section (`Frontend/PROGRESS.md` §8) for the new Cheque Management screens and to hold Cash/Bank Accounts, which moved out of Ledgers into it (user-requested — Cheque Books/Received Cheques/Cash-Bank Accounts are all the same kind of operational account bookkeeping, not a statutory report). Migration **`AddAccountsNavSeed`**: `InsertData` for `NavItem` `accounts` (id 12) and two new `SubNavItem`/`Permission` pairs (`accounts.cheque-books` id 21/33, `accounts.received-cheques` id 22/34); **`UpdateData`, not delete-and-recreate**, for the existing Cash/Bank Accounts `SubNavItem`/`Permission` (ids 15/26) — same ids, just new `Code`/`Href`/`NavItemId` — so a role that had already been granted this permission under its old `ledgers.bank-accounts` code doesn't silently lose it just because the section changed. `Down()` correctly reverses both the inserts and the renamed-row update back to its Ledgers-era values. +> **No locked-process issue avoided this time** — `ERPCore.exe` was found running twice during this pass (the user had restarted it between turns to test the Tax Report fix); confirmed with the user before killing it each time, per this session's standing caution around stopping their dev server. `dotnet build` clean (0 warnings/0 errors); `dotnet ef migrations list` shows all 8 migrations with none pending. **Applied to the live database this session** (`dotnet ef database update`) — unlike every prior nav-seed migration this session, this one did not have to wait for a live Postgres instance to become available. +> **Operational step still needed post-deploy (not code):** same as every previous nav addition — an administrator must grant the new `NAV:accounts`/`NAV:accounts.cheque-books`/`NAV:accounts.received-cheques` permissions to the relevant role(s) via **Settings → Roles** before anyone sees the new sidebar entries (the re-homed `NAV:accounts.bank-accounts` keeps whatever grants it already had). + ## Deferred (Phase 2+ — do NOT build now, hooks only) - [ ] Vendor invoice + three-way match - [ ] Reservation/allocation fulfilment diff --git a/Frontend/PROGRESS.md b/Frontend/PROGRESS.md index 90d3a13..b6cb645 100644 --- a/Frontend/PROGRESS.md +++ b/Frontend/PROGRESS.md @@ -83,6 +83,46 @@ Convention: `docs/01-DOC-GUIDE.md §6`. Update this file in the **same commit** - [ ] `412` conflict → prompt refetch before retry — `apiRequestWithETag` surfaces the ETag but no screen edits a GRN yet (GRN has no PUT), so untested in practice - [x] No client-side gating on stock/availability/status (server-authoritative) — GRN create always submits to the server and surfaces `OVER_RECEIPT_TOLERANCE`/etc. via `error-map.ts` rather than pre-blocking +## 8. General Ledger (Ledgers + Accounts sections) +> Two sidebar sections (`app/dashboard/ledgers/*`, `app/dashboard/accounts/*`), sourced entirely from the external General Ledger service via ERPCore's generic proxy (`docs/12-GENERAL-LEDGER-INTEGRATION.md`). Full detail, decisions, and known gaps: `docs/21-GENERAL-LEDGER-FRONTEND.md`. +- [x] Ledgers: reports hub + 7 report screens (Trial Balance, Balance Sheet, General Ledger, Profit & Loss, Cash Flow, Budget vs Actual, Tax Report) — statutory-format header/table, PDF **and CSV** download via the same endpoint with `outputFormat=Pdf`/`Csv` +- [x] Accounts: hub + Cash/Bank Accounts — unified list (GL's own server-side `accountType` union + client-side text search) + create (Cash/Bank toggle; GL account is now auto-created server-side, **no picker** — see 2026-07-31 (6) below). **Moved here from Ledgers (2026-07-31 (5))** +- [ ] Cash/Bank Accounts — edit: **not built**, GL has no `GET`/`PUT` by id for either table to build it against (list shows a disabled Edit affordance with an explanatory tooltip instead of a broken form) +- [x] Accounts: Cheque Books — list/filter, create (auto-generates every leaf), drill-down to a book's own pages list, per-page details/issue/status-update in a modal +- [x] Accounts: Received Cheques — list/filter, create, per-row details/status-update in a modal +- [x] Sidebar "Ledgers" (7 sub-items) + new "Accounts" (3 sub-items) nav items (`components/Layouts/AppSidebar.tsx`) + header title mappings (`components/Layouts/Header.tsx`) +- [x] Dedicated GL fetch client (`lib/api/general-ledger.ts`) — GL's envelope differs from ERPCore's own `ProblemDetails`, so this does not reuse `lib/api-client.ts`; now also covers Cheque Management (`chequeBooksApi`/`chequePagesApi`/`receivedChequesApi`) + +> **2026-07-30 — GL's 2026-07-22 backend revision built out (large pass).** Five reports restructured (Trial Balance flattened, Profit & Loss → nested named sections with a Gross Profit subtotal, Cash Flow → a real structured statement replacing the four `StatCard`s), a new CSV export on all seven reports (`components/reports/DownloadCsvButton.tsx`), a brand-new **Tax Report** screen (Income Tax Computation, collapsible optional-adjustments panel, payable/refundable sign-dependent final row), and Cash/Bank accounts split into two real GL endpoints (`POST /bank-accounts` vs `POST /cash-accounts`, unified `GET /bank-accounts?accountType=`) with a two-choice create-form toggle and a Cash Account Type picker that can create a new type on the fly. Extracted `components/reports/{ReportSection,ReportSubtotal}.tsx` — shared by Profit & Loss and Cash Flow rather than duplicating the "bordered section + bold subtotal" markup twice. Three response shapes (`ProfitAndLossResponse`/`CashFlowResponse`/`TaxSummaryResponse`) are **inferred** where GL's own reference doesn't spell out every field verbatim — flagged in `types/general-ledger.ts`'s own comments and `docs/21-GENERAL-LEDGER-FRONTEND.md`, same posture as the original inferred `BankAccount` shape. Backend: migration `AddTaxReportNavSeed` adds the 8th sidebar sub-item + its permission row. Verified: `tsc --noEmit` clean, `eslint` clean across every touched file, `npm run build` succeeds with all 9 `/dashboard/ledgers/*` routes (incl. `/tax-report`), `dotnet build` clean. **Not done:** live smoke test against a running GL instance (still no instance available this session) — the three inferred response shapes are the highest-value thing to verify first. + +> **2026-07-20, same-day fixes (user-reported):** (1) General Ledger report was wrongly calling `GET /accounts` to populate an account picker — GL documents `accountId` on this report as a raw id, not a code-lookup value, so the picker is gone; the screen now only ever calls `/reports`, entering `accountId` directly and reading the account's code/name for display off the report's own returned rows instead. (2) `ReportType`/`ReportOutputFormat`/`GlAccountTypeId` converted from string/numeric literal unions to real TS enums. (3) Fixed a UI-only bug where a selected ``s elsewhere in the app likely share this latent bug; flagged in `docs/21-GENERAL-LEDGER-FRONTEND.md` §4 for whoever next touches one). Verified: `tsc --noEmit` and `eslint` clean. +> +> **2026-07-20 (2) — `react-hooks/set-state-in-effect` errors resolved, Ledgers pages only (scope confirmed with the user — this is not an app-wide lint pass; the same error is pre-existing on ~35 other files elsewhere in the app, left untouched).** All 7 report/list screens called `setState` synchronously as the first statement of a data-fetching effect (clearing stale results before the async call) — flagged as an error, not just a warning, by this project's current eslint config. Fixed with React's own "adjust state during render" pattern instead of an effect: each page now tracks the key it last loaded for (`asOfDate`/period/`accountId`/`budgetId`) in a small extra piece of state, and resets the result/error state **during render** when that key changes (before the effect below ever runs) rather than synchronously inside the effect. Behavior is unchanged — stale results still clear the instant a filter changes. `bank-accounts/page.tsx`'s mount-only `load()` had a redundant `setError(null)` (state already starts `null`; nothing else ever recalls `load()`), removed outright rather than worked around. Verified: `npx eslint app/dashboard/ledgers` produces zero output, `tsc --noEmit` clean, `npm run build` succeeds. +> +> **2026-07-31 — Fixed a live runtime crash on Cash Flow: GL omits empty list/section fields entirely instead of sending `[]`/`{lines:[],total:0}`.** User-reported error clicking into the page: `TypeError: Cannot read properties of undefined (reading 'map')` at `bucketOperatingLines` → `report.nonCashAdjustments.map(...)`, confirming the exact risk `CashFlowResponse` had been flagged with since it was built (inferred shape, never verified live). Root cause: GL's serializer drops a list/section property from the JSON body altogether when there's nothing to report for the period, rather than emitting an empty array/zero-totalled object. Fixed defensively in `cash-flow/page.tsx` (`?? []` on `nonCashAdjustments`/`workingCapitalChanges`, a new `activitySectionLines()` helper + optional chaining for `investingActivities`/`financingActivities`/their `.total`) and, proactively, in `profit-and-loss/page.tsx` (`isEmpty` check and every section's `.total` access) since `ProfitAndLossResponse` shares the identical nested-section shape and was equally exposed — not yet crashed on, but certain to under the same conditions (a section with nothing posted for the period). `types/general-ledger.ts`'s `CashFlowResponse`/`ProfitAndLossResponse` fields updated from required to optional to match, with comments pointing back at this confirmed-live behavior. Verified: `tsc --noEmit`/`eslint` clean on all touched files; `npm run build`'s TypeScript step fails, but only on a pre-existing, unrelated `app/dashboard/hrm/employees/[id]/page.tsx` error present before this pass — out of scope per standing instruction to keep fixes scoped to Ledgers. **Tax Report's `TaxSummaryResponse` is the one remaining inferred shape not yet defensively hardened or live-verified** — same class of risk, flagged for the next time that screen is touched. +> +> **2026-07-31 (2) — Corrected against GL's own authoritative API reference (`04_API_Reference_And_Scenarios.md`, user-supplied): Cash Flow's shape was fundamentally wrong, not just missing defensive guards; Tax Report was missing five real fields.** With the actual GL API reference in hand (not inference), checked every report's response shape against it: Trial Balance, Balance Sheet, General Ledger, Profit & Loss, and Budget vs Actual all match exactly, confirming those five were built correctly. Two did not: **(1) `CashFlowResponse` doesn't have `netEarnings`/`nonCashAdjustments`/`workingCapitalChanges`/`netCashFromOperations` as flat top-level fields at all — everything genuinely nests under `operatingActivities` (`{ profitForPeriod, nonCashAdjustments[], workingCapitalChanges[], netCashFromOperatingActivities }`), and `investingActivities`/`financingActivities` each carry their own differently-named total (`netCashFromInvestingActivities`/`netCashFromFinancingActivities`), not a shared `total`.** This — not just "the field might be missing" — was the real cause of the crash fixed in the previous entry; the previous fix's defensive `?? []` guards were correct in spirit but pointed at the wrong (nonexistent) top-level fields, so the page would have kept rendering an empty operating-activities section forever even without crashing. Rewrote `cash-flow/page.tsx` and `CashFlowResponse`/added `CashFlowOperatingActivities`/`CashFlowInvestingActivities`/`CashFlowFinancingActivities` to `types/general-ledger.ts` to match the confirmed contract exactly; also caught that `workingCapitalChanges[]` entries use `changeAmount`, not `amount`. **(2) `TaxSummaryResponse`/the Tax Report's `ROWS` table were missing `nonDeductibleExpenses`, `corporateIncomeTax`, `apitCredit`, `whtCredit`, and `quarterlyTaxPayments` entirely** — real GL-computed figures that were silently never rendered, not just a wrong guess at a field name. Added all five in their correct position in the confirmed row order (`profitBeforeTax` → `balanceTaxPayable`). Verified: `tsc --noEmit`/`eslint` clean on every touched file. +> +> **2026-07-31 (3) — Balance Sheet regrouped into a proper LKAS Statement of Financial Position layout (user-reported).** `BalanceSheetRow`'s shape was already correct (confirmed against GL's reference above), but the flat one-table rendering made a rollup total visually indistinguishable from the leaf amounts it already sums — e.g. "Cash and Bank"'s balance already includes "Petty Cash"/"Main Operating Bank Account"/"Savings Bank Account" beneath it, but every row read the same weight (only `depth===0` did any, subtle, bolding), inviting a user to double-count by adding up everything they see. Rewrote `balance-sheet/page.tsx`: rows now group by `accountType` into ASSETS/LIABILITIES/EQUITY sections, each ending in a bold "Total {Section Name}" row (summed from that section's depth-0 rows only — a depth-0 row's balance already rolls up its own descendants, so summing depth-0 rows avoids double-counting), any row with a deeper row immediately following it is bolded as a rollup regardless of its own depth (not just the very top level), and a final "Total Liabilities and Equity" row for the standard balance-check. One quirk handled explicitly: GL's synthetic "Current Year Earnings" balancing row is documented to always carry `depth: 1` even though it's a peer Equity entry, not a child of whatever real account happens to precede it — a new `effectiveDepth()` helper special-cases it to 0 so it isn't mis-rendered as nested under (and excluded from the total alongside) an unrelated account. Manually verified the new grouping/summing logic against the actual numbers from the reported screenshot: Total Assets (5,880,466.50) = Total Liabilities (2,025,000.00) + Total Equity (3,855,466.50), exact match. Verified: `tsc --noEmit`/`eslint` clean. +> +> **2026-07-31 (4) — Superseded by GL's own retrofit: `BalanceSheet` is a genuinely different, classified response shape now, not just a re-grouping of the same flat array.** GL's own API reference (user-supplied) documents a 2026-07-31 backend retrofit: the flat recursive-rollup array (`{depth, lineItem, accountType, balance}`, what entry (3) above regrouped client-side) is replaced entirely by a **pre-classified nested object** — `{ asOfDate, nonCurrentAssets: {lines[], total}, currentAssets: {lines[], total}, unclassifiedAssets: {lines[], total}, totalAssets, equity: {lines[], total}, nonCurrentLiabilities: {lines[], total}, currentLiabilities: {lines[], total}, unclassifiedLiabilities: {lines[], total}, totalEquityAndLiabilities }`, driven by a new `accounts.balance_sheet_classification` tag GL now maintains server-side. This means entry (3)'s client-side grouping/rollup logic (`effectiveDepth`, `sectionTotal`, the `depth`-based rollup-bolding) is entirely obsolete — GL now does the Non-Current/Current classification itself, the frontend just renders the sections it's given. Replaced `BalanceSheetRow` with `BalanceSheetLine`/`BalanceSheetSection`/`BalanceSheetResponse` in `types/general-ledger.ts` (every section marked optional, same defensive posture adopted for `CashFlowResponse`/`ProfitAndLossResponse` after the Cash Flow crash, since this exact shape isn't live-verified against this frontend yet) and rewrote `balance-sheet/page.tsx` from scratch to consume it. **Also changed the layout to match a user-supplied reference Statement of Financial Position image** (a real classified SOFP: Non-Current Assets/Current Assets each their own subtotaled block, then Equity and Liabilities the same way, ending in a Total Assets vs Total Equity-and-Liabilities check) — rather than inventing new one-off markup for this, reused the same `ReportSection`/`ReportSubtotal` shared components Profit & Loss and Cash Flow already use (one `ReportSection` per GL-provided section, a `ReportSubtotal` for each side's grand total), keeping Balance Sheet visually and structurally consistent with the rest of the Ledgers screens rather than a bespoke table. Account codes are deliberately not shown per line (the reference template shows plain line-item names only). Verified: `tsc --noEmit`/`eslint` clean; grepped the codebase to confirm no lingering references to the removed `BalanceSheetRow`/flat shape. +> +> **2026-07-31 (5) — New "Accounts" nav section: Cheque Management built out, Cash/Bank Accounts moved under it.** New Cheque Management module (`04_API_Reference_And_Scenarios.md`, Module: Cheque Management — added to GL 2026-07-30, beyond its original plan): two independent sub-areas, **Cheque Books/Pages** (cheques issued from this company's own supply) and **Received Cheques** (cheques received from others, deliberately unlinked to any cheque book). Added `PayeeType`/`ReceivedFromType`/`ChequeBookStatus`/`ChequePageIssueStatus`/`ChequePageStatusAction`/`ReceivedChequeStatus`/`ReceivedChequeStatusAction` enums and `ChequeBook`/`ChequePage`/`ReceivedCheque` (+ their create/status-update request types) to `types/general-ledger.ts`, and `chequeBooksApi`/`chequePagesApi`/`receivedChequesApi` to `lib/api/general-ledger.ts`. `branchId`/`companyId`/`payeeId`/`voucherId`/`referenceId` are GL's own documented "loose references" (no Branch/Company/Customer/Supplier table exists in that service) — taken as plain numeric inputs, not picker dropdowns, matching GL's stated design rather than fabricating master data that doesn't exist. +> +> **Cheque Books** (`app/dashboard/accounts/cheque-books/{page,new,[chequeBookNo]/page}.tsx`): list with a status filter, create form (bank account picker restricted to `Bank`-type accounts only — GL's own module note says cheque books are bank-account-only, never cash-account), and a book-detail page showing every leaf (`GET /cheque-books/{chequeBookNo}?expand=pages`) — clicking a leaf opens `components/accounts/ChequePageDialog.tsx`, a modal with read-only details plus status-appropriate actions (`Unused` → Issue/Cancel/Void; `Issued` → Clear/Bounce/Cancel; terminal statuses → read-only), each action revealing only the fields that specific transition actually needs (e.g. Clear asks for `clearedDate`, Cancel asks for `cancelReason`, Bounce/Void need nothing beyond an optional `performedBy`). A modal was chosen over a second-level page for the leaf-details view (left open in the request) so working through several leaves in one book doesn't lose the list's scroll position/context each time. +> +> **Received Cheques** (`app/dashboard/accounts/received-cheques/{page,new/page}.tsx` + `components/accounts/ReceivedChequeDialog.tsx`): same list-then-modal shape — status filter, create form, and a details/status-update modal (`Received` → Deposit/Cancel; `Deposited` → Clear/Return), Deposit asking for a bank-account picker + date, the rest needing nothing beyond an optional note. +> +> **2026-07-31 (6) — Two user-reported fixes: `glAccountCode` removed from Cash/Bank Account creation (further GL retrofit), and the three GL create-form pages widened to fill the page.** (1) GL's reference now documents that `POST /bank-accounts`/`POST /cash-accounts` no longer accept `glAccountCode` — the backing GL account (a `Bank`/`Cash` root, plus a type-header node for Cash) is always found-or-created server-side, never caller-selected. Removed the field from `CreateBankAccountRequest`/`CreateCashAccountRequest`, deleted the "GL account" `Select` and its `glAccountsApi.list()` fetch from `bank-accounts/new/page.tsx` outright, and dropped the check from `validateBankAccountForm`. Typed the create response as a new `CreateCashOrBankAccountResponse` (`glAccount` nested, confirmed from GL's doc) so the success toast can surface the auto-generated GL account code. The Cash/Bank **list** page is untouched — GL's list endpoint still returns a flat `glAccountId` per row, still resolved via `glAccountsApi.list()` there. (2) `bank-accounts/new`, `cheque-books/new`, and `received-cheques/new` each wrapped their form in a `max-w-lg` card, leaving roughly half of any normal desktop screen blank. Dropped the `max-w-lg` cap (now full-width, matching the un-capped card convention every report page already uses) and replaced the vertical one-field-per-row stacking (plus scattered ad-hoc `grid grid-cols-2` pairs) with one consistent `grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3` wrapper per form. Left the two modals (`ChequePageDialog`/`ReceivedChequeDialog`) at their existing fixed width on purpose — the complaint was about full-page create forms, not dialogs. Verified: `tsc --noEmit`/`eslint` clean on every touched file; `npm run build`'s Turbopack compile succeeds, its TypeScript step fails only on the same pre-existing, unrelated `app/dashboard/hrm/employees/[id]/page.tsx` error noted in earlier entries. +> +> **Cash/Bank Accounts moved from Ledgers to the new Accounts section** (user-requested), since it's the same kind of "operational account bookkeeping" as cheques, not a statutory report — `app/dashboard/ledgers/bank-accounts/*` relocated verbatim to `app/dashboard/accounts/bank-accounts/*` (internal links updated, no behavior change), removed from the Ledgers hub's card grid. +> +> **Backend:** migration `AddAccountsNavSeed` adds `NavItem` `accounts` (id 12) and two new `SubNavItem`/`Permission` pairs (`accounts.cheque-books`, `accounts.received-cheques`), and **re-homes** the existing Cash/Bank Accounts `SubNavItem`/`Permission` (ids 15/26) from Ledgers to Accounts via `UpdateData` (new `Code`/`Href`/`NavItemId`) rather than delete-and-recreate — keeps the same ids so any role already granted that permission doesn't silently lose it just because the section it lives under changed. Applied to the live database this session (`dotnet ef database update`). +> +> **Fields not explicitly spelled out verbatim in GL's reference** (its own numeric-id column names for `ChequeBook`/`ChequePage`, and `ReceivedCheque`'s JSON id field) are built from the request-body field names GL *does* document plus this project's consistent `Id` convention, flagged in `types/general-ledger.ts`'s comments — `chequeNo`/`chequeBookNo` (both explicitly documented as the identifying route values) are used for keys/URLs throughout instead, sidestepping the guess entirely wherever possible. **Not done:** live smoke test against a running GL instance — this entire module is unverified against real Cheque Management data. Verified: `tsc --noEmit`/`eslint` clean on every touched file; `npm run build` compiles successfully (Turbopack), its full-project TypeScript check still blocked only by the pre-existing, unrelated `hrm/employees/[id]` error. +> +> **2026-07-20 (3) — General Ledger report corrected again: `accountId` dropped entirely, not just made direct-entry.** The GL service's own contract changed (confirmed against its updated docs): `GeneralLedger`'s `accountId` is now optional, and the *omitted* case is the real General Ledger (every postable account together, each with its own running balance, sorted by `accountCode` then `entryDate`) — supplying `accountId` is a separate "Account Ledger" (single account + descendants) mode this page doesn't use. Superseding the same-day entry above: the numeric Account ID input is gone, `reportsApi.generalLedger()` dropped the `accountId` parameter, and the page now fetches on `periodStart`/`periodEnd` alone with sensible defaults — auto-fetching on page load like every other report screen (this also resolves the earlier-reported "no network call when landing on the page," which was the now-removed account-required gate). Result rows are grouped into per-account sections in the table (a header row wherever `accountCode` changes), matching the API's per-account running-balance reset. No frontend change was needed for the same-day `BalanceSheet` response addition (a synthetic `"Current Year Earnings"` equity row) — the existing generic row renderer already displays whatever rows come back. Verified: `tsc --noEmit` clean, `npx eslint app/dashboard/ledgers lib/api/general-ledger.ts` produces zero output, `npm run build` succeeds. + ## 7. UX states - [~] Loading / empty / error states on every list — done for the GRN list/create/detail screens; other screens still unbuilt - [x] Transactional actions show server-returned side effects as confirmation — GRN confirm renders `createdLayers`/`ledgerRefs`/`poStatus` from the response diff --git a/Frontend/erp-system/app/dashboard/accounts/bank-accounts/new/page.tsx b/Frontend/erp-system/app/dashboard/accounts/bank-accounts/new/page.tsx new file mode 100644 index 0000000..c80eab0 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/bank-accounts/new/page.tsx @@ -0,0 +1,204 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { useRouter } from "next/navigation" +import { ArrowLeft } from "lucide-react" + +import { bankAccountsApi, cashAccountTypesApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { validateBankAccountForm } from "@/lib/validations/general-ledger" +import { cn } from "@/lib/utils" +import { CashAccountType, CashBankAccountType } from "@/types/general-ledger" + +import { Button, buttonVariants } from "@/components/ui/button" +import { Field, FieldError, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { toast } from "@/components/ui/toast" + +const OTHER_CASH_TYPE = "__other__" + +export default function NewBankAccountPage() { + const router = useRouter() + + const [accountType, setAccountType] = useState(CashBankAccountType.Bank) + + const [cashAccountTypes, setCashAccountTypes] = useState(null) + const [cashAccountTypesError, setCashAccountTypesError] = useState(null) + + const [accountName, setAccountName] = useState("") + const [bankName, setBankName] = useState("") + const [cashAccountTypeChoice, setCashAccountTypeChoice] = useState("") + const [customCashAccountTypeName, setCustomCashAccountTypeName] = useState("") + const [accountNumber, setAccountNumber] = useState("") + const [currencyCode, setCurrencyCode] = useState("LKR") + const [errors, setErrors] = useState>({}) + const [submitting, setSubmitting] = useState(false) + + useEffect(() => { + if (accountType !== CashBankAccountType.Cash || cashAccountTypes !== null) return + cashAccountTypesApi + .list() + .then(setCashAccountTypes) + .catch((err) => setCashAccountTypesError(errorMessage(err))) + // Only fetched once, lazily, the first time "Cash" is selected. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [accountType]) + + const cashAccountTypeName = + cashAccountTypeChoice === OTHER_CASH_TYPE ? customCashAccountTypeName.trim() : cashAccountTypeChoice + + async function handleSubmit() { + const nextErrors = validateBankAccountForm({ accountName }) + if (accountType === CashBankAccountType.Cash && !cashAccountTypeName) { + nextErrors.cashAccountTypeName = "Select or enter a cash account type" + } + setErrors(nextErrors) + if (Object.keys(nextErrors).length > 0) return + + setSubmitting(true) + try { + const created = + accountType === CashBankAccountType.Bank + ? await bankAccountsApi.createBank({ + accountName, + bankName: bankName || null, + accountNumber: accountNumber || null, + currencyCode: currencyCode || undefined, + }) + : await bankAccountsApi.createCash({ + accountName, + cashAccountTypeName, + accountNumber: accountNumber || null, + currencyCode: currencyCode || undefined, + }) + toast.success(`${accountType} account created`, `${created.accountName} — GL account ${created.glAccount.accountCode}`) + router.push("/dashboard/accounts/bank-accounts") + } catch (err) { + toast.error(`Could not create ${accountType.toLowerCase()} account`, errorMessage(err)) + } finally { + setSubmitting(false) + } + } + + return ( +
+
+ + + +
+

New Cash / Bank Account

+

+ Its ledger account is created automatically — no need to pick one. +

+
+
+ +
+
+ + +
+ +
+ + Account name + setAccountName(e.target.value)} + placeholder={accountType === CashBankAccountType.Bank ? "Main Account" : "Head Office Petty Cash"} + aria-invalid={!!errors.accountName} + /> + + + + {accountType === CashBankAccountType.Bank ? ( + <> + + Bank name (optional) + setBankName(e.target.value)} placeholder="Commercial Bank" /> + + + Account number (optional) + setAccountNumber(e.target.value)} placeholder="8001234567" /> + + + ) : ( + <> + + Cash account type + value={cashAccountTypeChoice} onValueChange={(v) => setCashAccountTypeChoice(v ?? "")}> + + + + + {(cashAccountTypes ?? []).map((t) => ( + + {t.name} + + ))} + + Other, please specify… + + + + {cashAccountTypeChoice === OTHER_CASH_TYPE && ( + setCustomCashAccountTypeName(e.target.value)} + placeholder="e.g. Site Cash" + className="mt-2" + /> + )} + {cashAccountTypesError && ( +

{cashAccountTypesError}

+ )} + +
+ + Account number (optional) + setAccountNumber(e.target.value)} + placeholder="Auto-generated if left blank" + /> + + + )} + + + Currency + setCurrencyCode(e.target.value)} maxLength={3} placeholder="LKR" /> + +
+ +
+ + Cancel + + +
+
+
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/bank-accounts/page.tsx b/Frontend/erp-system/app/dashboard/accounts/bank-accounts/page.tsx new file mode 100644 index 0000000..214ff90 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/bank-accounts/page.tsx @@ -0,0 +1,192 @@ +"use client" + +import { useEffect, useMemo, useState } from "react" +import Link from "next/link" +import { ArrowLeft, Pencil, Plus, Search, Wallet } from "lucide-react" + +import { bankAccountsApi, glAccountsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatReportDate } from "@/lib/format" +import { cn } from "@/lib/utils" +import { CashAndBankAccountDto, CashBankAccountType, GlAccount } from "@/types/general-ledger" + +import { Badge } from "@/components/ui/badge" +import { Button, buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip" + +type AccountTypeFilter = CashBankAccountType | "Both" + +export default function BankAccountsPage() { + const [accounts, setAccounts] = useState(null) + const [glAccounts, setGlAccounts] = useState(null) + const [error, setError] = useState(null) + const [search, setSearch] = useState("") + const [accountType, setAccountType] = useState("Both") + + // GL's own server-side accountType filter (2026-07-22 rework — was client-only over one table + // before) — re-fetches whenever the filter changes, unlike the plain client-side search below. + useEffect(() => { + let cancelled = false + Promise.all([bankAccountsApi.list(accountType), glAccountsApi.list()]) + .then(([banks, gl]) => { + if (cancelled) return + setAccounts(banks) + setGlAccounts(gl.items) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [accountType]) + + const glAccountsById = useMemo(() => new Map((glAccounts ?? []).map((a) => [a.accountId, a])), [glAccounts]) + + const filtered = useMemo(() => { + if (!accounts) return null + const q = search.trim().toLowerCase() + if (!q) return accounts + return accounts.filter((a) => { + const gl = glAccountsById.get(a.glAccountId) + return ( + a.accountName.toLowerCase().includes(q) || + (a.bankName ?? "").toLowerCase().includes(q) || + (a.cashAccountTypeName ?? "").toLowerCase().includes(q) || + (a.accountNumber ?? "").toLowerCase().includes(q) || + a.currencyCode.toLowerCase().includes(q) || + (gl?.accountCode ?? "").toLowerCase().includes(q) + ) + }) + }, [accounts, search, glAccountsById]) + + return ( +
+
+
+ + + +
+

Cash / Bank Accounts

+

Cash and Bank accounts linked to a GL account, for reconciliation.

+
+
+ + + New Account + +
+ +
+
+ + setSearch(e.target.value)} + placeholder="Search name, bank/type, account no. or currency…" + className="h-14 w-full pl-11 text-base" + aria-label="Search cash/bank accounts" + /> +
+ value={accountType} onValueChange={(v) => setAccountType(v ?? "Both")}> + + + + + All types + Bank + Cash + + +
+ + {error && ( +
{error}
+ )} + + {!error && filtered === null && ( +
+ {Array.from({ length: 4 }).map((_, i) => ( + + ))} +
+ )} + + {!error && filtered !== null && filtered.length === 0 && ( +
+ +

+ {search ? "No accounts match your search." : "No cash/bank accounts yet."} +

+
+ )} + + {!error && filtered !== null && filtered.length > 0 && ( + + + + Type + Account name + Bank / Cash type + Account no. + GL account + Currency + Created + Actions + + + + {filtered.map((a) => { + const gl = glAccountsById.get(a.glAccountId) + return ( + + + + {a.accountType} + + + {a.accountName} + {a.bankName ?? a.cashAccountTypeName ?? "—"} + {a.accountNumber ?? "—"} + + {gl ? `${gl.accountCode} — ${gl.accountName}` : `#${a.glAccountId}`} + + {a.currencyCode} + {formatReportDate(a.createdAt)} + + + + } + > + + + + Editing isn't available yet — the General Ledger service has no update endpoint for + {a.accountType === CashBankAccountType.Cash ? " cash" : " bank"} accounts. + + + + + ) + })} + +
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/cheque-books/[chequeBookNo]/page.tsx b/Frontend/erp-system/app/dashboard/accounts/cheque-books/[chequeBookNo]/page.tsx new file mode 100644 index 0000000..9aa9de6 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/cheque-books/[chequeBookNo]/page.tsx @@ -0,0 +1,159 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { useParams } from "next/navigation" +import { ArrowLeft, BookText } from "lucide-react" + +import { bankAccountsApi, chequeBooksApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate } from "@/lib/format" +import { cn } from "@/lib/utils" +import { CashAndBankAccountDto, CashBankAccountType, ChequeBook, ChequePage, ChequePageIssueStatus } from "@/types/general-ledger" + +import { Badge } from "@/components/ui/badge" +import { buttonVariants } from "@/components/ui/button" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { ChequePageDialog } from "@/components/accounts/ChequePageDialog" + +const STATUS_BADGE: Record = { + [ChequePageIssueStatus.Unused]: "bg-muted text-muted-foreground", + [ChequePageIssueStatus.Issued]: "bg-primary/10 text-primary", + [ChequePageIssueStatus.Cleared]: "bg-success/10 text-success", + [ChequePageIssueStatus.Bounced]: "bg-destructive/10 text-destructive", + [ChequePageIssueStatus.Cancelled]: "bg-destructive/10 text-destructive", + [ChequePageIssueStatus.Void]: "bg-muted text-muted-foreground", +} + +export default function ChequeBookDetailPage() { + const params = useParams<{ chequeBookNo: string }>() + const chequeBookNo = decodeURIComponent(params.chequeBookNo) + + const [book, setBook] = useState(null) + const [bankAccount, setBankAccount] = useState(null) + const [error, setError] = useState(null) + const [selectedPage, setSelectedPage] = useState(null) + const [dialogOpen, setDialogOpen] = useState(false) + + useEffect(() => { + let cancelled = false + chequeBooksApi + .get(chequeBookNo, true) + .then((res) => { + if (cancelled) return + setBook(res) + return bankAccountsApi.list(CashBankAccountType.Bank).then((banks) => { + if (cancelled) return + setBankAccount(banks.find((b) => b.accountId === res.bankAccountId) ?? null) + }) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [chequeBookNo]) + + function handlePageUpdated(updated: ChequePage) { + setBook((prev) => (prev ? { ...prev, pages: prev.pages.map((p) => (p.chequeNo === updated.chequeNo ? updated : p)) } : prev)) + setSelectedPage(updated) + } + + return ( +
+
+ + + +
+

Cheque Book {chequeBookNo}

+

Every leaf in this book — click one to view details or take an action.

+
+
+ + {error && ( +
{error}
+ )} + + {!error && book === null && ( +
+ {Array.from({ length: 4 }).map((_, i) => ( + + ))} +
+ )} + + {!error && book !== null && ( + <> +
+
+

Bank account

+

{bankAccount ? bankAccount.accountName : `#${book.bankAccountId}`}

+
+
+

Branch

+

#{book.branchId}

+
+
+

Range

+

+ {book.startChequeNo} – {book.endChequeNo} +

+
+
+

Received

+

{formatReportDate(book.receivedDate)}

+
+
+ + {book.pages.length === 0 ? ( +
+ +

No pages found for this book.

+
+ ) : ( + + + + Cheque no. + Status + Payee + Issue date + Amount + + + + {book.pages.map((p) => ( + { + setSelectedPage(p) + setDialogOpen(true) + }} + > + {p.chequeNo} + + + {p.issueStatus} + + + {p.payeeName ?? "—"} + {formatReportDate(p.issueDate)} + + {p.amount !== null ? formatAmount(p.amount) : "—"} + + + ))} + +
+ )} + + )} + + +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/cheque-books/new/page.tsx b/Frontend/erp-system/app/dashboard/accounts/cheque-books/new/page.tsx new file mode 100644 index 0000000..f910f1a --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/cheque-books/new/page.tsx @@ -0,0 +1,216 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { useRouter } from "next/navigation" +import { ArrowLeft } from "lucide-react" + +import { bankAccountsApi, chequeBooksApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { validateChequeBookForm } from "@/lib/validations/general-ledger" +import { cn } from "@/lib/utils" +import { CashAndBankAccountDto, CashBankAccountType } from "@/types/general-ledger" + +import { Button, buttonVariants } from "@/components/ui/button" +import { Field, FieldError, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { toast } from "@/components/ui/toast" + +export default function NewChequeBookPage() { + const router = useRouter() + + const [bankAccounts, setBankAccounts] = useState(null) + const [bankAccountsError, setBankAccountsError] = useState(null) + + const [branchId, setBranchId] = useState("") + const [bankAccountId, setBankAccountId] = useState("") + const [chequeBookNo, setChequeBookNo] = useState("") + const [startChequeNo, setStartChequeNo] = useState("") + const [endChequeNo, setEndChequeNo] = useState("") + const [totalLeaves, setTotalLeaves] = useState("") + const [receivedDate, setReceivedDate] = useState("") + const [description, setDescription] = useState("") + const [createdBy, setCreatedBy] = useState("") + const [errors, setErrors] = useState>({}) + const [submitting, setSubmitting] = useState(false) + + // Cheque books can only be tied to a real bank account — GL's own module note (§5.8) says + // statement import/reconcile, and by extension cheque books, are bank_account-only, never cash_account. + useEffect(() => { + bankAccountsApi + .list(CashBankAccountType.Bank) + .then(setBankAccounts) + .catch((err) => setBankAccountsError(errorMessage(err))) + }, []) + + async function handleSubmit() { + const nextErrors = validateChequeBookForm({ + branchId, + bankAccountId, + chequeBookNo, + startChequeNo, + endChequeNo, + totalLeaves, + receivedDate, + }) + setErrors(nextErrors) + if (Object.keys(nextErrors).length > 0) return + + setSubmitting(true) + try { + const created = await chequeBooksApi.create({ + branchId: Number(branchId), + bankAccountId: Number(bankAccountId), + chequeBookNo, + startChequeNo, + endChequeNo, + totalLeaves: Number(totalLeaves), + receivedDate, + description: description || undefined, + createdBy: createdBy || undefined, + }) + toast.success("Cheque book created", `${created.chequeBookNo} — ${created.totalLeaves} leaves`) + router.push(`/dashboard/accounts/cheque-books/${encodeURIComponent(created.chequeBookNo)}`) + } catch (err) { + toast.error("Could not create cheque book", errorMessage(err)) + } finally { + setSubmitting(false) + } + } + + return ( +
+
+ + + +
+

New Cheque Book

+

+ Every leaf from the start to end cheque number is generated automatically, all "Unused". +

+
+
+ + {bankAccountsError && ( +
{bankAccountsError}
+ )} + +
+
+ + Bank account + value={bankAccountId} onValueChange={(v) => setBankAccountId(v ?? "")}> + + + + + {(bankAccounts ?? []).map((a) => ( + + {a.accountName} + {a.bankName ? ` — ${a.bankName}` : ""} + + ))} + + + + + + + Branch ID + setBranchId(e.target.value)} + placeholder="1" + aria-invalid={!!errors.branchId} + /> + + + + + Cheque book number + setChequeBookNo(e.target.value)} + placeholder="CB-0001" + aria-invalid={!!errors.chequeBookNo} + /> + + + + + Start cheque no. + setStartChequeNo(e.target.value)} + placeholder="000001" + aria-invalid={!!errors.startChequeNo} + /> + + + + End cheque no. + setEndChequeNo(e.target.value)} + placeholder="000025" + aria-invalid={!!errors.endChequeNo} + /> + + + + + Total leaves + setTotalLeaves(e.target.value)} + placeholder="25" + aria-invalid={!!errors.totalLeaves} + /> +

Must equal end − start + 1.

+ +
+ + + Received date + setReceivedDate(e.target.value)} + aria-invalid={!!errors.receivedDate} + /> + + + + + Description (optional) + setDescription(e.target.value)} /> + + + + Created by (optional) + setCreatedBy(e.target.value)} /> + +
+ +
+ + Cancel + + +
+
+
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/cheque-books/page.tsx b/Frontend/erp-system/app/dashboard/accounts/cheque-books/page.tsx new file mode 100644 index 0000000..c925ddb --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/cheque-books/page.tsx @@ -0,0 +1,154 @@ +"use client" + +import { useEffect, useMemo, useState } from "react" +import Link from "next/link" +import { useRouter } from "next/navigation" +import { ArrowLeft, BookText, Plus } from "lucide-react" + +import { bankAccountsApi, chequeBooksApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatReportDate } from "@/lib/format" +import { cn } from "@/lib/utils" +import { CashAndBankAccountDto, CashBankAccountType, ChequeBook, ChequeBookStatus } from "@/types/general-ledger" + +import { Badge } from "@/components/ui/badge" +import { buttonVariants } from "@/components/ui/button" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" + +type StatusFilter = ChequeBookStatus | "All" + +const STATUS_BADGE: Record = { + [ChequeBookStatus.Active]: "bg-success/10 text-success", + [ChequeBookStatus.Completed]: "bg-primary/10 text-primary", + [ChequeBookStatus.Cancelled]: "bg-destructive/10 text-destructive", +} + +export default function ChequeBooksPage() { + const router = useRouter() + const [books, setBooks] = useState(null) + const [bankAccounts, setBankAccounts] = useState(null) + const [error, setError] = useState(null) + const [status, setStatus] = useState("All") + + useEffect(() => { + let cancelled = false + Promise.all([ + chequeBooksApi.list(status === "All" ? undefined : { status }), + bankAccounts ? Promise.resolve(bankAccounts) : bankAccountsApi.list(CashBankAccountType.Bank), + ]) + .then(([result, banks]) => { + if (cancelled) return + setBooks(result.items) + setBankAccounts(banks) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + // bankAccounts intentionally excluded — fetched once, reused across status re-fetches. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [status]) + + const bankAccountsById = useMemo(() => new Map((bankAccounts ?? []).map((a) => [a.accountId, a])), [bankAccounts]) + + return ( +
+
+
+ + + +
+

Cheque Books

+

Cheque books issued from this company's own supply.

+
+
+ + + New Cheque Book + +
+ +
+ value={status} onValueChange={(v) => setStatus(v ?? "All")}> + + + + + All statuses + Active + Completed + Cancelled + + +
+ + {error && ( +
{error}
+ )} + + {!error && books === null && ( +
+ {Array.from({ length: 4 }).map((_, i) => ( + + ))} +
+ )} + + {!error && books !== null && books.length === 0 && ( +
+ +

No cheque books yet.

+
+ )} + + {!error && books !== null && books.length > 0 && ( + + + + Cheque book no. + Bank account + Branch + Range + Leaves + Received + Status + + + + {books.map((b) => { + const bank = bankAccountsById.get(b.bankAccountId) + return ( + router.push(`/dashboard/accounts/cheque-books/${encodeURIComponent(b.chequeBookNo)}`)} + > + {b.chequeBookNo} + + {bank ? bank.accountName : `#${b.bankAccountId}`} + + #{b.branchId} + + {b.startChequeNo} – {b.endChequeNo} + + {b.totalLeaves} + {formatReportDate(b.receivedDate)} + + + {b.status} + + + + ) + })} + +
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/page.tsx b/Frontend/erp-system/app/dashboard/accounts/page.tsx new file mode 100644 index 0000000..34e7de5 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/page.tsx @@ -0,0 +1,58 @@ +import Link from "next/link" +import { BookText, Inbox, Wallet, type LucideIcon } from "lucide-react" + +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" + +const areas: { title: string; description: string; href: string; icon: LucideIcon }[] = [ + { + title: "Cash / Bank Accounts", + description: "Cash and Bank accounts linked to a GL account — list, create, and reconcile against them.", + href: "/dashboard/accounts/bank-accounts", + icon: Wallet, + }, + { + title: "Cheque Books", + description: "Cheque books issued from this company’s own supply — issue, clear, bounce, cancel or void a leaf.", + href: "/dashboard/accounts/cheque-books", + icon: BookText, + }, + { + title: "Received Cheques", + description: "Cheques received from customers/suppliers — deposit, clear, return, or cancel.", + href: "/dashboard/accounts/received-cheques", + icon: Inbox, + }, +] + +export default function AccountsHubPage() { + return ( +
+
+

Accounts

+

+ Cash/Bank accounts and cheque management, from the General Ledger service. +

+
+ +
+ {areas.map((area) => ( + + + +
+
+ +
+ {area.title} +
+
+ +

{area.description}

+
+
+ + ))} +
+
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/received-cheques/new/page.tsx b/Frontend/erp-system/app/dashboard/accounts/received-cheques/new/page.tsx new file mode 100644 index 0000000..49684d4 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/received-cheques/new/page.tsx @@ -0,0 +1,215 @@ +"use client" + +import { useState } from "react" +import Link from "next/link" +import { useRouter } from "next/navigation" +import { ArrowLeft } from "lucide-react" + +import { receivedChequesApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { validateReceivedChequeForm } from "@/lib/validations/general-ledger" +import { cn } from "@/lib/utils" +import { ReceivedFromType } from "@/types/general-ledger" + +import { Button, buttonVariants } from "@/components/ui/button" +import { Field, FieldError, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { toast } from "@/components/ui/toast" + +export default function NewReceivedChequePage() { + const router = useRouter() + + const [companyId, setCompanyId] = useState("") + const [branchId, setBranchId] = useState("") + const [receivedFromType, setReceivedFromType] = useState(ReceivedFromType.Customer) + const [receivedFromId, setReceivedFromId] = useState("") + const [receivedFromName, setReceivedFromName] = useState("") + const [drawerBankName, setDrawerBankName] = useState("") + const [drawerBankBranch, setDrawerBankBranch] = useState("") + const [accountHolderName, setAccountHolderName] = useState("") + const [chequeNo, setChequeNo] = useState("") + const [chequeDate, setChequeDate] = useState("") + const [amount, setAmount] = useState("") + const [receivedDate, setReceivedDate] = useState("") + const [referenceType, setReferenceType] = useState("") + const [referenceId, setReferenceId] = useState("") + const [notes, setNotes] = useState("") + const [createdBy, setCreatedBy] = useState("") + const [errors, setErrors] = useState>({}) + const [submitting, setSubmitting] = useState(false) + + async function handleSubmit() { + const nextErrors = validateReceivedChequeForm({ companyId, receivedFromName, chequeNo, chequeDate, amount, receivedDate }) + setErrors(nextErrors) + if (Object.keys(nextErrors).length > 0) return + + setSubmitting(true) + try { + const created = await receivedChequesApi.create({ + companyId: Number(companyId), + branchId: branchId ? Number(branchId) : undefined, + receivedFromType, + receivedFromId: receivedFromId ? Number(receivedFromId) : undefined, + receivedFromName, + drawerBankName: drawerBankName || undefined, + drawerBankBranch: drawerBankBranch || undefined, + accountHolderName: accountHolderName || undefined, + chequeNo, + chequeDate, + amount: Number(amount), + receivedDate, + referenceType: referenceType || undefined, + referenceId: referenceId ? Number(referenceId) : undefined, + notes: notes || undefined, + createdBy: createdBy || undefined, + }) + toast.success("Received cheque recorded", `${created.chequeNo} — ${created.receivedFromName}`) + router.push("/dashboard/accounts/received-cheques") + } catch (err) { + toast.error("Could not record received cheque", errorMessage(err)) + } finally { + setSubmitting(false) + } + } + + return ( +
+
+ + + +
+

New Received Cheque

+

Record a cheque received from a customer, supplier, or other party.

+
+
+ +
+
+ + Company ID + setCompanyId(e.target.value)} + placeholder="1" + aria-invalid={!!errors.companyId} + /> + + + + Branch ID (optional) + setBranchId(e.target.value)} /> + + + + Received from type + value={receivedFromType} onValueChange={(v) => setReceivedFromType(v ?? ReceivedFromType.Customer)}> + + + + + {Object.values(ReceivedFromType).map((t) => ( + + {t} + + ))} + + + + + + Received from name + setReceivedFromName(e.target.value)} + aria-invalid={!!errors.receivedFromName} + /> + + + + Received from ID (optional) + setReceivedFromId(e.target.value)} /> + + + + Drawer bank (optional) + setDrawerBankName(e.target.value)} /> + + + Drawer branch (optional) + setDrawerBankBranch(e.target.value)} /> + + + Account holder name (optional) + setAccountHolderName(e.target.value)} /> + + + + Cheque number + setChequeNo(e.target.value)} aria-invalid={!!errors.chequeNo} /> + + + + Cheque date + setChequeDate(e.target.value)} + aria-invalid={!!errors.chequeDate} + /> + + + + + Amount + setAmount(e.target.value)} aria-invalid={!!errors.amount} /> + + + + Received date + setReceivedDate(e.target.value)} + aria-invalid={!!errors.receivedDate} + /> + + + + + Reference type (optional) + setReferenceType(e.target.value)} placeholder="Invoice" /> + + + Reference ID (optional) + setReferenceId(e.target.value)} /> + + + + Notes (optional) + setNotes(e.target.value)} /> + + + Created by (optional) + setCreatedBy(e.target.value)} /> + +
+ +
+ + Cancel + + +
+
+
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/accounts/received-cheques/page.tsx b/Frontend/erp-system/app/dashboard/accounts/received-cheques/page.tsx new file mode 100644 index 0000000..d66699e --- /dev/null +++ b/Frontend/erp-system/app/dashboard/accounts/received-cheques/page.tsx @@ -0,0 +1,151 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, Inbox, Plus } from "lucide-react" + +import { receivedChequesApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate } from "@/lib/format" +import { cn } from "@/lib/utils" +import { ReceivedCheque, ReceivedChequeStatus } from "@/types/general-ledger" + +import { Badge } from "@/components/ui/badge" +import { buttonVariants } from "@/components/ui/button" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { ReceivedChequeDialog } from "@/components/accounts/ReceivedChequeDialog" + +type StatusFilter = ReceivedChequeStatus | "All" + +const STATUS_BADGE: Record = { + [ReceivedChequeStatus.Received]: "bg-muted text-muted-foreground", + [ReceivedChequeStatus.Deposited]: "bg-primary/10 text-primary", + [ReceivedChequeStatus.Cleared]: "bg-success/10 text-success", + [ReceivedChequeStatus.Returned]: "bg-destructive/10 text-destructive", + [ReceivedChequeStatus.Cancelled]: "bg-destructive/10 text-destructive", +} + +export default function ReceivedChequesPage() { + const [cheques, setCheques] = useState(null) + const [error, setError] = useState(null) + const [status, setStatus] = useState("All") + const [selected, setSelected] = useState(null) + const [dialogOpen, setDialogOpen] = useState(false) + + useEffect(() => { + let cancelled = false + receivedChequesApi + .list(status === "All" ? undefined : { status }) + .then((res) => { + if (!cancelled) setCheques(res.items) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [status]) + + function handleUpdated(updated: ReceivedCheque) { + setCheques((prev) => (prev ? prev.map((c) => (c.receivedChequeId === updated.receivedChequeId ? updated : c)) : prev)) + setSelected(updated) + } + + return ( +
+
+
+ + + +
+

Received Cheques

+

Cheques received from customers, suppliers, or others.

+
+
+ + + New Received Cheque + +
+ +
+ value={status} onValueChange={(v) => setStatus(v ?? "All")}> + + + + + All statuses + Received + Deposited + Cleared + Returned + Cancelled + + +
+ + {error && ( +
{error}
+ )} + + {!error && cheques === null && ( +
+ {Array.from({ length: 4 }).map((_, i) => ( + + ))} +
+ )} + + {!error && cheques !== null && cheques.length === 0 && ( +
+ +

No received cheques yet.

+
+ )} + + {!error && cheques !== null && cheques.length > 0 && ( + + + + Cheque no. + Received from + Type + Amount + Received + Status + + + + {cheques.map((c) => ( + { + setSelected(c) + setDialogOpen(true) + }} + > + {c.chequeNo} + {c.receivedFromName} + {c.receivedFromType} + {formatAmount(c.amount)} + {formatReportDate(c.receivedDate)} + + + {c.status} + + + + ))} + +
+ )} + + +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/balance-sheet/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/balance-sheet/page.tsx new file mode 100644 index 0000000..d835278 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/balance-sheet/page.tsx @@ -0,0 +1,156 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, Landmark } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatReportDate, todayIso } from "@/lib/format" +import { cn } from "@/lib/utils" +import { BalanceSheetResponse, BalanceSheetSection, ReportType } from "@/types/general-ledger" + +import { buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Skeleton } from "@/components/ui/skeleton" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" +import { ReportHeader } from "@/components/reports/ReportHeader" +import { ReportSection, ReportSectionLine } from "@/components/reports/ReportSection" +import { ReportSubtotal } from "@/components/reports/ReportSubtotal" + +// GL's leaf rows carry `accountCode` too, but a classified Statement of Financial Position +// (matching the reference template this screen follows) shows plain line-item names only, no +// codes — same convention as the Balance Sheet's account-code-free presentation elsewhere. +function sectionLines(section?: BalanceSheetSection): ReportSectionLine[] { + return (section?.lines ?? []).map((l) => ({ label: l.accountName, amount: l.balance })) +} + +export default function BalanceSheetPage() { + const [asOfDate, setAsOfDate] = useState(todayIso()) + const [report, setReport] = useState(null) + const [error, setError] = useState(null) + + // Clears stale results the instant asOfDate changes, during the render that reacts to it — + // not inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const [loadedFor, setLoadedFor] = useState(null) + if (loadedFor !== asOfDate) { + setLoadedFor(asOfDate) + setReport(null) + setError(null) + } + + useEffect(() => { + if (!asOfDate) return + let cancelled = false + reportsApi + .balanceSheet(asOfDate) + .then((res) => { + if (!cancelled) setReport(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [asOfDate]) + + const isEmpty = + report !== null && + (report.nonCurrentAssets?.lines?.length ?? 0) === 0 && + (report.currentAssets?.lines?.length ?? 0) === 0 && + (report.unclassifiedAssets?.lines?.length ?? 0) === 0 && + (report.equity?.lines?.length ?? 0) === 0 && + (report.nonCurrentLiabilities?.lines?.length ?? 0) === 0 && + (report.currentLiabilities?.lines?.length ?? 0) === 0 && + (report.unclassifiedLiabilities?.lines?.length ?? 0) === 0 + + return ( +
+
+ + + +
+

Balance Sheet

+

Statement of Financial Position — Assets, Liabilities, Equity.

+
+
+ +
+
+ + setAsOfDate(e.target.value)} className="h-11 w-full text-base sm:w-60" /> +
+
+ + +
+
+ + {error && ( +
{error}
+ )} + + {!error && report === null && ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ )} + + {!error && isEmpty && ( +
+ +

No Asset/Liability/Equity accounts as at this date.

+
+ )} + + {!error && report !== null && !isEmpty && ( +
+ + +
+

Assets

+ + + + + +

Equity and Liabilities

+ + + + + +
+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/budget-vs-actual/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/budget-vs-actual/page.tsx new file mode 100644 index 0000000..fc51fd2 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/budget-vs-actual/page.tsx @@ -0,0 +1,179 @@ +"use client" + +import { useEffect, useMemo, useState } from "react" +import Link from "next/link" +import { ArrowLeft, BadgeDollarSign } from "lucide-react" + +import { glBudgetsApi, reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount } from "@/lib/format" +import { cn } from "@/lib/utils" +import { BudgetVsActualRow, GlBudget, ReportType } from "@/types/general-ledger" + +import { buttonVariants } from "@/components/ui/button" +import { Label } from "@/components/ui/label" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" +import { ReportHeader } from "@/components/reports/ReportHeader" + +export default function BudgetVsActualPage() { + const [budgets, setBudgets] = useState(null) + const [budgetsError, setBudgetsError] = useState(null) + const [budgetId, setBudgetId] = useState("") + + const [rows, setRows] = useState(null) + const [error, setError] = useState(null) + + useEffect(() => { + glBudgetsApi + .list() + .then((res) => setBudgets(res)) + .catch((err) => setBudgetsError(errorMessage(err))) + }, []) + + // Clears stale results the instant budgetId changes, during the render that reacts to it — + // not inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const [loadedFor, setLoadedFor] = useState("") + if (loadedFor !== budgetId) { + setLoadedFor(budgetId) + setRows(null) + setError(null) + } + + useEffect(() => { + if (!budgetId) return + let cancelled = false + reportsApi + .budgetVsActual(budgetId) + .then((res) => { + if (!cancelled) setRows(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [budgetId]) + + const selectedBudget = useMemo(() => (budgets ?? []).find((b) => b.budgetId === budgetId) ?? null, [budgets, budgetId]) + + const totalBudgeted = (rows ?? []).reduce((sum, r) => sum + r.budgetedAmount, 0) + const totalActual = (rows ?? []).reduce((sum, r) => sum + r.actualAmount, 0) + const totalVariance = (rows ?? []).reduce((sum, r) => sum + r.variance, 0) + + return ( +
+
+ + + +
+

Budget vs Actual

+

Budgeted amounts against real postings per account/period.

+
+
+ + {budgetsError && ( +
{budgetsError}
+ )} + +
+
+ + value={budgetId} onValueChange={(v) => setBudgetId(v ?? "")}> + + + + + {(budgets ?? []).map((b) => ( + + {b.name} + + ))} + + +
+
+ + +
+
+ + {error && ( +
{error}
+ )} + + {!error && !budgetId && ( +
+ +

Select a budget to compare against actuals.

+
+ )} + + {!error && budgetId && rows === null && ( +
+ {Array.from({ length: 5 }).map((_, i) => ( + + ))} +
+ )} + + {!error && budgetId && rows !== null && rows.length === 0 && ( +
+ +

This budget has no lines yet.

+
+ )} + + {!error && budgetId && rows !== null && rows.length > 0 && ( +
+ + + + + Account + Budgeted + Actual + Variance + + + + {rows.map((row) => ( + + + {row.accountCode}{" "} + {row.accountName} + + {formatAmount(row.budgetedAmount)} + {formatAmount(row.actualAmount)} + + {formatAmount(row.variance)} + + + ))} + + + + Total + {formatAmount(totalBudgeted)} + {formatAmount(totalActual)} + {formatAmount(totalVariance)} + + +
+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/cash-flow/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/cash-flow/page.tsx new file mode 100644 index 0000000..9468a69 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/cash-flow/page.tsx @@ -0,0 +1,184 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, Wallet } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatReportDate, startOfMonthIso, todayIso } from "@/lib/format" +import { cn } from "@/lib/utils" +import { + CashFlowFinancingActivities, + CashFlowInvestingActivities, + CashFlowResponse, + ReportType, +} from "@/types/general-ledger" + +import { buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Skeleton } from "@/components/ui/skeleton" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" +import { ReportHeader } from "@/components/reports/ReportHeader" +import { ReportSection, ReportSectionLine } from "@/components/reports/ReportSection" +import { ReportSubtotal } from "@/components/reports/ReportSubtotal" + +/** + * Combines `operatingActivities.nonCashAdjustments` + `.workingCapitalChanges` into one labeled + * set, then buckets by sign — per docs/21-GENERAL-LEDGER-FRONTEND.md §3: "Additions to Cash" + * (amount >= 0) and "Subtractions From Cash" (amount < 0). A working-capital line's label uses its + * `direction` field ("Decrease in Trade Receivables"); a non-cash-adjustment line just prints its + * plain `description` ("Depreciation"), no Increase/Decrease prefix. + */ +function bucketOperatingLines(report: CashFlowResponse): { additions: ReportSectionLine[]; subtractions: ReportSectionLine[] } { + // GL omits these list fields entirely (rather than sending `[]`) when there's nothing to + // report for the period, instead of an empty array — confirmed live, not just a type-safety guard. + const operating = report.operatingActivities + const combined: ReportSectionLine[] = [ + ...(operating?.nonCashAdjustments ?? []).map((a) => ({ label: a.description, amount: a.amount })), + ...(operating?.workingCapitalChanges ?? []).map((w) => ({ + label: `${w.direction} in ${w.accountName}`, + amount: w.changeAmount, + })), + ] + return { + additions: combined.filter((l) => l.amount >= 0), + subtractions: combined.filter((l) => l.amount < 0), + } +} + +/** Same "GL omits empty list fields" defense as bucketOperatingLines — the section itself, + * or just its `lines[]`, may be missing entirely rather than `{ lines: [], ...: 0 }`. */ +function activitySectionLines( + section?: CashFlowInvestingActivities | CashFlowFinancingActivities | null +): ReportSectionLine[] { + return (section?.lines ?? []).map((l) => ({ label: l.description, amount: l.amount })) +} + +export default function CashFlowPage() { + const [periodStart, setPeriodStart] = useState(startOfMonthIso()) + const [periodEnd, setPeriodEnd] = useState(todayIso()) + const [report, setReport] = useState(null) + const [error, setError] = useState(null) + + // Clears stale results the instant the period changes, during the render that reacts to it — + // not inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const periodKey = `${periodStart}|${periodEnd}` + const [loadedFor, setLoadedFor] = useState(null) + if (loadedFor !== periodKey) { + setLoadedFor(periodKey) + setReport(null) + setError(null) + } + + useEffect(() => { + if (!periodStart || !periodEnd) return + let cancelled = false + reportsApi + .cashFlow(periodStart, periodEnd) + .then((res) => { + if (!cancelled) setReport(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [periodStart, periodEnd]) + + const buckets = report ? bucketOperatingLines(report) : null + + return ( +
+
+ + + +
+

Cash Flow

+

Statement of Cash Flows for a period.

+
+
+ +
+
+
+ + setPeriodStart(e.target.value)} className="h-11 text-base" /> +
+
+ + setPeriodEnd(e.target.value)} className="h-11 text-base" /> +
+
+
+ + +
+
+ + {error && ( +
{error}
+ )} + + {!error && report === null && ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ )} + + {!error && report !== null && buckets !== null && ( +
+ + +
+ + + + + + 1 + ? report.investingActivities?.netCashFromInvestingActivities + : undefined + } + /> + 1 + ? report.financingActivities?.netCashFromFinancingActivities + : undefined + } + /> + + +
+ +

+ + Opening/closing cash balances are computed by the General Ledger service but not shown on this + screen, matching GL's own PDF/CSV output. +

+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/general-ledger/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/general-ledger/page.tsx new file mode 100644 index 0000000..5b6f70b --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/general-ledger/page.tsx @@ -0,0 +1,148 @@ +"use client" + +import { Fragment, useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, BookOpen } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate, startOfMonthIso, todayIso } from "@/lib/format" +import { cn } from "@/lib/utils" +import { GeneralLedgerRow, ReportType } from "@/types/general-ledger" + +import { buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" +import { ReportHeader } from "@/components/reports/ReportHeader" + +export default function GeneralLedgerReportPage() { + const [periodStart, setPeriodStart] = useState(startOfMonthIso()) + const [periodEnd, setPeriodEnd] = useState(todayIso()) + + const [rows, setRows] = useState(null) + const [error, setError] = useState(null) + + // Clears stale results the instant the period changes, during the render that reacts to it — + // not inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const periodKey = `${periodStart}|${periodEnd}` + const [loadedFor, setLoadedFor] = useState(null) + if (loadedFor !== periodKey) { + setLoadedFor(periodKey) + setRows(null) + setError(null) + } + + useEffect(() => { + if (!periodStart || !periodEnd) return + let cancelled = false + reportsApi + .generalLedger(periodStart, periodEnd) + .then((res) => { + if (!cancelled) setRows(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [periodStart, periodEnd]) + + return ( +
+
+ + + +
+

General Ledger

+

Every posted movement on every account, with a running balance per account.

+
+
+ +
+
+
+ + setPeriodStart(e.target.value)} className="h-11 text-base" /> +
+
+ + setPeriodEnd(e.target.value)} className="h-11 text-base" /> +
+
+
+ + +
+
+ + {error && ( +
{error}
+ )} + + {!error && rows === null && ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ )} + + {!error && rows !== null && rows.length === 0 && ( +
+ +

No postings on any account in the selected period.

+
+ )} + + {!error && rows !== null && rows.length > 0 && ( +
+ + + + + Date + Journal No. + Narration + Debit + Credit + Running balance + + + + {rows.map((row, i) => { + const isNewAccount = i === 0 || row.accountCode !== rows[i - 1].accountCode + return ( + + {isNewAccount && ( + + + {row.accountCode} — {row.accountName} + + + )} + + {formatReportDate(row.entryDate)} + {row.journalNo} + {row.narration ?? "—"} + {formatAmount(row.debitAmount, true)} + {formatAmount(row.creditAmount, true)} + {formatAmount(row.runningBalance)} + + + ) + })} + +
+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/page.tsx new file mode 100644 index 0000000..e9d3482 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/page.tsx @@ -0,0 +1,91 @@ +import Link from "next/link" +import { + BadgeDollarSign, + BookOpen, + Landmark, + LineChart, + PieChart, + Receipt, + Scale, + type LucideIcon, +} from "lucide-react" + +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" + +const areas: { title: string; description: string; href: string; icon: LucideIcon }[] = [ + { + title: "Trial Balance", + description: "Every postable account's debit/credit balance as at a given date.", + href: "/dashboard/ledgers/trial-balance", + icon: Scale, + }, + { + title: "Balance Sheet", + description: "Statement of Financial Position — Assets, Liabilities and Equity as at a date.", + href: "/dashboard/ledgers/balance-sheet", + icon: Landmark, + }, + { + title: "General Ledger", + description: "Every posted movement on one account across a date range, with running balance.", + href: "/dashboard/ledgers/general-ledger", + icon: BookOpen, + }, + { + title: "Profit & Loss", + description: "Statement of Profit or Loss — Income and Expense for a period.", + href: "/dashboard/ledgers/profit-and-loss", + icon: LineChart, + }, + { + title: "Cash Flow", + description: "Statement of Cash Flows — operating, investing and financing movement for a period.", + href: "/dashboard/ledgers/cash-flow", + icon: PieChart, + }, + { + title: "Budget vs Actual", + description: "Budgeted amounts against real postings per account/period, with variance.", + href: "/dashboard/ledgers/budget-vs-actual", + icon: BadgeDollarSign, + }, + { + title: "Tax Report", + description: "Income Tax Computation for a period, with optional adjustments.", + href: "/dashboard/ledgers/tax-report", + icon: Receipt, + }, +] + +export default function LedgersHubPage() { + return ( +
+
+

Ledgers

+

+ Statutory-format financial reports from the General Ledger service. +

+
+ +
+ {areas.map((area) => ( + + + +
+
+ +
+ {area.title} +
+
+ +

{area.description}

+
+
+ + ))} +
+
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/profit-and-loss/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/profit-and-loss/page.tsx new file mode 100644 index 0000000..f6be336 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/profit-and-loss/page.tsx @@ -0,0 +1,166 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, LineChart } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatReportDate, startOfMonthIso, todayIso } from "@/lib/format" +import { cn } from "@/lib/utils" +import { ProfitAndLossResponse, ProfitAndLossSection, ReportType } from "@/types/general-ledger" + +import { buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Skeleton } from "@/components/ui/skeleton" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" +import { ReportHeader } from "@/components/reports/ReportHeader" +import { ReportSection } from "@/components/reports/ReportSection" +import { ReportSubtotal } from "@/components/reports/ReportSubtotal" + +function pnlSectionLines(section: ProfitAndLossSection | undefined) { + return (section?.lines ?? []).map((line) => ({ + label: ( + <> + {line.accountCode} {line.accountName} + + ), + amount: line.amount, + })) +} + +export default function ProfitAndLossPage() { + const [periodStart, setPeriodStart] = useState(startOfMonthIso()) + const [periodEnd, setPeriodEnd] = useState(todayIso()) + const [report, setReport] = useState(null) + const [error, setError] = useState(null) + + // Clears stale results the instant the period changes, during the render that reacts to it — + // not inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const periodKey = `${periodStart}|${periodEnd}` + const [loadedFor, setLoadedFor] = useState(null) + if (loadedFor !== periodKey) { + setLoadedFor(periodKey) + setReport(null) + setError(null) + } + + useEffect(() => { + if (!periodStart || !periodEnd) return + let cancelled = false + reportsApi + .profitAndLoss(periodStart, periodEnd) + .then((res) => { + if (!cancelled) setReport(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [periodStart, periodEnd]) + + // GL omits an empty/zero section entirely rather than sending `{ lines: [], total: 0 }` — + // confirmed on Cash Flow's equivalent fields, same inferred nested-section shape here. + const isEmpty = + report !== null && + (report.sales?.lines?.length ?? 0) === 0 && + (report.costOfSales?.lines?.length ?? 0) === 0 && + (report.otherIncome?.lines?.length ?? 0) === 0 && + (report.distributionExpenses?.lines?.length ?? 0) === 0 && + (report.administrationExpenses?.lines?.length ?? 0) === 0 && + (report.otherExpenses?.lines?.length ?? 0) === 0 && + (report.financialExpenses?.lines?.length ?? 0) === 0 && + (report.unclassified?.lines?.length ?? 0) === 0 + + return ( +
+
+ + + +
+

Profit & Loss

+

Statement of Profit or Loss — Income and Expense for a period.

+
+
+ +
+
+
+ + setPeriodStart(e.target.value)} className="h-11 text-base" /> +
+
+ + setPeriodEnd(e.target.value)} className="h-11 text-base" /> +
+
+
+ + +
+
+ + {error && ( +
{error}
+ )} + + {!error && report === null && ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ )} + + {!error && isEmpty && ( +
+ +

No Income/Expense accounts posted in this period.

+
+ )} + + {!error && report !== null && !isEmpty && ( +
+ + +
+ + + + + + + + + {report.unclassified && ( + + )} + +
+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/tax-report/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/tax-report/page.tsx new file mode 100644 index 0000000..84fc52d --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/tax-report/page.tsx @@ -0,0 +1,284 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, ChevronDown, ChevronRight, Receipt } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate, startOfMonthIso, todayIso } from "@/lib/format" +import { cn } from "@/lib/utils" +import { ReportType, TaxSummaryResponse } from "@/types/general-ledger" + +import { Button, buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" + +// Fixed row order + Add:/Less: labels per the confirmed GL contract +// (04_API_Reference_And_Scenarios.md, Module: Reporting — `profitBeforeTax` through +// `balanceTaxPayable`) — GL sends plain numbers, not pre-formatted rows; the prefix/bold treatment +// lives here, not derived from sign. `taxRatePercent` is shown separately below the table (it's a +// percentage, not a currency amount) rather than run through `formatAmount` here. +const ROWS: { key: keyof TaxSummaryResponse; label: string; bold?: boolean }[] = [ + { key: "profitBeforeTax", label: "Profit Before Tax" }, + { key: "nonDeductibleExpenses", label: "Add: Non-Deductible Expenses" }, + { key: "allowableDeductions", label: "Less: Allowable Deductions" }, + { key: "adjustedBusinessProfit", label: "Adjusted Business Profit", bold: true }, + { key: "otherTaxableIncome", label: "Add: Other Taxable Income" }, + { key: "assessableIncome", label: "Assessable Income", bold: true }, + { key: "qualifyingPaymentsReliefs", label: "Less: Qualifying Payments / Reliefs" }, + { key: "taxableIncome", label: "Taxable Income", bold: true }, + { key: "corporateIncomeTax", label: "Corporate Income Tax" }, + { key: "surchargeAmount", label: "Add: Surcharge / Education Levy" }, + { key: "grossTaxLiability", label: "Gross Tax Liability", bold: true }, + { key: "apitCredit", label: "Less: APIT Credit" }, + { key: "whtCredit", label: "Less: WHT Credit" }, + { key: "quarterlyTaxPayments", label: "Less: Quarterly Tax Payments" }, +] + +export default function TaxReportPage() { + const [periodStart, setPeriodStart] = useState(startOfMonthIso()) + const [periodEnd, setPeriodEnd] = useState(todayIso()) + + const [adjustmentsOpen, setAdjustmentsOpen] = useState(false) + const [allowableDeductions, setAllowableDeductions] = useState("") + const [otherTaxableIncome, setOtherTaxableIncome] = useState("") + const [qualifyingPaymentsReliefs, setQualifyingPaymentsReliefs] = useState("") + const [surchargeAmount, setSurchargeAmount] = useState("") + const [taxRateOverride, setTaxRateOverride] = useState("") + + const [report, setReport] = useState(null) + const [error, setError] = useState(null) + + // Optional inputs get no client-side default — an untouched field sends nothing (undefined, + // dropped by lib/api/general-ledger.ts's query builder), letting GL's own server-side + // defaulting be the single source of truth for what "not supplied" means. + const params = { + periodStart, + periodEnd, + allowableDeductions: allowableDeductions === "" ? undefined : Number(allowableDeductions), + otherTaxableIncome: otherTaxableIncome === "" ? undefined : Number(otherTaxableIncome), + qualifyingPaymentsReliefs: qualifyingPaymentsReliefs === "" ? undefined : Number(qualifyingPaymentsReliefs), + surchargeAmount: surchargeAmount === "" ? undefined : Number(surchargeAmount), + taxRateOverride: taxRateOverride === "" ? undefined : Number(taxRateOverride), + } + const paramsKey = JSON.stringify(params) + + // Clears stale results the instant a param changes, during the render that reacts to it — not + // inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const [loadedFor, setLoadedFor] = useState(null) + if (loadedFor !== paramsKey) { + setLoadedFor(paramsKey) + setReport(null) + setError(null) + } + + useEffect(() => { + if (!periodStart || !periodEnd) return + let cancelled = false + reportsApi + .taxSummary(params) + .then((res) => { + if (!cancelled) setReport(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + // paramsKey covers every field inside params; re-running on params itself would compare by + // reference and fire every render, since it's a fresh object literal each time. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [paramsKey, periodStart, periodEnd]) + + const isRefund = report !== null && report.balanceTaxPayable < 0 + const finalLabel = isRefund ? "BALANCE TAX REFUNDABLE" : "BALANCE TAX PAYABLE" + const finalAmount = report ? Math.abs(report.balanceTaxPayable) : 0 + + return ( +
+
+ + + +
+

Tax Report

+

Income Tax Computation for a period.

+
+
+ +
+
+
+ + setPeriodStart(e.target.value)} className="h-11 text-base" /> +
+
+ + setPeriodEnd(e.target.value)} className="h-11 text-base" /> +
+
+
+ + +
+
+ +
+ + {adjustmentsOpen && ( +
+
+ + setAllowableDeductions(e.target.value)} + placeholder="0" + className="h-10 text-base" + /> +
+
+ + setOtherTaxableIncome(e.target.value)} + placeholder="0" + className="h-10 text-base" + /> +
+
+ + setQualifyingPaymentsReliefs(e.target.value)} + placeholder="System default" + className="h-10 text-base" + /> +
+
+ + setSurchargeAmount(e.target.value)} + placeholder="0" + className="h-10 text-base" + /> +
+
+ + setTaxRateOverride(e.target.value)} + placeholder="System default" + className="h-10 text-base" + /> +
+ {(allowableDeductions || + otherTaxableIncome || + qualifyingPaymentsReliefs || + surchargeAmount || + taxRateOverride) && ( +
+ +
+ )} +
+ )} +
+ + {error && ( +
{error}
+ )} + + {!error && report === null && ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ )} + + {!error && report !== null && ( +
+ {/* Own header, not the shared ReportHeader — GL's own PDF gives this report a fuller + identity block (company name/address/TIN/BRN) that today lives only in GL's own + appsettings.json, with no endpoint exposing it. Deliberately not fabricated here — + see docs/21-GENERAL-LEDGER-FRONTEND.md §3's open question. */} +
+

+ General Ledger +

+

Income Tax Computation

+

+ For the period {formatReportDate(periodStart)} to {formatReportDate(periodEnd)} +

+

+ Company identity (name/address/TIN/BRN) isn't shown here — GL exposes no endpoint for it yet. +

+
+ +
+ +

+ All amounts in Sri Lankan Rupees (LKR) unless stated otherwise. +

+
+ + + + {ROWS.map((row) => ( + + {row.label} + + {formatAmount(report[row.key] as number)} + + + ))} + + {finalLabel} + + {formatAmount(finalAmount)} + + + +
+ +

+ Tax rate applied: {report.taxRatePercent}% +

+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/app/dashboard/ledgers/trial-balance/page.tsx b/Frontend/erp-system/app/dashboard/ledgers/trial-balance/page.tsx new file mode 100644 index 0000000..b2640a4 --- /dev/null +++ b/Frontend/erp-system/app/dashboard/ledgers/trial-balance/page.tsx @@ -0,0 +1,134 @@ +"use client" + +import { useEffect, useState } from "react" +import Link from "next/link" +import { ArrowLeft, Scale } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate, todayIso } from "@/lib/format" +import { cn } from "@/lib/utils" +import { ReportType, TrialBalanceRow } from "@/types/general-ledger" + +import { buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Skeleton } from "@/components/ui/skeleton" +import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table" +import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton" +import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton" +import { ReportHeader } from "@/components/reports/ReportHeader" + +export default function TrialBalancePage() { + const [asOfDate, setAsOfDate] = useState(todayIso()) + const [rows, setRows] = useState(null) + const [error, setError] = useState(null) + + // Clears stale results the instant asOfDate changes, during the render that reacts to it — + // not inside the effect below, which would be a synchronous setState-in-effect + // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during + // render" pattern instead. + const [loadedFor, setLoadedFor] = useState(null) + if (loadedFor !== asOfDate) { + setLoadedFor(asOfDate) + setRows(null) + setError(null) + } + + useEffect(() => { + if (!asOfDate) return + let cancelled = false + reportsApi + .trialBalance(asOfDate) + .then((res) => { + if (!cancelled) setRows(res) + }) + .catch((err) => { + if (!cancelled) setError(errorMessage(err)) + }) + return () => { + cancelled = true + } + }, [asOfDate]) + + const totalDebit = (rows ?? []).reduce((sum, r) => sum + r.debit, 0) + const totalCredit = (rows ?? []).reduce((sum, r) => sum + r.credit, 0) + + return ( +
+
+ + + +
+

Trial Balance

+

Every postable account's balance as at a date.

+
+
+ +
+
+ + setAsOfDate(e.target.value)} className="h-11 w-full text-base sm:w-60" /> +
+
+ + +
+
+ + {error && ( +
{error}
+ )} + + {!error && rows === null && ( +
+ {Array.from({ length: 6 }).map((_, i) => ( + + ))} +
+ )} + + {!error && rows !== null && rows.length === 0 && ( +
+ +

No postable accounts as at this date.

+
+ )} + + {!error && rows !== null && rows.length > 0 && ( +
+ + + + + Account + Debit + Credit + + + + {rows.map((row, i) => ( + + + {row.accountCode}{" "} + {row.accountName} + + {formatAmount(row.debit, true)} + {formatAmount(row.credit, true)} + + ))} + + + + Total + {formatAmount(totalDebit)} + {formatAmount(totalCredit)} + + +
+
+ )} +
+ ) +} diff --git a/Frontend/erp-system/components/Layouts/AppSidebar.tsx b/Frontend/erp-system/components/Layouts/AppSidebar.tsx index c80abe1..8b52e99 100644 --- a/Frontend/erp-system/components/Layouts/AppSidebar.tsx +++ b/Frontend/erp-system/components/Layouts/AppSidebar.tsx @@ -5,26 +5,36 @@ import Link from "next/link" import { usePathname } from "next/navigation" import { Banknote, + BadgeDollarSign, + BookOpen, + BookText, Boxes, Building2, CalendarCheck, CalendarClock, ChevronRight, ClipboardList, + CreditCard, Factory, FileBarChart, FileText, HelpCircle, IdCard, + Inbox, + Landmark, LayoutGrid, LayoutTemplate, + LineChart, ListTree, Menu, Package, PackageCheck, PackageX, PlayCircle, + PieChart, + Receipt, Ruler, + Scale, Settings, ShieldCheck, ShoppingCart, @@ -32,6 +42,7 @@ import { Tag, Truck, Users, + Wallet, Warehouse, X, type LucideIcon, @@ -120,6 +131,34 @@ const navItems: { { title: "Settings", code: "hrm.settings", href: "/dashboard/hrm/settings", icon: SlidersHorizontal }, ], }, + { + title: "Ledgers", + code: "ledgers", + href: "/dashboard/ledgers", + icon: Landmark, + chevron: true, + children: [ + { title: "Trial Balance", code: "ledgers.trial-balance", href: "/dashboard/ledgers/trial-balance", icon: Scale }, + { title: "Balance Sheet", code: "ledgers.balance-sheet", href: "/dashboard/ledgers/balance-sheet", icon: Landmark }, + { title: "General Ledger", code: "ledgers.general-ledger", href: "/dashboard/ledgers/general-ledger", icon: BookOpen }, + { title: "Profit & Loss", code: "ledgers.profit-and-loss", href: "/dashboard/ledgers/profit-and-loss", icon: LineChart }, + { title: "Cash Flow", code: "ledgers.cash-flow", href: "/dashboard/ledgers/cash-flow", icon: PieChart }, + { title: "Budget vs Actual", code: "ledgers.budget-vs-actual", href: "/dashboard/ledgers/budget-vs-actual", icon: BadgeDollarSign }, + { title: "Tax Report", code: "ledgers.tax-report", href: "/dashboard/ledgers/tax-report", icon: Receipt }, + ], + }, + { + title: "Accounts", + code: "accounts", + href: "/dashboard/accounts", + icon: CreditCard, + chevron: true, + children: [ + { title: "Cash / Bank Accounts", code: "accounts.bank-accounts", href: "/dashboard/accounts/bank-accounts", icon: Wallet }, + { title: "Cheque Books", code: "accounts.cheque-books", href: "/dashboard/accounts/cheque-books", icon: BookText }, + { title: "Received Cheques", code: "accounts.received-cheques", href: "/dashboard/accounts/received-cheques", icon: Inbox }, + ], + }, { title: "Settings", code: "settings", @@ -157,7 +196,13 @@ function SidebarContent({ // route auto-expanded; user toggles are preserved across navigation. const [expanded, setExpanded] = useState>({}) - useEffect(() => { + // Adjusted during render (not in an effect) each time pathname or the + // available item set changes — `items` starts empty while auth/nav codes + // are loading, so this also needs to re-run once the real list arrives. + const autoExpandKey = `${pathname}::${items.map((i) => i.code).join(",")}` + const [lastAutoExpandKey, setLastAutoExpandKey] = useState(null) + if (autoExpandKey !== lastAutoExpandKey) { + setLastAutoExpandKey(autoExpandKey) const parent = items.find((i) => { if (!i.children?.length) return false if (i.children.some((c) => pathname === c.href || pathname.startsWith(`${c.href}/`))) return true @@ -168,7 +213,7 @@ function SidebarContent({ if (parent) { setExpanded((prev) => (prev[parent.code] ? prev : { ...prev, [parent.code]: true })) } - }, [pathname, items]) + } const toggleExpand = (code: string) => setExpanded((prev) => ({ ...prev, [code]: !prev[code] })) diff --git a/Frontend/erp-system/components/Layouts/Header.tsx b/Frontend/erp-system/components/Layouts/Header.tsx index 44d22af..7e0942d 100644 --- a/Frontend/erp-system/components/Layouts/Header.tsx +++ b/Frontend/erp-system/components/Layouts/Header.tsx @@ -1,6 +1,6 @@ "use client" -import { useEffect, useState } from "react" +import { useState } from "react" import Link from "next/link" import { usePathname, useRouter } from "next/navigation" import { ArrowLeft, Bell, LogOut, Settings, User } from "lucide-react" @@ -41,6 +41,27 @@ const PROCUREMENT_TITLES: Record = { "/dashboard/procurement/purchase-returns/new": "New Purchase Return", } +const LEDGER_TITLES: Record = { + "/dashboard/ledgers": "Ledgers", + "/dashboard/ledgers/trial-balance": "Trial Balance", + "/dashboard/ledgers/balance-sheet": "Balance Sheet", + "/dashboard/ledgers/general-ledger": "General Ledger", + "/dashboard/ledgers/profit-and-loss": "Profit & Loss", + "/dashboard/ledgers/cash-flow": "Cash Flow", + "/dashboard/ledgers/budget-vs-actual": "Budget vs Actual", + "/dashboard/ledgers/tax-report": "Tax Report", +} + +const ACCOUNTS_TITLES: Record = { + "/dashboard/accounts": "Accounts", + "/dashboard/accounts/bank-accounts": "Cash / Bank Accounts", + "/dashboard/accounts/bank-accounts/new": "New Bank Account", + "/dashboard/accounts/cheque-books": "Cheque Books", + "/dashboard/accounts/cheque-books/new": "New Cheque Book", + "/dashboard/accounts/received-cheques": "Received Cheques", + "/dashboard/accounts/received-cheques/new": "New Received Cheque", +} + const STOCK_TITLES: Record = { "/dashboard/stock": "Stock Management", "/dashboard/stock/enquiry": "Stock Enquiry", @@ -62,6 +83,11 @@ function titleFromPath(pathname: string) { if (pathname === "/dashboard/receiving/grn/new") return "Create Goods Receipt Note" if (/^\/dashboard\/receiving\/grn\/[^/]+$/.test(pathname)) return "Goods Receipt Note" + if (LEDGER_TITLES[pathname]) return LEDGER_TITLES[pathname] + + if (ACCOUNTS_TITLES[pathname]) return ACCOUNTS_TITLES[pathname] + if (/^\/dashboard\/accounts\/cheque-books\/[^/]+$/.test(pathname)) return "Cheque Book" + if (STOCK_TITLES[pathname]) return STOCK_TITLES[pathname] if (/^\/dashboard\/stock\/transfers\/[^/]+$/.test(pathname)) return "Stock Transfer" if (/^\/dashboard\/stock\/counts\/[^/]+$/.test(pathname)) return "Stock Count" @@ -140,8 +166,7 @@ export function Header() { // Read after mount, not during render: localStorage doesn't exist on the server, and // reading it while rendering would desync the hydration pass. - const [user, setUser] = useState(null) - useEffect(() => setUser(getStoredUser()), []) + const [user] = useState(() => getStoredUser()) const markAllAsRead = () => setNotifications((prev) => prev.map((n) => ({ ...n, unread: false }))) diff --git a/Frontend/erp-system/components/accounts/ChequePageDialog.tsx b/Frontend/erp-system/components/accounts/ChequePageDialog.tsx new file mode 100644 index 0000000..62c75a3 --- /dev/null +++ b/Frontend/erp-system/components/accounts/ChequePageDialog.tsx @@ -0,0 +1,381 @@ +"use client" + +import { useState } from "react" + +import { chequePagesApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate } from "@/lib/format" +import { validateIssueChequeForm } from "@/lib/validations/general-ledger" +import { cn } from "@/lib/utils" +import { ChequePage, ChequePageIssueStatus, ChequePageStatusAction, PayeeType } from "@/types/general-ledger" + +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog" +import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { toast } from "@/components/ui/toast" + +const STATUS_BADGE: Record = { + [ChequePageIssueStatus.Unused]: "bg-muted text-muted-foreground", + [ChequePageIssueStatus.Issued]: "bg-primary/10 text-primary", + [ChequePageIssueStatus.Cleared]: "bg-success/10 text-success", + [ChequePageIssueStatus.Bounced]: "bg-destructive/10 text-destructive", + [ChequePageIssueStatus.Cancelled]: "bg-destructive/10 text-destructive", + [ChequePageIssueStatus.Void]: "bg-muted text-muted-foreground", +} + +type PendingAction = "Issue" | ChequePageStatusAction | null + +interface ChequePageDialogProps { + page: ChequePage | null + open: boolean + onOpenChange: (open: boolean) => void + /** Called with the server's response after a successful issue/status-update, so the caller's list stays in sync. */ + onUpdated: (updated: ChequePage) => void +} + +/** View a single cheque page's details, and (from `Unused`/`Issued`) issue it or move it through + * Clear/Bounce/Cancel/Void — a modal rather than a separate page, so acting on several leaves from + * a book's page list doesn't lose scroll position/context each time (docs/21 §7). */ +export function ChequePageDialog({ page, open, onOpenChange, onUpdated }: ChequePageDialogProps) { + const [pendingAction, setPendingAction] = useState(null) + const [submitting, setSubmitting] = useState(false) + const [errors, setErrors] = useState>({}) + + const [payeeType, setPayeeType] = useState(PayeeType.Supplier) + const [payeeName, setPayeeName] = useState("") + const [payeeId, setPayeeId] = useState("") + const [issueDate, setIssueDate] = useState("") + const [amount, setAmount] = useState("") + const [currencyCode, setCurrencyCode] = useState("LKR") + const [voucherId, setVoucherId] = useState("") + const [referenceNo, setReferenceNo] = useState("") + const [purpose, setPurpose] = useState("") + const [isCrossCheque, setIsCrossCheque] = useState(false) + const [isAccountPayee, setIsAccountPayee] = useState(false) + const [isPostDated, setIsPostDated] = useState(false) + const [notes, setNotes] = useState("") + const [printedBy, setPrintedBy] = useState("") + + const [clearedDate, setClearedDate] = useState("") + const [cancelReason, setCancelReason] = useState("") + const [performedBy, setPerformedBy] = useState("") + + function resetActionState() { + setPendingAction(null) + setErrors({}) + setPayeeType(PayeeType.Supplier) + setPayeeName("") + setPayeeId("") + setIssueDate("") + setAmount("") + setCurrencyCode("LKR") + setVoucherId("") + setReferenceNo("") + setPurpose("") + setIsCrossCheque(false) + setIsAccountPayee(false) + setIsPostDated(false) + setNotes("") + setPrintedBy("") + setClearedDate("") + setCancelReason("") + setPerformedBy("") + } + + function handleOpenChange(next: boolean) { + if (!next) resetActionState() + onOpenChange(next) + } + + async function submitIssue() { + if (!page) return + const nextErrors = validateIssueChequeForm({ payeeName, issueDate, amount }) + setErrors(nextErrors) + if (Object.keys(nextErrors).length > 0) return + setSubmitting(true) + try { + const updated = await chequePagesApi.issue(page.chequeNo, { + payeeType, + payeeId: payeeId ? Number(payeeId) : undefined, + payeeName, + issueDate, + amount: Number(amount), + currencyCode: currencyCode || undefined, + voucherId: voucherId ? Number(voucherId) : undefined, + referenceNo: referenceNo || undefined, + purpose: purpose || undefined, + isCrossCheque, + isAccountPayee, + isPostDated, + notes: notes || undefined, + printedBy: printedBy || undefined, + }) + toast.success("Cheque issued", `${updated.chequeNo} → ${updated.payeeName}`) + onUpdated(updated) + resetActionState() + } catch (err) { + toast.error("Could not issue cheque", errorMessage(err)) + } finally { + setSubmitting(false) + } + } + + async function submitStatusAction(action: ChequePageStatusAction) { + if (!page) return + if (action === ChequePageStatusAction.Clear && !clearedDate) { + setErrors({ clearedDate: "Cleared date is required" }) + return + } + if (action === ChequePageStatusAction.Cancel && !cancelReason.trim()) { + setErrors({ cancelReason: "Cancel reason is required" }) + return + } + setSubmitting(true) + try { + const updated = await chequePagesApi.updateStatus(page.chequeNo, { + action, + clearedDate: action === ChequePageStatusAction.Clear ? clearedDate : undefined, + cancelReason: action === ChequePageStatusAction.Cancel ? cancelReason : undefined, + performedBy: performedBy || undefined, + }) + toast.success(`Cheque ${action.toLowerCase()}d`, updated.chequeNo) + onUpdated(updated) + resetActionState() + } catch (err) { + toast.error(`Could not ${action.toLowerCase()} cheque`, errorMessage(err)) + } finally { + setSubmitting(false) + } + } + + if (!page) return null + + const availableActions: ChequePageStatusAction[] = + page.issueStatus === ChequePageIssueStatus.Unused + ? [ChequePageStatusAction.Cancel, ChequePageStatusAction.Void] + : page.issueStatus === ChequePageIssueStatus.Issued + ? [ChequePageStatusAction.Clear, ChequePageStatusAction.Bounce, ChequePageStatusAction.Cancel] + : [] + + return ( + + + + + Cheque {page.chequeNo} + + {page.issueStatus} + + + + + {!pendingAction && ( +
+
+
Payee
+
{page.payeeName ?? "—"}
+
Payee type
+
{page.payeeType ?? "—"}
+
Issue date
+
{formatReportDate(page.issueDate)}
+
Amount
+
{page.amount !== null ? formatAmount(page.amount) : "—"}
+
Reference no.
+
{page.referenceNo ?? "—"}
+
Purpose
+
{page.purpose ?? "—"}
+
Notes
+
{page.notes ?? "—"}
+ {page.issueStatus === ChequePageIssueStatus.Cleared && ( + <> +
Cleared date
+
{formatReportDate(page.clearedDate)}
+ + )} + {page.issueStatus === ChequePageIssueStatus.Cancelled && ( + <> +
Cancel reason
+
{page.cancelReason ?? "—"}
+ + )} +
+ + {availableActions.length > 0 && ( +
+ {page.issueStatus === ChequePageIssueStatus.Unused && ( + + )} + {availableActions.map((action) => ( + + ))} +
+ )} +
+ )} + + {pendingAction === "Issue" && ( + + + Payee name + setPayeeName(e.target.value)} aria-invalid={!!errors.payeeName} /> + + + + + Payee type + value={payeeType} onValueChange={(v) => setPayeeType(v ?? PayeeType.Supplier)}> + + + + + {Object.values(PayeeType).map((t) => ( + + {t} + + ))} + + + + + + Payee ID (optional) + setPayeeId(e.target.value)} /> + + +
+ + Issue date + setIssueDate(e.target.value)} + aria-invalid={!!errors.issueDate} + /> + + + + Amount + setAmount(e.target.value)} aria-invalid={!!errors.amount} /> + + +
+ +
+ + Currency + setCurrencyCode(e.target.value)} maxLength={3} /> + + + Voucher ID (optional) + setVoucherId(e.target.value)} /> + +
+ + + Reference no. (optional) + setReferenceNo(e.target.value)} /> + + + + Purpose (optional) + setPurpose(e.target.value)} /> + + +
+ + + +
+ + + Notes (optional) + setNotes(e.target.value)} /> + + + + Printed by (optional) + setPrintedBy(e.target.value)} /> + +
+ )} + + {pendingAction === ChequePageStatusAction.Clear && ( + + + Cleared date + setClearedDate(e.target.value)} + aria-invalid={!!errors.clearedDate} + /> + + + + Performed by (optional) + setPerformedBy(e.target.value)} /> + + + )} + + {pendingAction === ChequePageStatusAction.Cancel && ( + + + Cancel reason + setCancelReason(e.target.value)} + aria-invalid={!!errors.cancelReason} + /> + + + + Performed by (optional) + setPerformedBy(e.target.value)} /> + + + )} + + {(pendingAction === ChequePageStatusAction.Bounce || pendingAction === ChequePageStatusAction.Void) && ( + + + Performed by (optional) + setPerformedBy(e.target.value)} /> + + + )} + + {pendingAction && ( + + + + + )} +
+
+ ) +} diff --git a/Frontend/erp-system/components/accounts/ReceivedChequeDialog.tsx b/Frontend/erp-system/components/accounts/ReceivedChequeDialog.tsx new file mode 100644 index 0000000..1ef4ec2 --- /dev/null +++ b/Frontend/erp-system/components/accounts/ReceivedChequeDialog.tsx @@ -0,0 +1,236 @@ +"use client" + +import { useEffect, useState } from "react" + +import { bankAccountsApi, receivedChequesApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { formatAmount, formatReportDate } from "@/lib/format" +import { cn } from "@/lib/utils" +import { + CashAndBankAccountDto, + CashBankAccountType, + ReceivedCheque, + ReceivedChequeStatus, + ReceivedChequeStatusAction, +} from "@/types/general-ledger" + +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog" +import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { toast } from "@/components/ui/toast" + +const STATUS_BADGE: Record = { + [ReceivedChequeStatus.Received]: "bg-muted text-muted-foreground", + [ReceivedChequeStatus.Deposited]: "bg-primary/10 text-primary", + [ReceivedChequeStatus.Cleared]: "bg-success/10 text-success", + [ReceivedChequeStatus.Returned]: "bg-destructive/10 text-destructive", + [ReceivedChequeStatus.Cancelled]: "bg-destructive/10 text-destructive", +} + +interface ReceivedChequeDialogProps { + cheque: ReceivedCheque | null + open: boolean + onOpenChange: (open: boolean) => void + onUpdated: (updated: ReceivedCheque) => void +} + +/** View a received cheque's details and (from `Received`/`Deposited`) move it through + * Deposit/Clear/Return/Cancel — a modal, same posture as `ChequePageDialog`. */ +export function ReceivedChequeDialog({ cheque, open, onOpenChange, onUpdated }: ReceivedChequeDialogProps) { + const [pendingAction, setPendingAction] = useState(null) + const [submitting, setSubmitting] = useState(false) + const [errors, setErrors] = useState>({}) + + const [bankAccounts, setBankAccounts] = useState(null) + const [depositBankAccountId, setDepositBankAccountId] = useState("") + const [depositDate, setDepositDate] = useState("") + const [performedBy, setPerformedBy] = useState("") + const [notes, setNotes] = useState("") + + useEffect(() => { + if (pendingAction !== ReceivedChequeStatusAction.Deposit || bankAccounts !== null) return + bankAccountsApi.list(CashBankAccountType.Bank).then(setBankAccounts).catch(() => setBankAccounts([])) + // Only fetched once, lazily, the first time Deposit is chosen. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pendingAction]) + + function resetActionState() { + setPendingAction(null) + setErrors({}) + setDepositBankAccountId("") + setDepositDate("") + setPerformedBy("") + setNotes("") + } + + function handleOpenChange(next: boolean) { + if (!next) resetActionState() + onOpenChange(next) + } + + async function submitStatusAction(action: ReceivedChequeStatusAction) { + if (!cheque) return + if (action === ReceivedChequeStatusAction.Deposit) { + const nextErrors: Record = {} + if (!depositBankAccountId) nextErrors.depositBankAccountId = "Select a deposit bank account" + if (!depositDate) nextErrors.depositDate = "Deposit date is required" + setErrors(nextErrors) + if (Object.keys(nextErrors).length > 0) return + } + setSubmitting(true) + try { + const updated = await receivedChequesApi.updateStatus(cheque.receivedChequeId, { + action, + depositBankAccountId: action === ReceivedChequeStatusAction.Deposit ? Number(depositBankAccountId) : undefined, + depositDate: action === ReceivedChequeStatusAction.Deposit ? depositDate : undefined, + notes: notes || undefined, + performedBy: performedBy || undefined, + }) + toast.success(`Cheque ${action.toLowerCase()}ed`, updated.chequeNo) + onUpdated(updated) + resetActionState() + } catch (err) { + toast.error(`Could not ${action.toLowerCase()} cheque`, errorMessage(err)) + } finally { + setSubmitting(false) + } + } + + if (!cheque) return null + + const availableActions: ReceivedChequeStatusAction[] = + cheque.status === ReceivedChequeStatus.Received + ? [ReceivedChequeStatusAction.Deposit, ReceivedChequeStatusAction.Cancel] + : cheque.status === ReceivedChequeStatus.Deposited + ? [ReceivedChequeStatusAction.Clear, ReceivedChequeStatusAction.Return] + : [] + + return ( + + + + + Cheque {cheque.chequeNo} + + {cheque.status} + + + + + {!pendingAction && ( +
+
+
Received from
+
{cheque.receivedFromName}
+
Type
+
{cheque.receivedFromType}
+
Cheque date
+
{formatReportDate(cheque.chequeDate)}
+
Amount
+
{formatAmount(cheque.amount)}
+
Received date
+
{formatReportDate(cheque.receivedDate)}
+
Drawer bank
+
{cheque.drawerBankName ?? "—"}
+
Drawer branch
+
{cheque.drawerBankBranch ?? "—"}
+
Account holder
+
{cheque.accountHolderName ?? "—"}
+
Reference
+
{cheque.referenceType ?? "—"}
+
Notes
+
{cheque.notes ?? "—"}
+ {cheque.status === ReceivedChequeStatus.Deposited && ( + <> +
Deposited to
+
#{cheque.depositBankAccountId}
+
Deposit date
+
{formatReportDate(cheque.depositDate)}
+ + )} +
+ + {availableActions.length > 0 && ( +
+ {availableActions.map((action) => ( + + ))} +
+ )} +
+ )} + + {pendingAction === ReceivedChequeStatusAction.Deposit && ( + + + Deposit bank account + value={depositBankAccountId} onValueChange={(v) => setDepositBankAccountId(v ?? "")}> + + + + + {(bankAccounts ?? []).map((a) => ( + + {a.accountName} + + ))} + + + + + + Deposit date + setDepositDate(e.target.value)} + aria-invalid={!!errors.depositDate} + /> + + + + Performed by (optional) + setPerformedBy(e.target.value)} /> + + + Notes (optional) + setNotes(e.target.value)} /> + + + )} + + {(pendingAction === ReceivedChequeStatusAction.Clear || + pendingAction === ReceivedChequeStatusAction.Return || + pendingAction === ReceivedChequeStatusAction.Cancel) && ( + + + Performed by (optional) + setPerformedBy(e.target.value)} /> + + + Notes (optional) + setNotes(e.target.value)} /> + + + )} + + {pendingAction && ( + + + + + )} +
+
+ ) +} diff --git a/Frontend/erp-system/components/reports/DownloadCsvButton.tsx b/Frontend/erp-system/components/reports/DownloadCsvButton.tsx new file mode 100644 index 0000000..76158fb --- /dev/null +++ b/Frontend/erp-system/components/reports/DownloadCsvButton.tsx @@ -0,0 +1,42 @@ +"use client" + +import { useState } from "react" +import { FileSpreadsheet } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { ReportType } from "@/types/general-ledger" + +import { Button } from "@/components/ui/button" +import { toast } from "@/components/ui/toast" + +interface DownloadCsvButtonProps { + reportType: ReportType + /** Same filter params already sent to the Json call — outputFormat is added here, not by the caller. */ + params: Record + /** Disable while the on-screen report itself hasn't loaded (nothing to name the download after would be odd otherwise). */ + disabled?: boolean +} + +/** Same mechanism as DownloadPdfButton, `outputFormat=Csv` — GL's bytes are downloaded unmodified. */ +export function DownloadCsvButton({ reportType, params, disabled }: DownloadCsvButtonProps) { + const [downloading, setDownloading] = useState(false) + + async function handleDownload() { + setDownloading(true) + try { + await reportsApi.downloadCsv(reportType, params) + } catch (err) { + toast.error("Could not download report", errorMessage(err)) + } finally { + setDownloading(false) + } + } + + return ( + + ) +} diff --git a/Frontend/erp-system/components/reports/DownloadPdfButton.tsx b/Frontend/erp-system/components/reports/DownloadPdfButton.tsx new file mode 100644 index 0000000..fc4fae2 --- /dev/null +++ b/Frontend/erp-system/components/reports/DownloadPdfButton.tsx @@ -0,0 +1,41 @@ +"use client" + +import { useState } from "react" +import { Download } from "lucide-react" + +import { reportsApi } from "@/lib/api/general-ledger" +import { errorMessage } from "@/lib/error-map" +import { ReportType } from "@/types/general-ledger" + +import { Button } from "@/components/ui/button" +import { toast } from "@/components/ui/toast" + +interface DownloadPdfButtonProps { + reportType: ReportType + /** Same filter params already sent to the Json call — outputFormat is added here, not by the caller. */ + params: Record + /** Disable while the on-screen report itself hasn't loaded (nothing to name the download after would be odd otherwise). */ + disabled?: boolean +} + +export function DownloadPdfButton({ reportType, params, disabled }: DownloadPdfButtonProps) { + const [downloading, setDownloading] = useState(false) + + async function handleDownload() { + setDownloading(true) + try { + await reportsApi.downloadPdf(reportType, params) + } catch (err) { + toast.error("Could not download report", errorMessage(err)) + } finally { + setDownloading(false) + } + } + + return ( + + ) +} diff --git a/Frontend/erp-system/components/reports/ReportHeader.tsx b/Frontend/erp-system/components/reports/ReportHeader.tsx new file mode 100644 index 0000000..c568ec8 --- /dev/null +++ b/Frontend/erp-system/components/reports/ReportHeader.tsx @@ -0,0 +1,27 @@ +// Statutory-style report header (docs/21-GENERAL-LEDGER-FRONTEND.md "Sri Lankan Standard report +// UI"): centered title block, LKAS-aligned statement names, period/as-at line, currency note — +// the same shape whether the report renders on screen or the downloaded PDF (the PDF itself is +// rendered server-side by the GL service; this header is the on-screen equivalent). + +interface ReportHeaderProps { + title: string + subtitle: string + currencyNote?: string +} + +export function ReportHeader({ + title, + subtitle, + currencyNote = "All amounts in Sri Lankan Rupees (LKR) unless stated otherwise.", +}: ReportHeaderProps) { + return ( +
+

+ General Ledger +

+

{title}

+

{subtitle}

+

{currencyNote}

+
+ ) +} diff --git a/Frontend/erp-system/components/reports/ReportSection.tsx b/Frontend/erp-system/components/reports/ReportSection.tsx new file mode 100644 index 0000000..f5d1aa4 --- /dev/null +++ b/Frontend/erp-system/components/reports/ReportSection.tsx @@ -0,0 +1,42 @@ +import { formatAmount } from "@/lib/format" +import { Table, TableBody, TableCell, TableFooter, TableRow } from "@/components/ui/table" + +export interface ReportSectionLine { + label: React.ReactNode + amount: number +} + +interface ReportSectionProps { + title: string + lines: ReportSectionLine[] + /** Omit to hide the total row entirely (e.g. a single-line section that would just repeat itself). */ + total?: number +} + +/** One bordered statement section: its lines, then an optional bold total row. Renders nothing when there are no lines. */ +export function ReportSection({ title, lines, total }: ReportSectionProps) { + if (lines.length === 0) return null + return ( +
+

{title}

+ + + {lines.map((line, i) => ( + + {line.label} + {formatAmount(line.amount)} + + ))} + + {total !== undefined && ( + + + Total {title} + {formatAmount(total)} + + + )} +
+
+ ) +} diff --git a/Frontend/erp-system/components/reports/ReportSubtotal.tsx b/Frontend/erp-system/components/reports/ReportSubtotal.tsx new file mode 100644 index 0000000..8da7d39 --- /dev/null +++ b/Frontend/erp-system/components/reports/ReportSubtotal.tsx @@ -0,0 +1,23 @@ +import { formatAmount } from "@/lib/format" +import { cn } from "@/lib/utils" + +interface ReportSubtotalProps { + label: string + amount: number + large?: boolean +} + +/** A bold, unbordered subtotal/total line (Gross Profit, Net Cash From Operations, the final total, etc.). */ +export function ReportSubtotal({ label, amount, large }: ReportSubtotalProps) { + return ( +
+ {label} + {formatAmount(amount)} +
+ ) +} diff --git a/Frontend/erp-system/lib/api/general-ledger.ts b/Frontend/erp-system/lib/api/general-ledger.ts new file mode 100644 index 0000000..c7948a9 --- /dev/null +++ b/Frontend/erp-system/lib/api/general-ledger.ts @@ -0,0 +1,322 @@ +// Client for the external General Ledger service, reached through ERPCore's generic +// reverse-proxy at /api/v1/gl/* (docs/12-GENERAL-LEDGER-INTEGRATION.md). Deliberately NOT +// built on lib/api-client.ts's apiRequest/apiRequestWithETag: those assume ERPCore's own +// RFC 7807 ProblemDetails error shape and a bare-DTO success body. GL wraps every response +// (success AND error) in its own `{ statusCode, success, message, data }` envelope instead, +// and — a documented GL quirk — success bodies are camelCase while error bodies are +// PascalCase, so this module unwraps both forms itself rather than trusting one casing. +import { + CashAccountType, + CashAndBankAccountDto, + CashBankAccountType, + CreateBankAccountRequest, + CreateCashAccountRequest, + CreateCashOrBankAccountResponse, + GlAccountListResult, + GlBudget, + GlFilePayload, + ReportOutputFormat, + ReportType, + TrialBalanceRow, + BalanceSheetResponse, + GeneralLedgerRow, + ProfitAndLossResponse, + CashFlowResponse, + BudgetVsActualRow, + TaxSummaryResponse, + TaxSummaryParams, + GlPagedResult, + ChequeBook, + ChequeBookStatus, + ChequePage, + CreateChequeBookRequest, + IssueChequePageRequest, + UpdateChequePageStatusRequest, + ReceivedCheque, + ReceivedChequeStatus, + ReceivedFromType, + CreateReceivedChequeRequest, + UpdateReceivedChequeStatusRequest, +} from "@/types/general-ledger" + +const GL_BASE = "/api/v1/gl" + +/** Duck-type compatible with lib/error-map.ts's ApiErrorLike — `detail` carries GL's own message. */ +export class GlApiError extends Error { + status: number + detail: string + + constructor(status: number, message: string) { + super(message) + this.status = status + this.detail = message + } +} + +interface GlEnvelope { + statusCode?: number + StatusCode?: number + success?: boolean + Success?: boolean + message?: string + Message?: string + data?: T + Data?: T + // Surfaces only when the proxy itself fails before reaching GL (e.g. ERPCore's own + // 503 GL_SERVICE_UNAVAILABLE ProblemDetails) rather than GL's own envelope. + title?: string + detail?: string +} + +type GlQueryValue = string | number | undefined + +async function glRequest( + path: string, + options: { method?: string; query?: Record; body?: unknown } = {} +): Promise { + const { method = "GET", query, body } = options + const search = new URLSearchParams() + if (query) { + for (const [key, value] of Object.entries(query)) { + if (value === undefined || value === "") continue + search.set(key, String(value)) + } + } + const qs = search.toString() + + const response = await fetch(`${GL_BASE}${path}${qs ? `?${qs}` : ""}`, { + method, + credentials: "include", // the proxy is ErpAccess-gated, same as every other v1 endpoint + headers: { + Accept: "application/json", + ...(body !== undefined ? { "Content-Type": "application/json" } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }) + + let envelope: GlEnvelope | null = null + try { + envelope = (await response.json()) as GlEnvelope + } catch { + // Non-JSON body — e.g. an unreachable proxy hop. Falls through to the generic message below. + } + + const success = envelope?.success ?? envelope?.Success ?? false + if (!response.ok || !success) { + const message = + envelope?.message ?? envelope?.Message ?? envelope?.detail ?? envelope?.title ?? + response.statusText ?? "General Ledger service request failed" + throw new GlApiError(response.status, message) + } + + return (envelope?.data ?? envelope?.Data) as T +} + +/** Decodes a base64 payload and triggers a browser download — no server round-trip needed. */ +function downloadBase64File(base64: string, fileName: string, contentType: string) { + const byteChars = atob(base64) + const byteNumbers = new Array(byteChars.length) + for (let i = 0; i < byteChars.length; i++) byteNumbers[i] = byteChars.charCodeAt(i) + const blob = new Blob([new Uint8Array(byteNumbers)], { type: contentType }) + const url = URL.createObjectURL(blob) + const link = document.createElement("a") + link.href = url + link.download = fileName + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + URL.revokeObjectURL(url) +} + +/** Shared by downloadPdf/downloadCsv — same report call, only `outputFormat` differs. */ +async function downloadReportFile( + reportType: ReportType, + outputFormat: ReportOutputFormat.Pdf | ReportOutputFormat.Csv, + params: Record +): Promise { + const payload = await glRequest("/reports", { + query: { reportType, outputFormat, ...params }, + }) + downloadBase64File(payload.contentBase64, payload.fileName, payload.contentType) +} + +export const reportsApi = { + trialBalance(asOfDate: string) { + return glRequest("/reports", { + query: { reportType: ReportType.TrialBalance, outputFormat: ReportOutputFormat.Json, asOfDate }, + }) + }, + + /** Confirmed classified-statement shape (2026-07-31 rework) — see types/general-ledger.ts's BalanceSheetResponse note. */ + balanceSheet(asOfDate: string) { + return glRequest("/reports", { + query: { reportType: ReportType.BalanceSheet, outputFormat: ReportOutputFormat.Json, asOfDate }, + }) + }, + + // GL's `accountCode` param is optional (renamed from `accountId` in GL's 2026-07-22 revision, + // CLAUDE.md Rule 8.2 on GL's side — behavior unchanged): omitted, this returns the true General + // Ledger — every postable account's own transactions together, each with its own running + // balance (resets per account), sorted by accountCode then entryDate. Supplying accountCode + // switches to "Account Ledger" mode (one account + its descendants, one running balance) — not + // used by this page; add it back with an accountCode param if a single-account view is needed later. + generalLedger(periodStart: string, periodEnd: string) { + return glRequest("/reports", { + query: { reportType: ReportType.GeneralLedger, outputFormat: ReportOutputFormat.Json, periodStart, periodEnd }, + }) + }, + + /** Nested-sections shape as of the 2026-07-22 rework — see types/general-ledger.ts's ProfitAndLossResponse note. */ + profitAndLoss(periodStart: string, periodEnd: string) { + return glRequest("/reports", { + query: { reportType: ReportType.ProfitAndLoss, outputFormat: ReportOutputFormat.Json, periodStart, periodEnd }, + }) + }, + + /** Confirmed structured-statement shape (2026-07-22 rework) — see types/general-ledger.ts's CashFlowResponse note; everything nests under `operatingActivities`. */ + cashFlow(periodStart: string, periodEnd: string) { + return glRequest("/reports", { + query: { reportType: ReportType.CashFlow, outputFormat: ReportOutputFormat.Json, periodStart, periodEnd }, + }) + }, + + budgetVsActual(budgetId: number) { + return glRequest("/reports", { + query: { reportType: ReportType.BudgetVsActual, outputFormat: ReportOutputFormat.Json, budgetId }, + }) + }, + + /** Income Tax Computation — new report (2026-07-22). Optional params get no client-side default; an untouched field sends nothing, letting GL's own server-side defaulting be the single source of truth. */ + taxSummary(params: TaxSummaryParams) { + return glRequest("/reports", { + query: { reportType: ReportType.TaxSummary, outputFormat: ReportOutputFormat.Json, ...params }, + }) + }, + + /** Same report call as the Json variants above, only `outputFormat` differs — the PDF bytes come from the same endpoint. */ + downloadPdf(reportType: ReportType, params: Record): Promise { + return downloadReportFile(reportType, ReportOutputFormat.Pdf, params) + }, + + /** Same mechanism as downloadPdf, `outputFormat=Csv` — GL's bytes are downloaded unmodified, not reshaped/reformatted client-side. */ + downloadCsv(reportType: ReportType, params: Record): Promise { + return downloadReportFile(reportType, ReportOutputFormat.Csv, params) + }, +} + +/** + * Chart of Accounts — used by the Cash/Bank Accounts list page to resolve each row's `glAccountId` + * into a readable account code/name (retrofit 2026-07-31: the create form no longer needs this at + * all, since `glAccountCode` was removed from the create request — the GL account is auto-created). + * The General Ledger **report** page deliberately does NOT use this: it always calls the report in + * full-ledger mode (no `accountCode`), so every account's code/name shown come from the report's own + * rows (`GeneralLedgerRow.accountCode`/`accountName`), not a separate `/accounts` call — see + * docs/21-GENERAL-LEDGER-FRONTEND.md. + */ +export const glAccountsApi = { + list(): Promise { + return glRequest("/accounts") + }, +} + +/** Used only to populate the Budget vs Actual report's budget picker. */ +export const glBudgetsApi = { + list(): Promise { + return glRequest("/budgets") + }, +} + +export const bankAccountsApi = { + /** GL's own server-side union of both tables (2026-07-22 rework) — `accountType` narrows which table(s) contribute rows; client-side filters still layer on top. */ + list(accountType?: CashBankAccountType | "Both"): Promise { + return glRequest("/bank-accounts", { query: { accountType } }) + }, + + createBank(request: CreateBankAccountRequest): Promise { + return glRequest("/bank-accounts", { method: "POST", body: request }) + }, + + createCash(request: CreateCashAccountRequest): Promise { + return glRequest("/cash-accounts", { method: "POST", body: request }) + }, + + // No get()/update(): GL exposes no GET/PUT by id for either bank_account or cash_account today + // (see docs/21-GENERAL-LEDGER-FRONTEND.md's "Known gap — edit"). +} + +/** Feeds the Cash/Bank create form's Cash Account Type picker; a name with no match creates a new type on the fly server-side (nothing to pre-create from this list). */ +export const cashAccountTypesApi = { + list(): Promise { + return glRequest("/cash-account-types") + }, +} + +/** + * Cheque Books/Pages — cheques issued from this company's own cheque books (Cheque Management + * module, added to GL 2026-07-30). `chequeBookNo` is the identifying value GL uses in its own + * routes, not a numeric id. No `list()`/`get()` for pages standalone — a book's pages are always + * read via `get(chequeBookNo, true)`'s `pages[]`, which is the only place this frontend needs them. + */ +export const chequeBooksApi = { + list(params?: { + bankAccountId?: number + branchId?: number + status?: ChequeBookStatus + page?: number + pageSize?: number + }): Promise> { + return glRequest>("/cheque-books", { query: { ...params } }) + }, + + /** `expandPages` maps to GL's `?expand=pages` — omit it for just the book's own fields. */ + get(chequeBookNo: string, expandPages = false): Promise { + return glRequest(`/cheque-books/${encodeURIComponent(chequeBookNo)}`, { + query: expandPages ? { expand: "pages" } : undefined, + }) + }, + + /** Auto-generates every leaf (`totalLeaves` `ChequePage` rows, all `Unused`) in the same call — the response's `pages[]` already has them. */ + create(request: CreateChequeBookRequest): Promise { + return glRequest("/cheque-books", { method: "POST", body: request }) + }, +} + +export const chequePagesApi = { + issue(chequeNo: string, request: IssueChequePageRequest): Promise { + return glRequest(`/cheque-pages/${encodeURIComponent(chequeNo)}/issue`, { + method: "PUT", + body: request, + }) + }, + + /** `Clear`/`Bounce`/`Cancel`/`Void` — only valid from certain `issueStatus` values, see `types/general-ledger.ts`'s `ChequePageStatusAction`. */ + updateStatus(chequeNo: string, request: UpdateChequePageStatusRequest): Promise { + return glRequest(`/cheque-pages/${encodeURIComponent(chequeNo)}/status`, { + method: "PUT", + body: request, + }) + }, +} + +/** Received Cheques — cheques received from customers/suppliers/others, deliberately unlinked to any `ChequeBook`. */ +export const receivedChequesApi = { + list(params?: { + companyId?: number + branchId?: number + status?: ReceivedChequeStatus + receivedFromType?: ReceivedFromType + page?: number + pageSize?: number + }): Promise> { + return glRequest>("/received-cheques", { query: { ...params } }) + }, + + create(request: CreateReceivedChequeRequest): Promise { + return glRequest("/received-cheques", { method: "POST", body: request }) + }, + + /** `Deposit`/`Clear`/`Return`/`Cancel` — only valid from certain statuses, see `types/general-ledger.ts`'s `ReceivedChequeStatusAction`. */ + updateStatus(id: number, request: UpdateReceivedChequeStatusRequest): Promise { + return glRequest(`/received-cheques/${id}/status`, { method: "PUT", body: request }) + }, +} diff --git a/Frontend/erp-system/lib/format.ts b/Frontend/erp-system/lib/format.ts new file mode 100644 index 0000000..28e9275 --- /dev/null +++ b/Frontend/erp-system/lib/format.ts @@ -0,0 +1,35 @@ +// Formatting helpers for statutory-style financial reports (docs/21-GENERAL-LEDGER-FRONTEND.md) — +// comma-grouped thousands, fixed 2 decimals, negatives in parentheses (standard financial-statement +// convention), rather than the plain `.toFixed(2)` used by the inventory-side stock screens. + +const AMOUNT_FORMATTER = new Intl.NumberFormat("en-US", { + minimumFractionDigits: 2, + maximumFractionDigits: 2, +}) + +/** `1234.5` -> "1,234.50"; `-1234.5` -> "(1,234.50)"; `0`/`null`/`undefined` -> the given fallback. */ +export function formatAmount(value: number | null | undefined, zeroDash = false): string { + if (value === null || value === undefined || Number.isNaN(value)) return "—" + if (zeroDash && value === 0) return "—" + const formatted = AMOUNT_FORMATTER.format(Math.abs(value)) + return value < 0 ? `(${formatted})` : formatted +} + +/** `"2026-07-01"` / an ISO timestamp -> "01 Jul 2026" for report headers and tables. */ +export function formatReportDate(value: string | null | undefined): string { + if (!value) return "—" + const date = new Date(value) + if (Number.isNaN(date.getTime())) return value + return date.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }) +} + +/** Today's date as `YYYY-MM-DD`, for default report filter values. */ +export function todayIso(): string { + return new Date().toISOString().slice(0, 10) +} + +/** The first day of the current month as `YYYY-MM-DD`, for default period-start filter values. */ +export function startOfMonthIso(): string { + const now = new Date() + return new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10) +} diff --git a/Frontend/erp-system/lib/validations/general-ledger.ts b/Frontend/erp-system/lib/validations/general-ledger.ts new file mode 100644 index 0000000..7420f32 --- /dev/null +++ b/Frontend/erp-system/lib/validations/general-ledger.ts @@ -0,0 +1,55 @@ +// Client-side UX validation only (docs/20-FRONTEND.md §3.1) — required fields the browser +// already knows about. Everything else is server-authoritative and surfaced via the GL +// service's own error message (lib/error-map.ts). + +export function validateBankAccountForm(input: { accountName: string }): Record { + const errors: Record = {} + if (!input.accountName.trim()) errors.accountName = "Account name is required" + return errors +} + +export function validateChequeBookForm(input: { + branchId: string + bankAccountId: string + chequeBookNo: string + startChequeNo: string + endChequeNo: string + totalLeaves: string + receivedDate: string +}): Record { + const errors: Record = {} + if (!input.branchId.trim()) errors.branchId = "Branch ID is required" + if (!input.bankAccountId) errors.bankAccountId = "Select a bank account" + if (!input.chequeBookNo.trim()) errors.chequeBookNo = "Cheque book number is required" + if (!input.startChequeNo.trim()) errors.startChequeNo = "Start cheque number is required" + if (!input.endChequeNo.trim()) errors.endChequeNo = "End cheque number is required" + if (!input.totalLeaves.trim()) errors.totalLeaves = "Total leaves is required" + if (!input.receivedDate) errors.receivedDate = "Received date is required" + return errors +} + +export function validateIssueChequeForm(input: { payeeName: string; issueDate: string; amount: string }): Record { + const errors: Record = {} + if (!input.payeeName.trim()) errors.payeeName = "Payee name is required" + if (!input.issueDate) errors.issueDate = "Issue date is required" + if (!input.amount.trim() || Number(input.amount) <= 0) errors.amount = "Amount must be greater than 0" + return errors +} + +export function validateReceivedChequeForm(input: { + companyId: string + receivedFromName: string + chequeNo: string + chequeDate: string + amount: string + receivedDate: string +}): Record { + const errors: Record = {} + if (!input.companyId.trim()) errors.companyId = "Company ID is required" + if (!input.receivedFromName.trim()) errors.receivedFromName = "Received-from name is required" + if (!input.chequeNo.trim()) errors.chequeNo = "Cheque number is required" + if (!input.chequeDate) errors.chequeDate = "Cheque date is required" + if (!input.amount.trim() || Number(input.amount) <= 0) errors.amount = "Amount must be greater than 0" + if (!input.receivedDate) errors.receivedDate = "Received date is required" + return errors +} diff --git a/Frontend/erp-system/types/general-ledger.ts b/Frontend/erp-system/types/general-ledger.ts new file mode 100644 index 0000000..66817fa --- /dev/null +++ b/Frontend/erp-system/types/general-ledger.ts @@ -0,0 +1,558 @@ +// Mirrors the external General Ledger service's own contract (04_API_Reference_And_Scenarios.md +// in that service's repo — ERPCore does not re-document it, see docs/12-GENERAL-LEDGER-INTEGRATION.md). +// Every field here is read through ERPCore's generic proxy (`lib/api/general-ledger.ts`), which +// forwards byte-for-byte, so these types describe GL's response `data` shape directly, not an +// ERPCore DTO. As of GL's 2026-07-22 revision (docs/21-GENERAL-LEDGER-FRONTEND.md §0/§3/§4). + +/** `account_type` seed rows — the block each drives in a generated account code (1000/2000/3000/4000/5000). */ +export enum GlAccountTypeId { + Asset = 1, + Liability = 2, + Equity = 3, + Income = 4, + Expense = 5, +} + +export interface GlAccount { + accountId: number + accountCode: string + accountName: string + accountTypeId: GlAccountTypeId + parentAccountId: number | null + isControlAccount: boolean + isPostable: boolean + isActive: boolean + currencyCode: string + cashFlowCategory?: string | null +} + +export interface GlAccountListResult { + items: GlAccount[] + totalCount: number + page: number | null + pageSize: number | null +} + +export interface GlBudget { + budgetId: number + fiscalYearId: number + name: string + lines: unknown[] +} + +export enum ReportOutputFormat { + Json = "Json", + Pdf = "Pdf", + Csv = "Csv", +} + +export enum ReportType { + TrialBalance = "TrialBalance", + BalanceSheet = "BalanceSheet", + GeneralLedger = "GeneralLedger", + ProfitAndLoss = "ProfitAndLoss", + CashFlow = "CashFlow", + BudgetVsActual = "BudgetVsActual", + TaxSummary = "TaxSummary", +} + +/** Flat as of the 2026-07-22 revision — GL dropped the hierarchy (`depth`/`indentedCode`) this report used to carry. */ +export interface TrialBalanceRow { + accountCode: string + accountName: string + debit: number + credit: number +} + +/** One leaf account within a Balance Sheet section — no `depth`/hierarchy anymore (2026-07-31 rework, see BalanceSheetResponse). */ +export interface BalanceSheetLine { + accountCode: string + accountName: string + balance: number +} + +export interface BalanceSheetSection { + lines: BalanceSheetLine[] + total: number +} + +/** + * Confirmed shape (04_API_Reference_And_Scenarios.md, Module: Reporting, retrofit 2026-07-31) — + * replaces the old flat recursive-rollup array (`{depth, lineItem, accountType, balance}`) entirely + * with a classified LKAS 1 Statement of Financial Position: Non-Current/Current split for both + * Assets and Liabilities, driven by GL's new `accounts.balance_sheet_classification` tag. + * `equity.lines[]` always includes a synthetic `{ accountCode: "", accountName: "Current Year + * Earnings", balance }` line (even at `0.00`). Untagged leaf accounts land in + * `unclassifiedAssets`/`unclassifiedLiabilities` rather than being silently dropped. + * + * Every section is optional — same defensive posture as `CashFlowResponse`/`ProfitAndLossResponse` + * (confirmed live: GL omits an empty section from the JSON entirely rather than sending + * `{ lines: [], total: 0 }`), applied here pre-emptively since this exact shape hasn't been + * live-verified against this frontend yet. + */ +export interface BalanceSheetResponse { + asOfDate: string + nonCurrentAssets?: BalanceSheetSection + currentAssets?: BalanceSheetSection + unclassifiedAssets?: BalanceSheetSection + totalAssets: number + equity?: BalanceSheetSection + nonCurrentLiabilities?: BalanceSheetSection + currentLiabilities?: BalanceSheetSection + unclassifiedLiabilities?: BalanceSheetSection + totalEquityAndLiabilities: number +} + +export interface GeneralLedgerRow { + entryDate: string + journalNo: string + accountCode: string + accountName: string + narration: string | null + debitAmount: number + creditAmount: number + runningBalance: number +} + +/** One line inside a Profit & Loss section — inferred shape (see the ProfitAndLossResponse note). */ +export interface ProfitAndLossLine { + accountCode: string + accountName: string + amount: number +} + +export interface ProfitAndLossSection { + lines: ProfitAndLossLine[] + total: number +} + +/** + * Nested-sections shape (2026-07-22 rework, replaces the old flat `ProfitAndLossRow[]`). GL's own + * reference names the sections and the two top-level totals but does not spell out each line's + * exact field names — `ProfitAndLossLine` above is an **inferred** shape (matching every other + * report's `accountCode`/`accountName` convention), not a confirmed contract. `unclassified` is + * only present with lines if the Chart of Accounts has untagged Income/Expense accounts. + * + * Every section is optional — **confirmed live** (2026-07-31, via the identical bug on + * `CashFlowResponse`'s list fields below): GL's serializer omits a section from the JSON + * entirely when it has nothing to report for the period, rather than sending `{ lines: [], total: 0 }`. + * Every consumer must optional-chain (`report.sales?.lines`), never assume presence. + */ +export interface ProfitAndLossResponse { + sales?: ProfitAndLossSection + costOfSales?: ProfitAndLossSection + grossProfit: number + otherIncome?: ProfitAndLossSection + distributionExpenses?: ProfitAndLossSection + administrationExpenses?: ProfitAndLossSection + otherExpenses?: ProfitAndLossSection + financialExpenses?: ProfitAndLossSection + unclassified?: ProfitAndLossSection + netProfitForPeriod: number +} + +export interface CashFlowNonCashAdjustment { + description: string + amount: number +} + +/** `changeAmount`, not `amount` — confirmed field name (04_API_Reference_And_Scenarios.md, Module: Reporting). */ +export interface CashFlowWorkingCapitalChange { + accountCode: string + accountName: string + direction: "Increase" | "Decrease" + changeAmount: number +} + +/** One line inside an Investing/Financing section — GL's reference confirms `lines[]` exists but not + * this line's own field names; `{description, amount}` here matches every other report's line-item + * convention but is not verified verbatim. */ +export interface CashFlowActivityLine { + description: string + amount: number +} + +export interface CashFlowOperatingActivities { + profitForPeriod: number + nonCashAdjustments: CashFlowNonCashAdjustment[] + workingCapitalChanges: CashFlowWorkingCapitalChange[] + netCashFromOperatingActivities: number +} + +export interface CashFlowInvestingActivities { + lines: CashFlowActivityLine[] + netCashFromInvestingActivities: number +} + +export interface CashFlowFinancingActivities { + lines: CashFlowActivityLine[] + netCashFromFinancingActivities: number +} + +/** + * Confirmed shape (04_API_Reference_And_Scenarios.md, Module: Reporting — GL's own API reference, + * not inferred). **Everything nests under `operatingActivities`** — the previous version of this + * type had `netEarnings`/`nonCashAdjustments`/`workingCapitalChanges`/`netCashFromOperations` as + * flat top-level fields, which was wrong and caused a live runtime crash (`Cannot read properties + * of undefined (reading 'map')` on `nonCashAdjustments` — it was never at the top level to begin + * with). `investingActivities`/`financingActivities` each have their own differently-named total + * field (`netCashFromInvestingActivities`/`netCashFromFinancingActivities`), not a shared `total`. + * `openingCashBalance`/`closingCashBalance` are returned for validation but deliberately not + * rendered on screen — GL's own PDF/CSV doesn't print them either. + */ +export interface CashFlowResponse { + periodStart: string + periodEnd: string + operatingActivities: CashFlowOperatingActivities + investingActivities: CashFlowInvestingActivities + financingActivities: CashFlowFinancingActivities + netIncreaseDecreaseInCash: number + openingCashBalance: number + closingCashBalance: number +} + +export interface BudgetVsActualRow { + budgetLineId: number + accountCode: string + accountName: string + periodId: number + budgetedAmount: number + actualAmount: number + variance: number +} + +/** + * Income Tax Computation (2026-07-22 redesign). Confirmed shape (04_API_Reference_And_Scenarios.md, + * Module: Reporting) — not inferred. The previous version of this type was missing + * `nonDeductibleExpenses`, `corporateIncomeTax`, `apitCredit`, `whtCredit`, and + * `quarterlyTaxPayments` entirely, which meant the Tax Report screen was silently dropping real + * GL-computed figures rather than a made-up guess just being wrong. Full row order, + * `profitBeforeTax` → `balanceTaxPayable`, with bold reconciliation checkpoints at + * `adjustedBusinessProfit`/`assessableIncome`/`taxableIncome`/`grossTaxLiability`/the final total. + */ +export interface TaxSummaryResponse { + periodStart: string + periodEnd: string + profitBeforeTax: number + nonDeductibleExpenses: number + allowableDeductions: number + adjustedBusinessProfit: number + otherTaxableIncome: number + assessableIncome: number + qualifyingPaymentsReliefs: number + taxableIncome: number + taxRatePercent: number + corporateIncomeTax: number + surchargeAmount: number + grossTaxLiability: number + apitCredit: number + whtCredit: number + quarterlyTaxPayments: number + balanceTaxPayable: number +} + +export interface TaxSummaryParams { + periodStart: string + periodEnd: string + allowableDeductions?: number + otherTaxableIncome?: number + qualifyingPaymentsReliefs?: number + surchargeAmount?: number + taxRateOverride?: number +} + +/** `outputFormat=Pdf`/`Csv` response shape — base64-encoded bytes inside the normal envelope either way. */ +export interface GlFilePayload { + fileName: string + contentType: string + contentBase64: string +} + +/** Cash and Bank are two separate GL tables/endpoints (2026-07-22 rework) — this discriminates the unified list row and the create-form toggle, not a database column on either side. */ +export enum CashBankAccountType { + Cash = "Cash", + Bank = "Bank", +} + +/** + * `GET /bank-accounts?accountType=Cash|Bank|Both` row shape (2026-07-22 rework) — GL's own reference + * documents this explicitly (`docs/21` §4), unlike the old single-table `BankAccount` shape it + * replaces, which was inferred. `bankName` is `null` on `Cash` rows, `cashAccountTypeName` is `null` + * on `Bank` rows. + */ +export interface CashAndBankAccountDto { + accountType: CashBankAccountType + accountId: number + accountName: string + bankName: string | null + cashAccountTypeName: string | null + accountNumber: string | null + glAccountId: number + currencyCode: string + createdAt: string +} + +/** + * Confirmed (04_API_Reference_And_Scenarios.md, Module: Bank, retrofit 2026-07-31) — + * `glAccountCode` was removed from this request entirely. The backing GL account is now always + * auto-created server-side (a root "Bank" header account is found-or-created, then a postable leaf + * named after `accountName` is created under it) — the caller never selects or supplies a GL account. + */ +export interface CreateBankAccountRequest { + accountName: string + bankName?: string | null + accountNumber?: string | null + currencyCode?: string +} + +/** + * Confirmed (retrofit 2026-07-31) — same `glAccountCode` removal as `CreateBankAccountRequest`, plus + * one more auto-created level: a root "Cash" header, then a per-`cashAccountTypeName` header (created + * once, reused thereafter), then a postable leaf named after `accountName`. + */ +export interface CreateCashAccountRequest { + accountName: string + cashAccountTypeName: string + accountNumber?: string | null + currencyCode?: string +} + +/** + * `POST /bank-accounts` / `POST /cash-accounts` response (retrofit 2026-07-31) — since the GL account + * is now auto-created rather than caller-supplied, the created leaf account (nested under its + * auto-created/reused header via `parentAccount`) is returned under `glAccount` so the caller can see + * exactly what was generated. `glAccount`/`glAccountId` are confirmed from the reference doc; the + * other fields are inferred (they mirror the create request's own fields plus an id, following this + * project's usual `` response convention). + */ +export interface CreateCashOrBankAccountResponse { + accountName: string + bankName?: string | null + cashAccountTypeName?: string | null + accountNumber?: string | null + currencyCode: string + glAccountId: number + glAccount: GlAccount & { parentAccount?: GlAccount | null } +} + +/** `GET /cash-account-types` row — flat reference list (seeded Petty Cash / Till Cash / Safe Cash / Cash in Transit, grows over time via on-the-fly creation from the create form). */ +export interface CashAccountType { + cashAccountTypeId: number + name: string +} + +/** Shared `{ items, totalCount, page, pageSize }` list envelope used by every Cheque Management list endpoint. */ +export interface GlPagedResult { + items: T[] + totalCount: number + page: number | null + pageSize: number | null +} + +// --------------------------------------------------------------------------- +// Cheque Management (new GL module, added 2026-07-30, beyond the original plan). +// Purely operational tracking — no endpoint here ever creates/touches a journal entry itself. +// `branchId`/`companyId`/`payeeId`/`voucherId`/`referenceId` are documented as deliberately +// "loose references" (plain unvalidated numbers) — no Branch/Company/Customer/Supplier table +// exists in this GL service for them to point at, so the frontend takes them as free-entry +// numbers rather than picker dropdowns, matching GL's own stated design. +// --------------------------------------------------------------------------- + +export enum PayeeType { + Supplier = "Supplier", + Customer = "Customer", + Employee = "Employee", + Other = "Other", +} + +export enum ReceivedFromType { + Customer = "Customer", + Supplier = "Supplier", + Other = "Other", +} + +export enum ChequeBookStatus { + Active = "Active", + Completed = "Completed", + Cancelled = "Cancelled", +} + +export enum ChequePageIssueStatus { + Unused = "Unused", + Issued = "Issued", + Cleared = "Cleared", + Bounced = "Bounced", + Cancelled = "Cancelled", + Void = "Void", +} + +/** `PUT /cheque-pages/{chequeNo}/status`'s `action` values. */ +export enum ChequePageStatusAction { + Clear = "Clear", + Bounce = "Bounce", + Cancel = "Cancel", + Void = "Void", +} + +export enum ReceivedChequeStatus { + Received = "Received", + Deposited = "Deposited", + Cleared = "Cleared", + Returned = "Returned", + Cancelled = "Cancelled", +} + +/** `PUT /received-cheques/{id}/status`'s `action` values. */ +export enum ReceivedChequeStatusAction { + Deposit = "Deposit", + Clear = "Clear", + Return = "Return", + Cancel = "Cancel", +} + +/** + * A single leaf of a Cheque Book. GL's own reference confirms every field named in the `issue` + * request body plus `issueStatus`/`printedAt`/`clearedDate`/`clearedByBank`/`cancelReason` in + * prose — this type is built from those, not a guessed shape. `chequeNo` (not a numeric id) is + * the documented identifying value for `GET/PUT /cheque-pages/{chequeNo}`, so it's used as the + * key/URL param throughout rather than an unconfirmed `chequePageId`. + */ +export interface ChequePage { + chequeNo: string + chequeBookNo?: string + issueStatus: ChequePageIssueStatus + payeeType: PayeeType | null + payeeId: number | null + payeeName: string | null + issueDate: string | null + amount: number | null + currencyCode: string | null + voucherId: number | null + referenceNo: string | null + purpose: string | null + isCrossCheque: boolean | null + isAccountPayee: boolean | null + isPostDated: boolean | null + notes: string | null + printedBy: string | null + printedAt: string | null + clearedDate: string | null + clearedByBank: boolean | null + cancelReason: string | null +} + +/** + * A cheque book issued from this company's own supply. `chequeBookNo` (caller-supplied, unique) + * is the documented identifying value for `GET /cheque-books/{chequeBookNo}`, used as the + * key/URL param throughout. `pages[]` is only populated when fetched with `?expand=pages`. + */ +export interface ChequeBook { + chequeBookNo: string + branchId: number + bankAccountId: number + startChequeNo: string + endChequeNo: string + totalLeaves: number + receivedDate: string + description: string | null + createdBy: string | null + status: ChequeBookStatus + pages: ChequePage[] +} + +export interface CreateChequeBookRequest { + branchId: number + bankAccountId: number + chequeBookNo: string + startChequeNo: string + endChequeNo: string + totalLeaves: number + receivedDate: string + description?: string + createdBy?: string +} + +export interface IssueChequePageRequest { + payeeType: PayeeType + payeeId?: number + payeeName: string + issueDate: string + amount: number + currencyCode?: string + voucherId?: number + referenceNo?: string + purpose?: string + isCrossCheque?: boolean + isAccountPayee?: boolean + isPostDated?: boolean + notes?: string + printedBy?: string +} + +export interface UpdateChequePageStatusRequest { + action: ChequePageStatusAction + /** Required only for `action: "Clear"`. */ + clearedDate?: string + /** Required only for `action: "Cancel"`. */ + cancelReason?: string + performedBy?: string +} + +/** + * A cheque received from a customer/supplier/other party — deliberately has no link to a + * `ChequeBook` (it isn't one of this company's own). GL's reference uses a numeric `{id}` in the + * URL for `GET/PUT /received-cheques/{id}` without spelling out the JSON field's exact name — + * `receivedChequeId` follows this project's consistent `Id` convention (e.g. `assetId`, + * `disposalId`), not a confirmed literal. + */ +export interface ReceivedCheque { + receivedChequeId: number + companyId: number + branchId: number | null + receivedFromType: ReceivedFromType + receivedFromId: number | null + receivedFromName: string + drawerBankName: string | null + drawerBankBranch: string | null + accountHolderName: string | null + chequeNo: string + chequeDate: string + amount: number + receivedDate: string + referenceType: string | null + referenceId: number | null + notes: string | null + createdBy: string | null + status: ReceivedChequeStatus + depositBankAccountId: number | null + depositDate: string | null +} + +export interface CreateReceivedChequeRequest { + companyId: number + branchId?: number + receivedFromType: ReceivedFromType + receivedFromId?: number + receivedFromName: string + drawerBankName?: string + drawerBankBranch?: string + accountHolderName?: string + chequeNo: string + chequeDate: string + amount: number + receivedDate: string + referenceType?: string + referenceId?: number + notes?: string + createdBy?: string +} + +export interface UpdateReceivedChequeStatusRequest { + action: ReceivedChequeStatusAction + /** Required only for `action: "Deposit"`. */ + depositBankAccountId?: number + /** Required only for `action: "Deposit"`. */ + depositDate?: string + notes?: string + performedBy?: string +} diff --git a/docs/00-CORE.md b/docs/00-CORE.md index 1d2d258..428709a 100644 --- a/docs/00-CORE.md +++ b/docs/00-CORE.md @@ -45,7 +45,9 @@ erp-monorepo/ ├── 02-SECURITY.md # accepted-risks register + per-feature security checklist ├── 10-BACKEND-PHASE1.md # backend spec: SRS + ER/entities + tech + architecture ├── 11-BACKEND-PHASE1.md # backend API reference (complete req/res) - └── 20-FRONTEND.md # frontend user-flows + architecture rules + validation posture + ├── 12-GENERAL-LEDGER-INTEGRATION.md # ERPCore ↔ external General Ledger service (transport only) + ├── 20-FRONTEND.md # frontend user-flows + architecture rules + validation posture + └── 21-GENERAL-LEDGER-FRONTEND.md # Ledgers section: reports UI + cash/bank accounts ``` The `Backend/ERPCore/` internal layout is created in §5.3. @@ -340,6 +342,8 @@ All frontend work is governed by `20-FRONTEND.md`. | API endpoints, request/response shapes, error catalog, enums (Phase 1) | **`11-BACKEND-PHASE1.md`** | | HRM requirements, business rules, entities, ER model (Phase 2) | **`12-BACKEND-HRM.md`** | | HRM API endpoints, request/response shapes, error catalog (Phase 2) | **`13-BACKEND-HRM-API.md`** | +| Connecting to the external General Ledger service (proxy, config, API key) | **`12-GENERAL-LEDGER-INTEGRATION.md`** | +| The Ledgers frontend section (reports, cash/bank accounts) | **`21-GENERAL-LEDGER-FRONTEND.md`** | | Frontend user-flows, screen flow, architecture rules, validation posture (Phase 1) | **`20-FRONTEND.md`** | | HRM frontend user-flows (Phase 2) | **`21-FRONTEND-HRM.md`** | | Manufacturing requirements, business rules, entities, stock/costing integration, API (Phase 2) | **`30-BACKEND-PHASE2.md`** | diff --git a/docs/01-DOC-GUIDE.md b/docs/01-DOC-GUIDE.md index f353525..ac7e22f 100644 --- a/docs/01-DOC-GUIDE.md +++ b/docs/01-DOC-GUIDE.md @@ -38,10 +38,12 @@ | `11-BACKEND-PHASE1.md` | High | Backend **API reference**: every endpoint with complete request/response, error catalog, enums. | Any API contract / controller / client work (Phase 1). | Claude + humans | | `12-BACKEND-HRM.md` | High | HRM backend spec: SRS, ER model, HRM-specific architecture notes. Schema is **authoritative** here. | Any HRM model / business-rule / requirement work (Phase 2). | Claude + humans | | `13-BACKEND-HRM-API.md` | High | HRM **API reference**: every endpoint, error catalog additions, enums. | Any HRM API contract / controller work. | Claude + humans | +| `12-GENERAL-LEDGER-INTEGRATION.md` | High | ERPCore ↔ external **General Ledger service**: connection/proxy contract, config, progress. GL's own endpoint contract lives in the GL service's own repo, not here. | Any work touching the GL proxy or a future internal GL caller. | Claude + humans | | `20-FRONTEND.md` | High | Frontend **user-flows**, architecture rules to follow, **validation posture**. | Any frontend work (Phase 1). | Claude + humans | | `21-FRONTEND-HRM.md` | High | HRM frontend **user-flows**, screens, validation specifics. | Any HRM frontend work. | Claude + humans | | `30-BACKEND-PHASE2.md` | High | Manufacturing (Production Lines) backend: SRS, ER model, status machines, stock/costing integration, **and** the full API contract — model and API in one doc, unlike Phase 1. Schema is **authoritative** here. | Any manufacturing model / rule / API work. | Claude + humans | | `21-FRONTEND-PHASE2.md` | High | Manufacturing frontend **user-flows**: template canvas builder, run board, run execution screens. | Any manufacturing frontend work. | Claude + humans | +| `21-GENERAL-LEDGER-FRONTEND.md` | High | **Ledgers** sidebar section: statutory-format report screens + PDF download, Cash/Bank Accounts (list/create; edit gap explained). Extends `20-FRONTEND.md` rather than duplicating it. | Any work on `app/dashboard/ledgers/*`. | Claude + humans | | `Backend/PROGRESS.md` | Low | Backend **change checklist**, git-shared. | After making backend changes. | **Claude** | | `Frontend/PROGRESS.md` | Low | Frontend **change checklist**, git-shared. | After making frontend changes. | **Claude** | diff --git a/docs/12-GENERAL-LEDGER-INTEGRATION.md b/docs/12-GENERAL-LEDGER-INTEGRATION.md new file mode 100644 index 0000000..a827537 --- /dev/null +++ b/docs/12-GENERAL-LEDGER-INTEGRATION.md @@ -0,0 +1,156 @@ +# 12 · GENERAL LEDGER INTEGRATION — ERPCore ↔ External GL Service + +> **Navigation:** you arrived from `00-CORE.md`. This doc is the **connection layer only** — the transport between ERPCore and the external General Ledger service. It is not the GL service's own API contract: every endpoint, request/response shape, and error code the GL service exposes is documented in that service's own repo (`04_API_Reference_And_Scenarios.md`, its `01_Full_Development_Plan.md`/`02_Phase_By_Phase_Development_Plan.md`/`03_Progress_Tracker.md` companions, and its Postman collection) — ERPCore does not duplicate that content here (`01-DOC-GUIDE.md` §5, single source of truth per topic). +> **Record work:** `Backend/PROGRESS.md`. + +--- + +## 1. What this is + +The General Ledger service is a **separate ASP.NET Core microservice** — its own repo, own database, no UI, no end-user login. It is called server-to-server, authenticated with a single shared secret (`X-Api-Key`), by "the core backend" — which, from this repo's side, is ERPCore. + +This pass connects the two systems at the **transport level only**: + +- A generic reverse-proxy endpoint on ERPCore (`/api/v1/gl/*`) that the frontend can call, which forwards the request to the GL service and returns its response unchanged. +- A service-layer function (`IGeneralLedgerService.ForwardAsync`) that does the actual forwarding — usable today by the controller, and **intended to be called directly by other ERPCore services later** (GRN confirm, adjustments, etc. posting real journal entries into GL instead of — or alongside — the local `JournalEntryStub`). That internal wiring is **explicitly deferred**; nothing in ERPCore calls GL yet except the proxy itself. + +There is **no GL-specific business logic, no typed DTOs, and no per-endpoint validation** in ERPCore for this integration. Every request under `/api/v1/gl/*` is forwarded byte-for-byte — method, path, query string, request body, and `Content-Type` — and GL's response (status code, content type, body) comes back exactly as GL sent it, un-reshaped. + +--- + +## 2. Architecture + +``` +Frontend ──► ERPCore /api/v1/gl/{**path} (ErpAccess door policy, same as every other v1 endpoint) + │ + ▼ + GeneralLedgerController (Controllers/GeneralLedgerController.cs) + │ Request.Method, path, QueryString, ContentType, Body — untouched + ▼ + IGeneralLedgerService.ForwardAsync (Services/GeneralLedgerService.cs) + │ the one function — controller and future internal callers both use this + ▼ + IGeneralLedgerClient.SendAsync (Infra/Gl/GeneralLedgerClient.cs) + │ attaches X-Api-Key, streams body through, no parsing + ▼ + External GL service (GeneralLedgerService:BaseUrl) +``` + +**Why a generic proxy and not typed endpoints:** the GL service's own reference (`04_API_Reference_And_Scenarios.md`) documents ~15 modules and 40+ endpoint variations (Accounts, Fiscal Calendar, Currency, Cost Centers, Journal Entries, Recurring Entries, Tax, Fixed Assets, Bank, Budget, Reporting, System Config, Audit Log). Modelling all of that as ERPCore DTOs before any of it is actually consumed would be premature — this pass connects the pipe; the next pass (deferred, see §6) picks specific GL calls to wire into specific ERPCore workflows and can build typed request/response DTOs for exactly those calls at that point. + +**Layering matches the existing AuthHex integration** (`Infra/Auth/AuthHex/IAuthHexClient` → `Services/Auth/*` → `AuthController`), except AuthHex's client unwraps a known envelope into typed results, while GL's client deliberately does not — see §4. + +--- + +## 3. Configuration + +`Backend/ERPCore/appsettings.json`: + +```json +"GeneralLedgerService": { + "BaseUrl": "https://localhost:7024/api/v1/", + "ApiKey": "" +} +``` + +| Key | Purpose | +|---|---| +| `GeneralLedgerService:BaseUrl` | The GL service's base URL, **including** `/api/v1/` and a trailing slash (so relative paths combine correctly against `HttpClient.BaseAddress`). GL's own docs note it calls `UseHttpsRedirection()` before its API-key check runs — use the `https://` URL directly, per GL's own integration guide §3, to avoid every call taking a `307` round-trip. | +| `GeneralLedgerService:ApiKey` | The shared secret sent as `X-Api-Key` on every forwarded call. **Ships blank** — same pattern as this project's own `ApiKey`-style secrets (02-SECURITY AR-06): get a value from the GL service's own `POST /api/v1/dev-tools/generate-api-key` (Development only) and paste it in here *and* into the GL service's own `ApiKey:Value` config — it is one shared string on both sides, not a per-caller credential. | + +Not touched by this pass: `appsettings.Development.json` / `appsettings.Production.json` — fill in a real key locally the same way `AuthHex:BaseUrl` and other per-environment values are handled today (edit the file directly for local dev; environment-variable override for prod, per `00-CORE.md §5.4`'s secrets note). + +--- + +## 4. The proxy contract + +### `{GET|POST|PUT} /api/v1/gl/{**path}` + +- **Auth:** requires a valid ERPCore session (AuthHex-issued token, `erp_at` cookie or Bearer header) satisfying the `ErpAccess` door policy — identical to every other `/api/v1/*` endpoint (`ApiControllerBase`). The GL `X-Api-Key` itself is attached **server-side only**; the frontend never sees it and cannot set it. +- **Method:** only `GET`/`POST`/`PUT` are exposed — the GL service's own API reference has no `PATCH` or `DELETE` endpoint anywhere in its surface, so those verbs aren't wired. +- **`{**path}`:** everything after `/api/v1/gl/` is forwarded as-is to the GL service's own `/api/v1/{path}` — e.g. a frontend call to `POST /api/v1/gl/journal-entries` reaches GL's `POST /api/v1/journal-entries`. Query string is forwarded unchanged. +- **Body:** for `POST`/`PUT`, the raw request body (and its `Content-Type` header) is streamed straight through — this is what makes the one `multipart/form-data` endpoint (bank statement import) work through the proxy without ERPCore needing to understand multipart at all. +- **Response:** GL's status code, `Content-Type`, and body are returned to the frontend **unchanged**. This deliberately preserves two documented GL quirks rather than papering over them: + - GL's success bodies are camelCase (`{"statusCode":200,...}`), its error bodies (from its own exception/API-key middleware) are PascalCase (`{"StatusCode":400,...}`) — GL's own docs flag this as a known inconsistency, not fixed on their side yet. ERPCore does not normalize it; the frontend must handle both shapes (case-insensitive deserialization), same as GL's own integration guide recommends to *its* callers. + - `outputFormat=Json` report amounts keep full decimal precision (no rounding) — since ERPCore never deserializes the body into its own model, nothing here can accidentally truncate it. +- **This proxy needs zero code changes whenever GL's own domain contract evolves — confirmed again as of GL's 2026-07-22 revision (§7).** Five reports were restructured, `outputFormat` gained a `Csv` value, Cash/Bank accounts split into two endpoints, and numerous fields were renamed from numeric IDs to business codes (`CLAUDE.md` Rule 8.2 on GL's side) — none of it touched this file. That's the entire point of a byte-for-byte proxy over typed per-endpoint DTOs (§2's rationale): a generic passthrough only ever needs a code change when the *transport* contract changes (new HTTP verb, new content type, new auth mechanism), never when GL's own request/response payloads gain, lose, or rename fields. §7 is a curated reference of what's actually being called today, kept for the frontend team's convenience — it is documentation, not something this proxy depends on or needs updated in lockstep with. + +### Failure modes added by ERPCore itself + +| Case | Status | `code` | +|---|---|---| +| GL service unreachable (connection refused/DNS/etc.) | 503 | `GL_SERVICE_UNAVAILABLE` | +| GL service timed out | 503 | `GL_SERVICE_UNAVAILABLE` | +| No/invalid ERPCore session | 401/403 | (standard ERPCore door-policy response — request never reaches the proxy) | + +Everything else — `401` for a bad `X-Api-Key` (can't happen here since ERPCore always attaches the configured key, but a misconfigured/blank key on either side would surface as this), every domain `400`/`404`/`409`/`422` GL itself returns — passes straight through with GL's own body and message, untouched. + +--- + +## 5. What is *not* done in this pass + +- **No internal service calls into GL.** `IGeneralLedgerService.ForwardAsync` exists and is registered in DI, but no ERPCore service (GRN, Adjustment, Transfer, PO, etc.) calls it yet. The local `JournalEntryStub` (docs/10 §C.7, FR-STK-13) is untouched and remains the only GL-adjacent artifact those flows produce today. +- **No typed request/response DTOs** for any GL endpoint — the proxy is byte-for-byte, so nothing in ERPCore currently understands GL's schema. +- **No path allowlist.** The proxy forwards *any* path under `/api/v1/gl/` to GL — it trusts GL's own routing/auth to reject anything invalid. Acceptable for now because the proxy is still gated by ERPCore's own door policy (only ERP-admitted users reach it at all) and GL requires its own valid `X-Api-Key` regardless, but worth revisiting alongside per-endpoint RBAC (02-SECURITY Part D) if GL exposes anything sufficiently destructive to warrant narrowing. +- **No `appsettings.Development.json`/`appsettings.Production.json` changes** — only the base `appsettings.json` shape was added, per this pass's scope (connect the pipe, not configure every environment). +- **No CORS/rate-limiting review specific to this proxy** — it inherits whatever ERPCore already has (currently none, same accepted gap as `AuthController`, 02-SECURITY AR-08). + +--- + +## 6. Progress + +- [x] **Transport wired (2026-07-20).** `Infra/Gl/{IGeneralLedgerClient,GeneralLedgerClient,GeneralLedgerResponse}` — typed `HttpClient` (`GeneralLedgerService:BaseUrl`), attaches `X-Api-Key` (`GeneralLedgerService:ApiKey`), streams request/response bodies through unparsed. `Services/{Interfaces/IGeneralLedgerService,GeneralLedgerService}` — the shared forwarding function. `Controllers/GeneralLedgerController` — `GET|POST|PUT /api/v1/gl/{**path}`, `ErpAccess`-gated like every other v1 controller. Config keys added to `appsettings.json`. Build verified clean (`dotnet build`, 0 warnings/0 errors). +- [ ] **Live smoke test against a running GL instance** — not yet run in this pass (no GL instance available in this session). Before relying on this in anger: generate a dev API key from GL's `POST /api/v1/dev-tools/generate-api-key`, put it in both sides' config, and round-trip at least one call per HTTP verb (e.g. `GET /api/v1/gl/accounts`, `POST /api/v1/gl/accounts`, `PUT /api/v1/gl/accounts/{code}`) plus the multipart import call, to confirm the byte-for-byte passthrough holds in practice (headers, streaming, status codes). +- [ ] **Internal wiring** — pick the first real ERPCore→GL use case (most likely candidate: posting `FifoCostingService`/`StockMutator`-driven movements as real GL journal entries instead of `JournalEntryStub` rows) and build the typed request/response DTOs + service calls for that specific flow through `IGeneralLedgerService`. Deliberately deferred per this pass's scope. +- [ ] **Security pass once real traffic flows** — revisit the "no path allowlist" note in §5, decide whether `GeneralLedgerService:ApiKey` needs to move to a secret store before any shared/staging use (same trigger as `02-SECURITY.md` AR-06), and whether this proxy needs its own accepted-risk entry there. + +--- + +## 7. Endpoint reference — GL endpoints currently used (or planned) by the frontend + +**Purpose of this section:** a quick-reference summary of exactly which GL endpoints the frontend calls, for connecting new screens without re-reading GL's full `04_API_Reference_And_Scenarios.md` from scratch each time. **This is a curated summary, not the canonical contract** — for exact request/response shapes, every field, and every error case, GL's own reference stays authoritative (`01-DOC-GUIDE.md §5`). Every call below goes through this proxy at `/api/v1/gl/{path}` (drop the leading `/api/v1` from GL's own documented paths, prefix `/api/v1/gl` instead — e.g. GL's `GET /api/v1/reports` is called here as `GET /api/v1/gl/reports`). + +As of GL's 2026-07-22 revision. Full detail for anything marked "see GL §X" is in GL's `04_API_Reference_And_Scenarios.md` at that section. + +### Reporting (`docs/21` §3 — all seven Ledgers report screens) + +| Method | Path | Used for | Key params | +|---|---|---|---| +| `GET` | `/reports` | All seven report screens, one shared endpoint | `reportType` (`GeneralLedger`\|`TrialBalance`\|`BalanceSheet`\|`ProfitAndLoss`\|`CashFlow`\|`BudgetVsActual`\|`TaxSummary`), `outputFormat` (`Json`\|`Pdf`\|`Csv`), plus report-specific params — see GL §"GET /reports" for the full per-`reportType` table | + +One endpoint, one row — every report screen and both download buttons (`DownloadPdfButton`/`DownloadCsvButton`) call this same path with different query parameters. Nothing else in this module hits a second reporting endpoint. + +### Accounts (`docs/21` §3/§4 — GL-account pickers only, never a screen of its own here) + +| Method | Path | Used for | Key params | +|---|---|---|---| +| `GET` | `/accounts` | Populates the `glAccountCode` picker on the Bank/Cash create forms | none required — full list | + +This module never creates, edits, or has a dedicated screen for GL's own Chart of Accounts — `GET /accounts` is called purely to feed a `code — name` dropdown elsewhere. + +### Bank & Cash Accounts (`docs/21` §4) + +| Method | Path | Used for | Key params | +|---|---|---|---| +| `GET` | `/bank-accounts` | Unified Cash+Bank list page | `accountType` (optional — `Cash`\|`Bank`\|`Both`, default `Both`) | +| `POST` | `/bank-accounts` | Create form, "Bank" selected | `accountName`, `bankName`/`accountNumber` (optional), `glAccountCode`, `currencyCode` (optional) | +| `POST` | `/cash-accounts` | Create form, "Cash" selected | `accountName`, `cashAccountTypeName`, `accountNumber` (optional, auto-generated if omitted), `glAccountCode`, `currencyCode` (optional) | +| `GET` | `/cash-account-types` | Populates the Cash Account Type picker on the create form | none — full list | +| `POST` | `/bank-accounts/{id}/statement-lines/import` | Not yet built on the frontend — bank statement `.xlsx` import, `multipart/form-data` | field name `file` | +| `PUT` | `/bank-statement-lines/{id}/reconcile` | Not yet built on the frontend — reconcile a statement line | `matchedJournalNo` | + +No `GET`/`PUT` by id exists on GL's side for either `bank_account` or `cash_account` — this is the entire reason edit can't be built yet (`docs/21` §4's known gap). + +### Budgets (`docs/21` §3 — picker only) + +| Method | Path | Used for | Key params | +|---|---|---|---| +| `GET` | `/budgets` | Populates the `budgetId` picker on the Budget vs Actual report screen | none — full list | + +### Not currently called by this frontend, listed for awareness + +GL exposes a substantially larger surface than this module touches — Journal Entries, Fiscal Calendar, Cost Centers, Currency, Tax Codes, Fixed Assets, Recurring Templates, System Config, Audit Log. None of these have a screen in `docs/21` today. If a future pass adds one, add its row to the relevant table above rather than leaving this reference to drift out of sync with what's actually called — that's the whole value of keeping this section current. + +--- + +*End of 12-GENERAL-LEDGER-INTEGRATION.md. Hub: `00-CORE.md`. Record work: `Backend/PROGRESS.md`.* diff --git a/docs/21-GENERAL-LEDGER-FRONTEND.md b/docs/21-GENERAL-LEDGER-FRONTEND.md new file mode 100644 index 0000000..c89cdbb --- /dev/null +++ b/docs/21-GENERAL-LEDGER-FRONTEND.md @@ -0,0 +1,532 @@ +# 21 · GENERAL LEDGER — Frontend (Ledgers section) + +> **Navigation:** you arrived from `00-CORE.md`. The transport this section calls through is +> `docs/12-GENERAL-LEDGER-INTEGRATION.md` (ERPCore's `/api/v1/gl/*` proxy into the external General +> Ledger service — that doc's new §7 has a curated endpoint reference for everything this page uses). +> General frontend architecture/validation rules are `20-FRONTEND.md` — this doc only adds what's +> specific to the Ledgers screens. Record work in `Frontend/PROGRESS.md`. +> **GL's own endpoint contract** (exact request/response shapes, error cases) lives in the General +> Ledger service's own repo (`04_API_Reference_And_Scenarios.md`) — not duplicated here in full, per +> `01-DOC-GUIDE.md §5`'s single-source-of-truth rule; `docs/12` §7 is a summary for quick reference, +> that doc is the canonical detail. + +--- + +## 0. Major update, 2026-07-22 — the GL backend changed substantially since this section was last built + +**Nothing in this pass has been implemented against the frontend codebase yet.** The 2026-07-20 build (§6's history) reflects an earlier, now-superseded GL contract. This revision describes the *target* design against the confirmed, live-verified-on-GL's-side contract as of 2026-07-22 — every section below should be read as "what to build," not "what exists," until §6 says otherwise. + +Three things changed on GL's side, in order of how much they affect this doc: + +1. **Five reports got real structural rework** (not just field renames) — Trial Balance flattened, Profit & Loss restructured into named sections, Cash Flow's display simplified, Tax Report **completely redesigned** into an Income Tax Computation (previously a VAT/WHT/NBT summary), plus a new `outputFormat=Csv` on all seven reports. +2. **Cash and Bank accounts are two separate GL tables/endpoints now**, not one table with a type field — `POST /bank-accounts` (unchanged) and a new `POST /cash-accounts`, unified for reading via `GET /bank-accounts?accountType=Cash|Bank|Both`. +3. **`CLAUDE.md` Rule 8.2 renamed numeric ID fields to business codes across most of GL's API** — the one that reaches this page: `GeneralLedger`'s `accountId` param is now `accountCode` (still optional, same two-mode behavior as before), and the Bank/Cash create forms' `glAccountId` is now `glAccountCode`. + +--- + +## 1. What this is + +A new **Ledgers** sidebar section (`app/dashboard/ledgers/*`) giving the frontend statutory-format +financial reports and cash/bank-account management, sourced entirely from the external General Ledger +service via ERPCore's generic proxy (`docs/12-GENERAL-LEDGER-INTEGRATION.md`). Every screen calls +`GET /api/v1/gl/reports` or `/gl/bank-accounts`/`/gl/cash-accounts` — there is no ERPCore business +logic behind any of it yet (that internal wiring, e.g. posting real journal entries from +GRN/adjustments, is tracked separately and deliberately deferred, see `docs/12` §6). + +**Sidebar structure** (`components/Layouts/AppSidebar.tsx`, mirrored server-side in +`Backend/ERPCore/Infra/Persistence/Configurations/{NavItem,SubNavItem,Permission}Configuration.cs` +per the existing RBAC-nav convention, docs/10 C.8/C.9) — **gains one entry, Tax Report:** + +``` +Ledgers +├── Trial Balance /dashboard/ledgers/trial-balance +├── Balance Sheet /dashboard/ledgers/balance-sheet +├── General Ledger /dashboard/ledgers/general-ledger +├── Profit & Loss /dashboard/ledgers/profit-and-loss +├── Cash Flow /dashboard/ledgers/cash-flow +├── Budget vs Actual /dashboard/ledgers/budget-vs-actual +├── Tax Report /dashboard/ledgers/tax-report (new) +└── Cash / Bank Accounts /dashboard/ledgers/bank-accounts (+ /new) +``` + +`/dashboard/ledgers` itself is a card-grid hub, same pattern as `/dashboard/stock` — gains an 8th card. + +--- + +## 2. Transport: a dedicated GL client, not `lib/api-client.ts` + +`lib/api/general-ledger.ts` is a **separate** fetch client from the one every other screen in this +app uses (`lib/api-client.ts`'s `apiRequest`/`apiRequestWithETag`). Reason: those assume ERPCore's +own RFC 7807 `ProblemDetails` error shape and a bare-DTO success body. The GL service wraps **every** +response — success and error alike — in its own `{ statusCode, success, message, data }` envelope, +and (a documented GL quirk, carried through the proxy unchanged per `docs/12` §4) success bodies are +camelCase while error bodies are PascalCase. `glRequest()` unwraps both casings itself and throws a +`GlApiError` shaped `{ status, detail }` — duck-type compatible with `lib/error-map.ts`'s +`ApiErrorLike`, so `errorMessage()`/toasts work unchanged across both API surfaces. + +All calls are relative to `/api/v1/gl/*` — same-origin through the existing Next `rewrites()` proxy +(`next.config.ts`) → ERPCore → the GL service. No new proxy config was needed, and **still isn't** for +any of this revision's changes — ERPCore's `GeneralLedgerController` (docs/12) is a byte-for-byte +passthrough that never inspects GL's own field names or report contents, so every rename/restructure +described in this doc requires zero ERPCore-side change, only frontend-side (`docs/12` §4's new note +on this). + +**No ETag/If-Match anywhere in this module** — the GL service's own reference documents no +concurrency tokens on any of the endpoints this UI calls. + +--- + +## 3. Reports: "Sri Lankan Standard" report UI + +Every report screen (`app/dashboard/ledgers/{trial-balance,balance-sheet,general-ledger,profit-and-loss,cash-flow,budget-vs-actual,tax-report}/page.tsx`) +shares three building blocks: + +- **`components/reports/ReportHeader.tsx`** — a centered statutory header block: small-caps + "General Ledger" eyebrow, the report's **LKAS-aligned statement name** (not always GL's own + `reportType` value — see the mapping below), the as-at/for-period line, and a currency note. This + is the "Sri Lankan Standard report UI" requested: the on-screen equivalent of the formal + company-financial-statement layout (title block, period line, right-aligned money columns, + bold/indented subtotal rows), not a bespoke ad-hoc table per screen. **The Tax Report screen does + not use this component** — see its own entry below, it needs a fuller identity block GL's own PDF + gives that report alone. +- **`components/reports/DownloadPdfButton.tsx`** — re-issues the *exact same* report call with + `outputFormat=Pdf` instead of `Json`, base64-decodes `data.contentBase64` client-side into a + `Blob`, and triggers a browser download. +- **`components/reports/DownloadCsvButton.tsx`** *(new)* — identical mechanism, `outputFormat=Csv` + instead, `Blob` typed `text/csv`, triggers a `.csv` download. Sits next to the PDF button on every + screen — two download buttons now, not one. No proxy/transport concern either (`docs/12` §7) — same + passthrough as `Pdf` always was. + +| Screen | `reportType` | On-screen title | Required params | Response shape | +|---|---|---|---|---| +| Trial Balance | `TrialBalance` | Trial Balance | `asOfDate` | **Flat** array `{accountCode, accountName, debit, credit}` — no `depth` anymore | +| Balance Sheet | `BalanceSheet` | Statement of Financial Position | `asOfDate` | Unchanged — hierarchical array `{depth, lineItem, accountType, balance}`, always ends with a synthetic `"Current Year Earnings"` row under Equity | +| General Ledger | `GeneralLedger` | General Ledger | `periodStart`, `periodEnd` (`accountCode` optional — renamed from `accountId`, see below) | Unchanged shape | +| Profit & Loss | `ProfitAndLoss` | Statement of Profit or Loss | `periodStart`, `periodEnd` | **Nested object**, not a flat array — named sections, see below | +| Cash Flow | `CashFlow` | Statement of Cash Flows | `periodStart`, `periodEnd` | Nested object; `workingCapitalChanges[]` gained `direction`; `openingCashBalance`/`closingCashBalance` still returned, not displayed | +| Budget vs Actual | `BudgetVsActual` | Budget vs Actual | `budgetId` | Unchanged | +| Tax Report *(new)* | `TaxSummary` | Income Tax Computation | `periodStart`, `periodEnd`; optional `allowableDeductions`, `otherTaxableIncome`, `qualifyingPaymentsReliefs`, `surchargeAmount`, `taxRateOverride` | Single flat object, see below | + +**Defaults, so a screen is never blank on first load:** `asOfDate`/`periodEnd` default to today, +`periodStart` to the 1st of the current month (`lib/format.ts`'s `todayIso`/`startOfMonthIso`) — +these params are *required* by GL (400 if missing), so the UI always sends something sensible rather +than erroring on mount. The Tax Report's five optional parameters get **no forced client-side +default** — an untouched field sends nothing, letting GL's own server-side defaulting (`0` for four +of them, `system_config`-driven for `qualifyingPaymentsReliefs`/the tax rate) be the single source of +truth for what "not supplied" means. + +**`reportType`/`outputFormat` are TS enums** (`types/general-ledger.ts`'s `ReportType`, +`ReportOutputFormat`) — `ReportOutputFormat` gains a `Csv` member. `GlAccount.accountTypeId` stays a +`GlAccountTypeId` enum (`Asset=1`…`Expense=5`). + +**General Ledger: `accountId` renamed to `accountCode` (GL's `CLAUDE.md` Rule 8.2), behavior +unchanged from the 2026-07-20 correction.** GL's own reference still documents two modes: +`accountCode` supplied → "Account Ledger" (one account + its descendants, one running balance); +`accountCode` omitted → the **true General Ledger**, every `is_postable` account's own transactions +together, each with its own running balance that resets whenever the account changes, sorted by +`accountCode` then `entryDate`. This screen still always calls the second mode — +`reportsApi.generalLedger(periodStart, periodEnd)` never sends `accountCode` — and has no account +picker/input, same as before; only the underlying param name the client would use *if* a +single-account mode were ever added changed, not this screen's own behavior. + +**Amount formatting** (`lib/format.ts`): comma-grouped thousands + fixed 2 decimals + parentheses for +negatives (`formatAmount`) — standard financial-statement convention. **CSV export does not reuse +this formatter** — GL's own CSV cells are plain decimals with a leading minus sign, no thousands +separator, no parentheses (spreadsheet-numeric-parsing convention, not human-display convention). +`DownloadCsvButton` downloads GL's bytes unmodified, same "don't reshape what GL sent" posture as the +PDF button. + +**Hierarchical rows:** Balance Sheet still carries `depth`, rendered with `depth`-proportional left +padding. **Trial Balance dropped this entirely** — now a plain flat list, same row-component style as +Budget vs Actual. + +**Profit & Loss is a nested object, not a flat array.** GL's response has named sections — `sales`, +`costOfSales`, `otherIncome`, `distributionExpenses`, `administrationExpenses`, `otherExpenses`, +`financialExpenses`, `unclassified` (only present with lines if the COA has untagged Income/Expense +accounts — GL flags this as worth watching for during setup) — each `{ lines[], total }`, plus +top-level `grossProfit`/`netProfitForPeriod`. The screen renders one bordered section per non-empty +group, in this fixed order: Sales, Cost of Sales, **Gross Profit** (its own bold subtotal row, not a +section), Other Income, the four expense groups, `unclassified` last if present, then **Net Profit +for the Period**. + +**Cash Flow is a structured statement layout, not four `StatCard`s.** `Net Earnings` as its own line, +an "Additions to Cash" bordered section and a "Subtractions From Cash" bordered section — client-side +bucketed by sign from the combined `nonCashAdjustments[]` + `workingCapitalChanges[]` (a working-capital +line's label uses its `direction` field, e.g. `direction: "Decrease"` + `accountName: "Trade +Receivables"` → `"Decrease in Trade Receivables"`; a non-cash-adjustment line just prints its plain +`description`, e.g. `"Depreciation"`, no Increase/Decrease prefix) — then `Net Cash From Operations` +as a subtotal, Investing/Financing sections (their `lines[]`, no subtotal row when a section has only +one line), ending in the final combined total. `openingCashBalance`/`closingCashBalance` are fetched +(still in the response) but **not rendered anywhere on screen** — same "computed but not displayed" +posture GL's own PDF/CSV takes. + +**Tax Report (`app/dashboard/ledgers/tax-report/page.tsx`) is an entirely new screen.** Layout: +- A `periodStart`/`periodEnd` date-range picker, same component as every other period-based report. +- **A collapsible "Adjustments" panel**, collapsed by default, with five optional numeric inputs — + `Allowable Deductions`, `Other Taxable Income`, `Qualifying Payments / Reliefs`, + `Surcharge / Education Levy`, and `Tax Rate Override` (%). Each maps directly to the report call's + optional query params. +- Result: a two-column `Description`/`Amount` table in GL's own fixed order (`profitBeforeTax` through + `balanceTaxPayable`) — `Add:`/`Less:` prefixes are literal row labels the component renders per a + fixed lookup, not derived from the amount's sign. Bold rows for the reconciliation checkpoints + (`Adjusted Business Profit`, `Assessable Income`, `Taxable Income`, `Gross Tax Liability`, the final + total). +- **The final row's label depends on the sign of `balanceTaxPayable`** — GL's own PDF renders a + negative value (credits/payments exceeded the gross liability) as **"BALANCE TAX REFUNDABLE"**, not + a negative "payable" figure (confirmed live on GL's own seeded loss-making test data, + `03_Progress_Tracker.md`). The on-screen table should match this exactly: `balanceTaxPayable >= 0` → + label `"BALANCE TAX PAYABLE"`, amount as-is; `balanceTaxPayable < 0` → label + `"BALANCE TAX REFUNDABLE"`, amount shown as its absolute value (not in parentheses — GL's own PDF + changes the *label*, not the sign display, for this one row specifically). +- Uses its own header block, not the shared `ReportHeader` — GL's own PDF gives this one report a + fuller identity block (company name, address, TIN, BRN) via `Company:Address`/`Tin`/`Brn` config + values (`05_LKAS_Report_PDF_Templates.md` §0/§8, confirmed implemented server-side). **Open question, + genuinely unresolved:** GL exposes no endpoint returning these four values as data — they're + `appsettings.json` entries, read only by the PDF renderer. The on-screen React version needs the + *same* values from *somewhere*, and there's no way to fetch them from GL today. Two options, neither + picked here: (a) GL adds a small `GET /company-info`-style endpoint; (b) the frontend duplicates + these four values in its own config/env, accepting the risk of drifting out of sync with GL's + `appsettings.json` whenever one side changes without the other. Flag this for a decision before + building this screen's header — don't silently pick one. + +--- + +## 4. Cash / Bank Accounts + +`app/dashboard/ledgers/bank-accounts/page.tsx` (list) + `/new/page.tsx` (create). No delete — GL's +own reference has no delete endpoint for either concept, consistent with every other master in this +system (FR-MD-08's deactivate-not-delete posture, though GL doesn't even expose deactivate here). + +**Rework — Cash and Bank are separate GL tables/endpoints, not one table with a type field.** An +earlier design (drafted, never shipped on GL's side) proposed a single `bank_account.accountType` +discriminator; GL's team judged a cash account a *peer* concept to a bank account, not a *kind of* +bank account, and built two separate tables instead (`Accounting_System_Design_LKAS.md` §5.8). This +still satisfies the original requirement — **the create page only ever offers exactly two choices, +Cash or Bank, nothing else** — the two-choice constraint now lives in "which endpoint does the form +submit to," not "which value of a discriminator field." + +### The three endpoints this page now uses + +- **`POST /bank-accounts`** — unchanged in shape from the original 2026-07-18 design, except + `glAccountId` → `glAccountCode` (Rule 8.2). Fields: `accountName` (required), `bankName`/ + `accountNumber` (both optional/nullable — a Bank account can genuinely be created with these blank + and filled in later, unlike Cash's stricter rule below), `glAccountCode` (required), `currencyCode` + (optional, defaults `"LKR"`). +- **`POST /cash-accounts`** *(new)* — `accountName` (required), `cashAccountTypeName` (required — + matched case-insensitively against GL's `cash_account_type` reference table; a name with no + existing match **creates a new type on the fly**, so a frontend "Other, please specify" free-text + option becomes a permanent selectable choice for every future cash account created after it), + `accountNumber` (**optional** — if omitted, GL auto-generates a sequential `CASH-000001`-style + reference; if supplied, used as entered), `glAccountCode` (required), `currencyCode` (optional, + defaults `"LKR"`). +- **`GET /cash-account-types`** *(new)* — flat, unfiltered list, seeded with Petty Cash / Till Cash / + Safe Cash / Cash in Transit, growing over time. Feeds the create form's Cash Account Type dropdown. + +### Create form +A **two-choice toggle** at the top — **Cash** or **Bank**, backed by a `CashBankAccountType` TS enum +(`Cash`/`Bank`) — decides which of the two fieldsets below shows and which endpoint the form submits +to: + +- **Bank selected:** Bank Name + Account Number fields (both optional on this side — GL doesn't + enforce them as required for a Bank row), submits to `POST /bank-accounts`. +- **Cash selected:** a Cash Account Type `` picker (bank account form, and Budget vs Actual's budget picker) displayed the +selected item's **numeric value** after picking it, even though the correct id/code was genuinely +being sent to the server. Cause: this app's `` (with `label={...}` set correctly from the start, avoiding the + raw-number-display bug from §4's earlier fix) fed by `GET /cash-account-types`, an "Other, please + specify" free-text option, `glAccountCode` picker now keyed by the account's code string instead + of its numeric id. + - Cash/Bank list page — server-side `accountType` filter (`Both`/`Bank`/`Cash`, a `