fix: not consuming ItemPrices from server-side vendor #798

Merged
Sainan merged 1 commits from steal-path into main 2025-01-17 22:06:07 -08:00
Owner

Fixes #796

Fixes #796
coderabbitai[bot] commented 2025-01-17 06:32:53 -08:00 (Migrated from github.com)
Author
Owner

Walkthrough

The pull request modifies the purchase service in src/services/purchaseService.ts, introducing a new helper function handleItemPrices to improve the handling of vendor purchases. The changes focus on modularizing the logic for processing item prices during a purchase transaction. A new inventoryChanges object is initialized to track inventory modifications, and the handleItemPrices function is designed to encapsulate the complex logic of updating inventory based on item prices. The return type of the handleSlotPurchase function has been updated to align with other purchase handling functions, suggesting a standardization of response structures across the purchase-related methods.

Assessment against linked issues

Objective Addressed Explanation
Handle ItemPrices for server-side vendor purchases [#796]
Correctly subtract special currencies (e.g., Steel Essence)

The changes directly address the issue by introducing a dedicated handleItemPrices function that appears designed to process item prices and manage inventory changes, which should resolve the problem of not subtracting special currencies during vendor purchases.

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 purchase service in `src/services/purchaseService.ts`, introducing a new helper function `handleItemPrices` to improve the handling of vendor purchases. The changes focus on modularizing the logic for processing item prices during a purchase transaction. A new `inventoryChanges` object is initialized to track inventory modifications, and the `handleItemPrices` function is designed to encapsulate the complex logic of updating inventory based on item prices. The return type of the `handleSlotPurchase` function has been updated to align with other purchase handling functions, suggesting a standardization of response structures across the purchase-related methods. ## Assessment against linked issues | Objective | Addressed | Explanation | |-----------|-----------|-------------| | Handle ItemPrices for server-side vendor purchases [#796] | ✅ | | | Correctly subtract special currencies (e.g., Steel Essence) | ✅ | | The changes directly address the issue by introducing a dedicated `handleItemPrices` function that appears designed to process item prices and manage inventory changes, which should resolve the problem of not subtracting special currencies during vendor purchases. <!-- walkthrough_end --> <!-- internal state start --> <!-- FAHghAtBAEAqAWBLAztF0CGA7TBXALgPYQ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WqiDo+aFdRjUkE2iEFOhLRSsGOFQelNgBGUJoXQthFKxLItYdndhlKuHss0lJbS3KUKwTjkZAVZAzIqUAEmEgtgVoPSCq+oaqNWP21Xqg1Rq4XWtNfdc19A81mhtfi1ORLHXUBdYy91IjNXiKDJksgwacChq5bpdUfLo3QUFeZTC2F3lARAsOVYlFLxThvGjRg95FzPlfGRD8ihvzKF/Bof8h4R3HnnKMfAAB9VoyB923TGn0Bg+7fGuHCAOUAQ4zgABYACM8Qn0AFZUSnEuPQVEABmJ9AAmB9wHLhvu/ZcMgAHLjPviMBt9AGmC/suPEc4D6AAMDVb07vvJoQ99Bj2npshekcgEDBAA== --> <!-- 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-17 06:34:47 -08:00
coderabbitai[bot] (Migrated from github.com) left a comment
Author
Owner

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9fd2fb6ba2 and 741f15678d.

📒 Files selected for processing (1)
  • src/services/purchaseService.ts (6 hunks)
🔇 Additional comments (3)
src/services/purchaseService.ts (3)

50-50: Good refactoring of inventory changes tracking!

The introduction of a separate inventoryChanges object and its combination with the purchase response improves code organization and maintainability.

Also applies to: 77-77


278-278: LGTM! Good standardization of return types.

The change to Promise<IPurchaseResponse> aligns the function's return type with other purchase handling functions, improving consistency across the codebase.


61-68: Verify potential duplicate item price handling.

The code processes item prices twice in different sections:

  1. For vendor manifest items (lines 61-68)
  2. For ExportVendors items (lines 130-135)

This could lead to duplicate processing if both conditions are met. Please verify that these sections are mutually exclusive.

Also applies to: 130-135

**Actionable comments posted: 1** <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 9fd2fb6ba293094f367299feee7d48ce8ed16c55 and 741f15678d6312444858d8e2841f4452c38f940c. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/services/purchaseService.ts` (6 hunks) </details> <details> <summary>🔇 Additional comments (3)</summary><blockquote> <details> <summary>src/services/purchaseService.ts (3)</summary> `50-50`: **Good refactoring of inventory changes tracking!** The introduction of a separate `inventoryChanges` object and its combination with the purchase response improves code organization and maintainability. Also applies to: 77-77 --- `278-278`: **LGTM! Good standardization of return types.** The change to `Promise<IPurchaseResponse>` aligns the function's return type with other purchase handling functions, improving consistency across the codebase. --- `61-68`: **Verify potential duplicate item price handling.** The code processes item prices twice in different sections: 1. For vendor manifest items (lines 61-68) 2. For ExportVendors items (lines 130-135) This could lead to duplicate processing if both conditions are met. Please verify that these sections are mutually exclusive. Also applies to: 130-135 </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) commented 2025-01-17 06:34:46 -08:00
Author
Owner

🛠️ Refactor suggestion

Add error handling for inventory operations.

While the function nicely modularizes item price handling, it lacks error handling for inventory operations. Consider:

  1. Validating input parameters
  2. Adding try-catch blocks
  3. Implementing rollback logic if an operation fails
 const handleItemPrices = async (
     accountId: string,
     itemPrices: IMiscItem[],
     purchaseQuantity: number,
     inventoryChanges: IInventoryChanges
 ): Promise<void> => {
+    if (!accountId || !itemPrices || !Array.isArray(itemPrices)) {
+        throw new Error('Invalid input parameters');
+    }
+
+    try {
         const inventory = await getInventory(accountId);
+        const originalState = JSON.parse(JSON.stringify(inventory));
+
         for (const item of itemPrices) {
             const invItem: IMiscItem = {
                 ItemType: item.ItemType,
                 ItemCount: item.ItemCount * purchaseQuantity * -1
             };

             addMiscItems(inventory, [invItem]);

             inventoryChanges.MiscItems ??= [];
             const change = (inventoryChanges.MiscItems as IMiscItem[]).find(x => x.ItemType == item.ItemType);
             if (change) {
                 change.ItemCount += invItem.ItemCount;
             } else {
                 (inventoryChanges.MiscItems as IMiscItem[]).push(invItem);
             }
         }
         await inventory.save();
+    } catch (error) {
+        logger.error('Failed to process item prices:', error);
+        throw new Error('Failed to process item prices');
+    }
 };

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

_:hammer_and_wrench: Refactor suggestion_ **Add error handling for inventory operations.** While the function nicely modularizes item price handling, it lacks error handling for inventory operations. Consider: 1. Validating input parameters 2. Adding try-catch blocks 3. Implementing rollback logic if an operation fails ```diff const handleItemPrices = async ( accountId: string, itemPrices: IMiscItem[], purchaseQuantity: number, inventoryChanges: IInventoryChanges ): Promise<void> => { + if (!accountId || !itemPrices || !Array.isArray(itemPrices)) { + throw new Error('Invalid input parameters'); + } + + try { const inventory = await getInventory(accountId); + const originalState = JSON.parse(JSON.stringify(inventory)); + for (const item of itemPrices) { const invItem: IMiscItem = { ItemType: item.ItemType, ItemCount: item.ItemCount * purchaseQuantity * -1 }; addMiscItems(inventory, [invItem]); inventoryChanges.MiscItems ??= []; const change = (inventoryChanges.MiscItems as IMiscItem[]).find(x => x.ItemType == item.ItemType); if (change) { change.ItemCount += invItem.ItemCount; } else { (inventoryChanges.MiscItems as IMiscItem[]).push(invItem); } } await inventory.save(); + } catch (error) { + logger.error('Failed to process item prices:', error); + throw new Error('Failed to process item prices'); + } }; ``` > Committable suggestion skipped: line range outside the PR's diff. <!-- This is an auto-generated comment by CodeRabbit -->
Sign in to join this conversation.
No description provided.