Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update games serializer and add slug validation with default generation #575

Merged
merged 7 commits into from
Dec 9, 2024

Conversation

thatguyinabeanie
Copy link
Owner

@thatguyinabeanie thatguyinabeanie commented Dec 9, 2024

Enhance the games model by adding slug validation and default generation based on the name. Update the serializer used in the games controller and adjust related parameters in tournament creation. Additionally, include a migration to add the slug column to the games table and populate it with initial values.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced tournament creation and management through updated API endpoints and request structures.
    • Added error handling for tournament creation and organization retrieval processes.
    • Introduced new endpoints for match check-in and reset operations.
    • Added support for unique slugs in game records to improve identification.
    • Implemented stricter player capacity validation for tournaments.
  • Bug Fixes

    • Improved parameter handling for tournaments to allow broader input without requiring specific keys.
    • Updated ownership checks in organization policies to prevent potential nil errors.
  • Documentation

    • Updated OpenAPI specifications to reflect new request and response structures, enhancing API usability.
    • Revised request schemas for tournaments to improve clarity and completeness.
  • Chores

    • Introduced new migration for adding slug fields to relevant database tables, ensuring data integrity.
    • Enhanced seeding logic for a more robust setup of tournament data.
  • Tests

    • Expanded test coverage for the GamesController and OrganizationsController to include new scenarios and error cases.
    • Updated tests to reflect changes in request and response structures for tournament creation.

@thatguyinabeanie thatguyinabeanie enabled auto-merge (squash) December 9, 2024 04:13
Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

This pull request introduces several changes across multiple controllers, models, and migration files in the application. The GamesController now uses a different serializer for game objects, while the OrganizationsController modifies how tournament parameters are permitted. The TournamentsController enhances error handling in various methods, and the Game model adds validations and a callback for the slug attribute. Additionally, a new migration adds a slug column to the games and organizations tables, along with data seeding updates. The OpenAPI specification has also been refined, reflecting these changes.

Changes

File Change Summary
app/controllers/api/v1/games_controller.rb Updated serializer_klass from Serializers::Game to Serializers::GameDetails.
app/controllers/api/v1/organizations_controller.rb Modified tournaments_permitted_params to use params.permit instead of params.require(:tournament).permit, and removed :format from permitted parameters.
app/controllers/api/v1/tournaments_controller.rb Enhanced error handling in create and set_organization methods; adjusted set_tournaments to check for organization_id and current time.
app/models/game.rb Added validation for slug presence and uniqueness; introduced before_validation callback to set defaults for slug.
app/policies/organization_policy.rb Updated owner? method to use safe navigation operators for nil checks.
db/migrate/20241209035641_insert_values_into_games_and_format.rb Added slug column to games table, created unique index, and seeded data for games and formats.
db/schema.rb Updated schema to include slug column in games and organizations tables with unique indexes.
db/seeds.rb Changed game name to "Scarlet & Violet" with slug "sv"; enhanced tournament creation logic.
openapi/v1/openapi.yaml Modified tournament creation endpoint and added new match management endpoints; updated response codes and schemas.
spec/requests/api/v1/games_controller_spec.rb Updated tests to include slug in test_game creation and structured responses for various operations.
spec/requests/api/v1/organizations_controller_spec.rb Updated tournament creation tests to reflect changes in request body schema and response codes.
spec/swagger_helper.rb Updated TOURNAMENT_REQUEST and TOURNAMENT_POST_REQUEST schemas with new and removed properties for clarity.

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @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

codecov bot commented Dec 9, 2024

Codecov Report

Attention: Patch coverage is 93.33333% with 1 line in your changes missing coverage. Please review.

Project coverage is 93.77%. Comparing base (4e647df) to head (416fe58).
Report is 1 commits behind head on main.

✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
app/controllers/api/v1/tournaments_controller.rb 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #575      +/-   ##
==========================================
+ Coverage   93.70%   93.77%   +0.07%     
==========================================
  Files          72       72              
  Lines        1731     1736       +5     
  Branches      305      306       +1     
==========================================
+ Hits         1622     1628       +6     
+ Misses        109      108       -1     
Flag Coverage Δ
rspec 93.77% <93.33%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (8)
db/seeds.rb (4)

88-88: Hey there! Consider making the game data more configurable 🎮

While the current setup works, it might be better to move the game data to a configuration file or environment variables for easier maintenance.

Here's a suggestion:

- game = Game.find_or_create_by!(name: "Scarlet & Violet", slug: "sv")
+ GAME_CONFIG = {
+   name: ENV.fetch('GAME_NAME', 'Scarlet & Violet'),
+   slug: ENV.fetch('GAME_SLUG', 'sv')
+ }
+ game = Game.find_or_create_by!(**GAME_CONFIG)

Line range hint 38-57: Heads up! Let's add some time validation to the tournament creation 🕒

The tournament creation looks good with both Swiss rounds and single elimination bracket, but we might want to add some validation to ensure the end time is always after the start time.

Here's a suggested improvement:

def create_tournament(name:, organization:, format:, game:, start_at:, end_at:)
+ raise ArgumentError, "End time must be after start time" if end_at <= start_at

  Tournament.find_or_create_by!(name:, organization:, format:, game:) do |tournament|
    tournament.published = true
    tournament.start_at = start_at
    tournament.check_in_start_at = start_at - 1.hour
    tournament.end_at = end_at
    # ... rest of the method
  end
end

Line range hint 124-156: Nice job on the query optimization! 🚀 Just a few suggestions for the Pokémon data

The preloading of profiles is great for performance! The Pokémon data validation could be a bit more robust though.

Consider adding more comprehensive validation:

- raise "Invalid pokemon data" unless pokemon_data.all? { |p| p[:species].present? && p[:position].present? }
+ REQUIRED_POKEMON_FIELDS = %i[species position ability tera_type nature]
+ pokemon_data.each do |pokemon|
+   missing_fields = REQUIRED_POKEMON_FIELDS.reject { |field| pokemon[field].present? }
+   raise "Invalid pokemon data: missing #{missing_fields.join(', ')}" if missing_fields.any?
+   raise "Invalid position: #{pokemon[:position]}" unless (1..6).include?(pokemon[:position])
+ end

Line range hint 1-24: Let's document those environment variables! 📝

The code uses several environment variables like ADMIN_USERNAME, TEST_ORG_NAME, and potentially others. It would be super helpful to document these at the top of the file.

Add something like this at the top of the file:

# Required environment variables:
# - ADMIN_USERNAME: Username for the admin account (default: thatguyinabeanie)
# - TEST_ORG_NAME: Name of the test organization (default: The Rise of Fuecoco)
# - SKIP_SEEDS: Set to "true" to skip seeding (optional)
spec/requests/api/v1/organizations_controller_spec.rb (1)

328-335: Consider enhancing the validation test coverage.

While the empty tournament hash will trigger validation errors, it would be valuable to add more specific test cases that verify individual validation rules (e.g., required fields, format constraints, etc.).

 let(:tournament) { {
+  # Test cases for specific validation scenarios
+  name: "", # Invalid empty name
+  game_id: nil, # Missing required field
+  registration_end_at: Time.current - 1.day # Invalid date (past)
 }
 }
spec/swagger_helper.rb (1)

254-264: The schema properties look good, but let's add some constraints! 🎯

While the properties are well-defined, adding some validation constraints would make the API more robust:

  • player_cap should probably have a minimum value > 0
  • start_at should probably be after the current date
  • registration_start_at should be before registration_end_at
 player_cap: { type: :integer, nullable: true },
+player_cap: { 
+  type: :integer, 
+  nullable: true,
+  minimum: 1 
+},
app/models/game.rb (1)

8-8: Looking good! Just one thing to consider about the validation.

Hey! The validation looks solid, but we might want to add a format validation to ensure the slug follows a consistent pattern (like lowercase alphanumeric with hyphens).

Here's a suggestion:

-  validates :slug, presence: true, uniqueness: true
+  validates :slug, presence: true, uniqueness: true,
+    format: { with: /\A[a-z0-9-]+\z/, message: "only allows lowercase letters, numbers, and hyphens" }
spec/requests/api/v1/games_controller_spec.rb (1)

89-89: Hey there! Let's beef up the slug testing 🎮

While adding the slug is great, we could make the tests even more robust by:

  1. Verifying the slug in response bodies
  2. Adding test cases for invalid slugs
  3. Testing slug uniqueness constraints

Here's a suggested addition to strengthen the test coverage:

 let(:test_game) { create(:game, name: "Test Game", slug: "tg") }
+
+context "with invalid slug" do
+  let(:game) { { game: { name: "New Game", slug: "invalid slug" } } }
+
+  response(400, "bad request") do
+    let(:request_account) { create(:admin) }
+    include_context "with Request Specs - Clerk JWT + Vercel OIDC Token Verification"
+    schema "$ref" => "#/components/schemas/Error"
+    run_test!
+  end
+end
🛑 Comments failed to post (4)
app/models/game.rb (1)

12-16: 🛠️ Refactor suggestion

Heads up about the callback and slug generation! 🤔

A couple of things to think about:

  1. The callback only runs on create - what happens if someone changes the name later?
  2. We're using &. on name but not on slug - might want to be consistent here.

Here's a suggested improvement:

-  before_validation :set_defaults, on: :create
+  before_validation :set_defaults
 
   def set_defaults
-    self.slug = name&.parameterize if slug.blank? && name.present?
+    self.slug = name&.parameterize if slug&.blank? && name.present?
   end
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  before_validation :set_defaults

  def set_defaults
    self.slug = name&.parameterize if slug&.blank? && name.present?
  end
db/migrate/20241209035641_insert_values_into_games_and_format.rb (2)

9-9: ⚠️ Potential issue

Oops! Found a typo in the game name! 🎯

There's a small typo in "Brilliand Diamond" - should be "Brilliant Diamond"!

Here's the fix:

-    bdsp = Game.create(name: "Brilliand Diamond & Shining Pearl", slug: "bdsp")
+    bdsp = Game.create(name: "Brilliant Diamond & Shining Pearl", slug: "bdsp")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    bdsp = Game.create(name: "Brilliant Diamond & Shining Pearl", slug: "bdsp")

6-42: 🛠️ Refactor suggestion

Let's make this migration more robust! 💪

A few suggestions to make this migration safer:

  1. Consider using create! instead of create to fail fast if something goes wrong
  2. Wrap the data creation in a transaction
  3. Consider moving the seed data to db/seeds.rb instead

Here's how we could improve it:

   def change
     add_column :games, :slug, :string, null: false
     add_index :games, :slug, unique: true
 
+    reversible do |dir|
+      dir.up do
+        ActiveRecord::Base.transaction do
-          sv = Game.create(name: "Scarlet & Violet", slug: "sv")
+          sv = Game.create!(name: "Scarlet & Violet", slug: "sv")
           # ... rest of the creation code with create! ...
+        end
+      end
+    end
   end

Committable suggestion skipped: line range outside the PR's diff.

db/schema.rb (1)

85-87: 💡 Codebase verification

Standardization needed for slug handling across tables 🎯

Found inconsistent null constraints for slug columns across different tables:

  • games: null: false (required)
  • sluggables: null: false (required)
  • Two other tables (likely organizations and another): allows null values

This confirms the inconsistency in slug handling. Since slugs are typically used as URL-friendly identifiers, having some as required and others as optional could lead to inconsistent behavior in the application.

🔗 Analysis chain

Heads up about the slug constraints! 🎯

I noticed that games.slug is NOT NULL while organizations.slug allows null values. This inconsistency might cause confusion or issues down the line, especially if these fields serve similar purposes.

Let's check if other tables in the schema use slugs and how they handle null constraints:

Consider standardizing the approach to slug handling across tables. If slugs are meant to be used as identifiers or in URLs, they should probably all be non-null.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all columns named 'slug' and their null constraints
rg -A 1 't\.string\s+"slug"' db/schema.rb

Length of output: 345

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

🧹 Outside diff range and nitpick comments (2)
app/models/tournament.rb (2)

30-30: Looking good! Consider using the constant though! 👍

The validation change from greater_than: 0 to greater_than: 3 aligns perfectly with the minimum player requirements. However, to keep things DRY, we could use the MINIMUM_PLAYER_COUNT constant here.

Here's a small tweak to consider:

-  validates :player_cap, numericality: { only_integer: true, greater_than: 3 }, allow_nil: true
+  validates :player_cap, numericality: { only_integer: true, greater_than_or_equal_to: MINIMUM_PLAYER_COUNT }, allow_nil: true

120-122: Hey there! Let's be consistent with our self usage! 🎯

I see you're being explicit with self.start_at (which is great!), but we should apply this consistently to all instance variable references in the method.

Here's how we could make it more consistent:

-    self.name ||= "#{organization.name}'s Tournament ##{organization.tournaments.count + 1}" if organization.present?
+    self.name ||= "#{self.organization.name}'s Tournament ##{self.organization.tournaments.count + 1}" if self.organization.present?

     return if self.start_at.blank?

-    self.late_registration ||= true
+    self.late_registration ||= true

-    self.registration_start_at ||= start_at - 1.week
-    self.registration_end_at ||= (start_at if late_registration)
-    self.check_in_start_at ||= start_at - 1.hour
+    self.registration_start_at ||= self.start_at - 1.week
+    self.registration_end_at ||= (self.start_at if self.late_registration)
+    self.check_in_start_at ||= self.start_at - 1.hour
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5b732a5 and f79914f.

📒 Files selected for processing (2)
  • app/controllers/api/v1/organizations_controller.rb (2 hunks)
  • app/models/tournament.rb (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/controllers/api/v1/organizations_controller.rb

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 9, 2024
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: 0

🧹 Outside diff range and nitpick comments (1)
spec/models/tournament_spec.rb (1)

Line range hint 1-236: Hey! Mind if I suggest adding some slug-related tests? 🏷️

I noticed this PR is all about adding slug validation and generation, but I don't see any tests covering that functionality yet. Would be super helpful to add some test cases to make sure those slugs are working as expected!

Here are some scenarios we might want to cover:

  • Generating a default slug from the tournament name
  • Handling duplicate slugs
  • Validating slug format

Want me to help draft those test cases? Just let me know! 😊

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f79914f and 3dd8782.

📒 Files selected for processing (1)
  • spec/models/tournament_spec.rb (1 hunks)
🔇 Additional comments (1)
spec/models/tournament_spec.rb (1)

22-22: Hey there! The player cap validation looks good! 🎮

Nice update to ensure tournaments have enough players to be interesting! Setting the minimum to 4 players makes perfect sense - after all, what's a tournament with just 2-3 players, right? 😄 The validation still allows nil values which is great for flexibility.

Let's double-check if this matches the model validation:

✅ Verification successful

Perfect match! The validation is spot on! 🎯

The spec perfectly mirrors the model validation - both require player_cap to be greater than 3 and allow nil values. Everything's aligned just the way it should be! 👍

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the player_cap validation in the Tournament model
rg -A 2 "validates.*player_cap" app/models/tournament.rb

Length of output: 216

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 9, 2024
Copy link

sonarcloud bot commented Dec 9, 2024

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

🧹 Outside diff range and nitpick comments (2)
cspell.config.yaml (2)

Line range hint 2-6: Hey there! Spotted a duplicate entry in ignorePaths 👀

db/schema.rb appears twice in the ignore paths list. We should keep things tidy and remove one of them!

 ignorePaths:
   - db/schema.rb
   - Gemfile
   - Gemfile.lock
   - db/migrate
-  - db/schema.rb

Line range hint 16-58: Quick suggestion to make this file more maintainable! 🎯

The words list is growing quite a bit! To make it easier to maintain and scan through, consider:

  1. Alphabetically sorting the words
  2. Using comments to group related words (e.g., Pokemon names, technical terms)

Here's how it could look:

 words:
+  # Technical terms
   - autobuild
   - bytesize
-  - fcontext
-  - fdescribe
-  - filesize
-  - ILIKE
+  - deepcode
+  - fcontext
+  - fdescribe
+  - filesize
+  - ILIKE
+  - jacoco
+  - logpanel
   
+  # Pokemon related
+  - Butterfree
+  - Clefable
+  - Fuecoco
+  - Sandslash
+  - Staryu
+  - Victreebel
+  - tera
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3dd8782 and 416fe58.

📒 Files selected for processing (1)
  • cspell.config.yaml (1 hunks)

@thatguyinabeanie thatguyinabeanie merged commit 9d367ac into main Dec 9, 2024
17 of 18 checks passed
@thatguyinabeanie thatguyinabeanie deleted the update-games-catalog branch December 9, 2024 20:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant