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

Fix issue #305: Kage can delete Anbu before the 24 hour lock out is up #306

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

TheNinja-RPG
Copy link
Collaborator

@TheNinja-RPG TheNinja-RPG commented Jan 22, 2025

This pull request fixes #305.

The issue has been successfully resolved based on the changes made. The core problem was that Kages could delete ANBU squads immediately without waiting for the required 24-hour period. The fix directly addresses this by:

  1. Adding a new constant ANBU_DELAY_SECS that defines exactly 24 hours in seconds (24 * 3600)
  2. Adding a validation check in the disbandSquad function that compares the squad's creation time against the required delay period using secondsFromDate(ANBU_DELAY_SECS, squad.createdAt)
  3. Returning an error message "Must wait 24 hours after squad creation" if the delay period hasn't elapsed

The implementation uses proper time comparison logic and integrates with existing game systems. The check is performed before any deletion actions can occur, which means it will effectively prevent premature ANBU squad deletion. The error message clearly communicates the restriction to users.

This matches the expected behavior described in the issue where "Kage needs to wait 24 hours before Anbus are deleted" and prevents the reported bug where "Kage can delete Anbu before the 24 hour lock out is up."

Automatic fix generated by OpenHands 🙌

Summary by CodeRabbit

  • New Features

    • Added a 24-hour delay restriction for disbanding ANBU squads.
    • Introduced a time-based constraint to prevent immediate squad disbandment.
  • Bug Fixes

    • Implemented a guard clause to enforce squad creation time requirements.

Copy link

vercel bot commented Jan 22, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
tnr ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 22, 2025 9:24pm

Copy link

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request introduces a new constant ANBU_DELAY_SECS set to 24 hours (86,400 seconds) and modifies the ANBU squad disbanding logic in the application. A new time-based restriction has been added to prevent immediate disbandment of ANBU squads, requiring a 24-hour waiting period before a Kage can disband a squad.

Changes

File Change Summary
app/drizzle/constants.ts Added ANBU_DELAY_SECS constant set to 24 hours in seconds
app/src/server/api/routers/anbu.ts Modified disbandSquad mutation to include a 24-hour delay check before allowing squad disbandment; added new utility function secondsFromDate

Assessment against linked issues

Objective Addressed Explanation
Prevent Kage from deleting Anbu before 24 hours [#305]

Possibly related PRs

  • Fix issue #270: Genins/Students Can be robed  #272: The changes in this PR involve adding a new validation check in the robPlayer procedure, which is related to the overall functionality of player interactions, similar to how ANBU_DELAY_SECS is used in the disbandSquad mutation to enforce time-based constraints. Both PRs deal with game mechanics that involve conditions for player actions.

Suggested reviewers

  • theeneon
  • MathiasGruber

Poem

In the realm of shinobi's might,
A rabbit's code brings wisdom's light
Twenty-four hours, a sacred wait
Before an ANBU meets its fate
Time's guardian, standing tall and bright! 🐰🕰️

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

📦 Next.js Bundle Analysis for tnr

This analysis was generated by the Next.js Bundle Analysis action. 🤖

This PR introduced no changes to the JavaScript bundle! 🙌

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73fe7ca and 6350611.

📒 Files selected for processing (2)
  • app/drizzle/constants.ts (1 hunks)
  • app/src/server/api/routers/anbu.ts (3 hunks)
🔇 Additional comments (1)
app/drizzle/constants.ts (1)

445-445: LGTM! The constant is well-defined.

The ANBU_DELAY_SECS constant is correctly defined with a clear calculation of 24 hours in seconds, properly grouped with other ANBU-related constants.

Comment on lines 250 to 252
if (secondsFromDate(ANBU_DELAY_SECS, squad.createdAt) > new Date()) {
return errorResponse("Must wait 24 hours after squad creation");
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the time comparison logic in the disbandment check.

The current time comparison logic is reversed. When secondsFromDate(ANBU_DELAY_SECS, squad.createdAt) returns a future date and it's greater than the current date, it means the waiting period hasn't elapsed yet. The condition should be:

-if (secondsFromDate(ANBU_DELAY_SECS, squad.createdAt) > new Date()) {
+if (new Date() < secondsFromDate(ANBU_DELAY_SECS, squad.createdAt)) {

Also, consider enhancing the error message to show the remaining time:

-  return errorResponse("Must wait 24 hours after squad creation");
+  const remainingTime = Math.ceil((secondsFromDate(ANBU_DELAY_SECS, squad.createdAt).getTime() - new Date().getTime()) / (1000 * 60 * 60));
+  return errorResponse(`Must wait ${remainingTime} more hours after squad creation`);
📝 Committable suggestion

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

Suggested change
if (secondsFromDate(ANBU_DELAY_SECS, squad.createdAt) > new Date()) {
return errorResponse("Must wait 24 hours after squad creation");
}
if (new Date() < secondsFromDate(ANBU_DELAY_SECS, squad.createdAt)) {
const remainingTime = Math.ceil((secondsFromDate(ANBU_DELAY_SECS, squad.createdAt).getTime() - new Date().getTime()) / (1000 * 60 * 60));
return errorResponse(`Must wait ${remainingTime} more hours after squad creation`);
}

@theeneon
Copy link
Collaborator

Solution is incorrect, this check to see if the anbu was created in 24 hours. What should happen is that the Kage should not be able to delete any anbu squads until after the 24 hour period regardless of when the anbu was created @openhands-agent

@TheNinja-RPG
Copy link
Collaborator Author

OpenHands started fixing the pr! You can monitor the progress here.

@TheNinja-RPG
Copy link
Collaborator Author

Overview of Changes:

✅ Successfully Resolved:

  • Changed timing restriction from squad creation to Kage appointment
  • Implemented proper 24-hour waiting period for new Kages
  • Updated error message to accurately reflect the rule
  • Fixed the loophole that allowed premature squad deletions

The changes appear to have fully addressed the core issue by properly implementing the intended business rule. The solution is logically sound and there are no apparent remaining issues with the 24-hour restriction functionality.

Recommendation: Monitor initial deployment to ensure the leaderUpdatedAt timestamp is being set and tracked correctly in all cases.

Copy link

📦 Next.js Bundle Analysis for tnr

This analysis was generated by the Next.js Bundle Analysis action. 🤖

🎉 Global Bundle Size Decreased

Page Size (compressed)
global 92.64 KB (-1 B)
Details

The global bundle is the javascript bundle that loads alongside every page. It is in its own category because its impact is much higher - an increase to its size means that every page on your website loads slower, and a decrease means every page loads faster.

Any third party scripts you have added directly to your app using the <script> tag are not accounted for in this analysis

If you want further insight into what is behind the changes, give @next/bundle-analyzer a try!

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 (1)
app/src/server/api/routers/anbu.ts (1)

250-252: ⚠️ Potential issue

Fix the time comparison logic and enhance the error message.

The implementation correctly uses the Kage's appointment time instead of the squad's creation time. However, there are two issues to address:

  1. The time comparison logic is reversed. When secondsFromDate returns a future date and it's greater than the current date, it means the waiting period hasn't elapsed yet.
  2. The error message could be more informative by showing the remaining time.

Apply this diff to fix both issues:

-      if (user.village && secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt) > new Date()) {
-        return errorResponse("Must have been kage for 24 hours");
+      if (user.village && new Date() < secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt)) {
+        const remainingTime = Math.ceil(
+          (secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt).getTime() - new Date().getTime()) / 
+          (1000 * 60 * 60)
+        );
+        return errorResponse(`Must wait ${remainingTime} more hours before you can disband ANBU squads`);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6350611 and 2cb115c.

📒 Files selected for processing (1)
  • app/src/server/api/routers/anbu.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: analyze
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
app/src/server/api/routers/anbu.ts (2)

12-12: LGTM! Import changes are well-organized.

The new imports for secondsFromDate and ANBU_DELAY_SECS are correctly placed and necessary for implementing the time-based validation.

Also applies to: 21-21


250-252: Verify leaderUpdatedAt is set during Kage appointment.

Let's verify that the leaderUpdatedAt timestamp is being set correctly when a new Kage is appointed.

✅ Verification successful

leaderUpdatedAt is properly maintained during Kage changes

The timestamp is correctly set to the current date whenever:

  • A new Kage takes the position
  • An elder takes over after Kage resignation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for where leaderUpdatedAt is being set in the codebase
echo "Searching for leaderUpdatedAt assignments..."
rg -l "leaderUpdatedAt.*=" 

# Search for Kage appointment logic
echo "Searching for Kage appointment logic..."
ast-grep --pattern 'update($village).set({ kageId: $_, leaderUpdatedAt: $_ })'

Length of output: 297


Script:

#!/bin/bash
# Search for village updates with broader patterns
echo "Searching for village updates..."
rg -A 5 "village.*update" 

# Search for kage-related mutations
echo "Searching for kage assignments..."
rg -A 5 "kageId.*=" 

# Search for leader-related updates
echo "Searching for leader updates..."
rg -A 5 "leader.*update"

Length of output: 19768


Script:

#!/bin/bash
# Search for kage appointment/resignation logic
echo "Searching for kage appointment code..."
rg -A 10 "appoint.*kage|resign.*kage"

# Search for village table updates with more context
echo "Searching for village table updates..."
ast-grep --pattern 'update(village).set({ $$$, kageId: $_ })'

# Search for transaction blocks containing kage updates
echo "Searching for kage update transactions..."
rg -A 10 "transaction.*kage"

Length of output: 1907


Script:

#!/bin/bash
# Get the full implementation of takeKage mutation
echo "Searching for takeKage implementation..."
rg -B 5 -A 20 "takeKage.*mutation"

# Search for any update statements in kage.ts
echo "Searching for village updates in kage.ts..."
rg -B 2 -A 5 "update.*village.*set" app/src/server/api/routers/kage.ts

Length of output: 2312

Comment on lines +250 to +252
if (user.village && secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt) > new Date()) {
return errorResponse("Must have been kage for 24 hours");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add proper error handling for missing village data.

The current implementation might fail if the village relation or leaderUpdatedAt field is undefined. Add proper error handling to ensure robustness.

+      if (!user.village?.leaderUpdatedAt) {
+        return errorResponse("Village leader information is not available");
+      }
       if (user.village && secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt) > new Date()) {
📝 Committable suggestion

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

Suggested change
if (user.village && secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt) > new Date()) {
return errorResponse("Must have been kage for 24 hours");
}
if (!user.village?.leaderUpdatedAt) {
return errorResponse("Village leader information is not available");
}
if (user.village && secondsFromDate(ANBU_DELAY_SECS, user.village.leaderUpdatedAt) > new Date()) {
return errorResponse("Must have been kage for 24 hours");
}

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.

Kage can delete Anbu before the 24 hour lock out is up
3 participants