-
Notifications
You must be signed in to change notification settings - Fork 72
WIP - CADTrust v2 Export functionality. #357
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Nolski
wants to merge
7
commits into
main
Choose a base branch
from
cadt-v2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c511c77
feat: Add CAD Trust V2 integration and export functionality
Nolski bbde4da
feat: Update Docker Compose configuration for development
Nolski cdf0f97
refactor: Move CADT Export under Reports with admin toggle
Nolski d221b4b
feat: Add SQL seed script with test data for development
Nolski 8719c58
fix: Settings toggle not persisting due to type mismatch
Nolski 5e33fa5
ci: Add GitHub Actions workflow to run tests on PRs to main
Nolski a5bee5d
Potential fix for code scanning alert no. 32: Workflow does not conta…
Nolski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| name: Tests | ||
|
|
||
| on: | ||
| pull_request: | ||
| branches: [main] | ||
| push: | ||
| branches: [main] | ||
|
|
||
| jobs: | ||
| backend-tests: | ||
| name: Backend Unit & Integration Tests | ||
| runs-on: ubuntu-latest | ||
| defaults: | ||
| run: | ||
| working-directory: backend/services | ||
|
|
||
| steps: | ||
| - uses: actions/checkout@v4 | ||
|
|
||
| - name: Use Node.js 20 | ||
| uses: actions/setup-node@v4 | ||
| with: | ||
| node-version: 20 | ||
| cache: yarn | ||
| cache-dependency-path: backend/services/yarn.lock | ||
|
|
||
| - name: Install dependencies | ||
| run: yarn install --frozen-lockfile | ||
|
|
||
| - name: Build | ||
| run: yarn build | ||
|
|
||
| - name: Run CADT v2 integration tests | ||
| run: > | ||
| npx jest --no-coverage --forceExit | ||
| --testPathPattern='cadt/__tests__|cadt-export\.controller' | ||
|
|
||
| - name: Run other passing unit tests | ||
| run: > | ||
| npx jest --no-coverage --forceExit | ||
| --testPathPattern='shared\.service|core\.service|casl-ability' | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
backend/services/libs/shared/src/cadt/__tests__/axios-mock.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import axios from "axios"; | ||
|
|
||
| jest.mock("axios"); | ||
|
|
||
| interface RecordedCall { | ||
| method: string; | ||
| url: string; | ||
| data: any; | ||
| headers: any; | ||
| } | ||
|
|
||
| export function createAxiosMock() { | ||
| const calls: RecordedCall[] = []; | ||
| const responses: Record<string, any> = {}; | ||
|
|
||
| const mockedAxios = axios as jest.MockedFunction<typeof axios>; | ||
| mockedAxios.mockImplementation(async (config: any) => { | ||
| const call: RecordedCall = { | ||
| method: config.method, | ||
| url: config.url, | ||
| data: config.data, | ||
| headers: config.headers, | ||
| }; | ||
| calls.push(call); | ||
|
|
||
| const matchingKey = Object.keys(responses).find( | ||
| (k) => config.url?.includes(k) | ||
| ); | ||
| if (matchingKey) { | ||
| return { data: responses[matchingKey], status: 200 }; | ||
| } | ||
|
|
||
| return { data: { uuid: `mock-uuid-${calls.length}` }, status: 200 }; | ||
| }); | ||
|
|
||
| return { | ||
| mock: mockedAxios, | ||
| calls, | ||
| setResponse(endpoint: string, response: any) { | ||
| responses[endpoint] = response; | ||
| }, | ||
| reset() { | ||
| calls.length = 0; | ||
| Object.keys(responses).forEach((k) => delete responses[k]); | ||
| mockedAxios.mockClear(); | ||
| }, | ||
| }; | ||
| } |
279 changes: 279 additions & 0 deletions
279
backend/services/libs/shared/src/cadt/__tests__/cadt-v2-api.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,279 @@ | ||
| import { CadtV2ApiService } from "../cadt-v2-api.service"; | ||
| import { CadtV2MappingService } from "../cadt-v2-mapping.service"; | ||
| import { createMockConfigService } from "./config-mock"; | ||
| import { | ||
| makeProjectEntity, | ||
| makeProgramme, | ||
| makeCompany, | ||
| makeCreditBlock, | ||
| } from "./test-fixtures"; | ||
| import { TxType } from "../../enum/txtype.enum"; | ||
|
|
||
| jest.mock("axios"); | ||
| import axios from "axios"; | ||
| const mockedAxios = axios as jest.MockedFunction<typeof axios>; | ||
|
|
||
| describe("CadtV2ApiService", () => { | ||
| let service: CadtV2ApiService; | ||
| let mappingService: CadtV2MappingService; | ||
| let mockEntityMapRepo: any; | ||
| let mockProjectRepo: any; | ||
| let mockProgrammeRepo: any; | ||
| let mockCreditBlockRepo: any; | ||
| let mockCountryRepo: any; | ||
| let mockCompanyService: any; | ||
| let mockLogger: any; | ||
|
|
||
| const storedEntities: Record<string, any> = {}; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| Object.keys(storedEntities).forEach((k) => delete storedEntities[k]); | ||
|
|
||
| const configService = createMockConfigService(); | ||
| mappingService = new CadtV2MappingService(configService as any); | ||
|
|
||
| mockEntityMapRepo = { | ||
| findOne: jest.fn().mockImplementation(({ where }) => { | ||
| const key = `${where.cadtEntityType}:${where.localEntityId}`; | ||
| return storedEntities[key] || null; | ||
| }), | ||
| save: jest.fn().mockImplementation((entity) => { | ||
| const key = `${entity.cadtEntityType}:${entity.localEntityId}`; | ||
| storedEntities[key] = entity; | ||
| return entity; | ||
| }), | ||
| count: jest.fn().mockResolvedValue(0), | ||
| createQueryBuilder: jest.fn().mockReturnValue({ | ||
| select: jest.fn().mockReturnThis(), | ||
| getRawOne: jest.fn().mockResolvedValue({ lastSync: null }), | ||
| }), | ||
| }; | ||
|
|
||
| mockProjectRepo = { | ||
| findOneBy: jest.fn().mockResolvedValue(makeProjectEntity()), | ||
| find: jest.fn().mockResolvedValue([makeProjectEntity()]), | ||
| }; | ||
|
|
||
| mockProgrammeRepo = { | ||
| createQueryBuilder: jest.fn().mockReturnValue({ | ||
| where: jest.fn().mockReturnThis(), | ||
| orWhere: jest.fn().mockReturnThis(), | ||
| getOne: jest.fn().mockResolvedValue(makeProgramme()), | ||
| }), | ||
| }; | ||
|
|
||
| mockCreditBlockRepo = { | ||
| find: jest.fn().mockResolvedValue([makeCreditBlock()]), | ||
| }; | ||
|
|
||
| mockCountryRepo = { | ||
| findOneBy: jest | ||
| .fn() | ||
| .mockResolvedValue({ alpha2: "NG", alpha3: "NGA", name: "Nigeria" }), | ||
| }; | ||
|
|
||
| mockCompanyService = { | ||
| findByCompanyIds: jest.fn().mockResolvedValue([makeCompany()]), | ||
| findByCompanyId: jest.fn().mockResolvedValue(makeCompany()), | ||
| }; | ||
|
|
||
| mockLogger = { | ||
| log: jest.fn(), | ||
| debug: jest.fn(), | ||
| warn: jest.fn(), | ||
| error: jest.fn(), | ||
| }; | ||
|
|
||
| let callCount = 0; | ||
| mockedAxios.mockImplementation(async () => { | ||
| callCount++; | ||
| return { | ||
| data: { uuid: `mock-uuid-${callCount}` }, | ||
| status: 200, | ||
| } as any; | ||
| }); | ||
|
|
||
| service = new CadtV2ApiService( | ||
| configService as any, | ||
| mappingService, | ||
| mockCompanyService, | ||
| mockEntityMapRepo, | ||
| mockProgrammeRepo, | ||
| mockProjectRepo, | ||
| mockCreditBlockRepo, | ||
| mockCountryRepo, | ||
| mockLogger | ||
| ); | ||
| }); | ||
|
|
||
| describe("syncProject", () => { | ||
| it("makes API calls in correct dependency chain order", async () => { | ||
| await service.syncProject("P-001"); | ||
|
|
||
| const urls = mockedAxios.mock.calls.map((c: any) => { | ||
| const url: string = c[0]?.url || ""; | ||
| return url.replace(/.*v2\//, ""); | ||
| }); | ||
|
|
||
| const methodologyIdx = urls.findIndex((u) => u === "methodology"); | ||
| const projectIdx = urls.findIndex((u) => u === "project"); | ||
| const locationIdx = urls.findIndex((u) => u === "location"); | ||
| const stakeholderIdx = urls.findIndex((u) => u === "stakeholder"); | ||
| const pmIdx = urls.findIndex((u) => u === "project-methodology"); | ||
| const validationIdx = urls.findIndex((u) => u === "validation"); | ||
| const verificationIdx = urls.findIndex((u) => u === "verification"); | ||
| const commitIdx = urls.indexOf("staging/commit"); | ||
|
|
||
| expect(methodologyIdx).toBeLessThan(pmIdx); | ||
| expect(projectIdx).toBeLessThan(locationIdx); | ||
| expect(projectIdx).toBeLessThan(stakeholderIdx); | ||
| expect(projectIdx).toBeLessThan(pmIdx); | ||
| expect(validationIdx).toBeLessThan(verificationIdx); | ||
| expect(verificationIdx).toBeLessThan(commitIdx); | ||
| }); | ||
|
|
||
| it("stores UUIDs in entity map", async () => { | ||
| await service.syncProject("P-001"); | ||
|
|
||
| expect(mockEntityMapRepo.save).toHaveBeenCalled(); | ||
| const savedTypes = mockEntityMapRepo.save.mock.calls.map( | ||
| (c: any) => c[0].cadtEntityType | ||
| ); | ||
| expect(savedTypes).toContain("project"); | ||
| expect(savedTypes).toContain("methodology"); | ||
| expect(savedTypes).toContain("location"); | ||
| }); | ||
|
|
||
| it("uses PUT for existing projects", async () => { | ||
| storedEntities["project:P-001"] = { | ||
| cadtEntityType: "project", | ||
| localEntityId: "P-001", | ||
| cadtUuid: "existing-uuid", | ||
| lastSyncedAt: Date.now(), | ||
| syncStatus: "committed", | ||
| }; | ||
|
|
||
| await service.syncProject("P-001"); | ||
|
|
||
| const putCalls = mockedAxios.mock.calls.filter( | ||
| (c: any) => c[0]?.method === "put" | ||
| ); | ||
| expect(putCalls.length).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| it("skips when project not found", async () => { | ||
| mockProjectRepo.findOneBy.mockResolvedValue(null); | ||
| await service.syncProject("P-NONEXISTENT"); | ||
| expect(mockLogger.warn).toHaveBeenCalled(); | ||
| expect(mockedAxios).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("handles issuance and unit creation for credit blocks", async () => { | ||
| await service.syncProject("P-001"); | ||
|
|
||
| const urls = mockedAxios.mock.calls.map( | ||
| (c: any) => c[0]?.url?.replace(/.*v2\//, "") || "" | ||
| ); | ||
| expect(urls).toContain("issuance"); | ||
| expect(urls).toContain("unit"); | ||
| }); | ||
|
|
||
| it("commits after staging all entities", async () => { | ||
| await service.syncProject("P-001"); | ||
|
|
||
| const urls = mockedAxios.mock.calls.map( | ||
| (c: any) => c[0]?.url?.replace(/.*v2\//, "") || "" | ||
| ); | ||
| const commitCalls = urls.filter((u) => u === "staging/commit"); | ||
| expect(commitCalls.length).toBeGreaterThanOrEqual(1); | ||
| }); | ||
| }); | ||
|
|
||
| describe("syncAll", () => { | ||
| it("returns synced and failed counts", async () => { | ||
| const result = await service.syncAll(); | ||
| expect(result.synced).toBe(1); | ||
| expect(result.failed).toBe(0); | ||
| }); | ||
|
|
||
| it("counts failures individually", async () => { | ||
| mockProjectRepo.find.mockResolvedValue([ | ||
| makeProjectEntity({ refId: "P-001" }), | ||
| makeProjectEntity({ refId: "P-002" }), | ||
| ]); | ||
|
|
||
| let callNum = 0; | ||
| mockedAxios.mockImplementation(async (config: any) => { | ||
| callNum++; | ||
| if (config?.url?.includes("P-002") || callNum > 20) { | ||
| throw new Error("API error"); | ||
| } | ||
| return { data: { uuid: `uuid-${callNum}` }, status: 200 } as any; | ||
| }); | ||
|
|
||
| const result = await service.syncAll(); | ||
| expect(result.synced + result.failed).toBe(2); | ||
| }); | ||
| }); | ||
|
|
||
| describe("config disabled", () => { | ||
| it("does not make API calls when disabled", async () => { | ||
| const disabledConfig = createMockConfigService({ | ||
| "cadTrustV2.enable": false, | ||
| }); | ||
| const disabledService = new CadtV2ApiService( | ||
| disabledConfig as any, | ||
| mappingService, | ||
| mockCompanyService, | ||
| mockEntityMapRepo, | ||
| mockProgrammeRepo, | ||
| mockProjectRepo, | ||
| mockCreditBlockRepo, | ||
| mockCountryRepo, | ||
| mockLogger | ||
| ); | ||
|
|
||
| await disabledService.syncProject("P-001"); | ||
| expect(mockedAxios).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns zero counts when disabled", async () => { | ||
| const disabledConfig = createMockConfigService({ | ||
| "cadTrustV2.enable": false, | ||
| }); | ||
| const disabledService = new CadtV2ApiService( | ||
| disabledConfig as any, | ||
| mappingService, | ||
| mockCompanyService, | ||
| mockEntityMapRepo, | ||
| mockProgrammeRepo, | ||
| mockProjectRepo, | ||
| mockCreditBlockRepo, | ||
| mockCountryRepo, | ||
| mockLogger | ||
| ); | ||
|
|
||
| const result = await disabledService.syncAll(); | ||
| expect(result).toEqual({ synced: 0, failed: 0 }); | ||
| }); | ||
| }); | ||
|
|
||
| describe("getSyncStatus", () => { | ||
| it("returns status with defaults when no syncs", async () => { | ||
| const status = await service.getSyncStatus(); | ||
| expect(status.lastSyncTime).toBeNull(); | ||
| expect(status.projectCount).toBe(0); | ||
| expect(status.failedCount).toBe(0); | ||
| }); | ||
| }); | ||
|
|
||
| describe("error handling", () => { | ||
| it("logs errors when API calls fail", async () => { | ||
| mockedAxios.mockRejectedValueOnce(new Error("Network error")); | ||
|
|
||
| await expect(service.syncProject("P-001")).rejects.toThrow(); | ||
| expect(mockLogger.error).toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.