Skip to content
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

Add endpoint for analytics dashboard #134

Merged
merged 11 commits into from
Oct 16, 2024

Conversation

MohammadPCh
Copy link
Collaborator

@MohammadPCh MohammadPCh commented Oct 15, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new GraphQL resolver for querying vouch counts by organization and date range.
    • Added new data structures for managing vouch count results and monthly breakdowns.
    • Implemented a date validation function to ensure proper date formats.
  • Bug Fixes

    • Updated export paths for resolver classes to ensure correct module references.
  • Documentation

    • Enhanced type definitions for better clarity on vouch count results and their organization.

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

The pull request introduces a new GraphQL resolver, OrganisationResolver, to handle queries for organization vouch counts. This resolver includes a method for retrieving vouch counts by date, utilizing TypeGraphQL and TypeORM for database interactions. Additionally, the resolvers/index.ts file is updated to include this new resolver and adjust the export paths. New types, VouchCountResult and VouchCountPerMonth, are defined in types.ts to structure the data returned by the resolver. A helper function, isValidDate, is also added to validate date formats.

Changes

File Path Change Summary
src/server-extension/organization-resolver.ts - Added OrganisationResolver class.
- Added method getOrganisationVouchCountByDate for querying vouch counts.
src/server-extension/resolvers/index.ts - Updated export for ProjectResolver from ../resolver to ../project-resolver.
- Added export for OrganisationResolver from ../organization-resolver.
src/server-extension/types.ts - Added VouchCountResult class with fields for total counts.
- Added VouchCountPerMonth class for monthly breakdown.
src/server-extension/helper.ts - Added isValidDate function for validating date strings.

Possibly related PRs

  • Add organization sort #133: The changes in this PR involve the introduction of a new GraphQL resolver class (ProjectResolver) and modifications to the helper.ts file, which are related to the overall structure of GraphQL resolvers, similar to the OrganisationResolver added in the main PR.

Poem

In the garden of code, a new resolver blooms,
OrganisationResolver, dispelling the glooms.
With vouch counts in hand, by date they align,
Data flows smoothly, like rabbits in line.
Hopping through queries, with grace and with cheer,
A structure of types, so lovely and clear! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 412eeaf and 7c59fa0.

📒 Files selected for processing (1)
  • src/server-extension/helper.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/server-extension/helper.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@MohammadPCh
Copy link
Collaborator Author

@coderabbitai review

Copy link
Contributor

@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: 5

🧹 Outside diff range and nitpick comments (2)
src/server-extension/types.ts (1)

24-37: LGTM! Consider using a more specific type for the date field.

The VouchCountPerMonth class is well-defined with appropriate decorators and field types. The use of default values is a good practice for preventing null/undefined errors.

However, consider using a more specific type for the date field instead of a string. GraphQL has a built-in DateTime scalar type which might be more appropriate for representing dates.

You could modify the date field as follows:

- @Field()
- date: string = "";
+ @Field(() => GraphQLISODateTime)
+ date: Date = new Date();

Don't forget to import GraphQLISODateTime from type-graphql at the top of the file:

import { ..., GraphQLISODateTime } from "type-graphql";

This change would provide better type safety and automatic date parsing/serialization.

src/server-extension/organization-resolver.ts (1)

7-7: Inconsistent spelling: 'Organisation' vs 'Organization'

The class is named OrganisationResolver, but the file is named organization-resolver.ts, using different spellings of "organization". For consistency and to prevent confusion, it's recommended to use the same spelling throughout the codebase.

Consider renaming the class to OrganizationResolver or renaming the file to organisation-resolver.ts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 72f9e10 and 55d78bc.

📒 Files selected for processing (3)
  • src/server-extension/organization-resolver.ts (1 hunks)
  • src/server-extension/resolvers/index.ts (1 hunks)
  • src/server-extension/types.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
src/server-extension/resolvers/index.ts (1)

1-1: LGTM. Verify the new import path.

The import path for ProjectResolver has been updated, which is likely part of a project structure reorganization. This change looks good, but it's important to ensure that the new path is correct.

Let's verify that the new import path is correct:

✅ Verification successful

Verified: The new import path for ProjectResolver exists and there are no remaining imports from the old path.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that the project-resolver file exists
fd -t f project-resolver.ts -X echo "project-resolver.ts exists"

# Check for any remaining imports from the old path
rg --type typescript '"../resolver"'

Length of output: 210


Script:

#!/bin/bash
# Verify that the project-resolver file exists
fd -t f project-resolver.ts -X echo "project-resolver.ts exists"

# Check for any remaining imports from the old path using a glob pattern
rg --glob '*.ts' '"../resolver"'

Length of output: 171

src/server-extension/types.ts (1)

15-22: LGTM! Well-structured class definition.

The VouchCountResult class is well-defined with appropriate decorators and field types. The use of default values is a good practice for preventing null/undefined errors.

src/server-extension/resolvers/index.ts Show resolved Hide resolved
src/server-extension/organization-resolver.ts Show resolved Hide resolved
src/server-extension/organization-resolver.ts Outdated Show resolved Hide resolved
src/server-extension/organization-resolver.ts Outdated Show resolved Hide resolved
src/server-extension/organization-resolver.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 55d78bc and 412eeaf.

📒 Files selected for processing (2)
  • src/server-extension/helper.ts (1 hunks)
  • src/server-extension/organization-resolver.ts (1 hunks)
🧰 Additional context used
🪛 Biome
src/server-extension/helper.ts

[error] 20-20: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (6)
src/server-extension/organization-resolver.ts (6)

1-9: LGTM: Imports and class declaration are well-structured.

The imports are appropriate for the functionality, and the class declaration with its constructor is correctly implemented.


11-27: Great job on input validation!

The input validation for date formats and range is well-implemented, addressing the previous concern about potential errors due to invalid date formats. The error messages are clear and informative.


1-74: Overall, good implementation with room for improvement

The OrganisationResolver class is well-structured and implements the required functionality for fetching organization vouch counts. The input validation and error handling are particularly well done. However, there are a few areas where the code could be further improved:

  1. Consider using TypeORM's QueryBuilder instead of raw SQL for better maintainability and security.
  2. Enhance type safety by avoiding the use of any types, especially in the result mapping function.
  3. Include more detailed error information when rethrowing exceptions to aid in debugging.

Implementing these suggestions will further improve the code quality, maintainability, and robustness of this resolver.


28-54: 🛠️ Refactor suggestion

Consider using TypeORM QueryBuilder for improved maintainability

While the current SQL query is well-structured, using TypeORM's QueryBuilder can enhance code readability, maintainability, and security. It provides better integration with TypeORM's features and helps prevent SQL injection vulnerabilities.

As suggested in a previous review, consider refactoring the query using QueryBuilder. Here's an example of how it could be implemented:

const resultPerMonth = await manager
  .getRepository('project_attestation')
  .createQueryBuilder('project_attestation')
  .select("TO_CHAR(project_attestation.attest_timestamp, 'YYYY-MM')", 'date')
  .addSelect('COUNT(*)', 'total_count')
  .addSelect(
    "SUM(CASE WHEN project_attestation.comment IS NOT NULL AND project_attestation.comment != '' THEN 1 ELSE 0 END)",
    'count_with_comments'
  )
  .leftJoin('attestor_organisation', 'attestor_organisation', 'project_attestation.attestor_organisation_id = attestor_organisation.id')
  .where('attestor_organisation.organisation_id = :organisationId', { organisationId })
  .andWhere('project_attestation.vouch = true')
  .andWhere('project_attestation.attest_timestamp BETWEEN :fromDate AND :toDate', { fromDate, toDate })
  .groupBy("TO_CHAR(project_attestation.attest_timestamp, 'YYYY-MM')")
  .orderBy('date')
  .getRawMany();

This approach would align better with TypeORM best practices and improve overall code quality.


56-68: 🛠️ Refactor suggestion

Enhance type safety by avoiding 'any' type

To improve type safety and prevent potential runtime errors, consider defining a specific interface or type for the query result instead of using any. This addresses a previous review comment and aligns with TypeScript best practices.

Here's a suggested implementation:

interface VouchCountRow {
  date: string;
  total_count: string;
  count_with_comments: string;
}

const totalPerMonth: VouchCountPerMonth[] = resultPerMonth.map(
  (row: VouchCountRow) => ({
    date: row.date,
    totalCount: Number(row.total_count),
    countWithComments: Number(row.count_with_comments),
    countWithoutComments: Number(row.total_count) - Number(row.count_with_comments),
  })
);

This approach provides better type checking and makes the code more robust and self-documenting.


69-73: 🛠️ Refactor suggestion

Improve error handling by including original error details

The current error handling approach of catching, logging, and rethrowing errors is good. However, to further aid in debugging, consider including the original error message in the thrown exception, as suggested in a previous review.

You can modify the error handling as follows:

} catch (error: unknown) {
  console.error("Error fetching vouch count by date:", error);
  if (error instanceof Error) {
    throw new Error(`Failed to fetch vouch count by date: ${error.message}`);
  } else {
    throw new Error("Failed to fetch vouch count by date: Unknown error");
  }
}

This change will provide more context about the specific error that occurred, making it easier to diagnose and fix issues in production.

src/server-extension/helper.ts Outdated Show resolved Hide resolved
@MohammadPCh MohammadPCh merged commit d7849fd into develop Oct 16, 2024
@MohammadPCh MohammadPCh deleted the add-endpoint-for-analytics-dashboard branch October 16, 2024 06:39
This was referenced Oct 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant