fix: track FreeFavorsEarned & FreeFavorsUsed #792

Merged
Sainan merged 2 commits from track-favors into main 2025-01-17 05:43:51 -08:00
Owner

Fixes #732

Fixes #732
coderabbitai[bot] commented 2025-01-16 21:41:11 -08:00 (Migrated from github.com)
Author
Owner

Walkthrough

The pull request introduces changes to two files: syndicateSacrificeController.ts and purchaseService.ts. In syndicateSacrificeController.ts, a new logic block is added to track free favors earned by a syndicate based on its title. When a syndicate's title increases, the code checks and adds the current title to a FreeFavorsEarned array if it's not already present. In purchaseService.ts, the handlePurchase function is modified to prioritize the use of free favors during purchases. The changes involve updating the logic for handling syndicate purchases, using the nullish coalescing assignment operator to initialize FreeFavorsUsed, and ensuring proper tracking of free favors earned and used.

Assessment against linked issues

Objective Addressed Explanation
Track free favors earned when reaching a new syndicate rank [#732]
Ensure free favors are properly committed to the database [#732]
Allow using free favors for purchases from syndicates [#732]

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 two files: `syndicateSacrificeController.ts` and `purchaseService.ts`. In `syndicateSacrificeController.ts`, a new logic block is added to track free favors earned by a syndicate based on its title. When a syndicate's title increases, the code checks and adds the current title to a `FreeFavorsEarned` array if it's not already present. In `purchaseService.ts`, the `handlePurchase` function is modified to prioritize the use of free favors during purchases. The changes involve updating the logic for handling syndicate purchases, using the nullish coalescing assignment operator to initialize `FreeFavorsUsed`, and ensuring proper tracking of free favors earned and used. ## Assessment against linked issues | Objective | Addressed | Explanation | |-----------|-----------|-------------| | Track free favors earned when reaching a new syndicate rank [#732] | ✅ | | | Ensure free favors are properly committed to the database [#732] | ✅ | | | Allow using free favors for purchases from syndicates [#732] | ✅ | | <!-- walkthrough_end --> <!-- internal state start --> <!-- FAHghAtBAEAqAWBLAztF0CGA7TBXALgPYQDmAplmQE4b5kAm0AxoQLasX4Bc0ADldEIAjAFZkm+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EjJyyuS8dSLodh+BQNNFU0QcRhi6BwrhsFBCsmvGKbs9kAD8MaAC89lNwbJtJOSQ61OW1wZSKzWzLWXSx6HiWuxTpWJVAvje6OczXeDZmGP5UgLKhGQD87xts/B6qoLk/JX99a+zVBAFELwlmojDW7CeBlVRLTQgQcUdLqAzEstZGJYp4m1xca5bwOCklxK6CHCgmAl7gI8Z3K4ITJBbXdd4t4atDoayxoIcser3FhlOSJS2pI6H6QstMwU5NkYQPRGKDA9ARDjHwLBF+LpqCUQEKuil2di6cDLtALFGT4QUELVygMHyvm0u6IUaOsd9h8IljvREaEppIQnK4eUe9r2TPGBgcglsADybafD2pIxyMj0tZZeBdA7HyAUXafUhSmnd8wrGMkSWC+EtTJCmPfj4BG4oHbh3COpddRs53pGfnPUhMlD0f1XkIje4h348f3j/Yof9vBnwvsAyQN874PyMzxzmWJzPb0EVZ3+MQT69EAZfEBmTwHQEgYKGBZJ2QILEhJW+eECKHmzupMCF5ILXhiDBe88FELUNQuhZQX4NDYT/IlgCt5+j4AAPpLGQNVwIeoIoMGq8Oo+uF8IVaYEII4QgACsJxBvxAACzDYOEIAAbAwA4AAOAAjGQYbfWJtMHoPEI48QDh9eGyNpgw2mAbcqgcDrSXKuaFq6PBrZAmtgPoNVo8HWgA= --> <!-- 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-16 21:43:12 -08:00
coderabbitai[bot] (Migrated from github.com) left a comment
Author
Owner

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/services/purchaseService.ts (2)

82-108: Consider adding transaction support for favor usage

The current implementation might lead to race conditions if multiple purchases attempt to use free favors simultaneously. Consider implementing a transaction mechanism or a locking system.


82-108: Add type definitions and documentation for the favor system

Consider the following improvements:

  1. Add TypeScript interfaces for favor-related fields
  2. Document the favor system's behavior
  3. Add unit tests for both earning and using favors

Example type definitions:

interface ISyndicateAffiliation {
  Tag: string;
  Standing: number;
  Title?: number;
  FreeFavorsEarned?: number[];
  FreeFavorsUsed?: number[];
}

interface IFavorPurchaseParams extends IPurchaseParams {
  UseFreeFavor?: boolean;
  SyndicateTag?: string;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d8845bc478 and cb9b5222f4.

📒 Files selected for processing (2)
  • src/controllers/api/syndicateSacrificeController.ts (1 hunks)
  • src/services/purchaseService.ts (1 hunks)
🔇 Additional comments (1)
src/controllers/api/syndicateSacrificeController.ts (1)

53-58: Verify the relationship between titles and favors

The current implementation tracks titles even if they don't correspond to actual favors in the manifest. Let's verify if this is the intended behavior.

Run this script to analyze the relationship between titles and favors:

Verification successful

The relationship between titles and favors is correctly implemented

The current implementation is intentional and follows a proper design where:

  • Each title (rank) level can earn one free favor
  • Checking manifest.favours.length ensures favors are available to be claimed
  • Tracking titles in FreeFavorsEarned prevents duplicate favor claims for the same title level
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all syndicate titles correspond to favors
# Expected: Find cases where titles don't have corresponding favors

ast-grep --pattern 'manifest.favours = $_' | rg -A 5 'favours'

# Check syndicate definitions
rg -A 10 'titles.*=.*\[' 

Length of output: 89


Script:

#!/bin/bash
# Find manifest and syndicate files
echo "=== Files containing manifest or syndicate ==="
fd -t f | rg -i "manifest|syndicate"

echo -e "\n=== Searching for favor/favour definitions ==="
rg -i "favou?rs?" -A 5

echo -e "\n=== Searching for title definitions and usage ==="
rg -i "title.*=|\.title" -A 5

echo -e "\n=== Searching for FreeFavorsEarned usage ==="
rg "FreeFavorsEarned" -A 5

Length of output: 100807


Script:

#!/bin/bash
# Find syndicate manifest and related files
echo "=== Searching manifest files for favors structure ==="
fd -t f -e json | rg -i "manifest" | xargs cat 2>/dev/null | rg -i "favou?rs?"

echo -e "\n=== Searching for syndicate title usage ==="
rg -i "syndicate.*title|title.*syndicate" -A 5

echo -e "\n=== Searching for favor/favour definitions ==="
ast-grep --pattern 'favours = $_' 

Length of output: 4113

**Actionable comments posted: 3** <details> <summary>🧹 Nitpick comments (2)</summary><blockquote> <details> <summary>src/services/purchaseService.ts (2)</summary><blockquote> `82-108`: **Consider adding transaction support for favor usage** The current implementation might lead to race conditions if multiple purchases attempt to use free favors simultaneously. Consider implementing a transaction mechanism or a locking system. --- `82-108`: **Add type definitions and documentation for the favor system** Consider the following improvements: 1. Add TypeScript interfaces for favor-related fields 2. Document the favor system's behavior 3. Add unit tests for both earning and using favors Example type definitions: ```typescript interface ISyndicateAffiliation { Tag: string; Standing: number; Title?: number; FreeFavorsEarned?: number[]; FreeFavorsUsed?: number[]; } interface IFavorPurchaseParams extends IPurchaseParams { UseFreeFavor?: boolean; SyndicateTag?: string; } ``` </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 d8845bc4786bfadad9f29ff771b936ef80f96ae9 and cb9b5222f447b6ed781e456cdf9f754f4c4c9f07. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/controllers/api/syndicateSacrificeController.ts` (1 hunks) * `src/services/purchaseService.ts` (1 hunks) </details> <details> <summary>🔇 Additional comments (1)</summary><blockquote> <details> <summary>src/controllers/api/syndicateSacrificeController.ts (1)</summary> `53-58`: **Verify the relationship between titles and favors** The current implementation tracks titles even if they don't correspond to actual favors in the manifest. Let's verify if this is the intended behavior. Run this script to analyze the relationship between titles and favors: <details> <summary>✅ Verification successful</summary> <!-- [monologue] [task verify_titles_favors_2/2] [observations] 1. Found critical relationships: - Title is incremented during sacrifice (syndicate.Title += 1) - Title is used to track progression and standing limits - Titles are tied to standing levels (minStanding, maxStanding) 2. Key implementation details: - FreeFavorsEarned is initialized as empty array - Titles are checked against manifest.favours.length - Favors are tracked per title level 3. Analysis: - The implementation appears intentional - Titles represent progression levels - Each title can earn one free favor - Favors list in manifest defines available rewards [analysis] The current implementation is correct because: 1. Titles represent progression/rank levels 2. Each new title earns the ability to claim a free favor 3. Checking manifest.favours.length ensures favors are available 4. Tracking titles in FreeFavorsEarned prevents duplicate claims [actions] Generate final response indicating the implementation is correct --> **The relationship between titles and favors is correctly implemented** The current implementation is intentional and follows a proper design where: - Each title (rank) level can earn one free favor - Checking manifest.favours.length ensures favors are available to be claimed - Tracking titles in FreeFavorsEarned prevents duplicate favor claims for the same title level </details> <details> <summary>🏁 Scripts executed</summary> The following scripts were executed for the analysis: Script: ```shell #!/bin/bash # Description: Check if all syndicate titles correspond to favors # Expected: Find cases where titles don't have corresponding favors ast-grep --pattern 'manifest.favours = $_' | rg -A 5 'favours' # Check syndicate definitions rg -A 10 'titles.*=.*\[' ``` Length of output: 89 --- Script: ```shell #!/bin/bash # Find manifest and syndicate files echo "=== Files containing manifest or syndicate ===" fd -t f | rg -i "manifest|syndicate" echo -e "\n=== Searching for favor/favour definitions ===" rg -i "favou?rs?" -A 5 echo -e "\n=== Searching for title definitions and usage ===" rg -i "title.*=|\.title" -A 5 echo -e "\n=== Searching for FreeFavorsEarned usage ===" rg "FreeFavorsEarned" -A 5 ``` Length of output: 100807 --- Script: ```shell #!/bin/bash # Find syndicate manifest and related files echo "=== Searching manifest files for favors structure ===" fd -t f -e json | rg -i "manifest" | xargs cat 2>/dev/null | rg -i "favou?rs?" echo -e "\n=== Searching for syndicate title usage ===" rg -i "syndicate.*title|title.*syndicate" -A 5 echo -e "\n=== Searching for favor/favour definitions ===" ast-grep --pattern 'favours = $_' ``` Length of output: 4113 </details> </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -53,0 +55,4 @@
if (!syndicate.FreeFavorsEarned.includes(syndicate.Title)) {
syndicate.FreeFavorsEarned.push(syndicate.Title);
}
}
coderabbitai[bot] (Migrated from github.com) commented 2025-01-16 21:43:11 -08:00
Author
Owner

⚠️ Potential issue

Add null check for manifest and type safety

The code needs additional safety checks:

  1. Add null check for manifest before accessing favours
  2. Consider adding type definitions for FreeFavorsEarned

Apply this diff to add the necessary checks:

-    if (syndicate.Title > 0 && manifest.favours.length != 0) {
+    if (syndicate.Title > 0 && manifest?.favours?.length > 0) {
         syndicate.FreeFavorsEarned ??= [];
         if (!syndicate.FreeFavorsEarned.includes(syndicate.Title)) {
             syndicate.FreeFavorsEarned.push(syndicate.Title);
         }
     }
📝 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.

    if (syndicate.Title > 0 && manifest?.favours?.length > 0) {
        syndicate.FreeFavorsEarned ??= [];
        if (!syndicate.FreeFavorsEarned.includes(syndicate.Title)) {
            syndicate.FreeFavorsEarned.push(syndicate.Title);
        }
    }
_:warning: Potential issue_ **Add null check for manifest and type safety** The code needs additional safety checks: 1. Add null check for `manifest` before accessing `favours` 2. Consider adding type definitions for `FreeFavorsEarned` Apply this diff to add the necessary checks: ```diff - if (syndicate.Title > 0 && manifest.favours.length != 0) { + if (syndicate.Title > 0 && manifest?.favours?.length > 0) { syndicate.FreeFavorsEarned ??= []; if (!syndicate.FreeFavorsEarned.includes(syndicate.Title)) { syndicate.FreeFavorsEarned.push(syndicate.Title); } } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **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. `````suggestion if (syndicate.Title > 0 && manifest?.favours?.length > 0) { syndicate.FreeFavorsEarned ??= []; if (!syndicate.FreeFavorsEarned.includes(syndicate.Title)) { syndicate.FreeFavorsEarned.push(syndicate.Title); } } ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -99,0 +102,4 @@
Tag: syndicateTag,
Standing: favour.standingCost
}
];
coderabbitai[bot] (Migrated from github.com) commented 2025-01-16 21:43:12 -08:00
Author
Owner

⚠️ Potential issue

Fix potential array index out of bounds and add validation

The current implementation has several critical issues:

  1. No validation that FreeFavorsEarned exists
  2. Potential array index out of bounds when accessing FreeFavorsEarned
  3. No check if there are available favors to use

Apply this diff to fix these issues:

     if (purchaseRequest.PurchaseParams.UseFreeFavor!) {
         const inventory = await getInventory(accountId);
         const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag)!;
+        if (!affiliation.FreeFavorsEarned?.length) {
+            throw new Error("No free favors available");
+        }
         affiliation.FreeFavorsUsed ??= [];
-        affiliation.FreeFavorsUsed.push(affiliation.FreeFavorsEarned![affiliation.FreeFavorsUsed.length]);
+        const availableFavors = affiliation.FreeFavorsEarned.length - (affiliation.FreeFavorsUsed?.length || 0);
+        if (availableFavors <= 0) {
+            throw new Error("All free favors have been used");
+        }
+        affiliation.FreeFavorsUsed.push(affiliation.FreeFavorsEarned[affiliation.FreeFavorsUsed.length]);
         await inventory.save();
📝 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.

                if (purchaseRequest.PurchaseParams.UseFreeFavor!) {
                    const inventory = await getInventory(accountId);
                    const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag)!;
                    if (!affiliation.FreeFavorsEarned?.length) {
                        throw new Error("No free favors available");
                    }
                    affiliation.FreeFavorsUsed ??= [];
                    const availableFavors = affiliation.FreeFavorsEarned.length - (affiliation.FreeFavorsUsed?.length || 0);
                    if (availableFavors <= 0) {
                        throw new Error("All free favors have been used");
                    }
                    affiliation.FreeFavorsUsed.push(affiliation.FreeFavorsEarned[affiliation.FreeFavorsUsed.length]);
                    await inventory.save();
_:warning: Potential issue_ **Fix potential array index out of bounds and add validation** The current implementation has several critical issues: 1. No validation that `FreeFavorsEarned` exists 2. Potential array index out of bounds when accessing `FreeFavorsEarned` 3. No check if there are available favors to use Apply this diff to fix these issues: ```diff if (purchaseRequest.PurchaseParams.UseFreeFavor!) { const inventory = await getInventory(accountId); const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag)!; + if (!affiliation.FreeFavorsEarned?.length) { + throw new Error("No free favors available"); + } affiliation.FreeFavorsUsed ??= []; - affiliation.FreeFavorsUsed.push(affiliation.FreeFavorsEarned![affiliation.FreeFavorsUsed.length]); + const availableFavors = affiliation.FreeFavorsEarned.length - (affiliation.FreeFavorsUsed?.length || 0); + if (availableFavors <= 0) { + throw new Error("All free favors have been used"); + } + affiliation.FreeFavorsUsed.push(affiliation.FreeFavorsEarned[affiliation.FreeFavorsUsed.length]); await inventory.save(); ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **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. `````suggestion if (purchaseRequest.PurchaseParams.UseFreeFavor!) { const inventory = await getInventory(accountId); const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag)!; if (!affiliation.FreeFavorsEarned?.length) { throw new Error("No free favors available"); } affiliation.FreeFavorsUsed ??= []; const availableFavors = affiliation.FreeFavorsEarned.length - (affiliation.FreeFavorsUsed?.length || 0); if (availableFavors <= 0) { throw new Error("All free favors have been used"); } affiliation.FreeFavorsUsed.push(affiliation.FreeFavorsEarned[affiliation.FreeFavorsUsed.length]); await inventory.save(); ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
coderabbitai[bot] (Migrated from github.com) commented 2025-01-16 21:43:12 -08:00
Author
Owner

🛠️ Refactor suggestion

Add error handling for invalid syndicate or favor

The standing-based purchase path needs proper error handling for cases where the syndicate or favor is not found.

Apply this diff to add error handling:

     const syndicate = ExportSyndicates[syndicateTag];
-    if (syndicate) {
+    if (!syndicate) {
+        throw new Error(`Invalid syndicate: ${syndicateTag}`);
+    }
     const favour = syndicate.favours.find(
         x => x.storeItem == purchaseRequest.PurchaseParams.StoreItem
     );
+    if (!favour) {
+        throw new Error(`Invalid favor for item: ${purchaseRequest.PurchaseParams.StoreItem}`);
+    }
-    if (favour) {
         const inventory = await getInventory(accountId);
         const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag);
-        if (affiliation) {
+        if (!affiliation) {
+            throw new Error(`No affiliation found for syndicate: ${syndicateTag}`);
+        }
📝 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.

                    const syndicate = ExportSyndicates[syndicateTag];
                    if (!syndicate) {
                        throw new Error(`Invalid syndicate: ${syndicateTag}`);
                    }
                    const favour = syndicate.favours.find(
                        x => x.storeItem == purchaseRequest.PurchaseParams.StoreItem
                    );
                    if (!favour) {
                        throw new Error(`Invalid favor for item: ${purchaseRequest.PurchaseParams.StoreItem}`);
                    }
                    const inventory = await getInventory(accountId);
                    const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag);
                    if (!affiliation) {
                        throw new Error(`No affiliation found for syndicate: ${syndicateTag}`);
                    }
                    purchaseResponse.Standing = [
                        {
                            Tag: syndicateTag,
                            Standing: favour.standingCost
                        }
                    ];
                    affiliation.Standing -= favour.standingCost;
                    await inventory.save();
_:hammer_and_wrench: Refactor suggestion_ **Add error handling for invalid syndicate or favor** The standing-based purchase path needs proper error handling for cases where the syndicate or favor is not found. Apply this diff to add error handling: ```diff const syndicate = ExportSyndicates[syndicateTag]; - if (syndicate) { + if (!syndicate) { + throw new Error(`Invalid syndicate: ${syndicateTag}`); + } const favour = syndicate.favours.find( x => x.storeItem == purchaseRequest.PurchaseParams.StoreItem ); + if (!favour) { + throw new Error(`Invalid favor for item: ${purchaseRequest.PurchaseParams.StoreItem}`); + } - if (favour) { const inventory = await getInventory(accountId); const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag); - if (affiliation) { + if (!affiliation) { + throw new Error(`No affiliation found for syndicate: ${syndicateTag}`); + } ``` <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **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. `````suggestion const syndicate = ExportSyndicates[syndicateTag]; if (!syndicate) { throw new Error(`Invalid syndicate: ${syndicateTag}`); } const favour = syndicate.favours.find( x => x.storeItem == purchaseRequest.PurchaseParams.StoreItem ); if (!favour) { throw new Error(`Invalid favor for item: ${purchaseRequest.PurchaseParams.StoreItem}`); } const inventory = await getInventory(accountId); const affiliation = inventory.Affiliations.find(x => x.Tag == syndicateTag); if (!affiliation) { throw new Error(`No affiliation found for syndicate: ${syndicateTag}`); } purchaseResponse.Standing = [ { Tag: syndicateTag, Standing: favour.standingCost } ]; affiliation.Standing -= favour.standingCost; await inventory.save(); ````` </details> <!-- suggestion_end --> <!-- This is an auto-generated comment by CodeRabbit -->
Sign in to join this conversation.
No description provided.