feat(webui): add "add missing mods" #804

Merged
Sainan merged 7 commits from addmods into main 2025-01-18 16:57:39 -08:00
Owner
No description provided.
coderabbitai[bot] commented 2025-01-18 01:55:53 -08:00 (Migrated from github.com)
Author
Owner

Walkthrough

The pull request introduces a new "Bulk Actions" section in the web interface's Mods card, specifically adding a button labeled "Add Missing Mods" in static/webui/index.html. Accompanying this UI change, a new JavaScript function doAddAllMods() is implemented in static/webui/script.js. This function enables users to automatically add all missing mods to their inventory in batches. The implementation first retrieves all available mods, checks the user's current inventory, and then provides a confirmation dialog to add the missing mods. When confirmed, the function sends POST requests to update the inventory, adding 21 of each missing mod type to ensure full upgrades for certain arcanes.

  • spaceninjaserver/SpaceNinjaServer#696: This issue directly matches the functionality implemented in the pull request, which adds an "Add all missing mods" feature to the WebUI. The PR appears to be a direct implementation of this issue's request.

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 a new "Bulk Actions" section in the web interface's Mods card, specifically adding a button labeled "Add Missing Mods" in `static/webui/index.html`. Accompanying this UI change, a new JavaScript function `doAddAllMods()` is implemented in `static/webui/script.js`. This function enables users to automatically add all missing mods to their inventory in batches. The implementation first retrieves all available mods, checks the user's current inventory, and then provides a confirmation dialog to add the missing mods. When confirmed, the function sends POST requests to update the inventory, adding 21 of each missing mod type to ensure full upgrades for certain arcanes. ## Possibly related issues - spaceninjaserver/SpaceNinjaServer#696: This issue directly matches the functionality implemented in the pull request, which adds an "Add all missing mods" feature to the WebUI. The PR appears to be a direct implementation of this issue's request. <!-- walkthrough_end --> <!-- internal state start --> <!-- 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= --> <!-- 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-18 02:04:51 -08:00
coderabbitai[bot] (Migrated from github.com) left a comment
Author
Owner

Actionable comments posted: 1

🧹 Nitpick comments (2)
static/webui/script.js (2)

1106-1118: Add error handling and progress indication for batch processing.

The batch processing lacks error handling and progress indication, which could lead to a poor user experience when processing large numbers of mods.

                 batches.forEach(batch => {
+                    const batchIndex = batches.indexOf(batch);
                     $.post({
                         url: "/api/missionInventoryUpdate.php?" + window.authz,
                         contentType: "text/plain",
                         data: JSON.stringify({
                             RawUpgrades: batch.map(mod => ({
                                 ItemType: mod,
                                 ItemCount: 21 // To fully upgrade certain arcanes
                             }))
                         })
-                    }).done(function () {
+                    }).done(function() {
+                        const progress = ((batchIndex + 1) / batches.length * 100).toFixed(0);
+                        console.log(`Processed batch ${batchIndex + 1}/${batches.length} (${progress}%)`);
                         updateInventory();
+                    }).fail(function(jqXHR, textStatus, errorThrown) {
+                        console.error(`Failed to process batch ${batchIndex + 1}: ${textStatus}`, errorThrown);
                     });
                 });
🧰 Tools
🪛 eslint

[error] 1106-1106: '$' is not defined.

(no-undef)


1112-1112: Document the magic number with a detailed comment.

The comment about arcanes could be more descriptive about why exactly 21 items are needed.

-                                ItemCount: 21 // To fully upgrade certain arcanes
+                                ItemCount: 21 // Adding 21 copies to ensure enough mods for maximum rank (R5) arcane upgrades
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79299db475 and 7591146cb79ecffa7cdeaee2b8f9fd50543eefa6.

📒 Files selected for processing (2)
  • static/webui/index.html (1 hunks)
  • static/webui/script.js (1 hunks)
🧰 Additional context used
🪛 eslint
static/webui/script.js

[error] 1080-1080: 'doAddAllMods' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 1087-1087: '$' is not defined.

(no-undef)


[error] 1097-1097: 'batch' is not defined.

(no-undef)


[error] 1106-1106: '$' is not defined.

(no-undef)

🔇 Additional comments (1)
static/webui/index.html (1)

202-207: LGTM! Clean implementation following existing UI patterns.

The new "Bulk Actions" card is well-structured and consistently implemented with the rest of the interface.

**Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments (2)</summary><blockquote> <details> <summary>static/webui/script.js (2)</summary><blockquote> `1106-1118`: **Add error handling and progress indication for batch processing.** The batch processing lacks error handling and progress indication, which could lead to a poor user experience when processing large numbers of mods. ```diff batches.forEach(batch => { + const batchIndex = batches.indexOf(batch); $.post({ url: "/api/missionInventoryUpdate.php?" + window.authz, contentType: "text/plain", data: JSON.stringify({ RawUpgrades: batch.map(mod => ({ ItemType: mod, ItemCount: 21 // To fully upgrade certain arcanes })) }) - }).done(function () { + }).done(function() { + const progress = ((batchIndex + 1) / batches.length * 100).toFixed(0); + console.log(`Processed batch ${batchIndex + 1}/${batches.length} (${progress}%)`); updateInventory(); + }).fail(function(jqXHR, textStatus, errorThrown) { + console.error(`Failed to process batch ${batchIndex + 1}: ${textStatus}`, errorThrown); }); }); ``` <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1106-1106: '$' is not defined. (no-undef) </details> </details> --- `1112-1112`: **Document the magic number with a detailed comment.** The comment about arcanes could be more descriptive about why exactly 21 items are needed. ```diff - ItemCount: 21 // To fully upgrade certain arcanes + ItemCount: 21 // Adding 21 copies to ensure enough mods for maximum rank (R5) arcane upgrades ``` </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 79299db47599e6b9145b3f015331173d58be0bb3 and 7591146cb79ecffa7cdeaee2b8f9fd50543eefa6. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `static/webui/index.html` (1 hunks) * `static/webui/script.js` (1 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🪛 eslint</summary> <details> <summary>static/webui/script.js</summary> [error] 1080-1080: 'doAddAllMods' is defined but never used. (@typescript-eslint/no-unused-vars) --- [error] 1087-1087: '$' is not defined. (no-undef) --- [error] 1097-1097: 'batch' is not defined. (no-undef) --- [error] 1106-1106: '$' is not defined. (no-undef) </details> </details> </details> <details> <summary>🔇 Additional comments (1)</summary><blockquote> <details> <summary>static/webui/index.html (1)</summary> `202-207`: **LGTM! Clean implementation following existing UI patterns.** The new "Bulk Actions" card is well-structured and consistently implemented with the rest of the interface. </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
coderabbitai[bot] (Migrated from github.com) commented 2025-01-18 02:04:50 -08:00
Author
Owner

⚠️ Potential issue

Fix the condition check using the correct variable.

The condition is using an undefined batch variable instead of modsAll. This will cause a runtime error.

-            if (
-                batch.length != 0 &&
-                window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?")
-            ) {
+            if (
+                modsAll.length > 0 &&
+                window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?")
+            ) {
📝 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.

                modsAll.length > 0 &&
                window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?")
            ) {
🧰 Tools
🪛 eslint

[error] 1097-1097: 'batch' is not defined.

(no-undef)

_:warning: Potential issue_ **Fix the condition check using the correct variable.** The condition is using an undefined `batch` variable instead of `modsAll`. This will cause a runtime error. ```diff - if ( - batch.length != 0 && - window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?") - ) { + if ( + modsAll.length > 0 && + window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?") + ) { ``` <!-- 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 modsAll.length > 0 && window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?") ) { ````` </details> <!-- suggestion_end --> <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1097-1097: 'batch' is not defined. (no-undef) </details> </details> <!-- This is an auto-generated comment by CodeRabbit -->
coderabbitai[bot] (Migrated from github.com) reviewed 2025-01-18 02:07:47 -08:00
coderabbitai[bot] (Migrated from github.com) left a comment
Author
Owner

Actionable comments posted: 1

🧹 Nitpick comments (2)
static/webui/script.js (2)

1080-1122: LGTM! Consider adding JSDoc documentation.

The implementation is well-structured with proper batching to handle large payloads. The use of Set for uniqueness and the batch size of 1000 are good choices.

Add JSDoc documentation to explain the function's purpose and the significance of the 21 mod count:

+/**
+ * Adds all missing mods to the user's inventory.
+ * Each mod is added with a count of 21 to ensure enough copies
+ * for fully upgrading certain arcanes.
+ */
function doAddAllMods() {
🧰 Tools
🪛 eslint

[error] 1080-1080: 'doAddAllMods' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 1087-1087: '$' is not defined.

(no-undef)


[error] 1106-1106: '$' is not defined.

(no-undef)


1100-1119: Optimize batch processing and inventory updates.

The current implementation updates inventory after each batch and processes batches sequentially.

Consider these optimizations:

  1. Update inventory only once after all batches complete:
+let batchPromises = [];
 batches.forEach(batch => {
-    $.post({
+    batchPromises.push($.post({
         // ... existing code ...
-    }).done(function () {
-        updateInventory();
-    });
+    }));
 });
+Promise.all(batchPromises).then(() => {
+    updateInventory();
+}).catch(error => {
+    console.error('Some batches failed:', error);
+    alert('Some mods may not have been added. Please check your inventory.');
+    updateInventory();
+});
  1. Document the batch size choice:
+// Batch size of 1000 chosen based on typical payload size limits
 for (let i = 0; i < modsAll.length; i += 1000) {
🧰 Tools
🪛 eslint

[error] 1106-1106: '$' is not defined.

(no-undef)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7591146cb79ecffa7cdeaee2b8f9fd50543eefa6 and 26d8d7696d.

📒 Files selected for processing (2)
  • static/webui/index.html (1 hunks)
  • static/webui/script.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • static/webui/index.html
🧰 Additional context used
🪛 eslint
static/webui/script.js

[error] 1080-1080: 'doAddAllMods' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 1087-1087: '$' is not defined.

(no-undef)


[error] 1106-1106: '$' is not defined.

(no-undef)

🔇 Additional comments (2)
static/webui/script.js (2)

1086-1089: LGTM! Security measures are appropriate.

The implementation includes proper authorization handling through revalidateAuthz, user confirmation for bulk operations, and controlled input sources.

🧰 Tools
🪛 eslint

[error] 1087-1087: '$' is not defined.

(no-undef)


1080-1084: LGTM! Well integrated with existing codebase.

The function follows established patterns and properly integrates with existing utilities.

🧰 Tools
🪛 eslint

[error] 1080-1080: 'doAddAllMods' is defined but never used.

(@typescript-eslint/no-unused-vars)

**Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments (2)</summary><blockquote> <details> <summary>static/webui/script.js (2)</summary><blockquote> `1080-1122`: **LGTM! Consider adding JSDoc documentation.** The implementation is well-structured with proper batching to handle large payloads. The use of Set for uniqueness and the batch size of 1000 are good choices. Add JSDoc documentation to explain the function's purpose and the significance of the 21 mod count: ```diff +/** + * Adds all missing mods to the user's inventory. + * Each mod is added with a count of 21 to ensure enough copies + * for fully upgrading certain arcanes. + */ function doAddAllMods() { ``` <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1080-1080: 'doAddAllMods' is defined but never used. (@typescript-eslint/no-unused-vars) --- [error] 1087-1087: '$' is not defined. (no-undef) --- [error] 1106-1106: '$' is not defined. (no-undef) </details> </details> --- `1100-1119`: **Optimize batch processing and inventory updates.** The current implementation updates inventory after each batch and processes batches sequentially. Consider these optimizations: 1. Update inventory only once after all batches complete: ```diff +let batchPromises = []; batches.forEach(batch => { - $.post({ + batchPromises.push($.post({ // ... existing code ... - }).done(function () { - updateInventory(); - }); + })); }); +Promise.all(batchPromises).then(() => { + updateInventory(); +}).catch(error => { + console.error('Some batches failed:', error); + alert('Some mods may not have been added. Please check your inventory.'); + updateInventory(); +}); ``` 2. Document the batch size choice: ```diff +// Batch size of 1000 chosen based on typical payload size limits for (let i = 0; i < modsAll.length; i += 1000) { ``` <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1106-1106: '$' is not defined. (no-undef) </details> </details> </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 7591146cb79ecffa7cdeaee2b8f9fd50543eefa6 and 26d8d7696db43635753353d04cd1177224314634. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `static/webui/index.html` (1 hunks) * `static/webui/script.js` (1 hunks) </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * static/webui/index.html </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🪛 eslint</summary> <details> <summary>static/webui/script.js</summary> [error] 1080-1080: 'doAddAllMods' is defined but never used. (@typescript-eslint/no-unused-vars) --- [error] 1087-1087: '$' is not defined. (no-undef) --- [error] 1106-1106: '$' is not defined. (no-undef) </details> </details> </details> <details> <summary>🔇 Additional comments (2)</summary><blockquote> <details> <summary>static/webui/script.js (2)</summary> `1086-1089`: **LGTM! Security measures are appropriate.** The implementation includes proper authorization handling through `revalidateAuthz`, user confirmation for bulk operations, and controlled input sources. <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1087-1087: '$' is not defined. (no-undef) </details> </details> --- `1080-1084`: **LGTM! Well integrated with existing codebase.** The function follows established patterns and properly integrates with existing utilities. <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1080-1080: 'doAddAllMods' is defined but never used. (@typescript-eslint/no-unused-vars) </details> </details> </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -1080,0 +1118,4 @@
});
}
});
});
coderabbitai[bot] (Migrated from github.com) commented 2025-01-18 02:07:46 -08:00
Author
Owner

🛠️ Refactor suggestion

Add error handling for network failures and batch operations.

The current implementation lacks explicit error handling for network requests and batch operations.

Add error handling and progress feedback:

 revalidateAuthz(() => {
     const req = $.get("/api/inventory.php?" + window.authz + "&xpBasedLevelCapDisabled=1");
+    req.fail((jqXHR, textStatus, errorThrown) => {
+        console.error('Failed to fetch inventory:', textStatus, errorThrown);
+        alert('Failed to fetch inventory. Please try again.');
+    });
     req.done(data => {
         // ... existing code ...
+        let completedBatches = 0;
         batches.forEach(batch => {
             $.post({
                 url: "/api/missionInventoryUpdate.php?" + window.authz,
                 contentType: "text/plain",
                 data: JSON.stringify({
                     RawUpgrades: batch.map(mod => ({
                         ItemType: mod,
                         ItemCount: 21
                     }))
                 })
             }).done(function () {
+                completedBatches++;
+                if (completedBatches === batches.length) {
                     updateInventory();
+                }
+            }).fail((jqXHR, textStatus, errorThrown) => {
+                console.error('Batch update failed:', textStatus, errorThrown);
+                alert('Failed to add some mods. Please try again.');
             });
         });
     });
 });
📝 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.

    revalidateAuthz(() => {
        const req = $.get("/api/inventory.php?" + window.authz + "&xpBasedLevelCapDisabled=1");
        req.fail((jqXHR, textStatus, errorThrown) => {
            console.error('Failed to fetch inventory:', textStatus, errorThrown);
            alert('Failed to fetch inventory. Please try again.');
        });
        req.done(data => {
            for (const modOwned of data.RawUpgrades) {
                if (modOwned.ItemCount ?? 1 > 0) {
                    modsAll.delete(modOwned.ItemType);
                }
            }

            modsAll = Array.from(modsAll);
            if (
                modsAll.length != 0 &&
                window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?")
            ) {
                // Batch to avoid PayloadTooLargeError
                const batches = [];
                for (let i = 0; i < modsAll.length; i += 1000) {
                    batches.push(modsAll.slice(i, i + 1000));
                }
                let completedBatches = 0;
                batches.forEach(batch => {
                    $.post({
                        url: "/api/missionInventoryUpdate.php?" + window.authz,
                        contentType: "text/plain",
                        data: JSON.stringify({
                            RawUpgrades: batch.map(mod => ({
                                ItemType: mod,
                                ItemCount: 21 // To fully upgrade certain arcanes
                            }))
                        })
                    }).done(function () {
                        completedBatches++;
                        if (completedBatches === batches.length) {
                            updateInventory();
                        }
                    }).fail((jqXHR, textStatus, errorThrown) => {
                        console.error('Batch update failed:', textStatus, errorThrown);
                        alert('Failed to add some mods. Please try again.');
                    });
                });
            }
        });
    });
🧰 Tools
🪛 eslint

[error] 1087-1087: '$' is not defined.

(no-undef)


[error] 1106-1106: '$' is not defined.

(no-undef)

_:hammer_and_wrench: Refactor suggestion_ **Add error handling for network failures and batch operations.** The current implementation lacks explicit error handling for network requests and batch operations. Add error handling and progress feedback: ```diff revalidateAuthz(() => { const req = $.get("/api/inventory.php?" + window.authz + "&xpBasedLevelCapDisabled=1"); + req.fail((jqXHR, textStatus, errorThrown) => { + console.error('Failed to fetch inventory:', textStatus, errorThrown); + alert('Failed to fetch inventory. Please try again.'); + }); req.done(data => { // ... existing code ... + let completedBatches = 0; batches.forEach(batch => { $.post({ url: "/api/missionInventoryUpdate.php?" + window.authz, contentType: "text/plain", data: JSON.stringify({ RawUpgrades: batch.map(mod => ({ ItemType: mod, ItemCount: 21 })) }) }).done(function () { + completedBatches++; + if (completedBatches === batches.length) { updateInventory(); + } + }).fail((jqXHR, textStatus, errorThrown) => { + console.error('Batch update failed:', textStatus, errorThrown); + alert('Failed to add some mods. Please try again.'); }); }); }); }); ``` <!-- 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 revalidateAuthz(() => { const req = $.get("/api/inventory.php?" + window.authz + "&xpBasedLevelCapDisabled=1"); req.fail((jqXHR, textStatus, errorThrown) => { console.error('Failed to fetch inventory:', textStatus, errorThrown); alert('Failed to fetch inventory. Please try again.'); }); req.done(data => { for (const modOwned of data.RawUpgrades) { if (modOwned.ItemCount ?? 1 > 0) { modsAll.delete(modOwned.ItemType); } } modsAll = Array.from(modsAll); if ( modsAll.length != 0 && window.confirm("Are you sure you want to add " + modsAll.length + " mods to your account?") ) { // Batch to avoid PayloadTooLargeError const batches = []; for (let i = 0; i < modsAll.length; i += 1000) { batches.push(modsAll.slice(i, i + 1000)); } let completedBatches = 0; batches.forEach(batch => { $.post({ url: "/api/missionInventoryUpdate.php?" + window.authz, contentType: "text/plain", data: JSON.stringify({ RawUpgrades: batch.map(mod => ({ ItemType: mod, ItemCount: 21 // To fully upgrade certain arcanes })) }) }).done(function () { completedBatches++; if (completedBatches === batches.length) { updateInventory(); } }).fail((jqXHR, textStatus, errorThrown) => { console.error('Batch update failed:', textStatus, errorThrown); alert('Failed to add some mods. Please try again.'); }); }); } }); }); ````` </details> <!-- suggestion_end --> <details> <summary>🧰 Tools</summary> <details> <summary>🪛 eslint</summary> [error] 1087-1087: '$' is not defined. (no-undef) --- [error] 1106-1106: '$' is not defined. (no-undef) </details> </details> <!-- This is an auto-generated comment by CodeRabbit -->
Sign in to join this conversation.
No description provided.