fix: 'account now owns a negative amount' not showing when it had 0 #877

Merged
Sainan merged 1 commits from warn-fix into main 2025-01-31 08:02:27 -08:00
Owner
No description provided.
coderabbitai[bot] commented 2025-01-31 07:05:50 -08:00 (Migrated from github.com)
Author
Owner

Walkthrough

The pull request introduces changes to the src/services/inventoryService.ts file, focusing on improving the logic for managing item quantities in the inventory. The modifications affect two primary functions: addMiscItems and addMods.

The updated implementation introduces more robust handling of item counts by implementing early return mechanisms when item counts are zero. Both functions now include enhanced logic for initializing items with zero counts, updating item quantities, and removing items from their respective arrays when their counts reach zero.

The changes aim to prevent potential issues with negative item counts by adding explicit checks and logging warnings if such scenarios occur. The modifications provide a more controlled approach to inventory management, ensuring that items are only processed and maintained when they have positive quantities.

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 introduces changes to the `src/services/inventoryService.ts` file, focusing on improving the logic for managing item quantities in the inventory. The modifications affect two primary functions: `addMiscItems` and `addMods`. The updated implementation introduces more robust handling of item counts by implementing early return mechanisms when item counts are zero. Both functions now include enhanced logic for initializing items with zero counts, updating item quantities, and removing items from their respective arrays when their counts reach zero. The changes aim to prevent potential issues with negative item counts by adding explicit checks and logging warnings if such scenarios occur. The modifications provide a more controlled approach to inventory management, ensuring that items are only processed and maintained when they have positive quantities. <!-- walkthrough_end --> <!-- internal state start --> <!-- FAHghAtBAEAqAWBLAztF0CGA7TBXALgPYQDmAplmQE4b5kAm0AxoQLasX4Bc0ADldEIAjAFZkm+RADcyqIQE9mhetQxChifADoMiaFAB8wY+CjHYmgDZkeAM0QAPHgHIMTFriz5oWQgHdBPyxUDB8yElppMkxWQk98Zx9Cb2R4f0QsEmg/eAo0b3gMRgAGYAA5XFYhah4ADgB2euAAVWQa6ABlXSxsY0MTSBgKRkJbPCJSClU6RhZ2Th5+QVFxSRk5RRYVGnVNHT1+0xgE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jkbm4K+E8F2feXeqV3jwKF8tCHcCTtUyfrjDJSlLDoG4D2c+05xUPb3mtW02XfcOqFuPNeFwIQixozg7K5YAYDKe0HOLmuy7XSuRqHiH67RJuBBbtuc07qdUD8ahuyKHnA/Qc1bFsZciQJPogRBIZfQhjACEuKYbgZOZ+24BKccZV4WTt75VF2f4DkPo47lYTQAH1ED0GQH/OCcIyDL3oH/Bi7xvD9FAIMTAAA2AAzGQAAjPUIQ29aiIPqBgZB9QAAsthCEACYyC2AYIgihtg0HFFsAATkQbUAArPg2oxQmBjDgd/G+/9AHANAYgcBDA/7DEBAYIAA= --> <!-- internal state end --> <!-- finishing_touch_checkbox_start --> <details> <summary>✨ Finishing Touches</summary> - [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings (Beta) </details> <!-- 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-31 07:07:49 -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)

890-905: Consistent implementation of item count management in addMods.

The changes mirror the improvements made to addMiscItems, ensuring consistent behavior across different item types.

Note: Consider extracting the common item count management logic into a shared utility function to maintain DRY principles.

+// utils/inventoryUtils.ts
+export const updateItemCount = <T extends { ItemType: string; ItemCount: number }>(
+  items: T[],
+  itemType: string,
+  itemCount: number,
+  createItem: (type: string) => T
+): void => {
+  if (itemCount === 0) return;
+
+  let itemIndex = items.findIndex(x => x.ItemType === itemType);
+  if (itemIndex === -1) {
+    const newItem = createItem(itemType);
+    newItem.ItemCount = 0;
+    itemIndex = items.push(newItem) - 1;
+  }
+
+  items[itemIndex].ItemCount += itemCount;
+  if (items[itemIndex].ItemCount === 0) {
+    items.splice(itemIndex, 1);
+  } else if (items[itemIndex].ItemCount < 0) {
+    logger.warn(`account now owns a negative amount of ${itemType}`);
+  }
+};

Usage:

 export const addMiscItems = (inventory: TInventoryDatabaseDocument, itemsArray: IMiscItem[] | undefined): void => {
     const { MiscItems } = inventory;
     itemsArray?.forEach(({ ItemCount, ItemType }) => {
-        if (ItemCount == 0) {
-            return;
-        }
-        let itemIndex = MiscItems.findIndex(x => x.ItemType === ItemType);
-        if (itemIndex == -1) {
-            itemIndex = MiscItems.push({ ItemType, ItemCount: 0 }) - 1;
-        }
-        MiscItems[itemIndex].ItemCount += ItemCount;
-        if (MiscItems[itemIndex].ItemCount == 0) {
-            MiscItems.splice(itemIndex, 1);
-        } else if (MiscItems[itemIndex].ItemCount <= 0) {
-            logger.warn(`account now owns a negative amount of ${ItemType}`);
-        }
+        updateItemCount(MiscItems, ItemType, ItemCount, type => ({ ItemType: type, ItemCount: 0 }));
     });
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 50c280cf01 and a63e17bff8.

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

822-835: Improved item count management in addMiscItems.

The changes correctly handle edge cases:

  • Early return for zero counts prevents unnecessary processing
  • Proper initialization of new items
  • Cleanup of zero-count items
  • Warning for negative counts
**Actionable comments posted: 0** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/services/inventoryService.ts (1)</summary><blockquote> `890-905`: **Consistent implementation of item count management in `addMods`.** The changes mirror the improvements made to `addMiscItems`, ensuring consistent behavior across different item types. Note: Consider extracting the common item count management logic into a shared utility function to maintain DRY principles. ```diff +// utils/inventoryUtils.ts +export const updateItemCount = <T extends { ItemType: string; ItemCount: number }>( + items: T[], + itemType: string, + itemCount: number, + createItem: (type: string) => T +): void => { + if (itemCount === 0) return; + + let itemIndex = items.findIndex(x => x.ItemType === itemType); + if (itemIndex === -1) { + const newItem = createItem(itemType); + newItem.ItemCount = 0; + itemIndex = items.push(newItem) - 1; + } + + items[itemIndex].ItemCount += itemCount; + if (items[itemIndex].ItemCount === 0) { + items.splice(itemIndex, 1); + } else if (items[itemIndex].ItemCount < 0) { + logger.warn(`account now owns a negative amount of ${itemType}`); + } +}; ``` Usage: ```diff export const addMiscItems = (inventory: TInventoryDatabaseDocument, itemsArray: IMiscItem[] | undefined): void => { const { MiscItems } = inventory; itemsArray?.forEach(({ ItemCount, ItemType }) => { - if (ItemCount == 0) { - return; - } - let itemIndex = MiscItems.findIndex(x => x.ItemType === ItemType); - if (itemIndex == -1) { - itemIndex = MiscItems.push({ ItemType, ItemCount: 0 }) - 1; - } - MiscItems[itemIndex].ItemCount += ItemCount; - if (MiscItems[itemIndex].ItemCount == 0) { - MiscItems.splice(itemIndex, 1); - } else if (MiscItems[itemIndex].ItemCount <= 0) { - logger.warn(`account now owns a negative amount of ${ItemType}`); - } + updateItemCount(MiscItems, ItemType, ItemCount, type => ({ ItemType: type, ItemCount: 0 })); }); }; ``` </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 50c280cf01013e6bdf48256647ff495aca3c9986 and a63e17bff867a374f42efed6eff10f9685a380cf. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/services/inventoryService.ts` (2 hunks) </details> <details> <summary>🔇 Additional comments (1)</summary><blockquote> <details> <summary>src/services/inventoryService.ts (1)</summary> `822-835`: **Improved item count management in `addMiscItems`.** The changes correctly handle edge cases: - Early return for zero counts prevents unnecessary processing - Proper initialization of new items - Cleanup of zero-count items - Warning for negative counts </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Sign in to join this conversation.
No description provided.