Skip to content

Replace products and services with brrg api - #62

Open
pernillehofgaard wants to merge 6 commits into
mainfrom
feature/replace-services-with-api
Open

pernillehofgaard wants to merge 6 commits into
mainfrom
feature/replace-services-with-api

Conversation

@pernillehofgaard

@pernillehofgaard pernillehofgaard commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator

Description

Replace products and services lookup with brønnøysund api when fetching annual financial resports and årsregnskap

Documentation

  • Doc updated

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a dedicated Annual Financial Report PDF endpoint for downloading a specific year’s report.
    • Extended available evidence codes to include PDF-based annual financial report data.
  • Refactor

    • Improved annual financial report retrieval by using the Regnskapsregisteret “years” list to generate year-specific evidence (including PDF URLs).
  • Breaking Changes

    • Removed the open/public Annual Financial Report endpoint.
    • Removed the open/public Regnskapsregisteret endpoint and its related evidence definition.
  • Documentation

    • Updated evidence-code listing formatting and entries.

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@pernillehofgaard, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 54 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b2af3d90-5fda-4f9e-8224-560b8b653e08

📥 Commits

Reviewing files that changed from the base of the PR and between 07698fa and 28052ba.

📒 Files selected for processing (1)
  • src/Dan.Plugin.Brreg/AnnualFinancialReport.cs

Walkthrough

AnnualFinancialReport is refactored to use an injected IHttpClientFactory-based HttpClient to call the Regnskapsregisteret "aar" and "kopi" endpoints directly. A new PDF endpoint (AnnualFinancialReportPdf) downloads single-year PDFs with optional Basic auth. All "Open" function endpoint variants (AnnualFinancialReportOpen, RegnskapsregisteretOpen) and their evidence definitions are removed, and related commented-out entries are cleaned from Metadata.cs.

Changes

Open Endpoint Removal and AnnualFinancialReport Migration

Layer / File(s) Summary
HttpClient integration and year-list migration
src/Dan.Plugin.Brreg/AnnualFinancialReport.cs
Adds System.Net.Http and Dan.Plugin.Brreg.Helpers imports, extends constructor to accept IHttpClientFactory and initializes _client field, updates the POST handler lambda, and replaces GetAnnualFinancialReports to fetch available years from the Regnskapsregisteret "/aar" endpoint via Requests.MakeRequest, validate non-empty results, select top N years descending, and build per-year PDF URL evidence from the configured base URI.
PDF endpoint and evidence definition
src/Dan.Plugin.Brreg/AnnualFinancialReport.cs
Introduces a new Azure Function handler RunPdfAsync (AnnualFinancialReportPdf) that authenticates and downloads PDFs from the Regnskapsregisteret "/kopi/{organization}/{year}" endpoint using the injected _client with optional Basic auth, validates success, and returns PDF bytes as application/pdf. Adds GetDefinitionPdf() evidence code definition and GetAnnualFinancialReportPdf helper to fetch and base64-encode the PDF evidence.
Open endpoint and metadata cleanup
src/Dan.Plugin.Brreg/Regnskapsregisteret.cs, src/Dan.Plugin.Brreg/Metadata.cs
Removes RRAccountsOpen Azure Function handler and GetDefinitionRegnskapOpen static definition from Regnskapsregisteret.cs, and removes commented-out "Open" evidence-code entries from Metadata.cs evidence-code list while adding AnnualFinancialReport.GetDefinitionPdf() to active definitions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • Replace annualaccounts with the new BR api #61: This PR directly implements the migration described in that issue — replacing the AnnualFinancialReport product-API retrieval with direct Regnskapsregisteret endpoint calls (/aar for year list, /kopi/{organization}/{year} for PDF downloads) and removing all "...Open" dataset variants from endpoints and metadata.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title 'Replace products and services with brrg api' is misleading and does not accurately reflect the actual changes in the pull request. Revise the title to accurately describe the main changes, such as 'Add dedicated PDF endpoint and refactor annual financial report fetching' or 'Migrate annual financial reports to Regnskapsregisteret API endpoints'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 22.22% which is sufficient. The required threshold is 0.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/replace-services-with-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs`:
- Around line 209-223: The broad catch block in the financial report retrieval
logic is masking all upstream failures (timeouts, server errors, authentication
issues) as a permanent "no report available" error, which breaks retry and
alerting behavior. Instead of catching all exceptions, distinguish between
actual "report not available" scenarios (such as specific response codes or
deserialize failures) and upstream infrastructure errors. For genuine "no
report" cases, throw the EvidenceSourcePermanentClientException, but for
transient failures from Requests.MakeRequest, either re-throw the original
exception or wrap it in an appropriate transient exception type that allows
retries.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a49487f7-0202-4baf-8a03-5e2bf719763b

📥 Commits

Reviewing files that changed from the base of the PR and between 1925cdb and ced4f8f.

📒 Files selected for processing (3)
  • src/Dan.Plugin.Brreg/AnnualFinancialReport.cs
  • src/Dan.Plugin.Brreg/Metadata.cs
  • src/Dan.Plugin.Brreg/Regnskapsregisteret.cs
💤 Files with no reviewable changes (1)
  • src/Dan.Plugin.Brreg/Regnskapsregisteret.cs

Comment thread src/Dan.Plugin.Brreg/AnnualFinancialReport.cs Outdated
@pernillehofgaard

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Dan.Plugin.Brreg/AnnualFinancialReport.cs (1)

40-46: 🩺 Stability & Availability | 🔴 Critical

Register the "SafeHttpClient" named client in the DI container.

The constructor calls httpClientFactory.CreateClient("SafeHttpClient") (line 45), but this named client is not registered in Program.cs. The DI configuration only registers "myMaskinportenClient". Without the registration, either an exception will be thrown at runtime or a default client will be returned, silently losing any intended resiliency/timeout policy.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs` around lines 40 - 46, The
AnnualFinancialReport constructor references a named HTTP client called
"SafeHttpClient" when calling httpClientFactory.CreateClient("SafeHttpClient"),
but this named client is not registered in the DI container in Program.cs.
Register the "SafeHttpClient" named client in Program.cs using the same pattern
as other HTTP clients (such as "myMaskinportenClient"), ensuring you configure
it with any required resiliency policies, timeout settings, or other
configuration needed for safe HTTP communication.
🧹 Nitpick comments (2)
src/Dan.Plugin.Brreg/AnnualFinancialReport.cs (2)

302-331: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Unused helper duplicates RunPdfAsync logic.

GetAnnualFinancialReportPdf reconstructs the exact same URL, Accept/Basic-auth headers, GET, and success check as RunPdfAsync (Lines 101-122), but does not appear to be called. Either wire it into the handler (see the contract comment on Lines 91-128) and remove the inline duplication, or delete it. Keeping both copies will let the two PDF paths drift.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs` around lines 302 - 331, The
GetAnnualFinancialReportPdf method duplicates the exact same URL construction,
Accept header setup, Basic authentication header logic, GET request, and success
status code checking that already exists in the RunPdfAsync method. To fix this,
either delete the GetAnnualFinancialReportPdf method entirely if it is unused,
or refactor both methods to extract the common HTTP request and header setup
logic into a shared helper method that both RunPdfAsync and
GetAnnualFinancialReportPdf can call to eliminate the duplication and prevent
future drift between the two PDF handling paths.

341-342: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Avoid the serialize→deserialize round-trip.

response is already a deserialized dynamic from Requests.MakeRequest; re-serializing then deserializing to List<string> is an extra full JSON round-trip on every call. Since MakeRequest returns the parsed JSON, you can cast/convert directly (e.g. ((JArray)response).ToObject<List<string>>()).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs` around lines 341 - 342, The
availableYears assignment is performing an unnecessary JSON
serialize-deserialize round-trip on the already-deserialized response object
from Requests.MakeRequest. Replace the JsonConvert.SerializeObject and
JsonConvert.DeserializeObject pattern with a direct cast and conversion using
the ToObject method (for example, cast response to JArray and call
ToObject<List<string>>()) to eliminate the inefficient round-trip and improve
performance on every call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs`:
- Around line 97-101: The year parameter extracted via TryGetParameter is not
validated before being interpolated into the URL path for the
RegnskapsregisteretUri endpoint. Add validation after the TryGetParameter call
to check that the method returned true (indicating year was successfully
retrieved) and that year matches an expected format such as a four-digit numeric
year. Only proceed to build the url variable if validation passes, otherwise
handle the validation failure by returning an error response or appropriate
exception. This prevents malformed URLs, null/empty path segments, and potential
path traversal issues.
- Around line 91-128: The RunPdfAsync method is returning raw PDF bytes directly
instead of conforming to the evidence framework contract. Replace the current
response logic that directly returns PDF bytes with a call to
EvidenceSourceResponse.CreateResponse(), passing a lambda that calls the
existing GetAnnualFinancialReportPdf() helper method (which properly converts
the PDF to base64 and wraps it in EvidenceValue objects). This will align the
RunPdfAsync endpoint with the contract defined in GetDefinitionPdf() and make
the implementation consistent with all other handlers in the class that use
EvidenceSourceResponse.CreateResponse().

---

Outside diff comments:
In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs`:
- Around line 40-46: The AnnualFinancialReport constructor references a named
HTTP client called "SafeHttpClient" when calling
httpClientFactory.CreateClient("SafeHttpClient"), but this named client is not
registered in the DI container in Program.cs. Register the "SafeHttpClient"
named client in Program.cs using the same pattern as other HTTP clients (such as
"myMaskinportenClient"), ensuring you configure it with any required resiliency
policies, timeout settings, or other configuration needed for safe HTTP
communication.

---

Nitpick comments:
In `@src/Dan.Plugin.Brreg/AnnualFinancialReport.cs`:
- Around line 302-331: The GetAnnualFinancialReportPdf method duplicates the
exact same URL construction, Accept header setup, Basic authentication header
logic, GET request, and success status code checking that already exists in the
RunPdfAsync method. To fix this, either delete the GetAnnualFinancialReportPdf
method entirely if it is unused, or refactor both methods to extract the common
HTTP request and header setup logic into a shared helper method that both
RunPdfAsync and GetAnnualFinancialReportPdf can call to eliminate the
duplication and prevent future drift between the two PDF handling paths.
- Around line 341-342: The availableYears assignment is performing an
unnecessary JSON serialize-deserialize round-trip on the already-deserialized
response object from Requests.MakeRequest. Replace the
JsonConvert.SerializeObject and JsonConvert.DeserializeObject pattern with a
direct cast and conversion using the ToObject method (for example, cast response
to JArray and call ToObject<List<string>>()) to eliminate the inefficient
round-trip and improve performance on every call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 769d3e2c-e0cc-4891-996c-846f598a1db2

📥 Commits

Reviewing files that changed from the base of the PR and between 64d2c9c and 63b1c6f.

📒 Files selected for processing (2)
  • src/Dan.Plugin.Brreg/AnnualFinancialReport.cs
  • src/Dan.Plugin.Brreg/Metadata.cs

Comment thread src/Dan.Plugin.Brreg/AnnualFinancialReport.cs
Comment thread src/Dan.Plugin.Brreg/AnnualFinancialReport.cs Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant