CognitixERP Developer Guide

CognitixERP Developer Guide

Full architecture deep-dive for buyers and integrators — how the Blazor WebApp, API host, business modules, database, licensing, and customization paths fit together.

Version 1.0.0 Modular monolith .NET 10
Also in source: Source/CognitixERP/docs/Architecture.md (markdown mirror of this guide for IDE/Git workflows). Start here if you purchased on CodeCanyon and want one offline HTML reference.

1. Introduction

CognitixERP is a modular monolith ERP: one deployable API and one Blazor WebAssembly client. Business logic lives in backend modules; the UI talks to the API over HTTP and SignalR.

AudienceUse this guide for
Buyer / integratorUnderstanding folders, safe customization, where UI vs API vs DB code lives
Developer extending ERPAdding pages, endpoints, reports, permissions, module services
DevOpsHow WebApp config, JWT, CORS, uploads, and same-origin deploy relate — see also Production Guide
Prerequisites: .NET 10 SDK, Visual Studio 2022+ (or Rider), SQL Server / PostgreSQL / MySQL for local dev. Follow Installation Guide first to run API + WebApp and complete Setup Wizard.

2. Big picture

At runtime there are two processes (development) or one public site (production same-origin):

Browser │ ├─► Cognitix.WebApp (Blazor WASM static files) │ Pages/*.razor → services/* → HttpClient "Cognitix.API" │ └─► Cognitix.API (ASP.NET Core Kestrel / IIS) Controllers → Module Application services → EF DbContexts Middleware: JWT, license, branch, user context SignalR: /chat-hub (CRM) Static: /uploads/ (logos, files)
GoalHow CognitixERP achieves it
Clear module boundariesDomain / Application / Infrastructure per business area
Single deployable APIAll modules registered in Cognitix.API DI
UI decouplingWebApp references Shared.DTOs only — never module Domain
Buyer-friendly installSetup Wizard migrates 12 DbContexts — no dotnet ef required
Marketplace protectionLicensing ships as obfuscated DLLs in buyer ZIP (BuyerBuild)

Production same-origin (recommended)

https://yourcompany.com/           → WebApp (nginx / IIS static)
https://yourcompany.com/api/...    → API (reverse proxy)
https://yourcompany.com/uploads/   → file storage
https://yourcompany.com/chat-hub   → SignalR

WebApp ApiBaseUrl = site origin with trailing slash — do not append /api.

3. Solution structure

Open Source/CognitixERP/CognitixERP.sln in Visual Studio. Top-level layout:

CognitixERP.sln
├── apps/
│   └── Cognitix.WebApp                 # Blazor WASM + MudBlazor UI
│
├── src/
│   ├── Cognitix.API                    # HTTP host, controllers, PDF, middleware
│   ├── Cognitix.Billing
│   ├── Cognitix.Procurement
│   ├── Cognitix.Inventory
│   ├── Cognitix.POS
│   ├── Cognitix.Financials
│   ├── Cognitix.Banking
│   ├── Cognitix.CRM
│   ├── Cognitix.HRM
│   ├── Cognitix.Branching
│   ├── Cognitix.Compliance
│   ├── Cognitix.Users
│   ├── Cognitix.BiometricAgent         # Optional Windows HRM agent
│   └── Cognitix.CrossCuttingConcerns/
│       ├── Cognitix.Shared.DTOs
│       ├── Cognitix.SharedKernel
│       ├── Cognitix.Localization
│       ├── Cognitix.Notifications
│       ├── Cognitix.FileStorage
│       └── Cognitix.SyncContracts
│
├── lib/Cognitix.Licensing/             # Licensing DLLs (Setup Wizard, enforce, CognitiveCircle)
├── deploy/hetzner/                     # Linux nginx + systemd samples
├── tools/                              # Author migration scripts
├── test/                               # Unit, Integration, Performance, E2E
└── docs/
    └── Architecture.md

Important notes

  • Licensing is shipped as precompiled DLLs under lib/Cognitix.Licensing/ — there is no Licensing source project in the buyer package. Publish the API with -p:BuyerBuild=true so the host references those DLLs.
  • sync/ (offline SyncEngine) may exist on disk but is not in the active v1.0 web release.
  • There is no mobile client in v1.0.
  • Logging uses Serilog on the API host (not a separate logging module in production).
  • Package root Database/ holds buyer notes and support recovery scripts — not the EF migration source (those live under each module's Infrastructure).

4. Request flow (end-to-end)

Typical authenticated API call from a Blazor page:

  1. User opens route e.g. /billing/invoices → Razor page in Pages/Billing/
  2. Page injects a WebApp service e.g. IInvoiceService from services/Billing/
  3. Service uses injected HttpClient (factory name Cognitix.API)
  4. AuthHeaderHandler attaches JWT; CultureHeaderHandler sends culture
  5. Request hits API controller e.g. Controllers/Billing/InvoicesController.cs
  6. Controller calls module Application service (validation, mapping, business rules)
  7. Service uses module Infrastructure DbContext + repositories
  8. Response returns DTO JSON → WebApp renders MudBlazor UI
Pages/Billing/Invoices.razor ↓ inject services/Billing/InvoiceService.cs ↓ HttpClient GET /api/billing/invoices Controllers/Billing/InvoicesController.cs ↓ Cognitix.Billing.Application.*Service ↓ Cognitix.Billing.Infrastructure.BillingDbContext
Rule of thumb: UI never touches EF or Domain entities. If you need a new field on screen, add DTO → API endpoint → Application service → entity/migration on the backend.

5. WebApp (Blazor WASM)

Location: apps/Cognitix.WebApp/

Folder / filePurpose
Pages/Razor routes grouped by module (Billing, CRM, HRM, Settings, …)
services/Thin API clients — one service per feature area
Components/Reusable MudBlazor UI pieces
Authorization/Client-side permission checks, route guards
wwwroot/appsettings.jsonApiBaseUrl — required for API calls
wwwroot/js/Preloader, theme, small JS interop
Program.csHttpClient factory, DI registration, MudBlazor, auth state

Configuration

// apps/Cognitix.WebApp/wwwroot/appsettings.json
{
  "ApiBaseUrl": "https://localhost:7149/"
}

Trailing slash required. After Setup Wizard, copy the JSON from the completion screen into this file.

HttpClient pipeline

  • Cognitix.API — authenticated calls (default injected client)
  • Cognitix.PublicApi — login branding, anonymous endpoints
  • Cognitix.AuthRefresh — token refresh (no auth handler — avoids recursion)

UI stack

  • MudBlazor — tables, dialogs, forms, theme
  • Localization@inject ISharedLocalizer L from Cognitix.Localization
  • Permissions — menu and pages hidden when role lacks page permission
  • Culture / RTLen-US, bn-BD, ar-SA (Arabic RTL)

Key routes

RoutePurpose
/setupFirst-run Setup Wizard (anonymous)
/users/loginLogin
/Dashboard (authenticated)
/settings/licenseLicense activate / re-verify
/pos/terminalPOS terminal

6. API host

Location: src/Cognitix.API/ — single ASP.NET Core host for all modules.

AreaLocationRole
ControllersControllers/{Module}/REST endpoints, route prefix /api/...
PlatformControllers/Platform/Setup, license, system version/health
ReportsReports/QuestPDF generators (invoices, payslips, analytics PDFs)
MiddlewareMiddleware/License enforcement, user/branch context
AuthorizationAuthorization/RequirePermission, ApiPermissionRegistry
HubsHubs/SignalR + license hub filter
ExtensionsExtensions/DB provider wiring, cache decorators, startup guards
Program.csRootDI composition — registers all module services

Controller modules (folders)

Controllers are grouped under:

Billing · Banking · Branching · Compliance · CRM · Dashboard · Financials · HRM · Inventory · Observability · Platform · POS · Procurement · Users

Composition root

Program.cs is the composition root: it registers DbContexts, application services, validators, PDF generators, hosted jobs, and cached query decorators. Cross-module orchestration (e.g. invoice posting → journal entry) is wired here via DI, not by modules referencing each other directly.

Configuration files

  • appsettings.json — JWT, CORS, database provider, licensing, SMTP, cache
  • appsettings.Development.json — local overrides
  • Environment variables — COGNITIX_JWT_KEY, Cors__AllowedOrigins__0, etc.

7. Business modules

Each business module follows the same internal shape:

Cognitix.{Module}/
├── Domain/           # Entities, enums, domain interfaces
├── Application/      # Services, validators, mappers, use cases
└── Infrastructure/   # EF DbContext, repositories, Migrations/{SqlServer|PostgreSql|MySql}
ModuleResponsibilityDbContext (schema)
UsersJWT auth, roles, permissions, preferences, auditUsers
BranchingCompany profile, branding, branches, multi-branch isolationBranching
FinancialsCOA, JE, fiscal periods, tax, FX, financial reportsFinancials
BillingQuotations, orders, invoices, credit notes, ARBilling
ProcurementPO, GRN, supplier invoices, AP, paymentsProcurement
InventoryProducts, stock, warehouses, transfers, WMSInventory
POSTerminal sales, sessions, receipts, stock integrationPOS
BankingBank accounts, cheques, reconciliationBanking
CRMLeads, opportunities, customers, pipelines, chat hubCRM
HRMEmployees, attendance, leave, payroll-oriented recordsHRM
ComplianceRegional tax / e-invoice profiles & reportsCompliance
Licensing (not a source module in the buyer ZIP): Setup Wizard, activate / trial / heartbeat, and license enforcement come from lib/Cognitix.Licensing/*.dll. The Licensing database schema is still one of the 12 schemas applied by Setup Wizard Step 1. See §11 Licensing & BuyerBuild.

BiometricAgent is an optional Windows desktop agent for biometric attendance devices — separate from the web stack.

8. Clean Architecture rules

  1. Dependency flow: DomainApplicationInfrastructureAPI
  2. WebApp decoupling: references only Shared.DTOs, SharedKernel, Localization
  3. Business logic stays in Application / Domain — not in Razor code-behind or controllers
  4. Cross-module calls use contracts in SyncContracts or are composed in API DI
  5. No .resx in Domain/Application — localization strings live in Cognitix.Localization

Shared projects (CrossCuttingConcerns)

ProjectContains
Shared.DTOsAPI contracts, request/response models, shared enums
SharedKernelBase entities, Result, Guard, IRepository, user/branch context interfaces
Localization.resx resources, ISharedLocalizer
NotificationsSMTP email sending
FileStorageUpload path helpers, file persistence
SyncContractsIn-process cross-module event/contract types (not offline mobile sync)
Do not add a project reference from WebApp to Cognitix.Billing.Domain (or any module Domain). Add or extend DTOs in Shared.DTOs instead.

9. Authentication & authorization

JWT authentication

SettingDetail
SchemeJWT Bearer — issuer, audience, signing key must match across API and login
KeyCOGNITIX_JWT_KEY env var → Jwt:Key → auto-generate on first dev run
Token lifetimeDefault 60 minutes (AccessTokenMinutes)
RefreshUsers module refresh-token flow
ProductionSet strong 32+ char key via environment — never commit secrets

Permission model

  • Each UI page maps to a SystemPage key (e.g. Invoices, POSTerminal)
  • Roles grant Create / Read / Update / Delete per page
  • API: [RequirePermission("Invoices", PermissionActions.Read)] on controller actions
  • Registry: ApiPermissionRegistry.cs maps controller names → page keys
  • WebApp: menu and routes respect the same permission keys

Branch isolation

Users can be branch-scoped. API middleware and filters apply branch filters on queries. Company-wide admins see all branches; branch users see only assigned branch data.

License middleware

LicenseEnforcementMiddleware blocks API access when trial expired or license revoked. SignalR uses LicenseEnforcementHubFilter. Setup and login endpoints are [AllowAnonymous].

10. Database & Setup Wizard

Buyers choose one engine in Setup Wizard Step 1: SQL Server, PostgreSQL, or MySQL. All 12 module schemas live in one database (buyer-chosen name).

Configuration

{
  "Database": { "Provider": "SqlServer" },
  "ConnectionStrings": { "DefaultConnection": "" }
}

Provider: SqlServer (default), PostgreSql, MySql. Connection string is written by the wizard.

Migration order (12 DbContexts)

Licensing → Users → Branching → Financials → Billing → Procurement → Inventory → POS → Banking → CRM → HRM → Compliance

Runtime components

ComponentRole
UseConfiguredCognitixDatabaseProvider + connection per DbContext
Provider-filtered migrationsOnly Migrations/{Provider}/ applied
ProviderAwareModelCustomizerSoftens SQL Server–specific Fluent API for PG/MySQL
POST /api/setup/prepare-databaseWizard Step 1 — test, create DB, migrate all contexts
AutoMigrateOnlyWhenSetupCompleteStartup auto-migrate only after setup finished

Setup Wizard steps

StepWhat happens
1Engine + URLs + DB credentials → Continue (~3–8 min schema apply)
2Create first admin (no default production password shipped)
3Activate purchase code or 14-day trial
Buyers: do not run dotnet ef for normal install. Use Setup Wizard Step 1. Support recovery: Database/apply-migrations.ps1 (see Database/MIGRATION-NOTES.md).

Authors extending schema

Set COGNITIX_DATABASE_PROVIDER=PostgreSql|MySql|SqlServer before dotnet ef. Bulk regenerate: tools/setup-multi-db-migrations.ps1 (authors only).

11. Licensing & BuyerBuild

In the CodeCanyon package, licensing is delivered only as DLLs — not as editable source under src/.

Where the binaries live

lib/Cognitix.Licensing/
  Cognitix.Licensing.Application.dll
  Cognitix.Licensing.Domain.dll
  Cognitix.Licensing.Infrastructure.dll

Publish / build the API with -p:BuyerBuild=true so Cognitix.API references these HintPath DLLs. The sample deploy.yml detects this layout automatically when the lib/ folder is present.

What the DLLs provide at runtime

  • Setup Wizard at /setup (database prepare, admin create, activate / trial)
  • CognitiveCircle: activate, verify, heartbeat (https://api.cognitivebd.com)
  • License enforcement (API middleware + SignalR hub filter)
  • 72h offline grace only when CognitiveCircle is unreachable
  • Admin revoke → immediate lock on next heartbeat / re-verify (not 72h grace)
Customization boundary: treat lib/Cognitix.Licensing/ as a black box. Use Setup Wizard, Settings → License, and documented Licensing:* config — do not replace or reverse-engineer the DLLs. Keep the three DLLs committed with your private deploy repo so CI can publish with BuyerBuild.

ERP config ships Licensing:ProductSlug (not Envato Item ID).

12. Cross-cutting services

ConcernImplementation
User / branch contextUserContext — request-scoped; API middleware
Company brandingBranching brand provider → logos, display name, preloader
Company timezoneICompanyTimeZoneService; WebApp CompanyTimeZoneState
File uploadsCognitix.FileStorage → served at /uploads/
EmailCognitix.Notifications — SMTP via SmtpSettings
Memory cacheIMemoryCache on API — hot read paths; restart clears cache
PDF reportsQuestPDF generators in Cognitix.API/Reports/
SignalRCRM ChatHub at /chat-hub (JWT via access_token query)

Cache

  • Config: appsettings.jsonCache
  • Registration: AddCognitixCachedQueryServices() — decorates read services
  • Invalidation on master-data writes and journal post/reverse
  • Diagnostics: GET /api/system/cache-probe (authenticated)
  • No Redis in v1.0 — in-process only

13. Localization

UI strings live in Cognitix.Localization (hybrid model):

  • SharedResource — common / nav / shared labels
  • Module resources — e.g. CRM_*, Procurement_*, Billing_*
LayerUses Localization?
WebAppYes — @inject ISharedLocalizer L
APIRequest culture; many PDF/email strings still English
Domain / ApplicationNo .resx files

Cultures: en-US, bn-BD, ar-SA (RTL via MudRTLProvider).

Key shape: {Module}_{Context}_{Element} — e.g. Common_Save, Nav_HRM.

14. Cross-module wiring

Modules stay loosely coupled. Typical integrations:

FlowHow it works
Billing invoice → Financials JEApplication service in Billing calls contract / orchestrator registered in API
POS sale → Inventory stockPOS Application posts stock movement via Inventory services
Procurement GRN → InventoryReceipt updates stock balances
CRM won opportunity → Billing customerCRM contracts + API-level composition
Compliance e-invoiceCompliance module profiles; Billing/Procurement trigger submission hooks

Look for interfaces in SyncContracts and registration blocks in Cognitix.API/Program.cs when tracing cross-module behavior.

15. Where to change what

You want to…Start here
Change UI layout / form on a pageapps/Cognitix.WebApp/Pages/{Module}/
Add API call from UIservices/{Module}/ + inject HttpClient
Add REST endpointControllers/{Module}/ + Application service
Add business rule / validationModule Application/ (+ FluentValidation)
Add DB table / columnModule Domain/ + Infrastructure/Migrations/ (author tooling)
Add DTO for APIShared.DTOs
Add menu item + permissionNav component + ApiPermissionRegistry + role seed / admin UI
Change company logo / faviconSetup Wizard / Company Setup (Branching) — not hardcoded in WebApp
Change PDF report layoutCognitix.API/Reports/
Change SMTPAPI SmtpSettings or Settings → Email in WebApp
Change production URLs / CORS / JWTAPI config + WebApp appsettings.json — see Production Guide
Safe first customizations: branding, extra fields on existing DTOs, new read-only report page, role permissions, custom MudBlazor dashboard widget calling existing API.

16. Add a new feature (checklist)

Example: add a simple “Customer Notes” list under Billing.

  • Define CustomerNoteDto in Shared.DTOs
  • Add entity + configuration in Cognitix.Billing.Domain / Infrastructure
  • Add Application service methods (list, create, update)
  • Register service in Cognitix.API/Program.cs
  • Add CustomerNotesController with [RequirePermission(...)]
  • Add page key to ApiPermissionRegistry and role management UI
  • Add CustomerNoteService.cs in WebApp services/Billing/
  • Add Pages/Billing/CustomerNotes.razor with route and nav link
  • Add localization keys in Cognitix.Localization
  • Authors: add EF migration for your provider; buyers: ship migration in product update
  • Test: unit test Application service; manual test via WebApp + API

17. API surface (selected)

EndpointNotes
GET /api/system/versionPublic product version
GET /api/system/healthHealth check (respect AllowedHosts in production)
GET /api/system/cache-probeAuthenticated cache smoke
GET /api/branching/companysetup/timezoneCompany TZ for WebApp
POST /api/setup/*Anonymous during first install
GET /api/license/statusLicense state (Trial / Active / Revoked)
/api/{module}/...Module controllers — discover under Controllers/
/chat-hubSignalR — CRM chat
/uploads/...Static files — logos, attachments

Product version is centralized in Directory.Build.props.

18. Testing

ProjectPurpose
Cognitix.Tests.UnitDomain, validators, application services
Cognitix.Tests.IntegrationAPI + DB; licensing smoke categories
Cognitix.Tests.PerformanceReport / query performance gates
Cognitix.Tests.E2EEnd-to-end workflows
test/QA/Manual smoke & security checklists
dotnet test Source/CognitixERP/CognitixERP.sln
dotnet test --filter Category=LicensingSmoke

Related install notes: Installation Guide, Troubleshooting FAQ (license / uploads).

19. Tech stack

  • .NET 10 / ASP.NET Core / Blazor WebAssembly
  • EF Core — SQL Server, PostgreSQL, MySQL
  • MudBlazor, FluentValidation, MediatR
  • QuestPDF (MIT-pinned), SignalR
  • Serilog, JWT auth, in-process IMemoryCache

Third-party inventory: package root LICENSES.md / NOTICE.txt.

20. What v1.0 is not

Do not assumeReality in v1.0
Offline-first / mobile ERPWeb-only release
SyncEngine in production pathNot in active solution host path
Redis / distributed cacheMemory cache on API process only
Default admin password in ZIPCreated only in Setup Wizard Step 2
Buyer runs dotnet efWizard migrates all 12 schemas
Editable Licensing project under src/Only lib/Cognitix.Licensing/*.dll

21. Please Contact us

  1. Sign up at https://cognitivebd.com
  2. Create a Support Ticket.
  3. Within 48hr we will reply.

Or email support@cognitivebd.com with your purchase code, version, and screenshots/logs.