CSC/ECE 517 Spring 2023 - E2330. Reimplement Invitation Controller

From Expertiza_Wiki
Jump to navigation Jump to search

Project Overview

Expertiza Background

Expertiza is an online platform designed to facilitate peer review and submission of various types of academic work, including articles, codes, and websites. The application allows instructors to add assignments, grade them, and assign students to teams based on their topic preferences. The platform also enables students to provide feedback on each other's work through peer reviews, which can be helpful in improving the quality of their projects. Expertiza is backed by the National Science Foundation.

Problem Statement

The Invitation model and InvitationsController are responsible for managing invitations between users in a team-based assignment system. The system allows a student to invite another student to their team by creating a new Invitation record, which is associated with the inviting and invited students and the assignment they are working on. The invited user can accept, decline, or cancel the invitation, which updates the corresponding Invitation record and may trigger actions such as adding or removing users from teams. The InvitationsController includes methods for creating, accepting, declining, and canceling invitations, as well as checking the status of the user and team before sending or accepting invitations. The system also sends email notifications to invited users when a new invitation is sent. Overall, the Invitation model and InvitationsController are crucial for managing team membership and collaboration in a team-based assignment system. Instructor’s note: There is already a project to merge this controller with the join_team_requests_controller. You should start with the code they have written.

Objectives

1. Write RESTful endpoints of create, show, delete to invitations and approving new invitations, listing pending invitations, creating new invitations, and notifying students about new team formation invite.

2. Develop and implement methods in the InvitationsController that enable the following functionality:Create invitations, Accept invitations, Decline invitations, Cancel invitations, and Check user and team status before sending or accepting invitations.

3. To implement a user-invitation system that allows invited users to accept, decline, or cancel invitations, which will update the corresponding Invitation record and trigger actions such as adding or removing users from teams.

4. Implement an email notification system in the user-invitation system, which sends email notifications to invited users when a new invitation is sent.

5. Return proper status codes and proper validation for RESTful endpoints.

6. Write models and controllers such that they use modern approaches to writing Ruby code, including utilizing language features and adhering to best practices for object-oriented design.

7. Write proper Rspec tests for all APIs, models, controllers.

Development Strategy

We have tried to follow a Test Driven Development approach to implement both the Invitation model and the Invitation Controller. Firstly a failing test case was written and then the code was added such that the test which was failing will pass now.

Also, we have tried to follow the rails philosophy of "Fat models" We have tried to move as much business logic from the controller to the model as possible. This will also help keep the controller code clean and encourage code reusability.

Project Design and Implementation

Use Case Diagram


Class Diagram

Functionality

In this project, we aim to add the following functions:

1. Enable users to create a new team invitation.

2. Enable users to Accept or Reject invitations.

3. Enable users to Retract invitations.

4. Enable users to send email notifications to invited users.

5. Ensure that data is validated properly in all the above APIs.

6. Test cases for all the above.

Screen Shots

1. Send an invite

File:Dshah6 send invite 3.png

2. Accept an invite

File:Dshah6 accept 3.png

3. Reject invite

4. Retract invite

5. We retracted invitation of angel and malka and added ofelia

Project Design

Invitation Validators

Invitation model has several custom validations. We have extracted out these validations into a separate class InvitationValidator to keep the Invitation model class simple.

filename: invitation_validator.rb
GitHub file Link to invitation_validator.rb

# app/validators/invitation_validator.rb
class InvitationValidator < ActiveModel::Validator
  ACCEPT_STATUS = 'A'.freeze
  REJECT_STATUS = 'R'.freeze
  WAITING_STATUS = 'W'.freeze

  DUPLICATE_INVITATION_ERROR_MSG = 'You cannot have duplicate invitations'.freeze
  TO_FROM_SAME_ERROR_MSG = 'to and from users should be different'.freeze
  REPLY_STATUS_ERROR_MSG = 'must be present and have a maximum length of 1'.freeze
  REPLY_STATUS_INCLUSION_ERROR_MSG = "must be one of #{[ACCEPT_STATUS, REJECT_STATUS, WAITING_STATUS].to_sentence}".freeze

  def validate(record)
    validate_reply_status(record)
    validate_reply_status_inclusion(record)
    validate_duplicate_invitation(record)
    validate_to_from_different(record)
  end

  private

  def validate_reply_status(record)
    unless record.reply_status.present? && record.reply_status.length <= 1
      record.errors.add(:reply_status, REPLY_STATUS_ERROR_MSG)
    end
  end

  def validate_reply_status_inclusion(record)
    unless [ACCEPT_STATUS, REJECT_STATUS, WAITING_STATUS].include?(record.reply_status)
      record.errors.add(:reply_status, REPLY_STATUS_INCLUSION_ERROR_MSG)
    end
  end

  def validate_duplicate_invitation(record)
    conditions = {
      to_id: record.to_id,
      from_id: record.from_id,
      assignment_id: record.assignment_id,
      reply_status: record.reply_status
    }
    if Invitation.where(conditions).exists?
      record.errors[:base] << DUPLICATE_INVITATION_ERROR_MSG
    end
  end

  def validate_to_from_different(record)
    if record.from_id == record.to_id
      record.errors.add(:from_id, TO_FROM_SAME_ERROR_MSG)
    end
  end
end

Model

The file invitation.rb defines the Invitation model which is a subclass of ApplicationRecord. The Invitation model has three foreign keys. to_user represents the user to whom the inviations is sent. from_user represents the user who is creating the invitation. assignment represents which assignment the invitation belongs to. reply_status represents whether the invitation is accepted, rejected or waiting. The default reply_status is waiting 'W'. There are also multiple validations defined for the various fields in this model. One of the important validation is to_from_cant_be_same validation, which prevents users from creating invitations to themselves. Moreover there are multiple helper methods defined for Invitations. These methods help keep the controller code short and clean. We are following the rails philosophy of "Fat Models". For the scope of this project the helper methods are kept simple, however once the project advances these helper methods need to be updated.


filename: invitation.rb
GitHub file Link to invitation.rb

class Invitation < ApplicationRecord
  after_initialize :set_defaults

  belongs_to :to_user, class_name: 'User', foreign_key: 'to_id', inverse_of: false
  belongs_to :from_user, class_name: 'User', foreign_key: 'from_id', inverse_of: false
  belongs_to :assignment, class_name: 'Assignment', foreign_key: 'assignment_id'

  validates_with InvitationValidator

  # Return a new invitation
  # params = :assignment_id, :to_id, :from_id, :reply_status
  def self.invitation_factory(params)
    Invitation.new(params)
  end

  # check if the user is invited
  def self.invited?(from_id, to_id, assignment_id)
    conditions = {
      to_id:,
      from_id:,
      assignment_id:,
      reply_status: InvitationValidator::WAITING_STATUS
    }
    @invitations_exist = Invitation.where(conditions).exists?
  end

  # send invite email
  def send_invite_email
    InvitationSentMailer.with(invitation: self)
                        .send_invitation_email
                        .deliver_later
  end

  # After a users accepts an invite, the teams_users table needs to be updated.
  # NOTE: Depends on TeamUser model, which is not implemented yet.
  def update_users_topic_after_invite_accept(_inviter_user_id, _invited_user_id, _assignment_id); end

  # This method handles all that needs to be done upon a user accepting an invitation.
  # Expected functionality: First the users previous team is deleted if they were the only member of that
  # team and topics that the old team signed up for will be deleted.
  # Then invites the user that accepted the invite sent will be removed.
  # Lastly the users team entry will be added to the TeamsUser table and their assigned topic is updated.
  # NOTE: For now this method simply updates the invitation's reply_status.
  def accept_invitation(_logged_in_user)
    update(reply_status: InvitationValidator::ACCEPT_STATUS)
  end

  # This method handles all that needs to be done upon an user declining an invitation.
  def decline_invitation(_logged_in_user)
    update(reply_status: InvitationValidator::REJECT_STATUS)
  end

  # This method handles all that need to be done upon an invitation retraction.
  def retract_invitation(_logged_in_user)
    destroy
  end

  # This will override the default as_json method in the ApplicationRecord class and specify
  def as_json(options = {})
    super(options.merge({
                          only: %i[id reply_status created_at updated_at],
                          include: {
                            assignment: { only: %i[id name] },
                            from_user: { only: %i[id name fullname email] },
                            to_user: { only: %i[id name fullname email] }
                          }
                        })).tap do |hash|
    end
  end

  def set_defaults
    self.reply_status ||= InvitationValidator::WAITING_STATUS
  end
end

Helper Methods in Invitation model.

to_from_cant_be_same:

Validate if the to_id and from_id are same i.e a users cannot send invitations to themselves.

self.invitation_factory(params):

This helper method will help in creating new Invitation with the given parameters. Custom parameters can be passed to create specific Invitation.

self.invited?(from_id, to_id, assignment_id):

Check if the user is invited given the from_id, to_id, and assignment_id. This is a class method to make it more generic and can be used by other classes.

send_invite_email:

This method uses the InvitaionSentMailer to send invitation emails to the invited user.

update_users_topic_after_invite_accept(inviter_user_id, invited_user_id, assignment_id) [Future work]:

After a users accepts an invite, the teams_users table needs to be updated. NOTE: Depends on TeamUser model, which is not implemented yet.

accept_invitation:

This method handles all that needs to be done upon a user accepting an invitation.

decline_invitation:

This method handles all that needs to be done upon an user decline an invitation.

retract_invitation:

This method handles all that need to be done upon an invitation retraction.

as_json:

This will override the default as_json method in the ApplicationRecord class and specify

set_defaults:

This will be used to set default parameters when creating new Invitation.

Changes in models/user.rb
GitHub Link to user.rb file
A user can have many invitations therefore we added a has_many relationship in the user model. On the other hand in the invitation model we added belongs_to relationship with the user model.

# added the following relations in the user.rb file.
has_many :invitations

Changes in models/assignment.rb

GitHub Link to assignment.rb file
An assignment can have many invitations therefore we added a has_many relationship in the assignment model. On the other hand in the invitation model we added belongs_to relationship with the assignment model.

# added the following relations in the assignment.rb file.
class Assignment < ApplicationRecord
 	has_many :invitations
end

Schema
GitHub Link to scheme.rb file
The invitation schema has three foreign keys. The foreign keys are "assignment_id", "from_id", "to_id". from_id and to_id are foreign keys to user model.

  create_table "invitations", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
    t.integer "assignment_id"
    t.integer "from_id"
    t.integer "to_id"
    t.string "reply_status", limit: 1
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["assignment_id"], name: "fk_invitation_assignments"
    t.index ["from_id"], name: "fk_invitationfrom_users"
    t.index ["to_id"], name: "fk_invitationto_users"
  end

Controllers

We create a new controller at app/controllers/invitation_controller.rb with following methods: [Implementation of the invitation controller[1]]

REST Route methods

create:

This will create a new invitation record.

index:

This will give a list of all the invitations

show:

This will be used to show a particular invitation with given invitation_id.

update:

This will be used to update the status of the current invitation. Either accepted or rejected

destroy:

This will be used to delete the invitation that is already sent to another participant using particular invite_id.

invitations_for_user_assignment:

This will be used to get all the invitations for a particular assignment for a particular student.

Helper methods

check_participant_before_invitation [Future work]:

This method will check if the invited user is a participant in the assignment.

End point description

create

Description: This route will create a new invitation record with default reply_status: w. w stands for waiting.
REST VERB: POST
Path: /invitations/

Response: 

Success:
Status code: 200

```
{
 {
  "id": 11,
  "reply_status": "W",
  "created_at": "2023-04-20T21:33:29.580Z",
  "updated_at": "2023-04-20T21:33:29.580Z",
  "assignment": {
    "id": 2,
    "name": "oodd program3"
  },
  "from_user": {
    "id": 2,
    "name": "jhon",
    "fullname": "jhon carmen",
    "email": "example1@gmail.com"
  },
  "to_user": {
    "id": 1,
    "name": "katy",
    "fullname": "katy shah",
    "email": "example2@gmail.com"
  }
}
 
```

Failure:
Status code: 422

```
{
  error: @invitation.errors 
}

```

index

Description: Get a list of all the invitations in the database.
REST VERB: GET
Path: /invitations/
Request: NA

Success
Status Code: 200
```
[
  {
    "id": 1,
    "reply_status": "A",
    "created_at": "2023-04-13T17:22:09.805Z",
    "updated_at": "2023-04-19T00:06:33.718Z",
    "assignment": {
      "id": 1,
      "name": "program4"
    },
    "from_user": {
      "id": 2,
      "name": "katy",
      "fullname": "katy kimson",
      "email": "kt@gmail.com"
    },
    "to_user": {
      "id": 1,
      "name": "john",
      "fullname": "john fella",
      "email": "john@gmail.com"
    }
  },
  {
    "id": 2,
    "reply_status": "W",
    "created_at": "2023-04-18T15:52:44.543Z",
    "updated_at": "2023-04-18T15:52:44.543Z",
    "assignment": {
      "id": 1,
      "name": "program4"
    },
    "from_user": {
      "id": 1,
      "name": "john",
      "fullname": "john fella",
      "email": "john@gmail.com"
    },
    "to_user": {
      "id": 3,
      "name": "rebecca",
      "fullname": "rebecca fiat",
      "email": "reb@gmail.com"
    }
  }
]

```

show

Description: Get a particular invite with the invite_id.
REST VERB: GET
Path: /invitations/<invite_id>
Request: NA
Response: 

success
status code: 200
```
{
    "id": 1,
    "reply_status": "A",
    "created_at": "2023-04-13T17:22:09.805Z",
    "updated_at": "2023-04-19T00:06:33.718Z",
    "assignment": {
        "id": 1,
        "name": "program4"
    },
    "from_user": {
        "id": 2,
        "name": "katy",
        "fullname": "katy kimson",
        "email": "kt@gmail.com"
    },
    "to_user": {
        "id": 1,
        "name": "john",
        "fullname": "john fella",
        "email": "john@gmail.com"
    }
}

```

Error
Status code: 404

```
{
    "error": "Couldn't find Invitation with 'id'=1021321"
}
```

update

Description: This route will modify the status of the invitation to be accepted or declined
REST VERB: PATCH
Path: /invitations/<invite_id>/
Request: 
```
{
"reply_status": ["A"/"R"],
}

```
Response: 

Success
Status Code: 200

```
{
    "id": 1,
    "reply_status": "A",
    "created_at": "2023-04-13T17:22:09.805Z",
    "updated_at": "2023-04-19T00:06:33.718Z",
    "assignment": {
        "id": 1,
        "name": "program4"
    },
    "from_user": {
        "id": 2,
        "name": "katy",
        "fullname": "katy kimson",
        "email": "kt@gmail.com"
    },
    "to_user": {
        "id": 1,
        "name": "john",
        "fullname": "john fella",
        "email": "john@gmail.com"
    }
}
```

Error
Status Code: 404/422

```
{
  "error": @invitation.errors
}
```

destroy

Description: Delete the invitation
REST VERB: DELETE
Path: /invitations/<invite_id>
Request: NA
Response: 

Success
Status code: 204 :no_content
Response: NA

Error
Status Code: 404
Response
```

{
  "error": @invitation.errors
}

```

invitations_for_user_assignment

Description: Get the invitations for the user with id: user_id for the given assignment with id: assignment_id.
REST VERB: GET
Path: /invitations/<user_id>/<assingment_id>
Request: NA
Response: 

Success
Status Code: 200 :ok

```
[
    {
        "id": 1,
        "reply_status": "A",
        "created_at": "2023-04-13T17:22:09.805Z",
        "updated_at": "2023-04-19T00:06:33.718Z",
        "assignment": {
            "id": 1,
            "name": "program4"
        },
        "from_user": {
            "id": 2,
            "name": "katy",
            "fullname": "katy kimson",
            "email": "kt@gmail.com"
        },
        "to_user": {
            "id": 1,
            "name": "john",
            "fullname": "john fella",
            "email": "john@gmail.com"
        }
    },
    {
        "id": 2,
        "reply_status": "W",
        "created_at": "2023-04-18T15:52:44.543Z",
        "updated_at": "2023-04-18T15:52:44.543Z",
        "assignment": {
            "id": 1,
            "name": "program4"
        },
        "from_user": {
            "id": 1,
            "name": "john",
            "fullname": "john fella",
            "email": "john@gmail.com"
        },
        "to_user": {
            "id": 1,
            "name": "john",
            "fullname": "john fella",
            "email": "john@gmail.com"
        }
    }
]

```

Error
Status Code: 404 :not_found

```
{
  "error": @invitations.errors
}

```

End point summary

Sr No Method Endpoint Request Body Description
1 create POST
/invitations
{
"assignment_id": INT,
"from_id": INT,
"to_id": INT,
"reply_status": CHAR
}
Create a new invitation record with default reply_status: w, w stands for waiting.
2 index GET
/invitations
Get a list of all the invitations.
3 show GET
/invitations/<assignment_id>
Get a particular invite with the invite_id.
4 update PATCH /invitations/<invite_id> {
"reply_status":["A"/"R"]
}
Modify the status of the invitation to be accepted or declined.
5 destroy DELETE
/invitations/<invite_id>
Delete the invitation.
6 invitations_for_user_assignment GET
/invitations/user/<user_id>/assignment/<assignment_id>
Get the invitations for the user with id: user_id for the given assignment with id: assignment_id

Testing Plan

We utilized RSpec as the testing framework for our system. We have used factoryBot along with Faker to create model objects for testing. The development process has followed Test Driven Development. The tests for the model and the controller are written in a comprehensive way.

Controller Tests

To run the controller tests:

1. git clone

2. cd reimplementation-back-end/

3. bundle install

4. bundle exec rspec spec/requests/api/v1/invitation_controller_spec.rb

File: invitation_controller_spec.rb

Sr No Test Description
1 Test to list all Invitations This test verifies if the system can successfully retrieve a list of all invitations available in the system.
2 Test to create an invitation with valid parameters This test verifies if the system can successfully create an invitation with valid parameters such as 'to' user, 'from' user, assignment, and reply status.
3 Test to create an invitation with invalid 'to' user parameters' This test verifies if the system can handle and reject an invitation creation request with invalid 'to' user parameters.
4 Test to create an invitation with invalid 'from' user parameters This test verifies if the system can handle and reject an invitation creation request with invalid 'from' user parameters.
5 Test to create an invitation with invalid assignment parameters This test verifies if the system can handle and reject an invitation creation request with invalid assignment parameters.
6 Test to create an invitation with invalid reply_status parameter This test verifies if the system can handle and reject an invitation creation request with an invalid reply_status parameter.
7 Test to create an invitation with same to user and from user parameters' This test verifies if the system can handle and reject an invitation creation request with the same 'to' and 'from' user parameters.
8 Test to show invitation with valid invitation id This test verifies if the system can successfully retrieve an invitation with a valid invitation id.
9 Test to show invitation with invalid invitation id This test verifies if the system can handle and reject a request to retrieve an invitation with an invalid invitation id.
10 Test to accept invite successfully This test verifies if the system can successfully update an invitation's reply status to 'accepted.'
11 Test to reject invite successfully This test verifies if the system can successfully update an invitation's reply status to 'rejected.'
12 Test to update invitation with invalid reply_status This test verifies if the system can handle and reject a request to update an invitation with an invalid reply_status parameter.
13 Test to update status with invalid invitation_id This test verifies if the system can handle and reject a request to update the status of an invitation with an invalid invitation id.
14 Test to delete invitation with valid invite id This test verifies if the system can successfully delete an invitation with a valid invitation id.
15 Test to delete invitation with invalid invite id his test verifies if the system can handle and reject a request to delete an invitation with an invalid invitation id.
16 Test to show all invitations for the user for an assignment This test verifies if the system can successfully retrieve all invitations for a specific user for a specific assignment.
17 Test to show invitation with invalid user and assignment This test verifies if the system can handle and reject a request to retrieve an invitation with an invalid user and assignment.
18 Test to Show invitation with user and invalid assignment The function of the 'Test to show invitation with valid user and invalid assignment' test case is to verify that the API handles the scenario of attempting to retrieve an invitation with an invalid assignment ID but with a valid user ID, and returns an appropriate response.
19 Test to show invitation with invalid user and invalid assignment The function of the 'Test to show invitation with invalid user and invalid assignment' test case is to verify that the API handles the scenario of attempting to retrieve an invitation with invalid user ID and invalid assignment ID, and returns an appropriate response.

Rspec tests screenshot.

Model Tests

To run the model tests:

1. git clone

2. cd reimplementation-back-end/

3. bundle install

4. bundle exec rspec spec/models/invitation_spec.rb


File: invitation_spec.rb


Sr No Test Test Description
1 Test to create an invitation with valid parameters. This test verifies if the system can successfully create an invitation with valid parameters such as 'to' user, 'from' user, assignment, and reply status.
2 Test to create an invitation with the same "to" and "from" user. This test verifies if the system can handle and reject an invitation creation request with the same 'to' and 'from' user parameters.
3 Test to create an invitation with the invalid "to" user parameter This test verifies if the system can handle and reject an invitation creation request with an invalid 'to' user parameter.
4 Test to create an invitation with the invalid "from" user parameter This test verifies if the system can handle and reject an invitation creation request with an invalid 'from' user parameter.
5 Test to create an invitation with a invalid assignment argument. This test verifies if the system can handle and reject an invitation creation request with an invalid assignment parameter.
6 Test to create an invitation with an invalid reply_status argument. This test verifies if the system can handle and reject an invitation creation request with an invalid reply_status parameter.
7 Test to check is_invited? is a true case. This test verifies if the system can correctly identify if a user has been invited to an assignment.
8 Test to check is_invited? is a false case. This test verifies if the system can correctly identify if a user has not been invited to an assignment.
9 Test to check if the default reply_status for a new invitation is WAITING('W'). This test verifies if the system can correctly set the default reply status to 'waiting' for a new invitation.
10 Test to check if invitation_factory returns new invitation. This test verifies if the system can correctly create a new invitation using the invitation_factory method.
11 Test to check if invitation email is sent properly. This test verifies if the system can successfully send an email invitation to the 'to' user.
12 Test to check if accept_invitation changes reply_status to 'A'. This test verifies if the system can successfully update an invitation's reply status to 'accepted' using the accept_invitation method.
13 Test to check if decline_invitation changes reply_status to 'R'. This test verifies if the system can successfully update an invitation's reply status to 'rejected' using the decline_invitation method.
14 Test to check if retract_invitation destroys the invitation. This test verifies if the system can successfully delete an invitation using the retract_invitation method.
15 Test to check if as_json formats invitation as required. This test verifies if the 'as_json' method can correctly format an invitation as JSON with the required fields such as 'to_user', 'from_user', 'assignment', 'reply_status', and 'id'. The test case creates an invitation with valid parameters and expects the 'as_json' method to include the required fields.


Rspec tests screenshot.


Test Coverage Report for Invitation model.
Our tests covers 100% of the lines in the Invitation model.

Swagger UI Screenshot

Swagger is used to provide an easy to use API documentation for the users of the API. It also provides an easy to use interface to interact with the API in the browser itself. You can use the swagger page to test out our API by clicking on the "Try it out" button next to each route.

path: /api-docs/

Files modified/created

Future Work

Implement methods in invitation_controller.rb and invitation.rb. Some of the methods were not implemented due to dependency on other models which are not implemented yet. The dependency models need to be implemented first and then these methods can be implemented. We have left out the placeholder in the source code for such methods and a small explaination of what is expected from the future implementation of the method.

Authentication system is required for the working of invitation feature. Before performing any action related to invitation, authorization of the request must be done to make sure the user is able to perform the action requested.


Future work in invitation_controller.rb
check_participant_before_invitation

This method will check if the invited user is a participant in the assignment.

Future work in invitation.rb
update_users_topic_after_invite_accept

After a users accepts an invite, the teams_users table needs to be updated.

accept_invitation

This method handles all that needs to be done upon a user accepting an invitation. Expected functionality: First the users previous team is deleted if they were the only member of that team and topics that the old team signed up for will be deleted. Then invites the user that accepted the invite sent will be removed. Lastly the users team entry will be added to the TeamsUser table and their assigned topic is updated.


References

Team Members

  • Saigirishwar Rohit Geddam [sgeddam2]
  • Keerthana Telaprolu [ktelapr]
  • Dhrumil Shah [dshah6]

Mentor

Ankur Mundra [amundra]