Skip to content

Added mutations for action Item Category #3432

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

Conversation

NishantSinghhhhh
Copy link

@NishantSinghhhhh NishantSinghhhhh commented Apr 6, 2025

What kind of change does this PR introduce?

Feature: Migrates ActionItem Category handling from Express endpoints to GraphQL schema and resolvers.

Issue Number: #3320

Snapshots/Videos:

N/A (No UI changes; these changes affect backend GraphQL schemas and resolvers.)
If relevant, did you update the documentation?

I have added/updated relevant documentation within the code and README where needed.
Summary

Summary by CodeRabbit

  • New Features

    • Added mutations to create and update action item categories.
    • Introduced allotted hours field for action items.
    • Action items and categories now show nested related entities (assignee, creator, organization) instead of flat IDs.
  • Improvements

    • Enhanced input validation and structured error handling for action item/category operations.
    • Updated queries and mutations to use explicit, descriptive input types.
    • Streamlined GraphQL schema to unify entity references and clarify relationships.
    • Added detailed authorization checks on resolvers for action items and categories.
    • Replaced ID references with direct object relations in the schema.
  • Bug Fixes

    • Improved error handling for missing or invalid related entities in resolvers.
    • Adjusted resolver behaviors to return null instead of errors for missing assignees.
  • Chores

    • Updated database schema and sample data to support new action item/category features.
    • Revised test suites: added comprehensive tests for new mutations; removed tests for deprecated queries.
    • Renamed schema tables and updated related imports and references for consistency.

Copy link

coderabbitai bot commented Apr 6, 2025

Walkthrough

This change is a comprehensive refactor and extension of the ActionItem and ActionItemCategory domain in the GraphQL API and underlying database schema. It replaces ID fields referencing related entities with direct object references in both types, introduces new input types and mutations for creating and updating action item categories, adds an allottedHours field to ActionItem, and updates corresponding resolvers and validation logic. The database schema and Drizzle ORM models are renamed and updated to match the new structure, with new migrations handling table drops and re-creations. Extensive updates are made to tests, input schemas, and query/mutation document nodes to align with the new model and API surface.

Changes

File(s) / Path(s) Change Summary
schema.graphql, test/graphql/types/gql.tada.d.ts, test/graphql/types/gql.tada-cache.d.ts Refactored ActionItem and ActionItemCategory types to use direct object references instead of ID fields, added allottedHours, replaced/added input types for mutations, removed deprecated queries and input types, updated mutation and query signatures.
src/drizzle/tables/actionItems.ts, src/drizzle/tables/actionItemCategories.ts, src/drizzle/schema.ts, src/drizzle/tables/organizations.ts, src/drizzle/tables/users.ts Renamed tables and relation variables from actionsTable/actionCategoriesTable to actionItemsTable/actionItemCategoriesTable, updated references throughout, added allottedHours column, updated relations and insert schemas.
drizzle_migrations/*.sql, drizzle_migrations/meta/_journal.json Dropped and recreated actions and action_categories tables with new structure, added/altered allotted_hours column, updated migration journal.
src/graphql/types/ActionItem/*, src/graphql/types/ActionItemCategory/* Updated or added resolvers for new object references (category, organization, updater, creator), removed ID fields, added/updated field resolvers, adjusted error handling and authorization logic.
src/graphql/types/Mutation/createActionItem.ts, src/graphql/types/Mutation/createActionItemCategory.ts, src/graphql/types/Mutation/updateActionItemCategory.ts, src/graphql/types/Mutation/deleteActionItem.ts, src/graphql/types/Mutation/updateActionItem.ts Refactored/added mutation resolvers for action items and categories, using new input schemas, improved validation, and updated table references.
src/graphql/inputs/MutationCreateActionItem.ts, src/graphql/inputs/MutationCreateActionItemCategory.ts, src/graphql/inputs/MutationUpdateActionItemCategory.ts, src/graphql/inputs/MutationDeleteActionItemInput.ts, src/graphql/inputs/MutationUpdateActionItemInput.ts, src/graphql/inputs/QueryActionCategoriesByOrganizationInput.ts, src/graphql/inputs/QueryActionItemInput.ts Added or updated Zod schemas and Pothos input types for new/modified mutations and queries, including argument wrapper schemas.
src/graphql/types/Query/ActionCategorybyOrg.ts, src/graphql/types/Query/ActionItem.ts, src/graphql/types/Query/index.ts, src/graphql/types/Mutation/index.ts Updated queries and mutation type registrations for new/renamed types and input schemas, removed deprecated queries.
test/graphql/types/documentNodes.ts Updated GraphQL document nodes to use new input types and nested object references for related entities, added/removed fields in mutations and queries.
test/graphql/types/Mutation/createActionItem.test.ts, test/graphql/types/Mutation/createActionItemCategory.test.ts Refactored and added tests for new mutation logic, focusing on authentication, validation, and authorization.
test/graphql/types/ActionItem/*.test.ts, test/graphql/types/ActionItemCategory/*.test.ts Added or updated unit tests for new/modified field resolvers, covering authentication, authorization, error handling, and data retrieval.
test/scripts/dbManagement/helpers.test.ts, scripts/dbManagement/helpers.ts Updated test and helper logic for renamed tables and schema references.
test/graphql/types/Query/ActionCategory.test.ts, test/graphql/types/Query/ActionItem.test.ts, test/graphql/types/Query/Events.test.ts, test/graphql/types/Query/organizationUsers.test.ts, src/graphql/types/Query/Events.ts, src/graphql/types/Query/organizationUsers.ts Removed deprecated or replaced query fields and their associated tests.
scripts/dbManagement/sample_data/action_items.json Renamed data key from actorId to assigneeId in sample data.
src/createServer.ts, src/envConfigSchema.ts, test/_Mocks_/drizzleClientMock.ts Minor cleanup: removed commented code and unused comments.
src/graphql/types/ActionItem/index.ts, src/graphql/types/ActionItemCategory/index.ts Updated import/export structure to match new resolver and type organization.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GraphQLAPI
    participant DB

    Client->>GraphQLAPI: createActionItemCategory(input)
    GraphQLAPI->>GraphQLAPI: Validate input (Zod)
    GraphQLAPI->>DB: Fetch organization by ID
    alt Organization does not exist
        GraphQLAPI-->>Client: Error (arguments_associated_resources_not_found)
    else
        GraphQLAPI->>DB: Check user membership and role
        alt Not a member or not admin
            GraphQLAPI-->>Client: Error (unauthorized or forbidden)
        else
            GraphQLAPI->>DB: Insert new ActionItemCategory
            alt Insert fails
                GraphQLAPI-->>Client: Error (unexpected)
            else
                GraphQLAPI-->>Client: Return new ActionItemCategory
            end
        end
    end
Loading
sequenceDiagram
    participant Client
    participant GraphQLAPI
    participant DB

    Client->>GraphQLAPI: createActionItem(input)
    GraphQLAPI->>GraphQLAPI: Validate input (Zod)
    GraphQLAPI->>DB: Fetch organization, category, assignee
    alt Any resource does not exist
        GraphQLAPI-->>Client: Error (arguments_associated_resources_not_found)
    else
        GraphQLAPI->>DB: Check user membership and admin role
        alt Not a member or not admin
            GraphQLAPI-->>Client: Error (unauthorized)
        else
            GraphQLAPI->>DB: Insert new ActionItem with allottedHours
            alt Insert fails
                GraphQLAPI-->>Client: Error (unexpected)
            else
                GraphQLAPI-->>Client: Return new ActionItem
            end
        end
    end
Loading

Possibly related PRs

  • #3109: Adds test coverage for the creator.ts resolver, complementing the new or modified resolver logic introduced in this PR.
  • #3385: Implements the initial GraphQL type and resolvers for ActionItem, which this PR directly extends and refactors.
  • #2508: Modifies ActionItem and ActionItemCategory schema and resolvers, including changes to allottedHours and entity references, overlapping with the focus of this PR.

Suggested reviewers

  • meetulr
  • disha1202
  • palisadoes

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 280ed54 and a0ea106.

📒 Files selected for processing (1)
  • src/drizzle/tables/actionItems.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run tests for talawa api
✨ 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.
    • 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 generate docstrings to generate docstrings for 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.

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 Apr 6, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b12506 and 996dc79.

📒 Files selected for processing (4)
  • schema.graphql (6 hunks)
  • src/graphql/types/Mutation/createActionItemCategory.ts (1 hunks)
  • src/graphql/types/Mutation/index.ts (1 hunks)
  • src/graphql/types/Mutation/updateActionItemCategory.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (9)
src/graphql/types/Mutation/index.ts (1)

80-81: Imports for new ActionItemCategory mutations look good.
No concerns with these additions. They properly expose the new create/update mutations in the GraphQL schema.

src/graphql/types/Mutation/createActionItemCategory.ts (1)

1-10: Imports appear logically consistent.
No issues found with the usage of these modules.

src/graphql/types/Mutation/updateActionItemCategory.ts (1)

1-15: Inputs and imports are correct.
The approach of having a separate Zod schema is consistent with best practices.

schema.graphql (6)

514-518: New Input Type for Creating Action Item Categories

This addition defines the CreateActionItemCategoryInput with the expected fields:

  • isDisabled: Boolean (optional),
  • name: String! (required), and
  • organizationId: ID! (required).

The fields correctly cover the data needed for creating a new Action Item Category as per the PR objectives.


782-786: Addition of HasUserVoted Type

The new HasUserVoted type encapsulates the vote type using the required enum field PostVoteType!. This change updates the schema to more clearly represent user vote status.


1486-1488: New Mutation Field: createActionItemCategory

The mutation field
createActionItemCategory(input: CreateActionItemCategoryInput!): ActionItemCategory
has been added to create an Action Item Category. This aligns with the new input type and overall objective to transition to GraphQL-driven mutations. Please ensure that the corresponding resolver in src/graphql/types/Mutation/createActionItemCategory.ts is updated accordingly.


1663-1665: New Mutation Field: updateActionItemCategory

The mutation field
updateActionItemCategory(input: UpdateActionItemCategoryInput!): ActionItemCategory
is introduced for updating existing Action Item Categories. Verify that the resolver in src/graphql/types/Mutation/updateActionItemCategory.ts properly handles partial updates (if applicable) and input validations.


3686-3690: New Input Type for Updating Action Item Categories

The UpdateActionItemCategoryInput is defined with:

  • categoryId: ID! (required),
  • isDisabled: Boolean (optional), and
  • name: String (optional).

This input type provides the needed flexibility for updating one or more properties of an Action Item Category.


3380-3380: Updated Query Field: hasUserVoted

The updated query field now returns the new HasUserVoted type instead of the previous definition. This modification ensures consistency with the new type definitions for vote status.

Copy link

codecov bot commented Apr 6, 2025

Codecov Report

Attention: Patch coverage is 69.07731% with 372 lines in your changes missing coverage. Please review.

Project coverage is 59.55%. Comparing base (33d5b7b) to head (a0ea106).

Files with missing lines Patch % Lines
...graphql/types/Mutation/updateActionItemCategory.ts 20.00% 88 Missing ⚠️
src/graphql/types/ActionItemCategory/updatedAt.ts 2.77% 70 Missing ⚠️
src/graphql/types/Mutation/createActionItem.ts 54.16% 66 Missing ⚠️
src/graphql/types/ActionItem/updater.ts 17.94% 64 Missing ⚠️
...graphql/types/Mutation/createActionItemCategory.ts 84.95% 17 Missing ⚠️
...hql/types/ActionItemCategory/actionItemCategory.ts 17.64% 14 Missing ⚠️
src/graphql/types/ActionItem/actionItem.ts 37.50% 10 Missing ⚠️
src/graphql/types/Query/ActionCategorybyOrg.ts 16.66% 10 Missing ⚠️
src/graphql/types/Mutation/updateActionItem.ts 30.76% 9 Missing ⚠️
src/graphql/types/ActionItem/creator.ts 90.90% 6 Missing ⚠️
... and 9 more
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3432      +/-   ##
====================================================
- Coverage             59.60%   59.55%   -0.05%     
====================================================
  Files                   523      535      +12     
  Lines                 40782    41413     +631     
  Branches               1786     1831      +45     
====================================================
+ Hits                  24307    24665     +358     
- Misses                16464    16737     +273     
  Partials                 11       11              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@NishantSinghhhhh
Copy link
Author

NishantSinghhhhh commented Apr 6, 2025

@meetulr sir, @palisadoes sir, There is one problem that I am encountering, 1 problem The action Item data is rendering fine in Foundation 1 but gives an error in other organization, Can you tell me what am I doing wrong so that I can correct this error, Is there any problem with the API code ??

Screencast.from.2025-04-06.11-06-22.webm

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 6, 2025
@meetulr
Copy link
Contributor

meetulr commented Apr 6, 2025

I'll review it properly in a few days—please keep it ready, along with the admin pr.

Also, maintain code consistency and separation. Keep things where they belong: inputs in the inputs folder, queries in the queries folder, and so on. Follow the project's code practices.

@meetulr
Copy link
Contributor

meetulr commented Apr 6, 2025

Please do not ask them to be merged without proper review.

@NishantSinghhhhh
Copy link
Author

Okay sir, I will add the tests too for the added files and keep things modular

@palisadoes
Copy link
Contributor

  1. Please make coderabbit.ai approves your work.
  2. Resolve any conflicting files
  3. Make sure all tests pass and are valid.
  4. Ensure the test code coverage for your patch reaches as close to 100% as possible.

@NishantSinghhhhh
Copy link
Author

Okay sir will be adding tests

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 7, 2025
@mpdesai90
Copy link

Please fix the failing tests.

@NishantSinghhhhh
Copy link
Author

Yes I will be adding tests for this PR in a while

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

♻️ Duplicate comments (2)
src/graphql/types/Mutation/createActionItemCategory.ts (2)

13-18: 🧹 Nitpick (assertive)

Consider consolidating Zod and builder definitions.

You're currently defining input fields in both the Zod schema and the builder’s inputType. Referencing the Zod schema directly, or consolidating definitions, can reduce duplication and improve maintainability.


69-101: 🧹 Nitpick (assertive)

Use a shared helper for membership & role checks.

These membership and role checks mirror patterns seen in other mutations. Extract them into a reusable function to avoid code duplication and simplify updates if the logic changes in the future.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 75d910e and 04eba4f.

📒 Files selected for processing (5)
  • src/graphql/types/Mutation/createActionItem.ts (1 hunks)
  • src/graphql/types/Mutation/createActionItemCategory.ts (1 hunks)
  • test/graphql/types/Mutation/createActionItemCategory.test.ts (1 hunks)
  • test/graphql/types/documentNodes.ts (1 hunks)
  • test/graphql/types/gql.tada-cache.d.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/graphql/types/Mutation/createActionItem.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
test/graphql/types/Mutation/createActionItemCategory.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/graphql/types/documentNodes.ts (4)
  • Mutation_createOrganization (370-378)
  • Query_signIn (191-218)
  • Mutation_createActionItemCategory (1007-1019)
  • Mutation_createUser (12-40)
test/server.ts (1)
  • server (12-27)
src/graphql/types/Mutation/createActionItemCategory.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (13)
test/graphql/types/documentNodes.ts (1)

1006-1019: Looks good!

This new mutation document node for createActionItemCategory is well-structured and ensures clarity in test usage. No issues stand out here.

src/graphql/types/Mutation/createActionItem.ts (1)

20-24: Mutation name clarity is appreciated.

Using "createActionItem" as the mutation name ensures descriptive readability and aligns with GraphQL best practices.

src/graphql/types/Mutation/createActionItemCategory.ts (1)

14-14: Good job adding a minimum length constraint.

The z.string().min(1, "Category name cannot be empty") effectively prevents empty category names. This aligns with previous feedback on validating user inputs.

test/graphql/types/gql.tada-cache.d.ts (1)

131-132: GraphQL mutation type definition correctly implemented.

The new CreateActionItemCategory mutation is properly defined with the appropriate input and return types. The input takes required organizationId and name fields, plus an optional isDisabled field, which aligns well with the functionality being implemented.

test/graphql/types/Mutation/createActionItemCategory.test.ts (9)

1-14: Well-structured imports with appropriate dependencies.

The imports are properly organized, bringing in necessary testing utilities from Vitest, database tables, and GraphQL document nodes for the tests.


16-40: Well-implemented helper function for test setup.

The createOrganizationAndGetId helper function is well-structured and includes appropriate error handling and assertions. It creates an organization with unique test data for use in tests.


42-55: Clean utility function for test data setup.

The addMembership function provides a clean way to add organization memberships for test users, which is reused across multiple tests.


57-71: Good authentication setup for tests.

The code properly authenticates as an admin user to get a token for tests that require authentication. The assertions ensure that required data is available before proceeding with tests.


73-105: Comprehensive test for unauthenticated users.

The test correctly verifies that unauthenticated requests are rejected with the appropriate error code. This ensures the mutation properly enforces authentication requirements.


107-140: Thorough validation of non-existent organization handling.

The test effectively verifies that attempts to create a category for a non-existent organization are properly rejected with appropriate error details.


142-177: Well-implemented test for organization membership validation.

This test correctly verifies that users who are not members of an organization cannot create categories for it, enforcing proper authorization boundaries.


179-245: Comprehensive test for role-based access control.

This test suite thoroughly validates that non-administrator users cannot create categories even if they are members of the organization, enforcing proper role-based permissions.


1-294: Overall excellent test coverage for the new mutation.

The test suite provides comprehensive coverage of the createActionItemCategory mutation, testing authentication, authorization, input validation, and successful execution. The tests follow good practices with proper setup, teardown, and assertions.

@NishantSinghhhhh
Copy link
Author

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 9, 2025

✅ Actions performed

Full review triggered.

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

♻️ Duplicate comments (6)
src/graphql/types/Mutation/createActionItem.ts (1)

20-162: Membership & role check logic duplication.
You are repeating membership & role checks here, which have also appeared in other mutations. It may be beneficial to extract them into a shared helper for reusability.

Reevaluate automatic completionAt assignment.
At line 142, you set completionAt to new Date(), which marks the action item as completed at creation. Consider deferring this assignment until the action is truly completed or rename the field to avoid confusion.

src/graphql/types/Mutation/createActionItemCategory.ts (1)

1-127: 🧹 Nitpick (assertive)

Consider adding a max length or trimming for name.
You already validate that name is non-empty. Enforcing a reasonable maximum length or trimming input can further prevent data inconsistencies.

- name: z.string().min(1, "Category name cannot be empty"),
+ name: z.string().min(1, "Category name cannot be empty").max(50, "Name cannot exceed 50 characters"),

Consolidate membership & role checks.
Similar membership & role checks exist in other mutations. A shared utility could keep repeated logic consistent and easier to maintain.

Avoid duplicating Zod and builder definitions.
The input type validation is defined both in Zod and in the builder’s inputType. Centralizing or referencing a single schema helps prevent unintentional mismatches in future refactors.

src/graphql/types/Mutation/updateActionItemCategory.ts (2)

8-14: Consider referencing the Zod schema to unify input definitions
This is a repeated suggestion from a previous review comment. You might consolidate the builder’s input fields with the same Zod schema used here to ensure consistency across mutations.


65-86: Well-structured membership checks
As noted previously, consider moving this membership and role-check logic into a shared utility to reduce duplication across create/update mutations.

test/graphql/types/Mutation/createActionItemCategory.test.ts (2)

4-4: Consider removing or uncommenting the commented import.

There's a commented import for actionCategoriesTable which isn't being used in the code. If it's not needed, consider removing it entirely; if it will be needed, consider uncommenting it.

-// import { actionCategoriesTable } from "~/src/drizzle/tables/actionCategories";

247-292: Verify mock parameters in the success case test.

While the success test correctly mocks the database operation and asserts the response, it doesn't verify that the database insert was called with the expected parameters. Consider adding an assertion to verify the mock was called with the correct values.

 server.drizzleClient.insert = vi.fn().mockReturnValueOnce({
     values: vi.fn().mockReturnThis(),
     returning: vi.fn().mockResolvedValueOnce([
         {
             id: "category-123",
             name: "Test Category",
             organizationId: orgId,
             creatorId: adminUserId,
             isDisabled: false,
             createdAt: new Date(),
             updatedAt: new Date(),
         },
     ]),
 });

 const result = await mercuriusClient.mutate(
     Mutation_createActionItemCategory,
     {
         headers: { authorization: `bearer ${authToken}` },
         variables: {
             input: {
                 name: "Test Category",
                 organizationId: orgId,
                 isDisabled: false,
             },
         },
     },
 );

+// Verify insert was called with correct table and values
+expect(server.drizzleClient.insert).toHaveBeenCalledWith(expect.anything());
+expect(server.drizzleClient.insert().values).toHaveBeenCalledWith(
+    expect.objectContaining({
+        name: "Test Category",
+        organizationId: orgId,
+        isDisabled: false,
+        creatorId: adminUserId,
+    })
+);

 expect(result.errors).toBeUndefined();
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61a89c9 and 04eba4f.

📒 Files selected for processing (11)
  • schema.graphql (6 hunks)
  • src/createServer.ts (0 hunks)
  • src/envConfigSchema.ts (0 hunks)
  • src/graphql/types/Mutation/createActionItem.ts (1 hunks)
  • src/graphql/types/Mutation/createActionItemCategory.ts (1 hunks)
  • src/graphql/types/Mutation/index.ts (1 hunks)
  • src/graphql/types/Mutation/updateActionItemCategory.ts (1 hunks)
  • test/graphql/types/Mutation/createActionItemCategory.test.ts (1 hunks)
  • test/graphql/types/documentNodes.ts (1 hunks)
  • test/graphql/types/gql.tada-cache.d.ts (1 hunks)
  • test/graphql/types/gql.tada.d.ts (5 hunks)
💤 Files with no reviewable changes (2)
  • src/envConfigSchema.ts
  • src/createServer.ts
🧰 Additional context used
🧬 Code Graph Analysis (4)
src/graphql/types/Mutation/createActionItemCategory.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/graphql/types/Mutation/createActionItem.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
test/graphql/types/Mutation/createActionItemCategory.test.ts (3)
test/graphql/types/client.ts (1)
  • mercuriusClient (7-9)
test/graphql/types/documentNodes.ts (4)
  • Mutation_createOrganization (370-378)
  • Query_signIn (191-218)
  • Mutation_createActionItemCategory (1007-1019)
  • Mutation_createUser (12-40)
test/server.ts (1)
  • server (12-27)
src/graphql/types/Mutation/updateActionItemCategory.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
🔇 Additional comments (20)
test/graphql/types/documentNodes.ts (1)

1007-1019: Mutation registration looks good.
This newly added createActionItemCategory mutation appears consistent with the existing pattern in this file. The input type and returned fields align correctly with the rest of the codebase.

src/graphql/types/Mutation/index.ts (1)

80-81: Consistent import structure.
Importing and registering the new createActionItemCategory and updateActionItemCategory mutations here follows the existing convention of listing all mutation modules.

src/graphql/types/Mutation/createActionItem.ts (1)

16-17: Optional assignedAt field integration is well-handled.
Defining assignedAt as optional in the schema is a flexible approach. It’s clearly defaulted to new Date() if omitted in the mutation.

src/graphql/types/Mutation/updateActionItemCategory.ts (4)

32-45: Looks good
The authentication flow and argument parsing appear correct.


46-55: Straightforward retrieval
Fetching the existing category is clearly structured and typed properly.


56-63: Robust error handling
You correctly throw a TalawaGraphQLError when the category ID does not match any existing resource.


113-114: Returning updated data
Returning the updated record is straightforward and meets the mutation requirements.

test/graphql/types/gql.tada.d.ts (4)

38-38: Well-structured input type for action item category creation.

The CreateActionItemCategoryInput definition correctly includes the required fields with appropriate nullability constraints. The name and organizationId fields are correctly marked as non-nullable, while isDisabled can be optional.


61-61: Good type definition for HasUserVoted.

The HasUserVoted object type is well defined with a non-nullable type field that uses the PostVoteType enum. This makes the API response type-safe and prevents null values in critical fields.


73-73: Properly updated Mutation and Query objects.

The Mutation and Query objects have been correctly updated to include the new fields createActionItemCategory and hasUserVoted, respectively, ensuring they're accessible through the GraphQL API.

Also applies to: 187-187


224-224: Well-designed update input type.

The UpdateActionItemCategoryInput is properly structured with a required categoryId field and optional update fields for isDisabled and name. This follows best practices for partial updates.

test/graphql/types/Mutation/createActionItemCategory.test.ts (6)

16-40: Well-implemented organization creation helper function.

The helper function is well-structured with appropriate error handling, assertions, and meaningful variable names. It properly creates an organization with unique names using faker to prevent test conflicts.


42-55: Good utility function for adding memberships.

The addMembership function is concise and handles the database insertion correctly with typed role parameter.


79-106: Comprehensive authentication test.

Your test for unauthenticated access properly verifies that the mutation returns the expected error code and response structure. This ensures unauthorized users cannot create action item categories.


107-140: Good validation for non-existent organization.

The test correctly verifies that the mutation returns an appropriate error when attempting to create a category for a non-existent organization, with detailed assertion of the error structure.


142-177: Well-implemented membership validation.

This test properly verifies that users who are not members of an organization cannot create categories for it, ensuring proper access control.


179-245: Thorough administrator role check.

The test case for non-administrator users is comprehensive, creating a new user, adding appropriate membership, and verifying the correct error response when they attempt to create a category without admin rights.

schema.graphql (3)

782-785: New Type Definition: HasUserVoted

The new HasUserVoted type encapsulates the vote type information and replaces the previous scalar/boolean field. The field description is present and clear. Ensure that the resolver logic and client queries are updated accordingly to reflect this new type.


1486-1488: New Mutation Field: createActionItemCategory

The mutation field for creating an Action Item Category is added with a clear description and proper input type. Verify that the corresponding resolver (in its separate file) includes the necessary input validation, authentication, and authorization checks.


1663-1665: New Mutation Field: updateActionItemCategory

This mutation field for updating an existing Action Item Category is well defined. As with any update operation, ensure that the resolver enforces proper validation (e.g., at least one field to update is provided) and appropriate permission checks.

Signed-off-by: NishantSinghhhhh <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 9, 2025
Signed-off-by: NishantSinghhhhh <[email protected]>
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

♻️ Duplicate comments (4)
src/graphql/types/Mutation/updateActionItemCategory.ts (4)

8-14: Consider referencing a shared Zod schema for category inputs.
This helps keep the definitions for create/update operations in sync and reduces duplication in the codebase.


22-28: Place input definitions in a dedicated folder.
Following the existing folder structure for inputs (e.g., the inputs folder) can help maintain consistency and clarity.


65-86: Extract membership & role checks into a shared utility.
Moving membership and role validations to a shared utility promotes reusability across mutations.


110-121: Consider concurrency control and enhanced logging.
Row-level locking or version checks can help avoid conflicts if multiple users update the same category simultaneously. Logging the category ID in the error message can further aid debugging.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 04eba4f and 0bb9e11.

📒 Files selected for processing (1)
  • src/graphql/types/Mutation/updateActionItemCategory.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/graphql/types/Mutation/updateActionItemCategory.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
🪛 GitHub Actions: Pull request workflow
src/graphql/types/Mutation/updateActionItemCategory.ts

[error] 16-16: Formatter would have printed the following content: Code formatting issues detected. Please run the formatter to fix.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (3)
src/graphql/types/Mutation/updateActionItemCategory.ts (3)

32-45: Well-implemented authentication and validation.
The checks for user authentication and argument validation are clear and appropriately handled.


46-63: Straightforward existence check for the category.
Throwing an error for a missing category is a valid approach and keeps the logic simple.


102-109: Good approach to skip unnecessary updates.
Only performing an update when fields actually change helps reduce overhead and avoid needless writes.

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 22, 2025
@meetulr
Copy link
Contributor

meetulr commented Apr 22, 2025

Change the file names as well. Like I've been saying, please be consistent with names. actionItemCategories, actionItems.

I meant the file names in the tables, not in the types, it should be in pascal case like in the other types for the schema name.

also, this remains:

change table names to actionItemCategoriesTable, actionItemsTable.

Consistency across the code base. This need not be pointed out this many times. Look at how other tables are defined, how other types are defined, how other features are implemented...

@NishantSinghhhhh
Copy link
Author

I apologize for the confusion between the file name and the table name, which is why I was not able to make the desired changes that you pointed out

Signed-off-by: NishantSinghhhhh <[email protected]>
@NishantSinghhhhh
Copy link
Author

sir I have chnaged the table names as you said now the table actionItems is actionItemsTable and actionItemCategoriesTable is actionItemCategoriesTable

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

🔭 Outside diff range comments (2)
src/graphql/types/Query/ActionItem.ts (1)

26-153: 🧹 Nitpick (assertive)

Error handling could be simplified

The error handling logic is thorough but has some redundancy. There are multiple places checking for authorization issues with similar error generation. Consider extracting common error handling patterns into helper functions.

For example, you could create a helper function for authorization checks:

function ensureUserAuthorized(
  currentUser: { role?: string } | undefined,
  membership: any | undefined,
  resourcePath: string[]
) {
  if (!currentUser) {
    throw new TalawaGraphQLError({
      extensions: {
        code: "unauthenticated",
      },
    });
  }
  
  if (currentUser.role !== "administrator" && !membership) {
    throw new TalawaGraphQLError({
      extensions: {
        code: "unauthorized_action_on_arguments_associated_resources",
        issues: [{ argumentPath: resourcePath }],
      },
    });
  }
}

Then use it to simplify your code:

// Check authorization
ensureUserAuthorized(
  currentUser,
  currentUserOrganizationMembership,
  ["input", "organizationId"]
);
src/graphql/types/ActionItem/categoryId.ts.ts (1)

1-55: 🧹 Nitpick (assertive)

File name has duplicate extension

The file name categoryId.ts.ts has a duplicate .ts extension which seems to be a mistake.

Rename the file to categoryId.ts to follow standard naming conventions.

♻️ Duplicate comments (22)
test/graphql/types/ActionItem/categoryId.test.ts (1)

43-65: Consider consolidating duplicate function calls in error tests.

The test calls resolveCategory twice for the same inputs (lines 46-48 and 51). Consider restructuring to capture the error object once and run multiple assertions against it.

-		await expect(resolveCategory(parent, {}, ctx)).rejects.toBeInstanceOf(
-			TalawaGraphQLError,
-		);
-
-		try {
-			await resolveCategory(parent, {}, ctx);
-		} catch (err) {
+		try {
+			await resolveCategory(parent, {}, ctx);
+			fail("Expected function to throw an error");
+		} catch (err) {
+			expect(err).toBeInstanceOf(TalawaGraphQLError);
			expect(err).toMatchObject({
				message: "Category not found",
				extensions: {
					code: "arguments_associated_resources_not_found",
					issues: [{ argumentPath: ["categoryId"] }],
				},
			});
src/drizzle/schema.ts (1)

8-8: ⚠️ Potential issue

Inconsistent naming pattern for relation export

The naming pattern for your relation exports should follow <tableName>Relations. While you've properly renamed the table to actionItemsTable, the relation export is actionsItemRelations which is inconsistent.

-export { actionItemsTable, actionsItemRelations } from "./tables/actionItems";
+export { actionItemsTable, actionItemsRelations } from "./tables/actionItems";

This ensures you follow the established naming convention where the relation export name is derived from the table name.

src/graphql/types/ActionItem/actionItem.ts (1)

24-24: 🧹 Nitpick (assertive)

Consider adding a comment explaining why updatedAt is nullable

The change to make updatedAt nullable isn't obvious. A comment would help explain the rationale.

Add a comment explaining why updatedAt can be null:

  updatedAt: t.expose("updatedAt", {
    description: "Timestamp when the action item was last updated.",
    type: "DateTime",
+   // Nullable because new items might not have been updated yet
    nullable: true,
  }),
src/graphql/types/Mutation/createActionItemCategory.ts (3)

81-85: ⚠️ Potential issue

Unsafe hand‑rolled SQL in where clause can break portability & safety

Using raw template interpolation with SQL makes the statement harder to reason about and may bypass the query‑builder's parameterization guarantees.

A safer, clearer pattern is to rely on the logical helpers Drizzle already provides:

-	where: (fields, operators) =>
-		sql`${operators.eq(fields.memberId, currentUserId)} AND ${operators.eq(
-			fields.organizationId,
-			parsedArgs.input.organizationId,
-		)}`,
+	where: (fields, operators) =>
+		operators.and(
+			operators.eq(fields.memberId, currentUserId),
+			operators.eq(fields.organizationId, parsedArgs.input.organizationId),
+		)

115-123: 🛠️ Refactor suggestion

Missing updaterId in category creation

The resolver sets the creatorId but not the updaterId field, which should be set to maintain consistency in tracking who last modified the record.

Add the updaterId field to the insert operation:

  .values({
    id: uuidv7(),
    name: parsedArgs.input.name,
    organizationId: parsedArgs.input.organizationId,
    creatorId: currentUserId,
+   updaterId: currentUserId,
    // If isDisabled is provided, use it; otherwise, default to false (i.e. enabled).
    isDisabled: parsedArgs.input.isDisabled ?? false,
    createdAt: new Date(),
    updatedAt: new Date(),
  })

111-132: 🛠️ Refactor suggestion

Check for duplicate category names before inserting

Nothing prevents two admins from inserting the same category twice for one organization.

Add a uniqueness guard before insertion:

+ // 5½. Ensure category name is unique within the organisation.
+ const existingCategory = await ctx.drizzleClient.query.actionItemCategoriesTable.findFirst({
+   columns: { id: true },
+   where: (fields, operators) =>
+     operators.and(
+       operators.eq(fields.organizationId, parsedArgs.input.organizationId),
+       operators.eq(fields.name, parsedArgs.input.name),
+     ),
+ });
+ if (existingCategory) {
+   throw new TalawaGraphQLError({
+     extensions: {
+       code: "already_exists",
+       issues: [{ argumentPath: ["input", "name"], message: "Category name already exists" }],
+     },
+   });
+ }

// 6. Insert the new category into the database.
src/graphql/inputs/QueryActionCategoriesByOrganizationInput.ts (1)

33-36: 🧹 Nitpick (assertive)

Clarify the purpose of the optional arguments wrapper

The comment "optional for consistency" doesn't clearly explain why this wrapper is needed or when it should be used.

/**
- * 3️⃣ Arguments schema to wrap the input (optional for consistency)
+ * 3️⃣ Arguments schema to wrap the input
+ * This wrapper provides consistency with other query/mutation argument structures
+ * and allows validating the entire args object at once
 */
src/graphql/types/Mutation/updateActionItemCategory.ts (3)

81-84: ⚠️ Potential issue

Security issue in SQL query and formatting inconsistency

There are two issues with this code segment:

  1. SQL query construction using string templates could lead to security issues
  2. The indentation on line 83 is inconsistent

Replace the raw SQL template with Drizzle's logical operators and fix the indentation:

- where: (fields, operators) =>
-   sql`${operators.eq(fields.memberId, currentUserId)} 
-            AND ${operators.eq(fields.organizationId, existingCategory.organizationId)}`,
+ where: (fields, operators) =>
+   operators.and(
+     operators.eq(fields.memberId, currentUserId),
+     operators.eq(fields.organizationId, existingCategory.organizationId)
+   ),

104-107: 🛠️ Refactor suggestion

Missing uniqueness check when updating name

When updating the category name, there's no check to prevent creating a duplicate name within the same organization.

Add a check for an existing category with the same name:

if (typeof name === "string") {
+   // Check if another category with the same name exists in this organization
+   const existingCategoryWithSameName = await ctx.drizzleClient.query.actionItemCategoriesTable.findFirst({
+     columns: { id: true },
+     where: (fields, operators) =>
+       operators.and(
+         operators.eq(fields.organizationId, existingCategory.organizationId),
+         operators.eq(fields.name, name),
+         operators.ne(fields.id, categoryId), // Exclude the current category
+       ),
+   });
+ 
+   if (existingCategoryWithSameName) {
+     throw new TalawaGraphQLError({
+       extensions: {
+         code: "invalid_arguments",
+         issues: [
+           {
+             argumentPath: ["input", "name"],
+             message: "A category with this name already exists in the organization",
+           },
+         ],
+       },
+     });
+   }
    updates.name = name;
    hasUpdates = true;
}

115-119: 🛠️ Refactor suggestion

Missing updaterId in update operation and empty else block

Two issues in this code segment:

  1. The code sets the updatedAt timestamp but doesn't set the updaterId field
  2. There's an empty else block with just a comment

Fix both issues:

if (hasUpdates) {
  updates.updatedAt = new Date();
+ updates.updaterId = currentUserId;
- } else {
-   // Optionally handle scenario where nothing is provided to update.
}
src/drizzle/tables/actionItems.ts (5)

68-68: 🧹 Nitpick (assertive)

Add comment explaining the allottedHours field

The allottedHours field was added to track time allocation for action items but lacks documentation about its purpose and usage.

-	allottedHours: numeric("allotted_hours"),
+	// Number of hours estimated to complete this action item
+	allottedHours: numeric("allotted_hours"),

104-104: 🧹 Nitpick (assertive)

Incorrect relation variable name

The relation variable should match the table name for consistency.

-export const actionsItemRelations = relations(actionItemsTable, ({ one }) => ({
+export const actionItemsRelations = relations(actionItemsTable, ({ one }) => ({

113-113: ⚠️ Potential issue

Fix relationName to use the renamed tables

The relationName still references the old table names which doesn't match the renamed variables.

-	relationName: "action_categories.id:actions.category_id",
+	relationName: "action_item_categories.id:action_items.category_id",

27-27: 🛠️ Refactor suggestion

Update database column for assigneeId to match the TS field

The database column name actor_id doesn't match the field name assigneeId, creating inconsistency between the code and database schema.

-	assigneeId: uuid("actor_id").references(() => usersTable.id, {
+	assigneeId: uuid("assignee_id").references(() => usersTable.id, {

This will require a database migration to rename the column.


137-138: 🧹 Nitpick (assertive)

Add export comment for clarity

The export comment could be improved to clarify the purpose of this schema.

-// ✅ Export the insert schema with the new field included
+// ✅ Export the insert schema with the new field included
+// This schema is used for validating insertions into the actionItems table
src/graphql/types/Mutation/createActionItem.ts (2)

12-14: 🛠️ Refactor suggestion

Incorrect mutation export name

The exported mutation is named createActionItemCategoryMutation but it's actually implementing createActionItem. This naming mismatch could cause confusion.

-export const createActionItemCategoryMutation = builder.mutationField(
+export const createActionItemMutation = builder.mutationField(

145-145: ⚠️ Potential issue

Remove default completion date for incomplete items

Setting completionAt to the current date on creation is misleading since the item is marked as incomplete (isCompleted: false). Completion date should only be set when an item is actually completed.

-	completionAt: new Date(),
+	completionAt: null,
test/graphql/types/gql.tada.d.ts (5)

76-78: ⚠️ Potential issue

Input mismatch: allottedHours still Int, assignedAt still String

This repeats an earlier review point and remains unresolved. Please update the underlying MutationCreateActionItemInput definition as outlined above and regenerate the introspection file.


128-128: 🛠️ Refactor suggestion

Inconsistent id field name (categoryId vs id)

Previous review requested aligning with the rest of the API (id). Keeping a bespoke categoryId forces client‑side special‑cases and harms DX.

- t.id('categoryId', { required: true })
+ t.id('id', { required: true })

129-129: ⚠️ Potential issue

UpdateActionItemInput – type & nullability issues still pending

  1. allottedHours is Int (should be Float).
  2. isCompleted is non‑null, breaking PATCH‑style partial updates.
  3. assignedAt is missing entirely, so cannot be amended.

These were flagged before and are still present.


189-191: 🛠️ Refactor suggestion

Scalar inconsistency for organizationId in query inputs

QueryActionCategoriesByOrganizationInput now uses ID ✅, but QueryActionItemsByOrganizationInput still uses String. Use ID everywhere for identifier symmetry.

- t.string('organizationId', { required: true })
+ t.id('organizationId', { required: true })

Update the builder file and regenerate introspection.


6-7: 🛠️ Refactor suggestion

⚠️ Potential issue

ActionItem field type drift vs. input declarations

ActionItem.allottedHours is now correctly exposed as Float and assignedAt as DateTime, but their counterparts in the create / update input objects are still Int and String (see lines 77 & 129). Clients will either lose precision (FloatInt) or fail validation (DateTimeString).

Action items can no longer be created/updated consistently until the input types and resolvers are synchronised.

Recommended fix (GraphQL builder definitions, not this generated file):

- t.int('allottedHours')
+ t.float('allottedHours')

- t.string('assignedAt')
+ t.field('assignedAt', { type: 'DateTime' })

After adjusting the builder code, re‑run code‑gen so the .d.ts file self‑heals.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8fb5aa8 and fa3373a.

📒 Files selected for processing (28)
  • drizzle_migrations/20250422113008_fast_prism.sql (1 hunks)
  • drizzle_migrations/20250422113209_common_la_nuit.sql (1 hunks)
  • drizzle_migrations/meta/_journal.json (1 hunks)
  • scripts/dbManagement/helpers.ts (3 hunks)
  • src/createServer.ts (0 hunks)
  • src/drizzle/schema.ts (1 hunks)
  • src/drizzle/tables/actionItemCategories.ts (2 hunks)
  • src/drizzle/tables/actionItems.ts (2 hunks)
  • src/drizzle/tables/organizations.ts (2 hunks)
  • src/drizzle/tables/users.ts (2 hunks)
  • src/envConfigSchema.ts (0 hunks)
  • src/graphql/inputs/QueryActionCategoriesByOrganizationInput.ts (1 hunks)
  • src/graphql/types/ActionItem/actionItem.ts (3 hunks)
  • src/graphql/types/ActionItem/categoryId.ts.ts (1 hunks)
  • src/graphql/types/ActionItem/index.ts (1 hunks)
  • src/graphql/types/ActionItemCategory/actionItemCategory.ts (2 hunks)
  • src/graphql/types/Mutation/createActionItem.ts (1 hunks)
  • src/graphql/types/Mutation/createActionItemCategory.ts (1 hunks)
  • src/graphql/types/Mutation/deleteActionItem.ts (3 hunks)
  • src/graphql/types/Mutation/updateActionItem.ts (6 hunks)
  • src/graphql/types/Mutation/updateActionItemCategory.ts (1 hunks)
  • src/graphql/types/Query/ActionCategorybyOrg.ts (4 hunks)
  • src/graphql/types/Query/ActionItem.ts (2 hunks)
  • src/graphql/types/Query/index.ts (1 hunks)
  • test/graphql/types/ActionItem/assignee.test.ts (0 hunks)
  • test/graphql/types/ActionItem/categoryId.test.ts (1 hunks)
  • test/graphql/types/gql.tada.d.ts (5 hunks)
  • test/scripts/dbManagement/helpers.test.ts (4 hunks)
💤 Files with no reviewable changes (3)
  • src/envConfigSchema.ts
  • test/graphql/types/ActionItem/assignee.test.ts
  • src/createServer.ts
🧰 Additional context used
🧠 Learnings (1)
test/graphql/types/gql.tada.d.ts (1)
Learnt from: GlenDsza
PR: PalisadoesFoundation/talawa-api#2615
File: src/typeDefs/inputs.ts:80-80
Timestamp: 2024-11-01T10:39:50.333Z
Learning: In `src/typeDefs/inputs.ts`, the `orgId` field in `ActionItemWhereInput` is intentionally optional (`ID`) and should not be changed to non-nullable (`ID!`).
🧬 Code Graph Analysis (10)
src/graphql/types/Mutation/deleteActionItem.ts (1)
src/drizzle/tables/actionItems.ts (1)
  • actionItemsTable (18-102)
src/drizzle/tables/users.ts (3)
src/drizzle/schema.ts (2)
  • actionItemsTable (8-8)
  • actionItemCategoriesTable (5-5)
src/drizzle/tables/actionItems.ts (1)
  • actionItemsTable (18-102)
src/drizzle/tables/actionItemCategories.ts (1)
  • actionItemCategoriesTable (16-66)
test/graphql/types/ActionItem/categoryId.test.ts (3)
src/graphql/context.ts (1)
  • GraphQLContext (55-55)
test/_Mocks_/drizzleClientMock.ts (1)
  • createMockDrizzleClient (30-50)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/drizzle/tables/actionItemCategories.ts (3)
src/drizzle/tables/actionItems.ts (1)
  • actionItemsTable (18-102)
src/drizzle/tables/users.ts (1)
  • usersTable (59-216)
src/drizzle/tables/organizations.ts (1)
  • organizationsTable (31-128)
src/graphql/types/Mutation/updateActionItemCategory.ts (5)
src/graphql/builder.ts (1)
  • builder (10-20)
src/graphql/types/ActionItemCategory/actionItemCategory.ts (2)
  • ActionItemCategory (6-8)
  • ActionItemCategory (10-11)
src/graphql/inputs/MutationUpdateActionItemCategory.ts (2)
  • MutationUpdateActionItemCategoryInput (18-41)
  • mutationUpdateActionItemCategoryArgumentsSchema (46-48)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/drizzle/tables/actionItemCategories.ts (1)
  • actionItemCategoriesTable (16-66)
src/graphql/types/Mutation/updateActionItem.ts (1)
src/drizzle/tables/actionItems.ts (1)
  • actionItemsTable (18-102)
src/graphql/inputs/QueryActionCategoriesByOrganizationInput.ts (1)
src/graphql/builder.ts (1)
  • builder (10-20)
src/graphql/types/Query/ActionCategorybyOrg.ts (2)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/graphql/inputs/QueryActionCategoriesByOrganizationInput.ts (1)
  • queryActionCategoriesByOrganizationArgumentsSchema (37-39)
src/graphql/types/ActionItem/categoryId.ts.ts (4)
src/graphql/context.ts (1)
  • GraphQLContext (55-55)
src/graphql/types/ActionItemCategory/actionItemCategory.ts (2)
  • ActionItemCategory (6-8)
  • ActionItemCategory (10-11)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/graphql/types/ActionItem/actionItem.ts (2)
  • ActionItem (4-4)
  • ActionItem (6-6)
src/drizzle/tables/actionItems.ts (3)
src/drizzle/tables/users.ts (1)
  • usersTable (59-216)
src/drizzle/tables/actionItemCategories.ts (1)
  • actionItemCategoriesTable (16-66)
src/drizzle/tables/organizations.ts (1)
  • organizationsTable (31-128)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run tests for talawa api
🔇 Additional comments (35)
drizzle_migrations/meta/_journal.json (1)

11-59: Migration journal entries look good

The journal entries for the migrations related to action items and categories have been properly added with sequential indices and appropriate tags. This correctly documents the database schema changes for tracking and versioning purposes.

I notice that the migration entries include operations for dropping and likely recreating the action_categories and actions tables based on the migration file names (e.g., "fast_prism" and "common_la_nuit"). This aligns with the PR objective to migrate ActionItem Categories to GraphQL.

src/graphql/types/Query/ActionItem.ts (2)

3-7: Import organization looks good

The imports have been updated to be more organized and use absolute paths consistently. The consolidation of input imports and the consistent path structure for imports improve code maintainability.


66-66: Table naming change aligns with schema updates

The table reference has been updated from actionsTable to actionItemsTable, which correctly aligns with the database schema changes introduced in the migrations. This ensures consistency between the GraphQL schema and the underlying database tables.

src/drizzle/tables/organizations.ts (3)

14-15: Updated import statements to match renamed tables

The imports have been correctly updated to reflect the renaming of action-related tables from actionCategoriesTable and actionsTable to actionItemCategoriesTable and actionItemsTable, ensuring proper reference to the renamed table modules.


136-138: Updated relation references to use renamed actionItems table

The relation reference has been correctly updated from actionsTable to actionItemsTable while maintaining the original relation name, preserving the relationship logic while ensuring naming consistency.


142-144: Updated relation references to use renamed actionItemCategories table

The relation reference has been correctly updated from actionCategoriesTable to actionItemCategoriesTable while preserving the original relation name string. This maintains consistency with the broader refactoring effort to standardize action item terminology.

test/scripts/dbManagement/helpers.test.ts (4)

330-331: Updated test to use actionItemCategoriesTable reference

The test has been properly updated to use the renamed schema.actionItemCategoriesTable reference, aligning with the schema changes throughout the codebase.


344-345: Updated primary key reference to use actionItemCategoriesTable

The reference to the primary key has been correctly updated to use schema.actionItemCategoriesTable.id, ensuring the test continues to function properly with the renamed tables.


364-369: Updated type inference for captured data

The type inference has been correctly updated to use schema.actionItemsTable.$inferInsert, ensuring proper type safety when working with the renamed table in the test.


383-386: Updated table and primary key references in test function

The test case now correctly uses schema.actionItemsTable and its ID field, maintaining consistency with the renamed tables throughout the codebase.

src/drizzle/tables/users.ts (3)

22-23: Updated import statements to match renamed tables

The imports have been correctly updated to reflect the renaming of action-related tables from actionCategoriesTable and actionsTable to actionItemCategoriesTable and actionItemsTable, maintaining consistency with changes across the codebase.


222-236: Updated user-action relationships to use renamed action tables

All action-related relation definitions have been correctly updated to use actionItemsTable instead of actionsTable while maintaining the original relation names. This ensures consistency with the broader refactoring of action item terminology while preserving the underlying relationship structure.


240-248: Updated user-actionCategory relationships to use renamed category tables

The action category relation definitions have been correctly updated to use actionItemCategoriesTable instead of actionCategoriesTable while preserving the original relation names. This maintains consistency with the codewide updates to action item terminology.

src/graphql/types/Mutation/deleteActionItem.ts (3)

2-7: Updated imports and schema references

The imports have been updated to:

  1. Use the renamed actionItemsTable instead of actionsTable
  2. Fix the import path for ActionItem to correctly use actionItem (lowercase)
  3. Add an import for the shared mutationDeleteActionItemArgumentsSchema

These changes ensure consistency with the project's naming conventions and promote reuse of validation schemas.


58-64: Updated query to use renamed actionItemsTable

The database query now correctly references actionItemsTable instead of the previous actionsTable, aligning with the renamed table structure while maintaining the same query logic.


89-92: Updated delete operation to use renamed actionItemsTable

The delete operation now correctly uses actionItemsTable in both the table reference and the where clause, maintaining consistency with the renamed table structure throughout the codebase.

scripts/dbManagement/helpers.ts (2)

561-617: LGTM! Table references consistently updated.

The changes appropriately update references from the old table names (actionCategoriesTable and actionsTable) to the new names (actionItemCategoriesTable and actionItemsTable), aligning with the broader schema refactoring effort.


669-671: LGTM! Table references consistently updated in the tables array.

Tables array entries have been correctly updated to use the new table names, maintaining consistency with the changes made elsewhere in the file.

src/graphql/types/Mutation/updateActionItem.ts (1)

198-201:

❌ Incorrect review comment

Verify the handling of allottedHours as a string conversion.

The code converts allottedHours to a string before storing it, but the database column is defined as numeric. While Postgres can handle string-to-numeric conversion automatically, it's generally better to maintain type consistency.


🏁 Script executed:

#!/bin/bash
# Check how allottedHours is handled in other locations to ensure consistency
echo "Checking allottedHours handling in other mutations:"
rg --type ts "allottedHours.*toString\(\)" src/graphql/types/Mutation/

echo -e "\nChecking allottedHours column definition:"
rg --type ts -A 3 "allottedHours" src/drizzle/tables/

Length of output: 770


Remove incorrect concern about allottedHours conversion

The string conversion for allottedHours is intentional and consistent across both createActionItem.ts and updateActionItem.ts. In our Drizzle schema, numeric("allotted_hours") columns expect string values to preserve precision. No change needed here.

Likely an incorrect or invalid review comment.

test/graphql/types/ActionItem/categoryId.test.ts (1)

1-79: LGTM! Comprehensive test coverage for the resolveCategory function.

The test suite properly verifies all key scenarios for the resolveCategory function:

  1. Handling null categoryId
  2. Error behavior when category is not found
  3. Successful category resolution

The tests are well-structured with appropriate mocks and assertions.

src/drizzle/tables/actionItemCategories.ts (2)

12-12: Renaming looks good

The renaming from action categories to action item categories is consistent and well-implemented throughout the file, including imports, table definition, and relations.

Also applies to: 16-16, 68-71


76-77: Field references correctly updated

The field references in the relations definitions have been properly updated to use the new table name actionItemCategoriesTable.

Also applies to: 82-83, 88-89

src/graphql/types/Query/ActionCategorybyOrg.ts (4)

2-6: Import statement updates correctly reflect renamed types

The import statements have been properly updated to use the renamed types and schemas.


35-40: Good refactoring to use shared Zod schema

Replacing the inline schema with a shared validation schema improves code reusability and maintainability.


63-68: Table reference and argument access properly updated

The change from actionCategoriesTable to actionItemCategoriesTable is correct and consistent with the schema renaming. The organization ID is now properly accessed via parsedArgs.input.organizationId.


29-32: Code quality improvements

Added comments, improved error handling with specific error codes, and used null coalescing for the return value enhance code readability and robustness.

Also applies to: 56-57, 74-75, 94-94

src/graphql/types/ActionItem/categoryId.ts.ts (2)

6-43: Well-implemented resolver with appropriate error handling

The resolver function is well-structured with:

  1. Null check for the categoryId
  2. Database query using the correct table
  3. Comprehensive error handling with specific error code and logging

This approach correctly implements the GraphQL pattern of resolving related objects.


45-54: Good implementation of ActionItem type extension

The implementation properly extends the ActionItem type with a nullable category field that uses the resolver function. The field includes a descriptive comment that helps with API documentation.

src/graphql/types/ActionItem/actionItem.ts (1)

38-57: Well-implemented allottedHours field with robust type handling

The implementation thoroughly handles different input types and edge cases when parsing the allottedHours value, including string parsing, NaN checking, and proper null handling.

src/graphql/types/ActionItemCategory/actionItemCategory.ts (3)

53-58: Good improvement in error handling

The validation logic now properly uses safeParse and provides more detailed error information in case of failure.


59-67: Improved robustness with null checks

Good addition of null checks for the Drizzle client and table before attempting to query, preventing potential runtime errors.


69-71: Updated table reference correctly

The query now correctly references actionItemCategoriesTable in line with the schema changes throughout the codebase.

src/graphql/types/Mutation/createActionItem.ts (2)

32-47: Good improvement in argument validation

The switch to safeParseAsync with detailed error reporting is a significant improvement over the previous implementation. This provides better feedback to API consumers when arguments are invalid.


159-165: Improved error handling for empty result

Good addition of error logging and proper error response when the insert operation unexpectedly returns an empty array.

drizzle_migrations/20250422113209_common_la_nuit.sql (1)

43-43: Good indexing strategy

The unique index on name and organization_id ensures that category names are unique within each organization but can be reused across different organizations.

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 22, 2025
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: 8

♻️ Duplicate comments (1)
drizzle_migrations/20250418120528_remarkable_molecule_man.sql (1)

22-22: No default for is_completed
"is_completed" is NOT NULL but lacks DEFAULT false. Adding a default improves safety for ad‑hoc inserts and future migrations.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa3373a and 24804c3.

📒 Files selected for processing (3)
  • drizzle_migrations/20250406144036_curious_rattler.sql (3 hunks)
  • drizzle_migrations/20250418120528_remarkable_molecule_man.sql (1 hunks)
  • scripts/dbManagement/sample_data/action_items.json (165 hunks)
🔇 Additional comments (1)
scripts/dbManagement/sample_data/action_items.json (1)

5-11: Verify sample data matches the updated schema

In the first object, the "actorId" key has been correctly renamed to "assigneeId" (line 5) and a new "allottedHours": 5.5 field was inserted (line 11). This change pattern repeats for every action item entry. Please ensure:

  1. All occurrences of assigneeId in this JSON align with your GraphQL input types and resolver mappings.
  2. The new allottedHours field is properly handled in your migrations, ORM models, and GraphQL schema (nullable Float).

Can you confirm that the backend migrations and resolvers have been updated to use assigneeId and expose allottedHours as expected?

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 22, 2025
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: 5

♻️ Duplicate comments (9)
drizzle_migrations/20250406144036_curious_rattler.sql (3)

15-15: Snake_case naming enforced for assignee_id
The column "assignee_id" correctly uses snake_case, replacing the previous camelCase actorId/assigneeId as per the project's conventions.


443-443: Foreign key updated for assignee_id
The FK constraint "actions_assignee_id_users_id_fk" now references the snake_case column, aligning with other user‐referencing FKs in the schema.


557-557: Index created for assignee_id
The index "actions_assignee_id_index" has been added on the new snake_case column, maintaining consistency with existing index naming patterns.

drizzle_migrations/20250418120528_remarkable_molecule_man.sql (6)

12-38: Replace invalid SQL comment markers

The script uses --> statement-breakpoint which is not valid SQL. Standard SQL comments should use --. Please replace all occurrences:

---> statement-breakpoint
+-- statement-breakpoint

6-6: 🧹 Nitpick (assertive)

Add DEFAULT for is_disabled

Adding DEFAULT false to is_disabled ensures safe inserts and reduces boilerplate in future migrations.

-"is_disabled" boolean NOT NULL,
+"is_disabled" boolean NOT NULL DEFAULT false,

22-22: 🧹 Nitpick (assertive)

Add DEFAULT for is_completed

Set a default for the completion flag to avoid forcing explicit values on insert.

-"is_completed" boolean NOT NULL,
+"is_completed" boolean NOT NULL DEFAULT false,

1-11: ⚠️ Potential issue

Inconsistent table naming with code conventions

Your migration creates action_categories, but your ORM, GraphQL types, and application code use snake_case action_item_categories. Please rename the table and update all references to maintain consistency across the schema and resolvers.

-CREATE TABLE "action_categories" (
+CREATE TABLE "action_item_categories" (

13-28: ⚠️ Potential issue

Inconsistent table and column naming

Your migration defines "actions" and "assignee_id", but your GraphQL layer and code expect action_items and actor_id. Rename accordingly to avoid mapping errors.

-CREATE TABLE "actions" (
+CREATE TABLE "action_items" (
 ...
-"assignee_id" uuid,
+"actor_id" uuid,

39-49: ⚠️ Potential issue

Update indexes to use new table and column names

Ensure all index definitions reflect the renamed tables/columns. For example:

-CREATE INDEX "action_categories_created_at_index" ON "action_categories" USING btree ("created_at");
+CREATE INDEX "action_item_categories_created_at_index" ON "action_item_categories" USING btree ("created_at");

-CREATE INDEX "actions_assignee_id_index" ON "actions" USING btree ("assignee_id");
+CREATE INDEX "action_items_actor_id_index" ON "action_items" USING btree ("actor_id");
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 24804c3 and 280ed54.

📒 Files selected for processing (4)
  • drizzle_migrations/20250406144036_curious_rattler.sql (3 hunks)
  • drizzle_migrations/20250418120528_remarkable_molecule_man.sql (1 hunks)
  • drizzle_migrations/20250422113209_common_la_nuit.sql (1 hunks)
  • src/envConfigSchema.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/envConfigSchema.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (1)
drizzle_migrations/20250422113209_common_la_nuit.sql (1)

31-39: Verify TypeScript table constants and relationships

The foreign key constraints and cascading rules look correct. Please ensure that your Drizzle ORM table constants and GraphQL resolvers have been updated to reference the exact table names "action_categories" and "actions" (rather than any legacy constants like actionItemCategoriesTable or actionItemsTable) to avoid mismatches at runtime.

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 22, 2025
@NishantSinghhhhh
Copy link
Author

@meetulr sir I have too many migration files what should I do about them ??

Signed-off-by: NishantSinghhhhh <[email protected]>
@meetulr
Copy link
Contributor

meetulr commented Apr 22, 2025

Why do the number of lines keep increasing so dramatically?

Also, this and schema names, pascal case.

@NishantSinghhhhh
Copy link
Author

Why do the number of lines keep increasing so dramatically?

Also, this.

Sir number of snapshots are increasing and due to that only I beleive the number of lines are increasing

@meetulr
Copy link
Contributor

meetulr commented Apr 22, 2025

Should this be closed and raised again, after merging with the upstream?

@iamanishx
Copy link

iamanishx commented Apr 22, 2025

@NishantSinghhhhh you can drop the old migration files just keep the latest one

@NishantSinghhhhh
Copy link
Author

Should this be closed and raised again, after merging with the upstream?

Maybe yess as the number of commits are so much and the the drizzle migration files are also too much

@NishantSinghhhhh
Copy link
Author

@NishantSinghhhhh you can dropped the old migration files just keep the latest one

This will not work, if we delete any drizzle migration the server will crash

@NishantSinghhhhh
Copy link
Author

Sir I am closing this PR and raising a new one

@meetulr sir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants