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

feat: add endpoint to delete draft project #1752

Merged
merged 2 commits into from
Aug 12, 2024
Merged

Conversation

Reshzera
Copy link
Contributor

@Reshzera Reshzera commented Aug 6, 2024

Summary by CodeRabbit

  • New Features

    • Introduced functionality to delete draft projects along with related entities.
    • Added a new GraphQL mutation for deleting draft projects.
    • Enhanced user feedback with new error messages for deletion permissions.
  • Bug Fixes

    • Improved test coverage for draft project deletion scenarios, ensuring accurate handling of various cases.
  • Documentation

    • Updated localization files in English and Spanish to reflect new error messaging related to project deletion.

Copy link
Contributor

coderabbitai bot commented Aug 6, 2024

Walkthrough

This update significantly enhances project management by introducing a feature for deleting draft projects and their associated data. It includes comprehensive tests to ensure reliability and maintain data integrity, along with localized error messages for better user experience. The changes span both backend logic and corresponding GraphQL mutations, creating a cohesive and user-friendly interface throughout the application.

Changes

File Change Summary
src/repositories/projectRepository.* Added removeProjectAndRelatedEntities function for deleting a project and its associated entities.
src/repositories/projectRepository.test.ts Introduced tests for removeProjectAndRelatedEntities, validating the complete deletion of projects and related entities.
src/resolvers/projectResolver.* Added deleteDraftProject method in the resolver to enable deletion of draft projects based on ownership and status.
src/resolvers/projectResolver.test.ts Created test cases for deleteDraftProject, covering various scenarios for draft project deletion.
src/utils/errorMessages.ts Added new error message for attempts to delete non-draft projects.
src/utils/locales/*.json Introduced localization entries for error messages in English and Spanish for better user feedback.
test/graphqlQueries.ts Introduced deleteDraftProjectQuery for GraphQL mutations to facilitate draft project deletions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ProjectResolver
    participant Repository
    
    User->>ProjectResolver: Request to delete draft project
    ProjectResolver->>Repository: Call removeProjectAndRelatedEntities(projectId)
    Repository-->>ProjectResolver: Confirm deletion success
    ProjectResolver-->>User: Return success response
Loading

🐇 In the garden of code, a change took flight,
Drafts deleted, oh what a sight!
With tests added, all worries cease,
Now our projects rest in peace.
So hop along, let’s celebrate,
For clean data is truly great! 🌼✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1cc3b52 and d0a7ccd.

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

2457-2461: Addition of deleteDraftProjectQuery looks good.

The new mutation query for deleting a draft project is well-structured and consistent with the existing queries in the file. Ensure that this query is tested thoroughly in the application.


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.

@Reshzera
Copy link
Contributor Author

Reshzera commented Aug 6, 2024

#1519

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

Outside diff range, codebase verification and nitpick comments (2)
src/repositories/projectRepository.test.ts (1)

523-606: LGTM! Consider adding edge case tests.

The test case correctly verifies the deletion of a project and its related entities. However, consider adding tests for edge cases such as attempting to delete a non-existent project or handling database errors.

function removeProjectAndRelatedEntitiesTestCase() {
  it('should remove project and related entities', async () => {
    const user = await saveUserDirectlyToDb(generateRandomEtheriumAddress());
    const projectData = createProjectData();
    projectData.adminUserId = user.id;
    //It creates a project, projectUpdate, and ProjectAddress
    const project = await saveProjectDirectlyToDb(projectData);

    await Promise.all([
      saveDonationDirectlyToDb(
        {
          ...createDonationData(),
        },
        user.id,
        project.id,
      ),
      saveAnchorContractDirectlyToDb({
        creatorId: user.id,
        projectId: project.id,
      }),
      Reaction.create({
        projectId: project.id,
        userId: user.id,
        reaction: '',
      }).save(),
      ProjectSocialMedia.create({
        projectId: project.id,
        type: ProjectSocialMediaType.FACEBOOK,
        link: 'https://facebook.com',
      }).save(),
      ProjectStatusHistory.create({
        projectId: project.id,
        createdAt: new Date(),
      }).save(),
      ProjectVerificationForm.create({ projectId: project.id }).save(),
      FeaturedUpdate.create({ projectId: project.id }).save(),
      SocialProfile.create({ projectId: project.id }).save(),
    ]);

    const relatedEntitiesBefore = await Promise.all([
      Donation.findOne({ where: { projectId: project.id } }),
      Reaction.findOne({ where: { projectId: project.id } }),
      ProjectAddress.findOne({ where: { projectId: project.id } }),
      ProjectSocialMedia.findOne({ where: { projectId: project.id } }),
      AnchorContractAddress.findOne({ where: { projectId: project.id } }),
      ProjectStatusHistory.findOne({ where: { projectId: project.id } }),
      ProjectVerificationForm.findOne({
        where: { projectId: project.id },
      }),
      FeaturedUpdate.findOne({ where: { projectId: project.id } }),
      SocialProfile.findOne({ where: { projectId: project.id } }),
      ProjectUpdate.findOne({ where: { projectId: project.id } }),
    ]);

    relatedEntitiesBefore.forEach(entity => {
      assert.isNotNull(entity);
    });

    await removeProjectAndRelatedEntities(project.id);

    const relatedEntities = await Promise.all([
      Donation.findOne({ where: { projectId: project.id } }),
      Reaction.findOne({ where: { projectId: project.id } }),
      ProjectAddress.findOne({ where: { projectId: project.id } }),
      ProjectSocialMedia.findOne({ where: { projectId: project.id } }),
      AnchorContractAddress.findOne({ where: { projectId: project.id } }),
      ProjectStatusHistory.findOne({ where: { projectId: project.id } }),
      ProjectVerificationForm.findOne({
        where: { projectId: project.id },
      }),
      FeaturedUpdate.findOne({ where: { projectId: project.id } }),
      SocialProfile.findOne({ where: { projectId: project.id } }),
      ProjectUpdate.findOne({ where: { projectId: project.id } }),
    ]);

    const fetchedProject = await Project.findOne({ where: { id: project.id } });

    assert.isNull(fetchedProject);

    relatedEntities.forEach(entity => {
      assert.isNull(entity);
    });
  });

  it('should handle non-existent project gracefully', async () => {
    const nonExistentProjectId = 999999;
    await removeProjectAndRelatedEntities(nonExistentProjectId);
    // Add assertions to ensure no errors are thrown and the function handles this case correctly
  });

  it('should handle database errors gracefully', async () => {
    // Simulate a database error and ensure the function handles it correctly
    // Add assertions to verify error handling
  });
}
src/resolvers/projectResolver.test.ts (1)

5675-5675: Add a descriptive comment for the test suite.

Consider adding a comment to describe the purpose of the deleteDraftProjectTestCases function.

+ // Test cases for deleting draft projects
function deleteDraftProjectTestCases() {

Comment on lines +545 to +603
export const removeProjectAndRelatedEntities = async (
projectId: number,
): Promise<void> => {
// Delete related entities
await Donation.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await Reaction.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await ProjectAddress.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await ProjectSocialMedia.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await AnchorContractAddress.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await ProjectStatusHistory.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await ProjectVerificationForm.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await FeaturedUpdate.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await SocialProfile.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await ProjectUpdate.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();

await Project.createQueryBuilder()
.delete()
.where('id = :id', { id: projectId })
.execute();
};
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! But consider adding error handling.

The function correctly deletes the project and its related entities. However, it would be beneficial to add error handling to ensure that any issues during the deletion process are properly managed.

export const removeProjectAndRelatedEntities = async (
  projectId: number,
): Promise<void> => {
  try {
    // Delete related entities
    await Donation.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await Reaction.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await ProjectAddress.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await ProjectSocialMedia.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await AnchorContractAddress.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await ProjectStatusHistory.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await ProjectVerificationForm.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await FeaturedUpdate.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await SocialProfile.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await ProjectUpdate.createQueryBuilder()
      .delete()
      .where('projectId = :projectId', { projectId })
      .execute();

    await Project.createQueryBuilder()
      .delete()
      .where('id = :id', { id: projectId })
      .execute();
  } catch (error) {
    // Handle the error appropriately
    console.error('Error deleting project and related entities:', error);
    throw new Error('Failed to delete project and related entities');
  }
};
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 removeProjectAndRelatedEntities = async (
projectId: number,
): Promise<void> => {
// Delete related entities
await Donation.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await Reaction.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectAddress.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectSocialMedia.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await AnchorContractAddress.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectStatusHistory.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectVerificationForm.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await FeaturedUpdate.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await SocialProfile.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectUpdate.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await Project.createQueryBuilder()
.delete()
.where('id = :id', { id: projectId })
.execute();
};
export const removeProjectAndRelatedEntities = async (
projectId: number,
): Promise<void> => {
try {
// Delete related entities
await Donation.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await Reaction.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectAddress.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectSocialMedia.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await AnchorContractAddress.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectStatusHistory.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectVerificationForm.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await FeaturedUpdate.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await SocialProfile.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await ProjectUpdate.createQueryBuilder()
.delete()
.where('projectId = :projectId', { projectId })
.execute();
await Project.createQueryBuilder()
.delete()
.where('id = :id', { id: projectId })
.execute();
} catch (error) {
// Handle the error appropriately
console.error('Error deleting project and related entities:', error);
throw new Error('Failed to delete project and related entities');
}
};

@mohammadranjbarz
Copy link
Collaborator

@Reshzera Can you fix the CI/CD test workflow, it's failing

@Reshzera
Copy link
Contributor Author

Reshzera commented Aug 6, 2024

@mohammadranjbarz fixed

@mohammadranjbarz
Copy link
Collaborator

@Meriem-B Can you review this?

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 @Reshzera great job, please resolve conflicts then merge it yourself, after you merged it, let FE guys know that you implemented it by commenting the endpoint and instruction to have call it in the issue

@Reshzera Reshzera merged commit bbdb457 into staging Aug 12, 2024
5 checks passed
@Reshzera Reshzera deleted the feat/issue-1519 branch August 12, 2024 18:26
@maryjaf
Copy link
Collaborator

maryjaf commented Aug 28, 2024

The frontend change related to delete draft donation hasn't been merged on staging , am I right?
and it isn't in scope of this release ?
@Reshzera @mohammadranjbarz

@mohammadranjbarz
Copy link
Collaborator

The frontend change related to delete draft donation hasn't been merged on staging , am I right? and it isn't in scope of this release ? @Reshzera @mohammadranjbarz

@maryjaf Yes just the backend is on production, the FE side has not been implemented yet
Giveth/giveth-dapps-v2#1271

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