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

Query for recurring donation by date #1738

Merged
merged 7 commits into from
Aug 6, 2024

Conversation

lovelgeorge99
Copy link
Contributor

@lovelgeorge99 lovelgeorge99 commented Jul 30, 2024

I have added a query to fetch recurring donations of a projects from a given date for this issue Giveth/giveth-dapps-v2#4287 (comment)

Summary by CodeRabbit

  • New Features

    • Introduced a new GraphQL query to retrieve recurring donations filtered by project ID and optional date range.
    • Enhanced query results to include donor details and total count of donations matching the criteria.
  • Bug Fixes

    • Improved error handling for non-existent projects to provide localized messages.
  • Tests

    • Added comprehensive test cases for the new query to validate date range filtering and edge scenarios.
  • Style

    • Made minor formatting changes to the NETWORKS_IDS_TO_NAME object for cleaner code presentation.

Copy link
Contributor

coderabbitai bot commented Jul 30, 2024

Walkthrough

Recent changes enhance the GraphQL API by adding a new query, recurringDonationsByDate, which allows clients to filter recurring donations based on projectId and an optional date range. This update improves data retrieval capabilities, providing detailed donor information and a count of matching donations, thus making the API more versatile and user-friendly.

Changes

File Change Summary
src/resolvers/... Added recurringDonationsByDate method to RecurringDonationResolver for filtering donations by projectId, startDate, and endDate.
test/graphqlQueries.ts Introduced fetchRecurringDonationsByDate query for fetching recurring donations based on project ID and date range, including detailed donor information.
src/resolvers/...test.ts Added recurringDonationsByProjectDateTestCases function with tests for validating the new date filtering functionality.
src/provider.ts Minor formatting changes to the NETWORKS_IDS_TO_NAME object, removing unnecessary blank lines without affecting functionality.

Poem

In the garden of code, where donations flow,
A new path has sprouted, with data to show.
Rabbits rejoice, for queries now thrive,
Fetching donations with dates to derive.
Hops of delight in the API's dance,
Let’s celebrate this change—give it a chance! 🐇✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 07cfa35 and ef2d009.

Files selected for processing (3)
  • src/resolvers/recurringDonationResolver.test.ts (3 hunks)
  • src/resolvers/recurringDonationResolver.ts (1 hunks)
  • test/graphqlQueries.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • test/graphqlQueries.ts
Additional comments not posted (10)
src/resolvers/recurringDonationResolver.ts (5)

504-505: Fix typo in decorator return type.

The decorator _retuns should be corrected to _returns.

-  @Query(_retuns => PaginateRecurringDonations, { nullable: true })
+  @Query(_returns => PaginateRecurringDonations, { nullable: true })

511-513: Add error handling for project validation.

The error message should be more descriptive to help in debugging.

-  throw new Error(i18n.__(translationErrorMessagesKeys.PROJECT_NOT_FOUND));
+  throw new Error(`Project with ID ${projectId} not found.`);

516-531: Optimize query construction.

The query construction can be optimized by using parameterized queries to prevent SQL injection.

-  .where(`recurringDonation.projectId = ${projectId}`);
+  .where('recurringDonation.projectId = :projectId', { projectId });

532-542: Combine date filters.

Combine the date filters into a single condition to optimize the query.

-  if (startDate) {
-    query.andWhere('recurringDonation.createdAt >= :startDate', {
-      startDate: new Date(startDate),
-    });
-  }
-  if (endtDate) {
-    query.andWhere('recurringDonation.createdAt <= :endtDate', {
-      endtDate: new Date(endtDate),
-    });
+  if (startDate || endtDate) {
+    query.andWhere('recurringDonation.createdAt BETWEEN :startDate AND :endtDate', {
+      startDate: startDate ? new Date(startDate) : new Date(0),
+      endtDate: endDate ? new Date(endDate) : new Date(),
+    });
  }

544-548: Ensure proper error handling for query execution.

Add error handling for the query execution to catch and log any potential errors.

-  const [recurringDonations, donationsCount] = await query.getManyAndCount();
+  let recurringDonations, donationsCount;
+  try {
+    [recurringDonations, donationsCount] = await query.getManyAndCount();
+  } catch (error) {
+    logger.error('Error executing recurringDonationsByDate query', error);
+    throw new Error('Failed to fetch recurring donations.');
+  }
src/resolvers/recurringDonationResolver.test.ts (5)

2949-3000: Test case validation: Correctly retrieves donations within a specific date range.

The test case is well-structured and correctly validates the expected behavior of retrieving recurring donations within a specific date range.


3002-3036: Test case validation: Correctly retrieves all donations when no date range is specified.

The test case is well-structured and correctly validates the expected behavior of retrieving all recurring donations when no date range is provided.


3038-3088: Test case validation: Correctly retrieves donations up to the specified end date when no start date is provided.

The test case is well-structured and correctly validates the expected behavior of retrieving recurring donations up to the specified end date when no start date is provided.


3090-3140: Test case validation: Correctly retrieves donations from the specified start date when no end date is provided.

The test case is well-structured and correctly validates the expected behavior of retrieving recurring donations from the specified start date when no end date is provided.


3142-3182: Test case validation: Correctly returns an empty list when no donations exist within the specified date range.

The test case is well-structured and correctly validates the expected behavior of returning an empty list when no donations exist within the specified date range.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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
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: 6

Outside diff range, codebase verification and nitpick comments (1)
test/graphqlQueries.ts (1)

2467-2485: Add more fields to the query.

Consider adding more fields to the query to provide comprehensive donation details.

Consider adding fields such as isBatch, isForUpdate, and flowRate to the query.

Comment on lines +504 to +505
@Query(_retuns => PaginateRecurringDonations, { nullable: true })
async recurringDonationsByDate(
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix typo in decorator return type.

The decorator _retuns should be corrected to _returns.

-  @Query(_retuns => PaginateRecurringDonations, { nullable: true })
+  @Query(_returns => PaginateRecurringDonations, { nullable: true })
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Query(_retuns => PaginateRecurringDonations, { nullable: true })
async recurringDonationsByDate(
@Query(_returns => PaginateRecurringDonations, { nullable: true })
async recurringDonationsByDate(

Comment on lines +511 to +513
const project = await findProjectById(projectId);
if (!project) {
throw new Error(i18n.__(translationErrorMessagesKeys.PROJECT_NOT_FOUND));
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for project validation.

The error message should be more descriptive to help in debugging.

-  throw new Error(i18n.__(translationErrorMessagesKeys.PROJECT_NOT_FOUND));
+  throw new Error(`Project with ID ${projectId} not found.`);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const project = await findProjectById(projectId);
if (!project) {
throw new Error(i18n.__(translationErrorMessagesKeys.PROJECT_NOT_FOUND));
const project = await findProjectById(projectId);
if (!project) {
throw new Error(`Project with ID ${projectId} not found.`);

Comment on lines +544 to +548
const [recurringDonations, donationsCount] = await query.getManyAndCount();
return {
recurringDonations,
totalCount: donationsCount,
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for query execution.

Add error handling for the query execution to catch and log any potential errors.

-  const [recurringDonations, donationsCount] = await query.getManyAndCount();
+  let recurringDonations, donationsCount;
+  try {
+    [recurringDonations, donationsCount] = await query.getManyAndCount();
+  } catch (error) {
+    logger.error('Error executing recurringDonationsByDate query', error);
+    throw new Error('Failed to fetch recurring donations.');
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [recurringDonations, donationsCount] = await query.getManyAndCount();
return {
recurringDonations,
totalCount: donationsCount,
};
let recurringDonations, donationsCount;
try {
[recurringDonations, donationsCount] = await query.getManyAndCount();
} catch (error) {
logger.error('Error executing recurringDonationsByDate query', error);
throw new Error('Failed to fetch recurring donations.');
}
return {
recurringDonations,
totalCount: donationsCount,
};

Comment on lines 538 to 542
if (endtDate) {
query.andWhere('recurringDonation.createdAt <= :endtDate', {
endtDate: new Date(endtDate),
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Combine date filters.

Combine the date filters into a single condition to optimize the query.

-  if (startDate) {
-    query.andWhere('recurringDonation.createdAt >= :startDate', {
-      startDate: new Date(startDate),
-    });
-  }
-  if (endtDate) {
-    query.andWhere('recurringDonation.createdAt <= :endtDate', {
-      endtDate: new Date(endtDate),
-    });
+  if (startDate || endtDate) {
+    query.andWhere('recurringDonation.createdAt BETWEEN :startDate AND :endtDate', {
+      startDate: startDate ? new Date(startDate) : new Date(0),
+      endtDate: endtDate ? new Date(endtDate) : new Date(),
+    });
  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (endtDate) {
query.andWhere('recurringDonation.createdAt <= :endtDate', {
endtDate: new Date(endtDate),
});
}
if (startDate || endtDate) {
query.andWhere('recurringDonation.createdAt BETWEEN :startDate AND :endtDate', {
startDate: startDate ? new Date(startDate) : new Date(0),
endtDate: endtDate ? new Date(endtDate) : new Date(),
});
}

Comment on lines +516 to +531
const query = RecurringDonation.createQueryBuilder('recurringDonation')
.leftJoin('recurringDonation.donor', 'donor')
.addSelect([
'donor.id',
'donor.walletAddress',
'donor.name',
'donor.firstName',
'donor.lastName',
'donor.url',
'donor.avatar',
'donor.totalDonated',
'donor.totalReceived',
'donor.passportScore',
'donor.passportStamps',
])
.where(`recurringDonation.projectId = ${projectId}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize query construction.

The query construction can be optimized by using parameterized queries to prevent SQL injection.

-  .where(`recurringDonation.projectId = ${projectId}`);
+  .where('recurringDonation.projectId = :projectId', { projectId });
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const query = RecurringDonation.createQueryBuilder('recurringDonation')
.leftJoin('recurringDonation.donor', 'donor')
.addSelect([
'donor.id',
'donor.walletAddress',
'donor.name',
'donor.firstName',
'donor.lastName',
'donor.url',
'donor.avatar',
'donor.totalDonated',
'donor.totalReceived',
'donor.passportScore',
'donor.passportStamps',
])
.where(`recurringDonation.projectId = ${projectId}`);
const query = RecurringDonation.createQueryBuilder('recurringDonation')
.leftJoin('recurringDonation.donor', 'donor')
.addSelect([
'donor.id',
'donor.walletAddress',
'donor.name',
'donor.firstName',
'donor.lastName',
'donor.url',
'donor.avatar',
'donor.totalDonated',
'donor.totalReceived',
'donor.passportScore',
'donor.passportStamps',
])
.where('recurringDonation.projectId = :projectId', { projectId });

Comment on lines 2456 to 2487
export const fetchRecurringDonationsByDate = `
query (
$projectId: Int!
$startDate: String!
$endDate: String!
) {
recurringDonationsByDate(
projectId: $projectId
startDate: $startDate
endDate: $endDate
) {
recurringDonations {
id
txHash
networkId
flowRate
currency
anonymous
isArchived
status
donor {
id
walletAddress
firstName
email
}
createdAt
}
totalCount
}
}
`;
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure optional date parameters.

The startDate and endDate parameters should be optional to match the resolver method signature.

-    $startDate: String!
-    $endDate: String!
+    $startDate: String
+    $endDate: String
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const fetchRecurringDonationsByDate = `
query (
$projectId: Int!
$startDate: String!
$endDate: String!
) {
recurringDonationsByDate(
projectId: $projectId
startDate: $startDate
endDate: $endDate
) {
recurringDonations {
id
txHash
networkId
flowRate
currency
anonymous
isArchived
status
donor {
id
walletAddress
firstName
email
}
createdAt
}
totalCount
}
}
`;
export const fetchRecurringDonationsByDate = `
query (
$projectId: Int!
$startDate: String
$endDate: String
) {
recurringDonationsByDate(
projectId: $projectId
startDate: $startDate
endDate: $endDate
) {
recurringDonations {
id
txHash
networkId
flowRate
currency
anonymous
isArchived
status
donor {
id
walletAddress
firstName
email
}
createdAt
}
totalCount
}
}
`;

@mohammadranjbarz
Copy link
Collaborator

@lovelgeorge99 Can you write test cases for this new resolver?

Copy link
Collaborator

@mohammadranjbarz mohammadranjbarz left a comment

Choose a reason for hiding this comment

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

Thanks @lovelgeorge99 LGTM

@lovelgeorge99 lovelgeorge99 merged commit 50bfd89 into staging Aug 6, 2024
5 checks passed
@lovelgeorge99 lovelgeorge99 deleted the query-for-recurring-donation-by-date branch August 6, 2024 18:43
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