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

Update verify approve conditions #1866

Open
wants to merge 15 commits into
base: staging
Choose a base branch
from

Conversation

MohammadPCh
Copy link
Collaborator

@MohammadPCh MohammadPCh commented Oct 29, 2024

Summary by CodeRabbit

  • New Features

    • Added checks to prevent approval of projects in DRAFT status.
    • Introduced error handling for Givback eligible projects during verification.
    • Enhanced notification mechanisms for project status changes.
    • Implemented a new test script for project verification tab functionality.
    • Added new test cases for approval and rejection processes of Givback Eligibility Forms.
  • Bug Fixes

    • Improved error handling and logging consistency across various functions.
  • Refactor

    • Updated function signatures for clarity and consistency.
    • Streamlined approval and status update processes for better maintainability.
    • Enhanced test coverage for project verification processes.

@MohammadPCh MohammadPCh marked this pull request as ready for review October 29, 2024 10:34
Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the functionality and maintainability of project verification processes across multiple files. Key modifications include restructuring function parameters for clarity, improving error handling, and refining SQL logic. The approveMultipleProjects function now uses destructured parameters, while the projectVerificationTab and projectsTab files introduce checks to prevent unintended modifications to forms and improve notification handling. Overall, these updates aim to streamline the project verification workflow and ensure robust error management.

Changes

File Path Change Summary
src/repositories/projectVerificationRepository.ts Updated approveMultipleProjects to use destructured parameters and refined SQL update logic for clarity and efficiency.
src/server/adminJs/tabs/projectVerificationTab.ts Added checks for DRAFT status in approveVerificationForms, improved error handling, and added logging for processed form IDs.
src/server/adminJs/tabs/projectsTab.ts Enhanced verifyProjects with checks for Givback eligibility, standardized error handling, and improved notification mechanisms.
src/server/adminJs/tabs/projectsTab.test.ts Added new test suite for unverifyProjects() and updated existing tests for verifyProjects() to reflect new logic.
src/server/adminJs/tabs/projectVerificationTab.test.ts Introduced a new test suite for approveGivbacksEligibilityForm to validate approval and rejection processes.
package.json Added a new test script for projectVerificationTab functionality.

Possibly related PRs

Suggested labels

Code Review

Suggested reviewers

  • CarlosQ96
  • RamRamez
  • mohammadranjbarz

Poem

In the burrow where projects play,
Changes hop in a bright array.
With checks and logs, we pave the way,
For approvals clear, come what may!
A tidy code, a joyful day! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4d82302 and b3dfb59.

📒 Files selected for processing (2)
  • src/server/adminJs/tabs/projectVerificationTab.test.ts (1 hunks)
  • src/server/adminJs/tabs/projectsTab.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/server/adminJs/tabs/projectVerificationTab.test.ts
  • src/server/adminJs/tabs/projectsTab.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.

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

🧹 Outside diff range and nitpick comments (1)
src/server/adminJs/tabs/projectVerificationTab.ts (1)

249-267: LGTM! Consider these improvements for the DRAFT status check.

The preliminary check for DRAFT status is a good addition. Consider these enhancements:

  1. Use i18n for the error message to maintain consistency with other messages in the codebase
  2. Optimize the query to use COUNT instead of fetching entire records

Here's how you could optimize the query:

-    const draftProjects = await ProjectVerificationForm.createQueryBuilder(
-      'form',
-    )
-      .where('form.id IN (:...formIds)', { formIds })
-      .andWhere('form.status = :status', {
-        status: PROJECT_VERIFICATION_STATUSES.DRAFT,
-      })
-      .getMany();
-
-    if (draftProjects.length > 0) {
+    const draftCount = await ProjectVerificationForm.createQueryBuilder('form')
+      .where('form.id IN (:...formIds)', { formIds })
+      .andWhere('form.status = :status', {
+        status: PROJECT_VERIFICATION_STATUSES.DRAFT,
+      })
+      .getCount();
+
+    if (draftCount > 0) {
       throw new Error(
-        `Cannot ${approved ? 'approve' : 'reject'} project${draftProjects.length > 1 ? 's' : ''} in DRAFT status.`,
+        i18n.__(translationErrorMessagesKeys.CANNOT_APPROVE_REJECT_DRAFT_PROJECTS, {
+          action: approved ? 'approve' : 'reject',
+          count: draftCount
+        }),
       );
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5e9e255 and 7db802f.

📒 Files selected for processing (3)
  • src/repositories/projectVerificationRepository.ts (1 hunks)
  • src/server/adminJs/tabs/projectVerificationTab.ts (3 hunks)
  • src/server/adminJs/tabs/projectsTab.ts (2 hunks)
🔇 Additional comments (3)
src/repositories/projectVerificationRepository.ts (2)

396-399: LGTM! Parameter destructuring improves readability.

The change from a single params object to destructured parameters makes the function signature clearer and more maintainable.


396-413: Verify consistency with project verification workflow.

Let's ensure these changes align with the broader verification process:

  1. The function should be used consistently with approveProject
  2. The verification status changes should match the expected workflow
✅ Verification successful

Based on the results, I can now generate the final response as we have enough information about the implementation and usage of both single and multiple project approval functions, as well as the verification status handling.

Changes to approveMultipleProjects are consistent with project verification workflow

The implementation is consistent with the broader verification process:

  1. The function follows the same pattern as approveProject for handling verification status:

    • Both reset verificationStatus to null when approving
    • Both preserve verificationStatus when not approving
    • Both update isGivbackEligible and verified fields similarly
  2. The changes are used correctly in the admin interface (projectVerificationTab.ts) where both single and bulk approval actions maintain consistent behavior.

  3. The verification status transitions are properly handled across the codebase, with clear status management in the verification workflow (reminder -> warning -> last chance -> up for revoking -> revoked).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage and consistency of project approval functions

# Test 1: Compare with single project approval implementation
echo "Comparing with single project approval implementation..."
rg -A 5 "approveProject|approveMultipleProjects" --type ts

# Test 2: Check verification status transitions
echo "Checking verification status transitions..."
ast-grep --pattern 'verificationStatus = $_' --type ts

Length of output: 7504


Script:

#!/bin/bash
# Let's verify the implementation consistency and verification status handling

# Check single project approval implementation
echo "Checking single project approval implementation..."
rg -B 5 -A 10 "export const approveProject" src/repositories/projectVerificationRepository.ts

# Check verification status field usage
echo "Checking verification status field usage..."
rg "verificationStatus" --type ts -B 2 -A 2

# Check Project entity definition
echo "Checking Project entity definition..."
rg "class Project" --type ts -A 20

Length of output: 128418

src/server/adminJs/tabs/projectVerificationTab.ts (1)

316-316: LGTM! Error message formatting improvement.

The addition of a colon improves the readability of the error message.

src/repositories/projectVerificationRepository.ts Outdated Show resolved Hide resolved
src/server/adminJs/tabs/projectsTab.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 a680fa2 and 102ce11.

📒 Files selected for processing (2)
  • src/repositories/projectVerificationRepository.ts (1 hunks)
  • src/server/adminJs/tabs/projectsTab.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/repositories/projectVerificationRepository.ts
🔇 Additional comments (1)
src/server/adminJs/tabs/projectsTab.ts (1)

248-267: LGTM: Error handling implementation is robust

The error handling implementation is well-structured:

  • Proper error logging
  • Consistent response format
  • User-friendly error messages
  • Maintains the same response structure for both success and error cases

src/server/adminJs/tabs/projectsTab.ts 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: 0

🧹 Outside diff range and nitpick comments (2)
src/server/adminJs/tabs/projectsTab.test.ts (2)

Line range hint 10-10: Consider standardizing sleep durations and handling race conditions.

The test file uses inconsistent sleep durations (10ms vs 50ms) for waiting on history creation. This could lead to flaky tests on slower systems.

Consider these improvements:

- await sleep(50);
+ const HISTORY_CREATION_WAIT_MS = 50;
+ await sleep(HISTORY_CREATION_WAIT_MS);

- await sleep(10);
+ await sleep(HISTORY_CREATION_WAIT_MS);

Also, consider implementing a retry mechanism or polling for history creation instead of fixed delays:

async function waitForHistory(params: {
  projectId: number;
  userId: number;
  maxAttempts = 5;
  intervalMs = 10;
}): Promise<ProjectStatusHistory | null> {
  for (let i = 0; i < params.maxAttempts; i++) {
    const history = await findOneProjectStatusHistory({
      projectId: params.projectId,
      userId: params.userId,
    });
    if (history) return history;
    await sleep(params.intervalMs);
  }
  return null;
}

Also applies to: 50-50, 761-761, 824-824


Line range hint 425-824: Consider adding error case test coverage.

The test suite thoroughly covers the happy path scenarios but could benefit from additional test cases for error scenarios:

  1. Attempting to verify a non-existent project
  2. Handling database errors during verification
  3. Concurrent verification attempts
  4. Invalid verification status transitions

Consider adding test cases like:

it('should handle verification of non-existent project', async () => {
  const nonExistentId = 999999;
  const adminUser = await findUserById(SEED_DATA.ADMIN_USER.id);
  
  const result = await verifyProjects(
    {
      currentAdmin: adminUser as User,
      h: {},
      resource: {},
      records: [],
    },
    {
      query: {
        recordIds: String(nonExistentId),
      },
    },
    true,
  );
  
  assert.equal(result.notice.type, 'danger');
  assert.equal(result.notice.message, 'Project not found');
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 102ce11 and d23a58a.

📒 Files selected for processing (1)
  • src/server/adminJs/tabs/projectsTab.test.ts (5 hunks)
🔇 Additional comments (2)
src/server/adminJs/tabs/projectsTab.test.ts (2)

Line range hint 425-493: LGTM! Well-structured test case for badge revocation.

The test case thoroughly validates that the verification status remains unchanged while the verification form transitions to draft state when a badge is revoked.


601-601: LGTM! Consistent test data setup.

The addition of isGivbackEligible: false property across test cases ensures consistent test data setup for verification scenarios.

Also applies to: 658-658, 729-729

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

🧹 Outside diff range and nitpick comments (5)
src/server/adminJs/tabs/projectVerificationTab.test.ts (1)

22-151: Consider adding tests for edge cases and error scenarios.

The current test suite covers the main flows but misses important edge cases:

  1. Invalid/non-existent form ID
  2. Admin user without proper permissions
  3. Database/network error handling

Would you like me to help generate additional test cases for these scenarios?

package.json (1)

139-139: LGTM! Consider grouping admin tab test scripts.

The new test script follows the project's conventions and improves test coverage for the project verification functionality.

Consider grouping all admin tab test scripts under a single command for easier testing of related functionality. For example:

+"test:adminTabs": "NODE_ENV=test mocha ./test/pre-test-scripts.ts ./src/server/adminJs/tabs/**/*.test.ts",

This would complement the existing test:adminJs script and provide more granular control over testing admin functionality.

src/server/adminJs/tabs/projectsTab.test.ts (3)

71-135: Consider using more reliable async handling.

The test cases are well structured, but using fixed sleep delays for async operations could lead to flaky tests. Consider using proper async/await patterns or event listeners instead.

- await sleep(50);
+ await Promise.all([
+   // Wait for specific async operations to complete
+   // e.g., database transactions, event emissions, etc.
+ ]);

Line range hint 497-571: Consider splitting test cases for better maintainability.

The test case contains multiple assertions checking different aspects (verification status, form status, etc.). Consider splitting into smaller, focused test cases for better maintainability and easier debugging.

Example structure:

it('should maintain verification status when badge is revoked', async () => {
  // Test only verification status
});

it('should set verification form as draft when badge is revoked', async () => {
  // Test only form status
});

674-674: Consider adding edge cases for givbacks eligibility.

While the basic cases are covered, consider adding test cases for edge scenarios:

  • Projects transitioning between eligibility states
  • Projects with pending givbacks
  • Projects with historical givbacks but currently ineligible

Also applies to: 731-731, 802-802

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d23a58a and 9d99aff.

📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/server/adminJs/tabs/projectVerificationTab.test.ts (1 hunks)
  • src/server/adminJs/tabs/projectsTab.test.ts (8 hunks)
🧰 Additional context used
🪛 GitHub Check: test
src/server/adminJs/tabs/projectVerificationTab.test.ts

[failure] 1-1:
Expected 2-3 arguments, but got 1.

src/server/adminJs/tabs/projectVerificationTab.test.ts Outdated Show resolved Hide resolved
Comment on lines 108 to 150
it('Should be able to reject Givback Eligibility Form for not draft form', async () => {
const project = await saveProjectDirectlyToDb({
...createProjectData(),
title: String(new Date().getTime()),
slug: String(new Date().getTime()),
verified: true,
listed: true,
isGivbackEligible: false,
});

const projectVerificationForm = await createProjectVerificationForm({
projectId: project.id,
userId: project.adminUserId,
});
projectVerificationForm.status = PROJECT_VERIFICATION_STATUSES.SUBMITTED;
await projectVerificationForm.save();

const adminUser = await findUserById(SEED_DATA.ADMIN_USER.id);

await approveVerificationForms(
{
currentAdmin: adminUser as User,
h: {},
resource: {},
records: [],
},
{
query: {
recordIds: String(projectVerificationForm.id),
},
},
false,
);

const updatedForm = await findProjectVerificationFormById(
projectVerificationForm.id,
);
const updatedPorject = await findProjectById(project.id);

assert.isOk(updatedForm);
assert.equal(updatedForm?.status, PROJECT_VERIFICATION_STATUSES.REJECTED);
assert.isFalse(updatedPorject?.isGivbackEligible);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix variable name typo and enhance rejection assertions.

The test has a typo in the variable name and could benefit from additional assertions for rejection details:

-    const updatedPorject = await findProjectById(project.id);
+    const updatedProject = await findProjectById(project.id);
     assert.isOk(updatedForm);
     assert.equal(updatedForm?.status, PROJECT_VERIFICATION_STATUSES.REJECTED);
-    assert.isFalse(updatedPorject?.isGivbackEligible);
+    assert.isFalse(updatedProject?.isGivbackEligible);
+    assert.equal(updatedForm?.adminUserId, adminUser.id, 'Should record the admin who rejected');
📝 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
it('Should be able to reject Givback Eligibility Form for not draft form', async () => {
const project = await saveProjectDirectlyToDb({
...createProjectData(),
title: String(new Date().getTime()),
slug: String(new Date().getTime()),
verified: true,
listed: true,
isGivbackEligible: false,
});
const projectVerificationForm = await createProjectVerificationForm({
projectId: project.id,
userId: project.adminUserId,
});
projectVerificationForm.status = PROJECT_VERIFICATION_STATUSES.SUBMITTED;
await projectVerificationForm.save();
const adminUser = await findUserById(SEED_DATA.ADMIN_USER.id);
await approveVerificationForms(
{
currentAdmin: adminUser as User,
h: {},
resource: {},
records: [],
},
{
query: {
recordIds: String(projectVerificationForm.id),
},
},
false,
);
const updatedForm = await findProjectVerificationFormById(
projectVerificationForm.id,
);
const updatedPorject = await findProjectById(project.id);
assert.isOk(updatedForm);
assert.equal(updatedForm?.status, PROJECT_VERIFICATION_STATUSES.REJECTED);
assert.isFalse(updatedPorject?.isGivbackEligible);
});
it('Should be able to reject Givback Eligibility Form for not draft form', async () => {
const project = await saveProjectDirectlyToDb({
...createProjectData(),
title: String(new Date().getTime()),
slug: String(new Date().getTime()),
verified: true,
listed: true,
isGivbackEligible: false,
});
const projectVerificationForm = await createProjectVerificationForm({
projectId: project.id,
userId: project.adminUserId,
});
projectVerificationForm.status = PROJECT_VERIFICATION_STATUSES.SUBMITTED;
await projectVerificationForm.save();
const adminUser = await findUserById(SEED_DATA.ADMIN_USER.id);
await approveVerificationForms(
{
currentAdmin: adminUser as User,
h: {},
resource: {},
records: [],
},
{
query: {
recordIds: String(projectVerificationForm.id),
},
},
false,
);
const updatedForm = await findProjectVerificationFormById(
projectVerificationForm.id,
);
const updatedProject = await findProjectById(project.id);
assert.isOk(updatedForm);
assert.equal(updatedForm?.status, PROJECT_VERIFICATION_STATUSES.REJECTED);
assert.isFalse(updatedProject?.isGivbackEligible);
assert.equal(updatedForm?.adminUserId, adminUser.id, 'Should record the admin who rejected');
});

Comment on lines +23 to +62
it('Should throw error if Givback Eligibility Form is on draft', async () => {
const project = await saveProjectDirectlyToDb({
...createProjectData(),
title: String(new Date().getTime()),
slug: String(new Date().getTime()),
verified: true,
listed: true,
});

const projectVerificationForm = await createProjectVerificationForm({
projectId: project.id,
userId: project.adminUserId,
});

projectVerificationForm.status = PROJECT_VERIFICATION_STATUSES.DRAFT;
await projectVerificationForm.save();

const adminUser = await findUserById(SEED_DATA.ADMIN_USER.id);

await approveVerificationForms(
{
currentAdmin: adminUser as User,
h: {},
resource: {},
records: [],
},
{
query: {
recordIds: String(projectVerificationForm.id),
},
},
true,
);

const updatedForm = await findProjectVerificationFormById(
projectVerificationForm.id,
);
assert.isOk(updatedForm);
assert.equal(updatedForm?.status, PROJECT_VERIFICATION_STATUSES.DRAFT);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Test description doesn't match implementation.

The test description states it "Should throw error" but there's no assertion to verify that an error was thrown. Consider using chai's expect().to.throw():

-    await approveVerificationForms(
+    await expect(approveVerificationForms(
      {
        currentAdmin: adminUser as User,
        h: {},
        resource: {},
        records: [],
      },
      {
        query: {
          recordIds: String(projectVerificationForm.id),
        },
      },
      true,
-    );
+    )).to.throw('Cannot approve/reject draft forms');

Committable suggestion was skipped due to low confidence.

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