fix: remove ship decos from inventory when placed and vice-versa #770

Merged
Sainan merged 1 commits from consume-decos into main 2025-01-12 04:38:05 -08:00
Owner

Fixes #763

Fixes #763
coderabbitai[bot] commented 2025-01-11 20:15:34 -08:00 (Migrated from github.com)
Author
Owner

Walkthrough

The pull request modifies the shipCustomizationsService.ts file to improve ship decoration inventory management. The changes focus on enhancing the handleSetShipDecorations method to handle decoration placement and removal more precisely. The implementation now considers a configuration setting unlockAllShipDecorations to determine inventory behavior. When this setting is false, the method ensures that decorations are properly tracked in the user's inventory, either by adding back a removed decoration or decrementing the count of a placed decoration. New imports from inventoryService and configService support these inventory management operations.

Assessment against linked issues

Objective Addressed Explanation
Ensure decoration is removed from inventory when placed [#763]
Implement inventory tracking for ship decorations [#763]

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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. (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.

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.
<!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- walkthrough_start --> ## Walkthrough The pull request modifies the `shipCustomizationsService.ts` file to improve ship decoration inventory management. The changes focus on enhancing the `handleSetShipDecorations` method to handle decoration placement and removal more precisely. The implementation now considers a configuration setting `unlockAllShipDecorations` to determine inventory behavior. When this setting is false, the method ensures that decorations are properly tracked in the user's inventory, either by adding back a removed decoration or decrementing the count of a placed decoration. New imports from `inventoryService` and `configService` support these inventory management operations. ## Assessment against linked issues | Objective | Addressed | Explanation | |-----------|-----------|-------------| | Ensure decoration is removed from inventory when placed [#763] | ✅ | | | Implement inventory tracking for ship decorations [#763] | ✅ | | <!-- walkthrough_end --> <!-- internal state start --> <!-- FAHghAtBAEAqAWBLAztF0CGA7TBXALgPYQDmAplmQE4b5kAm0AxoQLasX4Bc0ADldEIAjAFZkm+RADcyqIQE9mhetQxChifADoMiaFAB8wY+CjGAxOegAFAErQAyrnYYq84wjJ9cAGx/QqMgBHXFl8aEl8HwZoACIAM0QADx5A1kIZaGQkXmgVFlR4qjY0LBksIjdoAHd4Cj4fDCYY7EYpRGaIGSpkD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inWkNlgsESEg7eaCnAUnZ4ZH3GMNZUegEWAAB1RSGQxvmBZArXeB1lDCf16X4GUAMMGgShRud2lCaQoRuKYABrb5Sgh5RoZiX4o+HJE9MDep04fFGS91BNoBVdH0wdeOJa0Ww4z1F76HR+LoBe95G/F5v0FbhhKOgZPlAznjmDqIuTy8dHnddrRWwLwunr8WOe71in5gkpdLnHj5YYvxkS/iTt5gDTRYwh6cKqdUcqAAcnQtkYKOwDhvWM8YYhN0JnOJoxdfiaADLgXg9BUL3zXGbdkTFwy0kZL6YOT1/g5g7H4f0mAsi3Cpq4Ve4hi7oADvqPCtYmB1wtB1ZCEsS5dxiEIAgy9wizyDmPd4nd7QMBPoTPuA8ZBDwpugLAhBwjvnmBUNOawnZKh3nvQgRdD4+GPlPRO0jChPzIPPRejB8hpE4CAlgrZwgZVrBwsxejcylCdDbM0wdPChn+oyWQoosCDlnAwpUZd/CHhXlMcGkNoZfjcVUTkGBuScHwnhLGrC9ZQNYkqJ029EAkB3JA8+khGQBgXFQZmKJ2KQTQTBQIh4ypWLPEky8dBrxpMThg/Je55AJQsFYQ+dAJZ9idPkRogzWnjmVnlPCtl84dD8ZEICxgYAAFkQIp0YLQ+gPB1aa1Fk4qM0icDo1ifId2ZAKaJWgKsmWGz/gMG2cbU2ACLYuOOdUtwZyLkwAAGquEQGoaIfxA7bJySQQ5qiXa5M+bde6iVFrLVSiojKnUso9Vyv1Ngg1UgjTGj9RQU1lAzQ0HNRq8Lmr5TGPgAA+psZAVLAjtAVgwKll5CILSWuSs4ABWaEAAmXlAAOeI9BeVnAAJwMC5WcaEAqACMZAzhnDIBKgVAAWY4sJZWKq5fQWE0JjiqsVYwJKoAUoUs0DS+gdKGXTjAvQKlaV2VAA= --> <!-- internal state end --> <!-- finishing_touch_checkbox_start --> ## Finishing Touches - [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings (Beta) <!-- finishing_touch_checkbox_end --> <!-- tips_start --> --- 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? <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <details> <summary>🪧 Tips</summary> ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - 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](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR. ([Beta](https://docs.coderabbit.ai/early-access#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. ### Documentation and Community - Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit. - Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements. </details> <!-- tips_end -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-01-11 20:17:01 -08:00
coderabbitai[bot] (Migrated from github.com) left a comment
Author
Owner

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/services/shipCustomizationsService.ts (1)

114-132: Consider using transactions for data consistency.

The code performs multiple database operations (saving personal rooms and inventory) that should maintain consistency. Consider wrapping these operations in a transaction to ensure atomicity.

Example approach:

const session = await mongoose.startSession();
try {
  await session.withTransaction(async () => {
    await personalRooms.save({ session });
    if (!config.unlockAllShipDecorations) {
      const inventory = await getInventory(accountId);
      addShipDecorations(inventory, [{ ItemType: placedDecoration.Type, ItemCount: count }]);
      await inventory.save({ session });
    }
  });
} finally {
  await session.endSession();
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2cd47c8ae2 and 056228fd20.

📒 Files selected for processing (1)
  • src/services/shipCustomizationsService.ts (2 hunks)
🔇 Additional comments (2)
src/services/shipCustomizationsService.ts (2)

11-12: LGTM! New imports align with PR objectives.

The added imports for inventory management and configuration services are appropriate for implementing the decoration inventory tracking functionality.


114-119: Verify decoration type before adding to inventory.

While the inventory management logic is correct, it would be safer to verify that placedDecoration.Type exists before adding it back to the inventory.

Consider adding a type check:

 if (!config.unlockAllShipDecorations) {
     const inventory = await getInventory(accountId);
+    if (!placedDecoration.Type) {
+        throw new Error("Invalid decoration type for inventory update");
+    }
     addShipDecorations(inventory, [{ ItemType: placedDecoration.Type, ItemCount: 1 }]);
     await inventory.save();
 }
**Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/services/shipCustomizationsService.ts (1)</summary><blockquote> `114-132`: **Consider using transactions for data consistency.** The code performs multiple database operations (saving personal rooms and inventory) that should maintain consistency. Consider wrapping these operations in a transaction to ensure atomicity. Example approach: ```typescript const session = await mongoose.startSession(); try { await session.withTransaction(async () => { await personalRooms.save({ session }); if (!config.unlockAllShipDecorations) { const inventory = await getInventory(accountId); addShipDecorations(inventory, [{ ItemType: placedDecoration.Type, ItemCount: count }]); await inventory.save({ session }); } }); } finally { await session.endSession(); } ``` </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used: .coderabbit.yaml** **Review profile: CHILL** **Plan: Pro** <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2cd47c8ae2e196363100c81fa3373526a298c9e3 and 056228fd209ed50681e00e9e84731005d367400d. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/services/shipCustomizationsService.ts` (2 hunks) </details> <details> <summary>🔇 Additional comments (2)</summary><blockquote> <details> <summary>src/services/shipCustomizationsService.ts (2)</summary> `11-12`: **LGTM! New imports align with PR objectives.** The added imports for inventory management and configuration services are appropriate for implementing the decoration inventory tracking functionality. --- `114-119`: **Verify decoration type before adding to inventory.** While the inventory management logic is correct, it would be safer to verify that `placedDecoration.Type` exists before adding it back to the inventory. Consider adding a type check: ```diff if (!config.unlockAllShipDecorations) { const inventory = await getInventory(accountId); + if (!placedDecoration.Type) { + throw new Error("Invalid decoration type for inventory update"); + } addShipDecorations(inventory, [{ ItemType: placedDecoration.Type, ItemCount: 1 }]); await inventory.save(); } ``` </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) commented 2025-01-11 20:17:00 -08:00
Author
Owner

💡 Codebase verification

Inventory quantity validation is required before placement

The codebase confirms that there's no validation of decoration quantity before decrementing from inventory. This could lead to negative quantities or allow placing decorations without having them in inventory.

  • src/services/shipCustomizationsService.ts: Add quantity check before addShipDecorations call
  • src/services/inventoryService.ts: Consider adding validation in addShipDecorations function
🔗 Analysis chain

Verify sufficient inventory quantity before placement.

When placing a decoration, we should verify that the user has sufficient quantity in their inventory before decrementing.

Consider adding an inventory check:

 if (!config.unlockAllShipDecorations) {
     const inventory = await getInventory(accountId);
+    const decoInventory = inventory.ShipDecorations?.find(
+        item => item.ItemType === placedDecoration.Type
+    );
+    if (!decoInventory || decoInventory.ItemCount <= 0) {
+        throw new Error("Insufficient decoration quantity in inventory");
+    }
     addShipDecorations(inventory, [{ ItemType: placedDecoration.Type, ItemCount: -1 }]);
     await inventory.save();
 }
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for inventory-related checks and ShipDecorations handling
rg -A 5 "ShipDecorations.*ItemCount|getInventory.*ShipDecorations" --type typescript

# Look for type definitions and interfaces
ast-grep --pattern 'interface $_ {
  ShipDecorations?: $$$
}'

# Search for decoration-related error handling
rg "throw.*(\"|').*decoration.*(\"|')" --type typescript

Length of output: 283


Script:

#!/bin/bash
# Search for inventory and decoration handling
rg -A 5 "ShipDecorations.*ItemCount|getInventory"

# Look for addShipDecorations function implementation
ast-grep --pattern 'function addShipDecorations($$$) {
  $$$
}'

# Search for decoration-related error handling
rg "throw.*decoration"

# Find files related to ship decorations
fd -e ts -e tsx | xargs rg "ShipDecorations"

Length of output: 65882

_:bulb: Codebase verification_ **Inventory quantity validation is required before placement** The codebase confirms that there's no validation of decoration quantity before decrementing from inventory. This could lead to negative quantities or allow placing decorations without having them in inventory. - `src/services/shipCustomizationsService.ts`: Add quantity check before `addShipDecorations` call - `src/services/inventoryService.ts`: Consider adding validation in `addShipDecorations` function <details> <summary>🔗 Analysis chain</summary> **Verify sufficient inventory quantity before placement.** When placing a decoration, we should verify that the user has sufficient quantity in their inventory before decrementing. Consider adding an inventory check: ```diff if (!config.unlockAllShipDecorations) { const inventory = await getInventory(accountId); + const decoInventory = inventory.ShipDecorations?.find( + item => item.ItemType === placedDecoration.Type + ); + if (!decoInventory || decoInventory.ItemCount <= 0) { + throw new Error("Insufficient decoration quantity in inventory"); + } addShipDecorations(inventory, [{ ItemType: placedDecoration.Type, ItemCount: -1 }]); await inventory.save(); } ``` </details> <details> <summary>🏁 Scripts executed</summary> The following scripts were executed for the analysis: Error: No shell scripts found --- Script: ```shell #!/bin/bash # Search for inventory-related checks and ShipDecorations handling rg -A 5 "ShipDecorations.*ItemCount|getInventory.*ShipDecorations" --type typescript # Look for type definitions and interfaces ast-grep --pattern 'interface $_ { ShipDecorations?: $$$ }' # Search for decoration-related error handling rg "throw.*(\"|').*decoration.*(\"|')" --type typescript ``` Length of output: 283 --- Script: ```shell #!/bin/bash # Search for inventory and decoration handling rg -A 5 "ShipDecorations.*ItemCount|getInventory" # Look for addShipDecorations function implementation ast-grep --pattern 'function addShipDecorations($$$) { $$$ }' # Search for decoration-related error handling rg "throw.*decoration" # Find files related to ship decorations fd -e ts -e tsx | xargs rg "ShipDecorations" ``` Length of output: 65882 </details> <!-- This is an auto-generated comment by CodeRabbit -->
Sign in to join this conversation.
No description provided.