fix: purchasing of ship decorations #761

Merged
Sainan merged 1 commits from deco-purchase-fix into main 2025-01-11 03:54:12 -08:00
Owner
No description provided.
coderabbitai[bot] commented 2025-01-10 23:04:36 -08:00 (Migrated from github.com)
Author
Owner

Walkthrough

The pull request modifies the addItem function in the inventoryService.ts file, introducing a new conditional branch specifically for handling items categorized as "ShipDecorations". This change involves creating a dedicated logic path for processing ship decoration items, which includes generating an array of inventory changes and calling the addShipDecorations method when the item type matches this category.

Simultaneously, the existing case for "Objects" that previously handled ship decoration items has been removed. This modification consolidates the processing of ship decoration items into the new "ShipDecorations" category, effectively streamlining the item handling logic by eliminating redundant processing paths and centralizing the management of these specific inventory items.

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 `addItem` function in the `inventoryService.ts` file, introducing a new conditional branch specifically for handling items categorized as "ShipDecorations". This change involves creating a dedicated logic path for processing ship decoration items, which includes generating an array of inventory changes and calling the `addShipDecorations` method when the item type matches this category. Simultaneously, the existing case for "Objects" that previously handled ship decoration items has been removed. This modification consolidates the processing of ship decoration items into the new "ShipDecorations" category, effectively streamlining the item handling logic by eliminating redundant processing paths and centralizing the management of these specific inventory items. <!-- walkthrough_end --> <!-- internal state start --> <!-- FAHghAtBAEAqAWBLAztF0CGA7TBXALgPYQDmAplmQE4b5kAm0AxoQLasX4Bc0ADldEIAjAFZkm+RADcyqIQE9mhetQxChifADoMiaFAB8wY+CjHYmgDZkeAM0QAPHr1xUm8DMkRYSg29GQkXmgVFhpJQixkYAA5XFYhah4AdgA2AEZgAFVkJOgAZV0sbGNDE0gYCkZCfwwCYnJKcIYldk5nAWExCWlZaAUlFRp1TR09MtMYBHR0bDwiUgpVOkYWNqxuaBoAdwD41gwqRQGWIbUNbV19CCNys2BkNwB6XKopRCZZJ+8ZDcIj/LUd6fLT4ZBcYAAImhwAAxL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nrgAGMh0gAJglWw27OoQABZ697pgmHr9IB4pDB0gATlSJhkjO3v0intR8KrjPI80XP6HzwvEGLhhs6qa4DCAA== --> <!-- 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-10 23:06:30 -08:00
coderabbitai[bot] (Migrated from github.com) left a comment
Author
Owner

Actionable comments posted: 0

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

Line range hint 584-601: Consider adding input validation and reducing code duplication.

While the implementation is solid, consider these improvements:

  1. Add validation for negative quantities
  2. Consider creating a generic function to handle array updates, as this pattern is repeated in addMiscItems, addConsumables, and addShipDecorations.

Example implementation:

+type ItemWithCount = {
+    ItemCount: number;
+    ItemType: string;
+};
+
+const addItemsToArray = <T extends ItemWithCount>(
+    array: T[],
+    items: T[] | undefined,
+    arrayPath: string,
+    inventory: TInventoryDatabaseDocument
+): void => {
+    items?.forEach(({ ItemCount, ItemType, ...rest }) => {
+        if (ItemCount <= 0) {
+            throw new Error(`Invalid quantity ${ItemCount} for item ${ItemType}`);
+        }
+        const itemIndex = array.findIndex(item => item.ItemType === ItemType);
+        if (itemIndex !== -1) {
+            array[itemIndex].ItemCount += ItemCount;
+            Object.assign(array[itemIndex], rest);
+            inventory.markModified(`${arrayPath}.${itemIndex}`);
+        } else {
+            array.push({ ItemCount, ItemType, ...rest } as T);
+        }
+    });
+};
+
 export const addShipDecorations = (
     inventory: TInventoryDatabaseDocument,
     itemsArray: IConsumable[] | undefined
 ): void => {
-    const { ShipDecorations } = inventory;
-
-    itemsArray?.forEach(({ ItemCount, ItemType }) => {
-        const itemIndex = ShipDecorations.findIndex(miscItem => miscItem.ItemType === ItemType);
-
-        if (itemIndex !== -1) {
-            ShipDecorations[itemIndex].ItemCount += ItemCount;
-            inventory.markModified(`ShipDecorations.${itemIndex}.ItemCount`);
-        } else {
-            ShipDecorations.push({ ItemCount, ItemType });
-        }
-    });
+    addItemsToArray(inventory.ShipDecorations, itemsArray, 'ShipDecorations', inventory);
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb8e19403e and 5880e12adf.

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

145-157: LGTM! Well-structured implementation of ShipDecorations handling.

The new conditional branch follows the established patterns and maintains type safety.


145-157: Verify the usage of ShipDecorations across the codebase.

Let's ensure that all code paths properly handle ShipDecorations consistently.

Run this script to verify the usage:

Verification successful

ShipDecorations implementation is consistent across the codebase

The implementation properly integrates with the inventory system through:

  • Consistent type definitions in the type system
  • Proper model structure in the database schema
  • Correct inventory change tracking
  • Well-defined interfaces for requests and responses
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent handling of ShipDecorations across the codebase

# Check for any direct references to ShipDecorations
echo "Checking direct references to ShipDecorations..."
rg -l "ShipDecorations"

# Check for any productCategory references
echo "Checking productCategory references..."
rg "productCategory.*=.*['\"]ShipDecorations['\"]"

# Check for any inventory change handlers
echo "Checking inventory change handlers..."
rg "InventoryChanges.*ShipDecorations"

Length of output: 1127


Script:

#!/bin/bash
# Check implementation details

# Check inventory changes structure
echo "Checking inventory changes structure..."
ast-grep --pattern 'InventoryChanges: { ShipDecorations: $_'

# Check addShipDecorations implementation
echo "Checking addShipDecorations implementation..."
ast-grep --pattern 'function addShipDecorations($_,$_) { $$$'

# Check type handling in controllers
echo "Checking type handling in controllers..."
rg -A 5 "ShipDecorations.*IMiscItem" src/controllers/

Length of output: 463


Script:

#!/bin/bash
# Check with broader patterns

# Check inventory model structure
echo "Checking inventory model..."
rg -A 5 "ShipDecorations" src/models/inventoryModels/inventoryModel.ts

# Check type definitions
echo "Checking type definitions..."
rg -A 5 "ShipDecorations" src/types/

# Check inventory changes handling
echo "Checking inventory changes handling..."
rg -A 5 "addShipDecorations" src/services/

Length of output: 2510

**Actionable comments posted: 0** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/services/inventoryService.ts (1)</summary><blockquote> Line range hint `584-601`: **Consider adding input validation and reducing code duplication.** While the implementation is solid, consider these improvements: 1. Add validation for negative quantities 2. Consider creating a generic function to handle array updates, as this pattern is repeated in `addMiscItems`, `addConsumables`, and `addShipDecorations`. Example implementation: ```diff +type ItemWithCount = { + ItemCount: number; + ItemType: string; +}; + +const addItemsToArray = <T extends ItemWithCount>( + array: T[], + items: T[] | undefined, + arrayPath: string, + inventory: TInventoryDatabaseDocument +): void => { + items?.forEach(({ ItemCount, ItemType, ...rest }) => { + if (ItemCount <= 0) { + throw new Error(`Invalid quantity ${ItemCount} for item ${ItemType}`); + } + const itemIndex = array.findIndex(item => item.ItemType === ItemType); + if (itemIndex !== -1) { + array[itemIndex].ItemCount += ItemCount; + Object.assign(array[itemIndex], rest); + inventory.markModified(`${arrayPath}.${itemIndex}`); + } else { + array.push({ ItemCount, ItemType, ...rest } as T); + } + }); +}; + export const addShipDecorations = ( inventory: TInventoryDatabaseDocument, itemsArray: IConsumable[] | undefined ): void => { - const { ShipDecorations } = inventory; - - itemsArray?.forEach(({ ItemCount, ItemType }) => { - const itemIndex = ShipDecorations.findIndex(miscItem => miscItem.ItemType === ItemType); - - if (itemIndex !== -1) { - ShipDecorations[itemIndex].ItemCount += ItemCount; - inventory.markModified(`ShipDecorations.${itemIndex}.ItemCount`); - } else { - ShipDecorations.push({ ItemCount, ItemType }); - } - }); + addItemsToArray(inventory.ShipDecorations, itemsArray, 'ShipDecorations', inventory); }; ``` </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 fb8e19403e9e54e1aee815704cbe98a3da209af4 and 5880e12adf2efb484cc8184ffa196c7ef4119abc. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/services/inventoryService.ts` (1 hunks) </details> <details> <summary>🔇 Additional comments (2)</summary><blockquote> <details> <summary>src/services/inventoryService.ts (2)</summary> `145-157`: **LGTM! Well-structured implementation of ShipDecorations handling.** The new conditional branch follows the established patterns and maintains type safety. --- `145-157`: **Verify the usage of ShipDecorations across the codebase.** Let's ensure that all code paths properly handle ShipDecorations consistently. Run this script to verify the usage: <details> <summary>✅ Verification successful</summary> <!-- [monologue] [task verify_ship_decorations_final] Analyzing the complete implementation of ShipDecorations [observations] 1. Type System: - Properly defined in inventoryTypes.ts as IConsumable[] - Has dedicated interfaces: IShipDecorationsRequest and IShipDecorationsResponse - Consistent with IMiscItem usage in the reviewed code 2. Model: - Correctly structured in inventoryModel using typeCountSchema - Properly positioned among other inventory items 3. Implementation: - addShipDecorations function is properly defined with correct parameters - Consistent inventory changes structure in inventoryService.ts - Proper type handling with IConsumable[] [analysis] The implementation shows: 1. Complete type safety through proper interfaces 2. Consistent handling in inventory model 3. Proper integration with the inventory system 4. Correct change tracking structure [actions] Generate final response confirming the verification as the implementation is consistent and complete --> **ShipDecorations implementation is consistent across the codebase** The implementation properly integrates with the inventory system through: - Consistent type definitions in the type system - Proper model structure in the database schema - Correct inventory change tracking - Well-defined interfaces for requests and responses </details> <details> <summary>🏁 Scripts executed</summary> The following scripts were executed for the analysis: Script: ```shell #!/bin/bash # Description: Check for consistent handling of ShipDecorations across the codebase # Check for any direct references to ShipDecorations echo "Checking direct references to ShipDecorations..." rg -l "ShipDecorations" # Check for any productCategory references echo "Checking productCategory references..." rg "productCategory.*=.*['\"]ShipDecorations['\"]" # Check for any inventory change handlers echo "Checking inventory change handlers..." rg "InventoryChanges.*ShipDecorations" ``` Length of output: 1127 --- Script: ```shell #!/bin/bash # Check implementation details # Check inventory changes structure echo "Checking inventory changes structure..." ast-grep --pattern 'InventoryChanges: { ShipDecorations: $_' # Check addShipDecorations implementation echo "Checking addShipDecorations implementation..." ast-grep --pattern 'function addShipDecorations($_,$_) { $$$' # Check type handling in controllers echo "Checking type handling in controllers..." rg -A 5 "ShipDecorations.*IMiscItem" src/controllers/ ``` Length of output: 463 --- Script: ```shell #!/bin/bash # Check with broader patterns # Check inventory model structure echo "Checking inventory model..." rg -A 5 "ShipDecorations" src/models/inventoryModels/inventoryModel.ts # Check type definitions echo "Checking type definitions..." rg -A 5 "ShipDecorations" src/types/ # Check inventory changes handling echo "Checking inventory changes handling..." rg -A 5 "addShipDecorations" src/services/ ``` Length of output: 2510 </details> </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Sign in to join this conversation.
No description provided.