Skip to content

added assignUserTag and removeUserTag mutations #3438

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

Open
wants to merge 5 commits into
base: develop-postgres
Choose a base branch
from

Conversation

gurramkarthiknetha
Copy link

@gurramkarthiknetha gurramkarthiknetha commented Apr 10, 2025

What kind of change does this PR introduce?

Feature: Added two new GraphQL mutations (assignUserTag and removeUserTag) to manage user tags from the frontend.

Issue Number:

Fixes # #3398

Snapshots/Videos:

N/A

If relevant, did you update the documentation?

No

Summary

This PR implements the ASSIGN_USER_TAG and REMOVE_USER_TAG GraphQL mutations in the backend. These mutations are required by the TagActions frontend component to assign or remove tags associated with users.

Each mutation takes a userId and a tagId as input, performs necessary validations (e.g., verifying user and tag existence), updates the database, and returns the updated tag information.

This solves the issue where the frontend TagActions modal would error due to the missing backend support.

Does this PR introduce a breaking change?

No

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

  • Ensured validations for existing user and tag before mutation
  • Tests cover success cases and relevant edge cases (e.g., non-existent user or tag)

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • New Features

    • Reorganized user operations by replacing legacy membership and blocking actions with enhanced tag management. Users can now assign, bulk assign, and remove tags seamlessly.
    • Introduced a new tag structure that streamlines interactions and feedback for tag-based actions.
  • Chores

    • Improved data validation and error handling across server operations for increased stability.
    • Updated system validations to ensure consistent email and tag assignment handling.

Copy link

coderabbitai bot commented Apr 10, 2025

Walkthrough

This pull request refactors the GraphQL schema by removing the legacy membership and blocking mutations and introducing new mutations and types for managing user tags. It adds mutations such as assignUserTag, assignToUserTags, removeFromUserTags, and assignToUserTag along with corresponding input and response types. Additionally, the database schema now enforces explicit UUID validations and changes the user email field type from text with a unique constraint to a constrained varchar. Enhanced error handling and Redis integration were also added to the server startup process.

Changes

File(s) Change Summary
schema.graphql
src/graphql/types/Mutation/(AddpeopleTag, assignToUserTag, removeFromUserTags, index.ts)
Updated GraphQL schema: Removed acceptMembershipRequest and blockUser mutations; added new tag management mutations and types (Tag, TagActionsInput, TagMutationResponse, etc.) with enhanced input validation and resolver logic.
src/drizzle/tables/(tagAssignments.ts, users.ts) Updated database schema: Specified explicit UUID schema for tag assignments; changed emailAddress in the users table from text("email_address").notNull().unique() to varchar("email_address", { length: 255 }).notNull().
src/index.ts Enhanced server initialization: Added robust error handling for uncaught exceptions, unhandled promise rejections, and integrated Redis setup with connection monitoring.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant G as GraphQL Resolver (assignUserTag)
    participant Auth as Authentication Module
    participant DB as Database
    C->>G: Call assignUserTag(input)
    G->>Auth: Verify authentication
    Auth-->>G: Return authentication status
    G->>G: Validate input (using Zod)
    G->>DB: Query for tag and user
    DB-->>G: Return tag and user records
    G->>DB: Insert tag assignment record
    DB-->>G: Confirmation of insertion
    G-->>C: Return tag object
Loading
sequenceDiagram
    participant C as Client
    participant G as GraphQL Resolver (removeFromUserTags)
    participant DB as Database
    C->>G: Call removeFromUserTags(input)
    G->>G: Validate input (currentTagId & selectedTagIds)
    G->>DB: Fetch tag by currentTagId
    DB-->>G: Return tag or null if not found
    G->>DB: Delete assignments for selectedTagIds
    DB-->>G: Return deletion confirmation
    G-->>C: Return processed tag or null on failure
Loading

Possibly related issues

Possibly related PRs

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • rishav-jha-mech
  • meetulr
✨ 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 plan to trigger planning for file edits and PR creation.
  • @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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6671885 and 695d4c7.

📒 Files selected for processing (9)
  • schema.graphql (4 hunks)
  • src/drizzle/tables/tagAssignments.ts (1 hunks)
  • src/drizzle/tables/users.ts (2 hunks)
  • src/graphql/schema.graphql (1 hunks)
  • src/graphql/types/Mutation/AddpeopleTag.ts (1 hunks)
  • src/graphql/types/Mutation/assignToUserTag.ts (1 hunks)
  • src/graphql/types/Mutation/index.ts (1 hunks)
  • src/graphql/types/Mutation/removeFromUserTags.ts (1 hunks)
  • src/index.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/graphql/types/Mutation/removeFromUserTags.ts (1)
Learnt from: meetulr
PR: PalisadoesFoundation/talawa-api#2616
File: src/resolvers/Mutation/removeFromUserTags.ts:136-152
Timestamp: 2025-04-10T12:10:06.081Z
Learning: Cycles cannot occur in the tag hierarchy in this project. Therefore, when traversing tags in functions like `removeFromUserTags` in `src/resolvers/Mutation/removeFromUserTags.ts`, infinite loops due to cyclic tag relationships are not a concern.
🧬 Code Graph Analysis (3)
src/graphql/types/Mutation/removeFromUserTags.ts (2)
src/graphql/builder.ts (1)
  • builder (10-20)
src/drizzle/tables/tagAssignments.ts (1)
  • tagAssignmentsTable (16-64)
src/index.ts (2)
test/server.ts (1)
  • server (12-27)
src/createServer.ts (1)
  • createServer (30-103)
src/graphql/types/Mutation/assignToUserTag.ts (4)
src/graphql/builder.ts (1)
  • builder (10-20)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/drizzle/tables/users.ts (1)
  • usersTable (60-217)
src/drizzle/tables/tagAssignments.ts (1)
  • tagAssignmentsTable (16-64)
🪛 GitHub Actions: Pull request workflow
src/graphql/types/Mutation/index.ts

[error] 80-82: Formatter would have printed the following content: import "./AddpeopleTag"; import "./assignToUserTag"; import "./removeFromUserTags";

src/graphql/types/Mutation/removeFromUserTags.ts

[error] 3-3: 'TalawaGraphQLError' is declared but its value is never read.


[error] 15-15: 'validateTagActions' is declared but its value is never read.


[error] 28-28: Type '"Tag"' is not assignable to type 'TypeParam<ExtendDefaultTypes<{ Context: GraphQLContext; Scalars: CustomScalars; }>>'.


[error] 36-36: Type '(_parent: {}, args: { input: { currentTagId: string; selectedTagIds: string[]; }; }, ctx: ExplicitGraphQLContext & ImplicitMercuriusContext) => Promise<...>' is not assignable to type 'Resolver<{}, { input: { currentTagId: string; selectedTagIds: string[]; }; }, ExplicitGraphQLContext & ImplicitMercuriusContext, any, unknown>'.


[error] 45-45: Property 'equals' does not exist on type 'PgColumn<{ name: "id"; tableName: "tags"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: true; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>'.


[error] 58-58: Property 'equals' does not exist on type 'PgColumn<{ name: "assignee_id"; tableName: "tag_assignments"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; ... 4 more ...; generated: undefined; }, {}, {}>'.

src/index.ts

[error] 37-37: No overload matches this call.


[error] 43-43: Parameter 'options' implicitly has an 'any' type.


[error] 72-72: 'err' is of type 'unknown'.


[error] 73-73: 'err' is of type 'unknown'.

src/drizzle/tables/tagAssignments.ts

[error] 96-103: Formatter would have printed the following content: export const tagAssignmentsTableInsertSchema = createInsertSchema(tagAssignmentsTable, { assigneeId: (schema) => schema.uuid(), tagId: (schema) => schema.uuid(), creatorId: (schema) => schema.uuid().optional(), });

src/graphql/types/Mutation/AddpeopleTag.ts

[error] 9-12: Formatter would have printed the following content: const AddUserTagInputSchema = z.object({ tagId: z.string(), userId: z.string(), });

src/graphql/types/Mutation/assignToUserTag.ts

[error] 2-2: 'tagsTable' is declared but its value is never read.


[error] 4-4: 'eq' is declared but its value is never read.


[error] 51-51: Parameter 'fields' implicitly has an 'any' type.


[error] 51-51: Parameter 'operators' implicitly has an 'any' type.


[error] 110-110: Type '"not_found"' is not assignable to type '"invalid_arguments" | "arguments_associated_resources_not_found" | "forbidden_action" | "forbidden_action_on_arguments_associated_resources" | "unauthenticated" | "unauthorized_action" | "unauthorized_action_on_arguments_associated_resources" | "unauthorized_arguments" | "unexpected" | "too_many_requests"'.


[error] 123-123: Parameter 'user' implicitly has an 'any' type.


[error] 127-127: Parameter 'tx' implicitly has an 'any' type.


[error] 190-190: Type '"Tag"' is not assignable to type 'TypeParam<ExtendDefaultTypes<{ Context: GraphQLContext; Scalars: CustomScalars; }>>'.

🪛 Biome (1.9.4)
src/graphql/types/Mutation/removeFromUserTags.ts

[error] 15-15: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

src/index.ts

[error] 43-49: This function expression can be turned into an arrow function.

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.

(lint/complexity/useArrowFunction)

src/graphql/types/Mutation/assignToUserTag.ts

[error] 26-26: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 28-28: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 65-65: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 65-65: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 103-103: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 103-103: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 119-119: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 119-119: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 144-144: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 144-144: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 180-180: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 180-180: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

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

1-6: LGTM! The Tag type definition is well-structured.

The Tag type includes essential fields for identification and organization relationships, which aligns with the requirements for user tag management.


8-14: Well-documented input type for tag operations.

The TagActionsInput type is properly documented with clear descriptions for each field. Using non-nullable fields ensures the required data is always provided.


16-21: LGTM! The mutation definition looks good.

The removeFromUserTags mutation is properly documented and requires the appropriate input type, maintaining consistency with the PR objectives.

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

126-159: Watch for possible collisions when creating placeholder users.

The code creates placeholder users in a transaction if they do not exist. If there's a real user with the same email in the future, collisions could arise. Confirm that this behavior is intentional or consider generating unique placeholder emails.

🧰 Tools
🪛 Biome (1.9.4)

[error] 144-144: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 144-144: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

🪛 GitHub Actions: Pull request workflow

[error] 127-127: Parameter 'tx' implicitly has an 'any' type.

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

9-12: Address formatting per pipeline failure.

The code formatter suggests a compact style for the schema definition. Please align with the recommended formatting to pass the pipeline check.

Below is the suggested formatting fix:

-const AddUserTagInputSchema = z.object({
-  tagId: z.string(),
-  userId: z.string(),
-});
+const AddUserTagInputSchema = z.object({ tagId: z.string(), userId: z.string() });
🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] 9-12: Formatter would have printed the following content: const AddUserTagInputSchema = z.object({ tagId: z.string(), userId: z.string(), });


173-194: Good validation for existing assignments.

The code effectively prevents duplicate assignments by checking existingAssignment. This helps prevent data anomalies. Nice job!

schema.graphql (1)

2411-2417: Functional synergy with the TS file.

AddUserTagInput matches the input schema from AddpeopleTag.ts. This consistency is good. Ensure references to assignUserTag in the resolvers reflect the correct type usage everywhere.

@gurramkarthiknetha
Copy link
Author

i am working on failing tests

@meetulr meetulr self-requested a review April 13, 2025 08:44
@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.

@gurramkarthiknetha
Copy link
Author

Apologies for the delay. I had exams recently, but I will address the failing tests as soon as possible.

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.

2 participants