HRM-10/CLAUDE.md
2026-11-12 14:58:04 +06:00

51 KiB
Raw Permalink Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Overview

CEL.HRM.5 is a large ASP.NET Core (net10.0) + Angular 22 HR Management System (payroll, attendance, leave, recruitment, fund/PF management, learning management, grievance management, PMP/talent, final settlement, etc.), plus a separate ERecruitment portal. It is a Windows/Visual Studio solution (CEL.HRM.5.sln).

Three facts shape almost everything else: there is no ORM, there is no migration framework, and there are no automated tests. Data access is hand-written ADO.NET with hand-built SQL strings, schema changes ship as hand-authored .sql scripts run manually, and verification is build-based and manual.

Solution structure

Project Type Purpose
HRM.UI ASP.NET Core Web API + Angular SPA host Main application. REST controllers under Controllers/<Module>/, Angular app in ClientApp/.
Erecruitment.UI ASP.NET Core Web API + Angular SPA host Separate e-recruitment portal (ClientApp project Erecruitment_Angular, output dist, dev port 44375). References HRM.BO + HRM.DA, same three-layer pattern.
HRM.BO Class library Business objects (deriving from ObjectTemplate) and service interfaces (IEmployeeService, …), organized by module.
HRM.DA Class library DA/ = internal static raw-SQL builders; Service/ = concrete I*Service implementations.
Ease.Core Class library The in-house framework everything sits on: DataAccess/ (TransactionContext, DataReader, SQLParser/MakeSQL, ConnectionFactory, DbConfig, NullHandler), Model/ (ObjectTemplate, ServiceTemplate, ServiceException), Utility/, EnumHelper.
HRM.Report Class library RDLC reporting (ReportProcessor, ~383 .rdlc; HRM.UI/RDLC holds ~104 more). Uses BinaryFormatter, hence EnableUnsafeBinaryFormatterSerialization.
HRM.AttendanceAutoProcess Console exe Scheduled attendance import job (single Program.cs).
HRM.MailNotificationProcess WinForms exe (net10.0-windows) Scheduled mail notification sender; SSH.NET for SFTP.
DatabaseComparison Legacy WinForms exe (net461, non-SDK csproj) Standalone DB schema diff tool, not part of the app runtime.

Reference graph: Ease.Core ← HRM.BO ← HRM.DA ← HRM.Report ← HRM.UI.

Gotcha: HRM.UI and Erecruitment.UI also carry an old Ease.NetCore NuGet PackageReference (v1.0.5, 2021) alongside the transitive Ease.Core project reference, and both DLLs ship to the output folder. The live framework is the Ease.Core project in this repo — that is the one to edit and read. But the NuGet is not dead: AuthController encrypts/decrypts every password with Ease.NetCore.Utility.Global.CipherFunctions. Keep it pinned at 1.0.5 — a newer version that ciphered differently would lock every user out.

Package policy (since the .NET 10 upgrade)

Microsoft packages track the runtime (10.0.x). Three are deliberately held back or gone: Aspose.Words stays at the version the client licence covers (a newer build than the subscription allows silently drops to evaluation mode), EPPlus stays on 8.x (licensed), and AutoMapper was removed — 10.1.1 had a high-severity advisory whose only fix is the commercial 15.x line, and nothing called IMapper. Don't add it back; map by hand. EF Core, Swashbuckle, Facebook and Microsoft.Extensions.PlatformAbstractions were removed too (never used). API versioning is Asp.Versioning.Mvc (+ .ApiExplorer), the successor of Microsoft.AspNetCore.Mvc.Versioning. dotnet list CEL.HRM.5.sln package --vulnerable --include-transitive was clean after the upgrade; System.Security.Cryptography.Pkcs/Xml are pinned directly in Ease.Core/HRM.BO only to lift vulnerable transitive versions.

There is a nested, separately-buildable HRM.UI/Controllers/MobileAPI/HRMobileAPI.csproj (legacy mobile API) included only in the narrower HRM.UI/HRM.UI.sln. But the live mobile API is not that project: MobileAPI/Controllers/*.cs (api/Mobile/User, api/Mobile/Attendance, …) are ASP.NET Core controllers that HRM.UI itself compiles and serves — search that folder too when changing anything app-wide. Don't confuse that solution with the root CEL.HRM.5.sln, which is the one for whole-solution work.

HRM.UI/CLAUDE.md is a second, frontend/backend-detailed file. Its architecture notes still hold, but several specifics are stale — prefer this file wherever the two disagree. It claims .git lives at e:\HRMGIT\ alongside a sibling IntegrationSuite project (this checkout is a single self-contained repo and no IntegrationSuite exists), lists npm run lint as a working command (it is broken — see below), describes Ease.Core as "referenced as the Ease.NetCore NuGet package" (the live one is the project in this repo), and counts "~250+" services (there are ~450 service classes, ~310 of them DI-registered).

Build & run

dotnet restore CEL.HRM.5.sln
dotnet build CEL.HRM.5.sln
dotnet build HRM.UI/HRM.UI.csproj
dotnet run --project HRM.UI/HRM.UI.csproj
dotnet run --project Erecruitment.UI/Erecruitment.UI.csproj   # the e-recruitment portal, :44375

dotnet build handles the whole solution including the net461 DatabaseComparison project; Visual Studio/MSBuild is not required for it. Building HRM.UI alone pulls in BO/DA/Report/Ease.Core and is the fast loop for backend work — ClientApp/** is excluded from the csproj, so a dotnet build never runs the Angular build.

Expect the solution build to fail on Erecruitment.UI — every other project builds clean. It does not compile on this branch, and did not on net8 either: SurveyController uses SurveyEmployee / SurveyResult members that HRM.BO no longer has, and its DI file registers a FinalSettlementService that does not exist. On a clean build it fails even earlier, on TypeScript: unlike HRM.UI it lacks <TypeScriptCompileBlocked>, so Microsoft.TypeScript.MSBuild compiles ClientApp and fails without node_modules.

Production servers need the ASP.NET Core 10 Hosting Bundle (IIS, AspNetCoreModuleV2, in-process) before a net10 build is deployed to them.

Dev URLs: API on https://localhost:44374 (HRM.UI/Properties/launchSettings.json); Angular dev server on http://localhost:4200, which is the only origin the "CORSPolicy" CORS policy allows. The normal full-stack loop is dotnet run from HRM.UI — in Development it proxies to ng serve via UseAngularCliServer. Run ng serve standalone only for Angular-only iteration, with the backend running separately.

Frontend (from HRM.UI/ClientApp or Erecruitment.UI/ClientApp):

npm install
npm start      # ng serve, http://localhost:4200
npm run build  # ng build -> dist/babylon (HRM.UI) | dist (Erecruitment.UI)
npm test       # ng test (Karma, entry src/test.ts)

Both SPAs ng serve on 4200, so only one of the two can run at a time.

  • npm run lint is broken: angular.json still points at the @angular-devkit/build-angular:tslint builder (with a tslint.json), which no longer exists in Angular 19. There is no ESLint config.
  • npm test works, but coverage is nominal — 18 .spec.ts files across the whole app. Single spec: ng test --include='**/some.component.spec.ts'.
  • There are no *.Tests.csproj anywhere in the solution.

Production build/deploy (HRM.UI)

deploy.ps1 does the whole thing: bumps HRM.UI/ClientApp/src/version.json (YYYYMMDD-NN, counter auto-increments per day), runs ng build --configuration production --base-href <baseHref>, dotnet publish for win-x64, copies dist/babylon into the publish folder's wwwroot, and writes an Angular web.config (SPA rewrites + no-cache for index.html/version.json). Edit $baseHref/$outputFolder at the top per client/environment before running. VersionCheckService (ClientApp/src/app/version-check.service.ts) polls version.json every 5 minutes and prompts a reload when the server version changes — keep the version bump intact if you touch the script. The repo-root publish/ folder is this script's output (gitignored) — never hand-edit it. HRM.UI/ClientApp/deploy.ps1 is a deprecated frontend-only shim that just forwards to the root script; don't extend it.

Architecture: BO → DA → Service → Controller

Every feature module mirrors the same folder name across HRM.BO/, HRM.DA/DA/, and HRM.DA/Service/ (e.g. Employee/, Leave/, Fund/, Attendance/).

  1. BO — the entity (class Employee : ObjectTemplate) plus its service interface (IEmployeeService). ObjectTemplate supplies ID, IsNew (_id <= 0), SortOrder and an ObjectState; BOs are not plain POCOs.
  2. DA (HRM.DA/DA/<Module>/<Entity>DA.cs) — internal static classes whose methods all take a TransactionContext as first argument, build SQL via SQLParser.MakeSQL(...), and return IDataReader/DataSet/scalars. Never called from controllers.
  3. Service (HRM.DA/Service/<Module>/<Entity>Service.cs) — public class XService : ServiceTemplate, IXService. Owns the transaction, maps rows to BOs, and is what controllers get via DI.
  4. Controller (HRM.UI/Controllers/<Module>/) — [ApiController], [Route("api/<Module>")], [Authorize], constructor-injects a long list of I*Service interfaces and delegates. Almost no logic. API versioning is configured (URL-segment) but routes are unversioned in practice.

All ~310 service registrations live in one file: HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs (ConfigureBusinessServices, almost all AddTransient<IX, X>()). Register new services there.

Note the asymmetry: DI is used at the controller boundary only. Inside HRM.DA, services instantiate each other directly (new LeaveService().Get(...), new EmployeeService().Get(...)), so following the existing style means new-ing a sibling service, not injecting it.

Mapping rows to objects

ServiceTemplate forces protected override T CreateObject<T>(DataReader dr). The house style is a private MapObject(Entity, DataReader) that CreateObject calls; lists come from the inherited CreateObjects<T>(dr), which also stamps ObjectState.Saved on each row.

Canonical service method

Every public service method follows this shape — match it exactly:

public int Save(LeaveEntry oLeaveEntry)
{
    TransactionContext tc = null;
    try
    {
        tc = TransactionContext.Begin(true);   // true = start a DB transaction (writes)
        Save(oLeaveEntry, tc);
        tc.End();                              // commit
    }
    catch (Exception e)
    {
        #region Handle Exception
        if (tc != null)
            tc.HandleError();                  // rollback
        ExceptionLog.Write(e);
        throw new ServiceException(e.Message, e);
        #endregion
    }
    return oLeaveEntry.ID;
}

TransactionContext.Begin() (no argument) is the read-only form used by every Get*. Services also expose Get(TransactionContext tc, ...) overloads so callers can join an outer transaction.

SQL is string interpolation, not parameterization

SQLParser.MakeSQL splices literals into the SQL text. Placeholders are positional and consume arguments in order; a null argument becomes NULL:

meaning
%n numeric literal (by far the most used — ~14.5k occurrences)
%s string, single-quoted, ' doubled
%u same as %s but N'...' (unicode)
%T same as %s
%d / %t / %D date / time / datetime literal
%b bit, emitted as 1/0
%q raw, verbatim, unescaped
%% a literal %
%{0} re-use the already-formatted argument at that ordinal

%q (~1.5k occurrences) is the injection surface — it exists for things like comma-separated ID lists in IN (%q) and for splicing fragments. Only ever pass values the code itself produced (joined ints, a fixed column name); never a user-supplied string. Do not introduce $"..." interpolation or + concatenation for SQL — use MakeSQL.

Primary keys are application-generated

There are no IDENTITY columns in this schema. New IDs come from tc.GenerateID("TableName", "ColumnName"), which is literally SELECT MAX(col) FROM table + 1 (optionally with a where-clause overload), executed inside the same transaction. When adding a table, follow this — do not add an IDENTITY column, or the pattern breaks.

Stored procedures

The escape hatch for heavy reporting queries. Used in ~12 DA files, e.g. in HRM.DA/DA/Attendance/DailyAttnProcessDA.cs:

var p = new List<SqlParameter> {
    SqlHelperExtension.CreateInParam("@FromDate", SqlDbType.Date, fromDate), ... };
return tc.ExecuteDataSet(CommandType.StoredProcedure, "usp_EmployeeAttendanceLeaveSummaryLM", p.ToArray());

These are properly parameterized. The proc body itself ships in the matching _DB_Changes.sql script (see below) — for this one, db/Script/AttendanceLeaveSummaryLM_DB_Changes.sql.

Excel import/export

Three Excel libraries are referenced: NPOI (in HRM.BO), plus ClosedXML and EPPlus (both in HRM.DA). Before adding a workbook feature, check which one the surrounding module already uses instead of adding a fourth. The newest and largest workbook feature (Employee Bulk Upload, below) uses ClosedXML for both writing and reading.

Every Excel interface in the app is served by the one DataUploadController (api/dataUpload) — do not add a separate controller for a new uploader.

Employee Bulk Upload

The whole information of many employees in one spreadsheet — one row per employee, carrying that employee's children, spouse, education, nominee and experience in the same row. ~8,000 lines across four files, and the pattern is worth following for any future uploader:

Layer File
Layout + DTOs + interface HRM.BO/EmployeeBulkUpload/EmployeeBulkUploadTemplate.cs
Raw SQL HRM.DA/DA/EmployeeBulkUpload/EmployeeBulkUploadDA.cs
Generate / validate / save HRM.DA/Service/EmployeeBulkUpload/EmployeeBulkUploadService.cs
Screen ClientApp/src/app/common-interface/employee-bulk-upload/ + _services/common/employee-bulk-upload.service.ts

Four things shape it:

  • EmployeeBulkUploadTemplate is the single source of truth. The static layout (groups → sub-groups → columns, with each column's mandatory flag, kind, width, dropdown list and number format) is declared once in BO. The downloadable .xlsx is generated from it on every request, and validation reads the uploaded file against the same declaration — so the template and the rules cannot drift apart. Add a column by appending it inside its sub-group, never by inserting in the middle: the uploader matches by position and heading.
  • Validation is 8 ordered layers, built in ReadUpload: Excel file → Sections and columns → Rows → Employee No and Name → Mandatory values → Data types → Employees → Master data. Every check of a layer runs and is reported even when it passes (Code, Title, Status, Message, Details, Fix); the next layer runs only once the previous one passed. Validation problems are returned in the result, not thrown — only an unexpected failure throws.
  • Save is all-or-nothing: SaveUpload re-validates every layer, then writes every row in ONE transaction. An Employee No already in the current payroll type updates that employee (only the cells the file fills); anything else creates a new one.
  • Missing master data can be added from the screen (AddMasterData) — but through each master table's own service Save, one record per transaction, so one failure does not undo the rest. That is deliberately not part of the all-or-nothing save.

Six endpoints, all on DataUploadController: employee-bulk-upload-layout, -template, -read, -save, -add-master-data, -master-options/{masterData}/{payrollTypeId}.

Gotcha: the screen has an Angular route (/common-interface/employee-bulk-upload) but no <Menu> node in any *-Menu.xml — key 2.3.7 under Manage Employee › Interface went to "Historical Career Data Upload" instead. So the page is reachable only by typing the URL until a menu node is added and the XML re-uploaded (see the menu flow under Auth and the current user).

Two later uploaders built on the same pattern

Both reuse the bulk-upload result types (EmployeeBulkUploadLayer, EnumBulkUploadCheckStatus), so the screens report problems the same way. Neither has a <Menu> node yet either — URL only.

  • Salary Master Data Bulk Upload (/common-interface/salary-master-bulk-upload; read-only grid at /payroll/salary-master-data-view). Layout in HRM.BO/Salary/SalaryMasterBulkUploadTemplate.cs, logic in HRM.DA/Service/Salary/SalaryMasterBulkUploadService.cs, rows saved to HistorySalaryMonthly / HistorySalaryMonthlyDetail through HistorySalaryMonthlyService. The workbook is per salary month (row 1 carries the month, checked against the month posted as the salaryMonth form field). 7 layers, not 8, and layers 4–7 all run once layer 3 passes, so one upload lists every problem of every row. A blank amount is saved as NULL — which needs HistorySalaryMonthlyAmountNull_DB_Changes.sql run first. That script is not in this repo — it was deleted (not archived) in cel.hrm commit 91369150c; recover it from there with git show 91369150c^:HistorySalaryMonthlyAmountNull_DB_Changes.sql. The service opens no transaction itself; the save is HistorySalaryMonthlyService's one all-or-nothing transaction.
  • Employee Profile Picture Bulk Upload (second tab of the Employee Bulk Upload screen; HRM.DA/Service/EmployeeBulkUpload/EmployeePhotoBulkUploadService.cs). No file upload: pictures are copied by hand into HRM.UI/EmployeePhotoBulkUpload/ on the server (gitignored), each named by Employee No, and the screen reads that folder. Each picture is stored exactly as an approved ESS profile-picture request stores it (EssController.ApproveRequest: HREmployeeDA.uplaodFile + EmployeePhotoService.GenerateThumbnail). The save is all-or-nothing for the whole folder, and because thousands of pictures take minutes it runs on EmailLogBackgroundRunner and the screen polls employee-photo-bulk-upload-run/{runId}. Run state is in memory — an app restart loses it. After a save the controller drops each changed employee's LandingPageEmployee cache entry.

Calendar module

A Google-Calendar-like module (/calendar/my-calendar, /calendar/my-tasks) on just two tables, CalendarItem and CalendarItemAttendee (schema: db/Script/Calendar_DB_Changes.sql):

  • One CalendarItem table holds all three ItemTypes: Event (1), Task (2) and Schedule Job (3, HR only). A Schedule Job is a template: each run creates an ordinary Task, made unique by SourceItemID + SourceOccurrence. Its Department targets stay as Department rows and are expanded at every run. The job itself is never notified about or sent to Outlook.
  • Schedule Email (ItemType 4, HR only, Calendar.ScheduleEmailsEnabled) is the same kind of template, but each run sends an e-mail instead of creating a Task: Title is the subject, Description the body, one optional file in CalendarItemAttachment. Each run claims a CalendarEmailRun row (unique per item + run moment) and becomes one MasterEmailLog batch (EnumEmailType.ScheduleEmail, file on the batch header like GeneralMail), sent by CalendarJobs.SendScheduleEmail through IEmailDispatchService — so it shows, and is retried, in Mail Manager › Mail Log History. Body/subject tags (<EMP-NAME>, <DEPARTMENT>, …) are listed and filled in one place, HRM.DA/Service/Calendar/ScheduleEmailTags.cs. Schema: ScheduleEmail_DB_Changes.sql is not in this repo — it was deleted unarchived in cel.hrm; recover it from a cel.hrm clone with git show 73f466cd0:ScheduleEmail_DB_Changes.sql.
  • The organizer is CreatedBy and an attendee row with Role = Organizer. Holidays, leave and birthdays are read-only layers, read live from the existing tables (nothing is copied).
  • Repeats are RFC 5545 RRULEs worked out with Ical.Net (HRM.DA/Service/Calendar/CalendarRecurrence.cs). Times are stored as floating local times. NextTriggerAt is the next reminder (Event/Task) or the next run (Schedule Job), and CalendarItemDA.AdvanceTrigger moves it optimistically, so only one dispatcher can ever take a given reminder or run.
  • Outlook (ICS mode): CalendarJobs.SyncOutlook mails a text/calendar REQUEST/CANCEL built by HRM.UI/BackgroundJobs/Calendar/CalendarIcsBuilder.cs. The UID is stable per item, SEQUENCE is CalendarItem.OutlookSequence, and per-person progress is CalendarItemAttendee.InviteSentSequence, so a retry only sends what is missing. Bump OutlookSequence only when what the invitation shows changes. In ICS mode, change notifications are bell-only (the invitation is the e-mail). OutlookSync = Graph (Microsoft 365) is planned but not built.
  • The controller only queues jobs (NotifyChange, NotifyOrganizer, SyncOutlook) after a successful save, through QueueJob, which never turns a saved change into an error. All permission checks live in CalendarItemService.
  • Frontend: the dialogs (quick add, item editor, item detail, day dialog) and the small month calendar (<app-calendar-mini-scheduler>, a hand-built grid, not the Kendo Scheduler) live in ClientApp/src/app/calendar/shared/ as CalendarSharedModule, imported by both CalendarModule and EssModule. The ESS landing page and the self-service dashboard's drawer show the mini calendar and open <app-calendar-day-dialog> from it (dateSelected / itemSelected). Change a dialog there once, not per screen. The mini calendar deliberately leaves out the Leave, Attendance and Schedule Job layers; the older dot calendar <app-custom-calendar> (custom-components/) is no longer used by any page.

Cross-cutting: central email log

Bulk outbound mail — payslips, tax cards, tax certificates, anything sent to many employees at once — goes through IEmailDispatchService (HRM.DA/Service/Mail/EmailDispatchService.cs), which writes a MasterEmailLog row per send operation and a MasterEmailLogDetails row per recipient. Do not call MailSender in a loop for a new bulk-mail feature; the whole point is that failures become replayable instead of lost. (Single-recipient notifications — workflow, leave, loan — still use MailSender directly, and are not logged.)

The contract:

  • Logged before sent. CreateBatch writes the header and every recipient row (details via SqlBulkCopy) before the first mail leaves, so nothing is lost if the run dies halfway.
  • One bad recipient never stops the run. Missing address, a document that will not build, an SMTP refusal — each is recorded on that recipient's own row and the loop carries on. SendOne never throws.
  • Skipped ≠ Failed. No/invalid e-mail address is Skipped (retrying is pointless — fix the address); everything else is Failed and is what RetryFailed replays. Retry updates the same rows in place and never creates a second batch.
  • Attachments are kept (MasterEmailLogDetails.AttachmentData, switchable per batch via MasterEmailLog.PreserveAttachment), which is what lets one retry screen replay any mail type without knowing how that document is produced.

Adding a mail type is two things and nothing else: a member on EnumEmailType, and an EmailDispatchRequest.AttachmentResolver that builds the document. The resolver has to live in HRM.UI because HRM.DA cannot reference HRM.Report — see SalaryController.sendPayslipForMultiple and IncomeTaxController.SendTaxCardForMultiple / SendTaxCertificateForMultiple for the pattern. Build the attachment with the same report call the matching report screen uses (e.g. tax card = RptIncomeTax.ShowMultipleTaxCard, the EnumReportType.EssTaxCard branch of ReportController.getCommonReportData), so the mailed document and the downloaded one cannot drift.

The one exception is EnumEmailType.GeneralMail (free-text mail + one optional uploaded file, ≤ 10 MB), sent from EmailLogController.sendGeneralMail. Every recipient gets the same file, so it is stored once on the batch header (MasterEmailLog.ParameterJson, base64) with PreserveAttachment = false, not copied onto each MasterEmailLogDetails row; retry (BuildGeneralMailResolver) and api/emailLog/downloadAttachment/{masterEmailLogId}/{detailId} read it back from the header. Follow that for any future "same file to everyone" mail type.

Batches run on a non-request thread (HRM.UI/Helpers/EmailLogBackgroundRunner.cs) and the endpoint returns the new masterEmailLogID immediately; the browser follows the batch by polling api/emailLog/getLog/{id}. Read side + generic retry: api/emailLog (Controllers/CommonInterface/EmailLogController.cs).

Frontend: <app-master-mail-log> (ClientApp/src/app/master-mail-log/, its own MasterMailLogModule) is the reusable view — history, live progress, per-recipient breakdown and retry. Import the module, drop the tag in, and after starting a batch call watchBatch(id) on it via @ViewChild. Inputs narrow it (emailType, showTypeFilter, showProgress, showFilterBar, showLogGrid, allowRetry). Mail Manager (/payroll/mail-manager) is the worked example.

Two things to know before building on it:

  • There is no _DB_Changes.sql for these two tables anywhere in the repo — the schema was applied by hand and the script never committed. Any other client branch or fresh database will fail at runtime until it is written and run. Treat that as outstanding work.
  • ProcessBatch only refreshes the header's counters (and its status) when the run ends, so a batch in flight reads Pending with Sent/Failed/Skipped still at 0; Processing is in the enum but effectively unused. The per-recipient rows are accurate throughout — it is the header that lags. The UI compensates with a spinner, not with real numbers.

Cross-cutting: approval workflow

Most "apply → approve" features (leave, attendance regularization, claims, requisitions) route through HRM.DA/Service/Workflow/ — WorkFlowEng, WFMovementTran, WFSetup, WFType, DelegateResponsibolity. Before writing a new approval path, look at how an existing module drives WFMovementTran.

Auth and the current user

JWT bearer (HS512), signing key from AppSettings.Secret — always through Ease.Core.Utility.JwtSigningKey.FromSecret(...), both where tokens are issued (AuthController, SalaryController, and the mobile login in HRM.UI/Controllers/MobileAPI/Controllers/UserController.cs) and in Startup. Microsoft.IdentityModel 8 refuses an HS512 key under 64 bytes (IDX10720) and the configured secrets are 40, so the helper stretches a short secret with SHA-512; a raw Encoding.ASCII.GetBytes(Secret) anywhere breaks login. The token carries custom claims, unpacked everywhere by CurrentUser.GetCurrentUser(HttpContext.User) (HRM.BO/User/Users.cs, used in ~45 controllers):

UserID, UserName, LoginID, UserType (EnumUserType), EmployeeID, PayrollTypeID, nextPayProcessDate, taxParamId, hasDataPermission.

Gotcha: dbo.Users e-mail columns differ per database: the older Email, and EmailAddress, which is the one the Add/Edit User form writes (UserEmailAddress_DB_Changes.sql). Some databases have both, some only one (the dev database has no Email at all), and naming a missing column fails the whole query — the calendar's Users dropdown once came back silently empty for exactly this reason. Don't hard-code either column: use the pattern in CalendarItemDA.UserEmailExpression, which checks COL_LENGTH once per process and builds COALESCE(EmailAddress, Email) from whichever columns exist. Server-side SQL errors that the UI swallows land in HRM.UI/Log/Error.log (ExceptionLog), the first place to look. Two places don't follow that pattern yet. UserDA.Insert writes only Email, so creating a user fails on a database that lacks it (the pending UsersEmailColumn_DB_Changes.sql adds it; its header wrongly says Insert writes both columns). UserService.MapObject reads only Email (the EmailAddress line is commented out), so the user list's email is blank wherever addresses live in EmailAddress.

Gotcha in user approval: UserDA.Approve always sets Status = Approved (5), whatever the request was. So "approving" an Inactive_Not_Yet_Approve (9) or Inactive (8) user re-activates them, and a deactivation can never actually be approved. The user list labels that action "Re-activate" for this reason; the fix belongs in the server.

PayrollTypeID is the scoping key threaded through most payroll/attendance queries — when adding a query that returns employee data, check whether existing siblings filter by it. Reading EmployeeID throws for a self-service (EnumUserType.Employee) login that has none, so guard accordingly.

Authorization is menu-driven, not route-driven: the server builds the user's permitted menu tree and the SPA stores it in localStorage as menuList; AuthGuard.canActivate() only checks that a token exists. A hidden menu item does not mean a protected endpoint — put real checks in the API.

The menu itself is data, not code: it is defined in per-client XML files under ClientApp/src/assets/resource/ (Menu.xml, Berger-Menu.xml, SGS-Menu.xml, …). An admin uploads one via Authentication > Configuration > Menu (FileManagerController.uploadConfigurationfile), which stores its attributes in dbo.ConfigurationAttribute and syncs name/link/icon onto dbo.RolePermission (matched by PermissionCode); RoleService.GetRolePermissionbyUserID builds the tree from those rows. So adding a new screen means adding a <Menu> node to the relevant XML(s) and re-uploading it, not just adding an Angular route. See db/Script/MenuIcon_DB_Changes.sql for the full flow.

The same upload mechanism (EnumConfigurationType: UI, Logic, Menu) carries per-client business rules: the *LogicConfiguration.xml files in that folder are uploaded as Logic and read at runtime via new SystemConfigarationService().GetconfigValue/GetconfigBooleanValue( EnumConfigurationType.Logic, "<parent>", "<child>") (~110 call sites, e.g. "costcenter", "manadatoryinsalary"; note the class-name spelling, file HRM.DA/Service/Common/SystemConfigurationService.cs). When behavior differs between clients, look for or add a Logic key rather than branching in code.

Branches: one product, many client deployments

This checkout is not that repo. It is HRM-10 (origin = 103.197.204.162:3025/CelHRTeam/HRM-10), a fresh import with a single branch main and a single squashed commit (838b8d4 "first commit"). None of the older history exists here: every commit hash quoted elsewhere in this file (c8588ce67, 91369150c, ac179c03e, 73f466cd0, bfd085e0e) is from the original CelHRTeam/cel.hrm repo, and git show/git log recovery commands only work in a clone of that repo, not here.

That original repo carries ~79 branches, and they are not short-lived feature branches. Its default/integration branch is devqc. The rest are long-lived per-client branches (BergerHR, SGSHR, IDLC_Payroll_Master, Square_PMS*, Wartsila, LiFungHR, Metlife_fund, PetromaxHR, ProclozPayroll, TexEbo_Payroll, Duncan_Payroll, HNM, PCSHRUAT, …) and per-developer ones (dev_<name>, dev_<name>Master).

Two consequences worth holding onto:

  • Work moves between client branches by hand, as bulk "transferred from <branch>" commits. So a fix made here is not automatically in any client's branch of cel.hrm (and vice versa), and a file can look freshly rewritten when it was only ported.
  • This is why per-client behavior belongs in uploaded *LogicConfiguration.xml / *-Menu.xml data and in the Calendar appsettings section rather than in if (client == …) code: config travels with the database, code branching has to be re-merged across ~79 branches.

Configuration (and which parts are actually live)

HRM.UI/appsettings.json holds real credentials committed to the repo. Treat it as sensitive: do not print its contents into chat or logs, and do not commit new secrets alongside code changes.

What actually drives the DB connection:

  • Ease.Core.DataAccess.DbConfig.GetConfig() reads the dbSettings section, and it does so by building its own ConfigurationBuilder over appsettings.json from Directory.GetCurrentDirectory() — completely outside the ASP.NET config pipeline. Consequence: appsettings.Development.json cannot override the database connection. There is exactly one live connection, dbSettings.Default.
  • Pointing the app at another database means editing which dbSettings line is commented out in appsettings.json (the file carries a commented-out "master project DB" alternate).
  • The AppSettings.DbConfig[] array (with its "Key": "spadb") is dead config — nothing binds it; the AppSettings POCO in Startup.cs has no such property.

Other live sections: AppSettings (Secret, DefaultDB, RDLCLocation, downloadFolder, attendance import settings), EmailSettings, EmployeeApiInfo, AdminPendingJob, MobileAppSettings, FundInfo, OpenAI, LDAPSettings, Calendar (bound to HRM.BO/Configuration/CalendarSettings.cs), plus many payroll/fund GL-head keys.

Startup.cs has large commented-out blocks — verify against live code before assuming a feature is on. In particular Swagger is commented out entirely even though AppSettings.Swagger.Enabled is true in config. Active: JWT bearer, URL-segment API versioning, CORS (http://localhost:4200), session + AddDistributedMemoryCache, ICacheManager/MemoryCacheService, an OpenAIService singleton (Semantic Kernel + OpenAI, with Controllers/OpenAIController and the Angular hrmopen-ai module), Hangfire (below), and the SPA host.

Background jobs (Hangfire)

Hangfire (Hangfire.AspNetCore/Hangfire.SqlServer) runs in-process inside HRM.UI; it is currently used only by the Calendar module. All wiring lives in HRM.UI/BackgroundJobs/Calendar/CalendarHangfireSetup.cs, hooked into Startup via services.AddCalendarBackgroundJobs(Configuration, HostingEnvironment) and app.UseCalendarBackgroundJobs():

  • Storage is the same database as the app, via ConnectionFactory.Default.CreateConnection() (so it follows dbSettings), in a separate HangFire schema that Hangfire auto-creates on first start — don't put Hangfire tables in a _DB_Changes.sql script.
  • One server, 4 workers, queues CalendarJobs.QueueName + default. Job classes are registered in DI (AddTransient<CalendarJobs>()) and invoked by type, so job methods must stay public and their arguments serializable.
  • CalendarJobs.Dispatch() is a per-minute recurring job that serves both reminders and schedule-job runs (HR's Schedule Jobs, ItemType = 3, which create a Task per run, made unique by SourceItemID + SourceOccurrence); it is added or removed at startup depending on Calendar.RemindersEnabled / Calendar.ScheduleJobsEnabled, and runs in server local time (the old daily birthday digest is retired; startup only removes its recurring job). Calendar.RedirectAllMailTo reroutes every outgoing calendar mail (use it on dev/UAT databases); SendMail turns sending off entirely, and in the Development environment mail is only sent while RedirectAllMailTo is set.
  • Calendar per-client switches (OutlookSync, ScheduleJobsEnabled, MaxAttendees, …) live in the Calendar section of appsettings.json, not in a Logic XML key. CalendarItemService receives them through its constructor (registered with a factory in ServiceCollectionExtensions). Some rules are fixed in code, not settings: every employee may create events, line managers assign tasks to their own team (HR to anyone), and the birthday / work-anniversary layers only ever show the user's own.
  • Dashboard at /hangfire, local requests only. UseCalendarBackgroundJobs() must stay before UseSpa, or the SPA fallback answers /hangfire with the Angular page.

Database change scripts

Schema/proc changes are hand-authored .sql scripts named <Feature>_DB_Changes.sql, run against each database manually. They live in two places and the distinction is the whole point:

  • Repo root — the pending ones. ls *_DB_Changes.sql shows what has not been applied yet Write new scripts here, in the same commit as the code that needs them. The root also holds generated DB analysis reports (UnusedTables_<db>.txt, TablesWithoutPK_<db>.txt). They are input for clean-up decisions, not proof a table is safe to drop: they only scan HRM.DA/DA SQL and DB objects, and HangFire.* is used by the library itself.
  • db/Script/ — the archive of shipped ones (Calendar, MenuIcon, AttendanceLeaveSummaryLM, TaxParameterEssDeadline, PMS_SquareAlign_IDP, EmpHistoricalData). Read them for precedent — they are the best worked examples of house style — but don't re-run one against a database that already has it.

The convention was not enforced in cel.hrm: EmpHistoricalData went straight into db/Script/, and several applied scripts were deleted instead of archived — ScheduleEmail, UserEmailAddress, HistorySalaryMonthlyAmountNull and others. None of those deleted scripts exist in this repo; the only copies are in cel.hrm history (git log --diff-filter=D --name-only -- '*_DB_Changes.sql' there). A fresh database built from this repo's scripts alone will be missing that schema, as well as the never-scripted MasterEmailLog tables.

Every script is guarded and re-runnable (IF COL_LENGTH(...) IS NULL, IF OBJECT_ID(...) IS NULL, sp_rename only when the old name is still there), documents its own run order, and states whether it must run before the matching code deploys. Follow that style.

Frontend (HRM.UI/ClientApp, Erecruitment.UI/ClientApp)

HRM.UI is on Angular 22.2 (framework 22.2.4, CLI/build/cdk 22.2.5) with Kendo 25 on the Babylon admin template; project name babylon, output dist/babylon; still NgModule-based (bootstrapModule(AppModule) with an explicit provideZoneChangeDetection()), templates on the @if/@for control flow. PrimeNG is gone (Parts 1–7b, 2026-11): PrimeNG 22 and primeicons 8 are under the paid PrimeUI licence (Community only for orgs under $1M revenue / 5 devs / 10 employees), so never add primeng, @primeuix/* or primeicons@8 back — primeicons stays on 7.0.0 (the last MIT release) and primeflex stays. Erecruitment.UI is a separate, unused Angular 13 app. Entry src/main.ts, root module src/app/app.module.ts, routes src/app/app.routes.ts.

What the Angular 22 upgrade (Part 8) changed, so don't undo it:

  • Angular 22 makes OnPush the default, so ng update wrote changeDetection: ChangeDetectionStrategy.Eager (the renamed Default) on every component — the code mutates arrays/objects in place and needs it. New components should state it too unless they are really written for OnPush.
  • In templates a?.b now yields undefined (JS semantics), not null; ng update wrapped the spots where that mattered in $safeNavigationMigration(...). Leave those wrappers alone.
  • TypeScript 6.0 (@angular/build 22 requires >=6.0 <6.1; TS 7 must wait for Angular). strictTemplates is off, so an extendedDiagnostics block in tsconfig.app.json fails the build (NG4003) — don't add one.
  • MSAL is @azure/msal-angular 6 / @azure/msal-browser 5 (v6 is the line for Angular 22). The app only uses loginRedirect, which works without MSAL 5's redirect-bridge page; adding loginPopup/ssoSilent would need that page and a new redirect URI in each client's Entra app registration. storeAuthStateInCookie no longer exists.
  • Left on purpose: @types/node 24 (matches Node 24), eslint 9 (eslint-plugin-import does not support 10).

What the earlier 19 → 21 upgrade fixed in place, so don't undo it:

  • Kendo needs a current licence key. Kendo checks the package release date against telerik-license.txt (replace the file, then npx kendo-ui-license activate); Kendo 25.3.0 was published 2026-10-07, so an older key shows a "Your license doesn't cover…" banner and an "Invalid license" watermark.

  • Kendo 25 removed primary from buttons and grid commands (now themeColor="primary") and look (now fillMode); a <kendo-formfield> must wrap exactly one form control. The AOT build does not report every unknown input on directive-bearing elements — the grid-command [primary] only showed up as a runtime NG0303 — so crawl the menu in dev mode after a UI-kit bump.

  • ess.module uses CUSTOM_ELEMENTS_SCHEMA, so a removed p-*/kendo-* tag there fails silently, not at build.

  • npm 11 blocks install scripts. package.json allowScripts approves @progress/kendo-licensing (its postinstall runs kendo-ui-license activate; without it Kendo shows an "unlicensed" watermark) and esbuild. After bumping either, re-run npm approve-scripts <pkg> or npx kendo-ui-license activate.

  • TabView is an adapter. Screens use app-tab-view / app-tab-panel (custom-components/tab-view-compat/tab-view-compat.ts, TabViewCompatModule), which keep the old PrimeNG index-based API ([(activeIndex)], (onChange) → {index}, *ngIf panels counted by visibility, <ng-template appTemplate="header">, tabView.tabs) and render a kendo-tabstrip. New screens should use kendo-tabstrip directly.

  • The ~570 'src/app/...' imports resolve through paths: { "src/*": ["./src/*"] } in tsconfig.json (no baseUrl, which TS 6 deprecates). ngx-toastr was removed (every call was commented out; there is no Angular 22 release).

  • Type-only imports must say type (import { type X }) — the CLI transpiles per file (isolatedModules).

  • The build is the esbuild/Vite @angular/build:application builder (webpack and @angular-devkit/build-angular are gone; prod build ~45 s, ng serve ready in ~40 s). outputPath.browser is "", so the output is still dist/babylon, which deploy.ps1 copies unchanged. AOT is on in development too. Google Fonts load from <link> tags in src/index.html: esbuild drops a CSS @import url(...) that is not at the top of a file.

  • npm start runs scripts/ng-serve.cjs, not ng serve directly. UseAngularCliServer (Startup) waits for webpack's "open your browser on " line, and the Vite dev server only prints "Local: ", so the script echoes that line. Remove it only together with moving Startup off UseAngularCliServer (e.g. to SpaProxy).

  • xlsx is 0.20.3 from https://cdn.sheetjs.com/...tgz (SheetJS no longer publishes to npm; 0.18.5 had a high advisory), so npm install needs that host reachable. 0.20 also fixed 0.18's Asia/Dhaka date bug: with cellDates: true, 0.18 read Excel dates 20 s early, and Historical Career Data Upload (toMiddayLocal) saved every date one day early — records uploaded before the switch may be off by a day. Known, unfixed: quill (low). package.json overrides pin glob ^14.0.3 under @progress/kendo-licensing (its CLI only; kendo-ui-license activate verified) and uuid ^11.1.1 under exceljs (the browser uses exceljs's prebuilt dist/exceljs.min.js). What is left in npm audit is exceljs's Node-only zip chain (archiver, glob 7) and dev tooling (eslint, karma) — none of it ships to the browser. Install with plain npm install/npm ci; --force is not needed.

  • Feature areas are lazy-loaded modules registered in app.routes.ts behind AuthGuard (payroll, leave, attendance, recruitment, core-hr, fund-admin, ess, ess-fund, ess-payroll, talent-management, final-settlement, claim, grievance-management, LMS, hrmopen-ai, calendar, survey, …), each under src/app/<name>/ with its own <name>.module.ts.

  • app.api.service.ts (ApiService) is the single HTTP wrapper (httpGet, httpPost, httpPostFile, httpDownloadFile, …). The base URL comes from environment.apiBaseUrl (src/environments/environment.ts → relative /api) in dev — proxy.json (the serve proxyConfig) forwards it to https://localhost:44374 — and from the page's <base href> + api in production.

  • Auth is cookie-based (MFA work, ported from GP_Master). AuthController.CreateTokenNew puts the real JWT in the HttpOnly, Secure, SameSite=Strict JWToken cookie and returns only a dummy-key copy, which the SPA keeps in localStorage/ApiService.AuthenticationToken for reading claims and sends as the Bearer header. Startup's JwtBearerEvents.OnMessageReceived lets the cookie win over that header; CredentialsInterceptor (app.api.service.ts) adds withCredentials; month-end (SalaryController.GenerateTokenAfterMonthEnd) re-sets the cookie; api/Authentication/logOut deletes it. So the API must stay same-origin with the page: never point the dev base URL back at an absolute https://localhost:44374, or every call after login is 401.

  • Shared code: _guards/, _models/<Module>/, _services/<module>/, picker//_picker// dynamic-picker/, custom-components/, form-builder/, helper/, SharedIconModule/.

  • The UI kit is Kendo UI Angular (@progress/kendo-angular-*, licensed) plus chart.js, sweetalert2, the two PDF viewers, exceljs/xlsx and MSAL (Azure AD, SSO.Config.ts). (Angular Material, Bootstrap, FullCalendar, apexcharts, Font Awesome, ng-busy and PrimeNG were removed.) New markup uses Kendo or plain HTML. The dialog pattern to copy: @if (show) { <div class="blur-background"><kendo-dialog title="…" [width]="900" maxHeight="90vh" (close)="show = false" (keydown.escape)="$event.stopPropagation()"> … </kendo-dialog></div> } (.blur-background is in styles.scss).

  • What PrimeNG left behind, kept on purpose: the Babylon layout-indigo.css / theme-indigo.css (the app layout depends on them — never remove), primeicons 7 (pi pi-*) and primeflex; the global rules PrimeNG's Aura theme used to inject at runtime (box-sizing, .pi 1rem, .p-disabled) live in src/styles/components/_primeng-base.scss; the old primeng/api types (MenuItem, SelectItem, TreeNode, …) live in _models/common/ui-types.ts; the sidebar ripple is @progress/kendo-ripple's register() in AppMenuComponent (pinned 1.0.2).

  • Compiled .js/.js.map files are checked in alongside .ts sources (~693 tracked .js files under src/). Always edit the .ts; never the generated .js.

  • Long-running actions show the shared loading panel: <app-loading-panel></app-loading-panel> in the template plus loadingPanel.ShowLoadingPanel = true/false around the call (~395 templates use it). The flag must be on the injected loadingPanelService (hrm-loding panel/loding.panel.service.ts), which is what <app-loading-panel> reads. UntilityHandlerService has a same-named ShowLoadingPanel that nothing renders, so ~10 older components that set it never show a spinner. Wrap every button/API action that can take a moment, and clear the flag in the error path too.

App bootstrap and the initial route

Four pieces decide where a page load actually lands, and they are easy to break one at a time:

  • Routing is hash-based ({provide: LocationStrategy, useClass: HashLocationStrategy} in app.module.ts), so every URL is …/#/path. RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'}).
  • path: '' is DashboardDemoComponent. It is not a dashboard so much as a dispatcher: its ngOnInit reads UserType from the JWT and forwards — Employee → /ess/self-dashboard, User → /ess/landing-page, SuperUser stays. So anything that lands on '' ends up on a dashboard.
  • AppMainComponent's constructor calls authService.logout() when the load is not a reload (performance.navigation.type), which is why opening a deep link in a fresh tab signs the user out.
  • <app-login [hidden]="!isLoginForm()"> sits in app.main.component.html — [hidden], not *ngIf. So LoginComponent's constructor runs once at bootstrap on every route, not just on /login. It redirects to / when it finds a token, and because ApiService's constructor now hydrates the static AuthenticationToken from localStorage, that check went live and started firing before the router's initial navigation — discarding the URL the user opened and dumping every deep link on a dashboard. It is now gated on window.location.hash actually containing /login (login.component.ts). Keep that gate: any unconditional router.navigate in a constructor that runs at bootstrap will beat the initial navigation and resurrect the same bug.

Styles

Global stylesheet is src/styles.scss, which imports vendor CSS then two local trees:

  • src/styles/vendors/kendo/** — centralized Kendo class overrides, split by component (grid/_rows.scss, buttons/_sizing.scss, card/_body.scss, …). These are global/unscoped, so they need no ::ng-deep.
  • src/styles/abstracts/_tokens.scss — app-wide SCSS design tokens ($brand-*, $gray-*, …). It has no dependencies of its own; never import a vendor partial from it.

There is an ongoing centralization effort tracked in HRM.UI/docs/css-centralization-progress.md: a per-file checklist of component styles that duplicate Kendo overrides, use ::ng-deep/ViewEncapsulation.None, or hardcode colors. Before adding a Kendo override to a component stylesheet, check whether a centralized partial already covers it, and update that document when you migrate a file.

One trap it documents: custom properties declared on :host do not resolve inside popups Kendo portals to the document root (appendTo: 'root' — dropdown/calendar popups). Use SCSS variables that compile to literals for those blocks, not var(--…).

Adding a feature: the full vertical slice

A typical feature commit touches, in order:

  1. HRM.BO/<Module>/<Entity>.cs (+ the I<Entity>Service interface)
  2. HRM.DA/DA/<Module>/<Entity>DA.cs — internal static, MakeSQL, takes TransactionContext
  3. HRM.DA/Service/<Module>/<Entity>Service.cs — transaction + MapObject/CreateObject
  4. HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs — register it
  5. HRM.UI/Controllers/<Module>/<Module>Controller.cs — thin endpoint
  6. ClientApp/src/app/_models/<Module>/<entity>.ts and _services/<module>/<module>.service.ts
  7. the feature component(s) under ClientApp/src/app/<feature>/
  8. a root <Feature>_DB_Changes.sql if the schema changes