Skip to content

remove deprecated Apollo onCompleted/onError callbacks#3845

Open
akanshaaa19 wants to merge 17 commits intomasterfrom
apollo_v4/batch_1
Open

remove deprecated Apollo onCompleted/onError callbacks#3845
akanshaaa19 wants to merge 17 commits intomasterfrom
apollo_v4/batch_1

Conversation

@akanshaaa19
Copy link
Copy Markdown
Member

@akanshaaa19 akanshaaa19 commented Mar 17, 2026

Following Apollo's deprecation of onCompleted/onError on query and mutation hooks, this PR refactors the affected files to use the recommended patterns:

Files changed

File Change
FormLayout.tsx Removed languageId/isLoadedData state; derived from query data. Removed onCompleted from USER_LANGUAGES query
List.tsx Moved deleteItem mutation callbacks to async deleteHandler
SideMenus.tsx Derived notificationCount from useLazyQuery data instead of state
HSM.tsx Moved uploadMedia callbacks to async handleFileUpload
Trigger.tsx Moved validateTriggerFlow callback to async handleFlowChange
FlowList.tsx Moved all mutation callbacks to dedicated async handlers; removed unused flowName state
HSMList.tsx Moved all three mutation callbacks to async call sites

Test plan

  • Edit/create form works correctly (language default, item loading)
  • Delete in list pages shows success/error notification
  • Notification count badge updates in sidebar
  • HSM file upload succeeds and fails gracefully
  • Trigger flow validation shows warning correctly
  • Flow export/import/pin works
  • HSM bulk apply, sync, and import work

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling and user notifications across uploads, deletions, imports/exports, validations, and bulk operations.
  • Refactor

    • Replaced mutation callbacks with async/await handlers for consistent loading, sequencing, and error flows.
  • Enhancement

    • Notification counts derive from live data; provider credential fields auto-populate; organization tier and language now use fetched values.
  • Localization

    • Added messages for CSV validation, template processing errors, and flow validation failure.
  • Tests

    • Updated test provider usage to default MockedProvider behavior.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 17, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This PR replaces many GraphQL mutation lifecycle callbacks (onCompleted/onError) with explicit async/await handlers and try/catch error handling, moves some UI state to be derived from query results, adds/renames async handlers for upload/import/export/pin/delete flows, introduces additional data queries in several components (languages, quality rating), adjusts test MockedProvider usage, and adds three i18n keys. No public/exported function signatures were intentionally changed except internalizing mutation handlers and making some local handlers async.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

status: ready for review, P2

Suggested reviewers

  • shijithkjayan
  • priyanshu6238

Poem

🐰 I hopped through callbacks, gentle and spry,
Replaced them with await and a careful try.
Queries now whisper the state I derive,
Mutations return — clearer paths to drive.
A tiny carrot celebration — code feels alive. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'remove deprecated Apollo onCompleted/onError callbacks' accurately and specifically describes the main change across all modified files in the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch apollo_v4/batch_1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@akanshaaa19 akanshaaa19 linked an issue Mar 17, 2026 that may be closed by this pull request
50 tasks
@github-actions
Copy link
Copy Markdown

github-actions bot commented Mar 17, 2026

@github-actions github-actions bot temporarily deployed to pull request March 17, 2026 03:48 Inactive
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/containers/Flow/FlowList/FlowList.tsx (1)

118-128: Parameter mismatch with ImportButton.

handleImport accepts one parameter (result: string), but ImportButton passes two: (fileReader.result, media). While the extra media parameter is ignored without error, other handlers in the codebase (e.g., HSMList.tsx:354) accept both parameters. For consistency with the ImportButton API, consider updating handleImport to accept both parameters:

const handleImport = async (result: string, media: any) => {
  try {
    const { data } = await importFlow({ variables: { flow: result } });
    const { status } = data.importFlow;
    setImportStatus(status);
  } catch {
    setNotification('An error occured while importing the flow', 'warning');
  } finally {
    setImporting(false);
  }
};

Also applies to: 233-234

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/Flow/FlowList/FlowList.tsx` around lines 118 - 128, The
handleImport function currently declared as handleImport(result: string) should
be updated to accept both parameters provided by ImportButton (e.g.,
handleImport(result: string, media: any)) to match the ImportButton API; change
the signature in FlowList.tsx for handleImport and any other duplicate handler
definitions in this file to (result: string, media: any) and keep the same body
(you can ignore or use media as needed) so the call sites that pass
(fileReader.result, media) align with HSMList.tsx style and avoid parameter
mismatches.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/containers/Flow/FlowList/FlowList.tsx`:
- Around line 130-139: The handlePin function lacks error handling around the
async updatePinned call; wrap the updatePinned invocation in a try/catch inside
handlePin, only call setRefreshList and setNotification on success, and in the
catch log the error (or use existing logger) and set a failure notification
(e.g., 'Failed to pin/unpin flow') so unhandled promise rejections are avoided;
update references: handlePin, updatePinned, setRefreshList, setNotification.

In `@src/containers/Form/FormLayout.tsx`:
- Around line 288-294: The computed languageId can throw if fetchedItem exists
but fetchedItem.language is null; update the ternary that sets languageId to
guard fetchedItem.language (e.g., check fetchedItem.language &&
fetchedItem.language.id) before accessing .id so it falls back to null/empty as
intended when language is missing; locate the languageId assignment in
FormLayout.tsx (symbols: languageId, fetchedItem, languageSupport) and apply a
null-safe access to fetchedItem.language (or use optional chaining) to prevent
runtime errors.

In `@src/containers/Trigger/Trigger.tsx`:
- Around line 251-266: handleFlowChange currently awaits validateTriggerFlow
without error handling; wrap the async call in a try/catch inside
handleFlowChange (around the validateTriggerFlow invocation) to catch
network/mutation errors, call setTriggerFlowWarning with a generic or
error.message value on failure, and optionally log the error (e.g.,
console.error or existing logger). Ensure existing logic that reads
result.data.validateTrigger remains in the try block and that
setTriggerFlowWarning(undefined) stays at the start of handleFlowChange.

---

Nitpick comments:
In `@src/containers/Flow/FlowList/FlowList.tsx`:
- Around line 118-128: The handleImport function currently declared as
handleImport(result: string) should be updated to accept both parameters
provided by ImportButton (e.g., handleImport(result: string, media: any)) to
match the ImportButton API; change the signature in FlowList.tsx for
handleImport and any other duplicate handler definitions in this file to
(result: string, media: any) and keep the same body (you can ignore or use media
as needed) so the call sites that pass (fileReader.result, media) align with
HSMList.tsx style and avoid parameter mismatches.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 35dde555-b94c-4bf6-85b4-167d3d858c2f

📥 Commits

Reviewing files that changed from the base of the PR and between 131af00 and 6a257db.

📒 Files selected for processing (6)
  • src/components/UI/Layout/Navigation/SideMenus/SideMenus.tsx
  • src/containers/Flow/FlowList/FlowList.tsx
  • src/containers/Form/FormLayout.tsx
  • src/containers/HSM/HSM.tsx
  • src/containers/List/List.tsx
  • src/containers/Trigger/Trigger.tsx

@cypress
Copy link
Copy Markdown

cypress bot commented Mar 17, 2026

Glific    Run #8146

Run Properties:  status check failed Failed #8146  •  git commit 6b3fd2f9e4 ℹ️: Merge 4709abdbf4c849a63f7eba573eeb9579194a081f into d021984dabf01003cb715f9707a0...
Project Glific
Branch Review apollo_v4/batch_1
Run status status check failed Failed #8146
Run duration 13m 28s
Commit git commit 6b3fd2f9e4 ℹ️: Merge 4709abdbf4c849a63f7eba573eeb9579194a081f into d021984dabf01003cb715f9707a0...
Committer Akansha Sakhre
View all properties for this run ↗︎

Test results
Tests that failed  Failures 1
Tests that were flaky  Flaky 1
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 97
View all changes introduced in this branch ↗︎

Tests for review

Failed  cypress/e2e/filesearch/Filesearch.spec.ts • 1 failed test

View Output

Test Artifacts
File search > should create a new assistant with file upload Test Replay Screenshots
Flakiness  cypress/e2e/chat/ChatCollection.spec.ts • 1 flaky test

View Output

Test Artifacts
ChatCollection > should send the emoji to collection Test Replay Screenshots

…r management in HSMList and Providers components
@github-actions github-actions bot temporarily deployed to pull request March 17, 2026 05:28 Inactive
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/containers/HSM/HSMList/HSMList.tsx`:
- Line 208: The notification strings in HSMList are hard-coded; update the calls
to setNotification to use i18next translation keys (e.g., import/use the t
function and call setNotification(t('hsm.upload.invalidCsv'), 'warning') and
similarly for the other occurrence), add the new keys to your translation
resource files (or default en.json), and run the translation extractor (yarn
extract-translations) so Lokalise picks them up; refer to the setNotification
usage and the HSMList component to locate both places to change.
- Around line 192-197: The code checks the wrong property for GraphQL errors —
replace the check for data.errors with a check for data.syncHsmTemplate.errors
(or destructure syncHsmTemplate from the response) in the async block that calls
syncHsmTemplates(); update the conditional that calls setNotification so it
reads something like: if (data && data.syncHsmTemplate &&
data.syncHsmTemplate.errors) { setNotification(... 'warning') } else {
setNotification(... 'success') } to ensure resolver errors trigger the warning
notification.
- Around line 212-216: The current handling after calling bulkApplyTemplates({
variables: { data: result } }) assumes any non-null payload is a success;
instead inspect data.bulkApplyTemplates.errors and only treat as success when
errors is empty. Update the logic in HSMList.tsx (the bulkApplyTemplates
response handling) to: if data?.bulkApplyTemplates &&
data.bulkApplyTemplates.errors?.length === 0 then call
exportCsvFile(data.bulkApplyTemplates.csv_rows, 'result') and
setNotification(t('Templates applied successfully. Please check the csv file for
the results')); otherwise handle the failure path by exporting the returned
csv_rows (if present) and calling setNotification with an error message (e.g.
include the first error message or count of errors via t) and do not show the
success toast. Ensure you reference bulkApplyTemplates,
data.bulkApplyTemplates.errors, exportCsvFile, and setNotification/t in the
change.

In `@src/containers/SettingList/Providers/Providers.tsx`:
- Around line 200-204: The code calls setCredential(credentialData) inside the
providers iteration even though credentialData is computed from
credential?.credential?.credential and does not depend on the current provider;
move the setCredential call out of the providers.forEach loop (compute
credentialData as const credentialData = credential?.credential?.credential and
then, after the loop ends, call setCredential(credentialData) only once) so you
avoid redundant state updates during the providers iteration.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 46f1e1f2-337b-4ab4-b35a-ab7b97f4f131

📥 Commits

Reviewing files that changed from the base of the PR and between 6a257db and 750725f.

📒 Files selected for processing (2)
  • src/containers/HSM/HSMList/HSMList.tsx
  • src/containers/SettingList/Providers/Providers.tsx

@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 04:01 Inactive
…and Trigger components; update language ID fallback in FormLayout; improve Providers component logic; add new translations for CSV validation messages
@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 04:29 Inactive
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/containers/SettingList/Organization/Organisation.test.tsx (1)

61-68: Consider extracting a render helper to reduce duplication.

Multiple tests render similar provider-wrapped structures. A local helper would consolidate this pattern.

const renderOrganization = (mocks = ORGANIZATION_MOCKS) =>
  render(
    <MockedProvider mocks={mocks}>
      <Router>
        <Organization />
      </Router>
    </MockedProvider>
  );

As per coding guidelines: "When repeatedly rendering the same provider-wrapped component in tests, extract a local renderXxx helper that accepts optional mocks and props overrides."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/SettingList/Organization/Organisation.test.tsx` around lines
61 - 68, Extract a local test helper named renderOrganization that wraps
Organization with MockedProvider and Router to avoid repeating the render(...)
pattern; implement it to accept an optional mocks parameter defaulting to
ORGANIZATION_MOCKS (and optional props if needed), use MockedProvider, Router
and render inside the helper, then replace direct calls to render(...) in tests
(the ones importing render, MockedProvider, Router and rendering Organization)
with calls to renderOrganization(mocks) to consolidate duplication.
src/containers/SettingList/Organization/Organization.tsx (1)

201-201: Prefer a nullish check for skip instead of a broad falsy check.

Line 201 currently uses !qualityRatingTier, which also hides the field for valid falsy values like 0 or ''. An explicit null/undefined check is safer.

Suggested diff
-      skip: !qualityRatingTier,
+      skip: qualityRatingTier === null || qualityRatingTier === undefined,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/SettingList/Organization/Organization.tsx` at line 201, The
skip flag currently uses a broad falsy check (!qualityRatingTier) which hides
valid falsy values; update the skip assignment to only skip when
qualityRatingTier is null or undefined (e.g., use qualityRatingTier == null or
qualityRatingTier === undefined) in the Organization component where skip:
!qualityRatingTier is set so 0 or '' remain valid values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/containers/Form/FormLayout.tsx`:
- Around line 259-271: The query is being skipped when item routes use a
credential shortcode because skip is tied only to itemId; update the useQuery
call for getItemQuery so its skip condition accounts for the credential
shortcode path (i.e., consider the computed variables or listItem ===
'credential' along with itemId). Locate the variables construction (variables,
listItem, itemId, params.type) and change the skip from skip: !itemId to a
condition that is false when variables contains the shortcode (for example skip
only when variables is falsy or when neither itemId nor credential shortcode is
present) so the credential shortcode route triggers the query and initializes
itemData/refetch correctly.

In `@src/containers/HSM/HSMList/HSMList.tsx`:
- Around line 237-248: The try/catch block in the import flow uses direct
destructuring of data.importTemplates which can throw if data is null/undefined
— update the handling in the function using importTemplatesMutation to use
optional chaining when accessing data.importTemplates (e.g., const errors =
data?.importTemplates?.errors) and keep the existing error notification path;
also mirror handleBulkApply by adding a success notification via
setNotification(t('Templates imported successfully'), 'success') when there are
no errors; ensure setImporting(false) remains in the finally block.

In `@src/containers/Trigger/Trigger.tsx`:
- Line 267: Replace the hardcoded error string passed to setTriggerFlowWarning
with an i18next translation key; locate the call in Trigger component
(setTriggerFlowWarning('Failed to validate flow. Please try again.')) and change
it to use the t(...) helper (e.g., t('trigger.validationFailedFallback')) so the
message is extracted, add the corresponding translation key to your source (or
en.json) and run yarn extract-translations to push to Lokalise.

---

Nitpick comments:
In `@src/containers/SettingList/Organization/Organisation.test.tsx`:
- Around line 61-68: Extract a local test helper named renderOrganization that
wraps Organization with MockedProvider and Router to avoid repeating the
render(...) pattern; implement it to accept an optional mocks parameter
defaulting to ORGANIZATION_MOCKS (and optional props if needed), use
MockedProvider, Router and render inside the helper, then replace direct calls
to render(...) in tests (the ones importing render, MockedProvider, Router and
rendering Organization) with calls to renderOrganization(mocks) to consolidate
duplication.

In `@src/containers/SettingList/Organization/Organization.tsx`:
- Line 201: The skip flag currently uses a broad falsy check
(!qualityRatingTier) which hides valid falsy values; update the skip assignment
to only skip when qualityRatingTier is null or undefined (e.g., use
qualityRatingTier == null or qualityRatingTier === undefined) in the
Organization component where skip: !qualityRatingTier is set so 0 or '' remain
valid values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7b4def55-7125-4eb5-a44c-eb6e9bd3fea1

📥 Commits

Reviewing files that changed from the base of the PR and between 750725f and 9b5cc51.

📒 Files selected for processing (8)
  • src/containers/Flow/FlowList/FlowList.tsx
  • src/containers/Form/FormLayout.tsx
  • src/containers/HSM/HSMList/HSMList.tsx
  • src/containers/SettingList/Organization/Organisation.test.tsx
  • src/containers/SettingList/Organization/Organization.tsx
  • src/containers/SettingList/Providers/Providers.tsx
  • src/containers/Trigger/Trigger.tsx
  • src/i18n/en/en.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/containers/SettingList/Providers/Providers.tsx
  • src/containers/Flow/FlowList/FlowList.tsx

…essages in HSMList and Trigger components; add missing translation for flow validation error
@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 05:54 Inactive
@codecov
Copy link
Copy Markdown

codecov bot commented Mar 18, 2026

Codecov Report

❌ Patch coverage is 78.57143% with 42 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.06%. Comparing base (d021984) to head (4709abd).

Files with missing lines Patch % Lines
src/containers/Form/FormLayout.tsx 77.27% 16 Missing and 9 partials ⚠️
src/containers/HSM/HSM.tsx 20.00% 8 Missing ⚠️
src/containers/HSM/HSMList/HSMList.tsx 78.57% 3 Missing and 3 partials ⚠️
src/containers/List/List.tsx 77.77% 1 Missing and 1 partial ⚠️
src/containers/Trigger/Trigger.tsx 88.88% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3845      +/-   ##
==========================================
- Coverage   82.11%   82.06%   -0.06%     
==========================================
  Files         311      311              
  Lines       13126    13122       -4     
  Branches     3039     3040       +1     
==========================================
- Hits        10778    10768      -10     
- Misses       1397     1405       +8     
+ Partials      951      949       -2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 06:02 Inactive
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/containers/HSM/HSMList/HSMList.tsx (1)

237-245: ⚠️ Potential issue | 🟡 Minor

Successful imports still complete silently.

The error path toasts, but the happy path just drops the loading screen. Please restore a success notification so imports behave like bulk apply and sync.

💡 Suggested fix
       try {
         const { data } = await importTemplatesMutation({ variables: { data: result } });
-        const errors = data?.importTemplates?.errors;
-        if (errors && errors.length > 0) {
+        const response = data?.importTemplates;
+        const errors = response?.errors;
+        if (errors?.length) {
           setNotification(t('Error importing templates'), 'warning');
+        } else if (response) {
+          setNotification(t('Templates imported successfully'), 'success');
         }
       } catch {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/HSM/HSMList/HSMList.tsx` around lines 237 - 245, The
importTemplatesMutation success branch currently does not notify the user;
update the try block in HSMList (where importTemplatesMutation is awaited) to
call setNotification with a success message (e.g. t('Templates imported
successfully')) when data?.importTemplates?.errors is empty or undefined,
keeping the existing warning call when errors exist and preserving the catch
warning behavior; ensure you use the same setNotification and i18n t() pattern
as elsewhere so the UI shows a success toast on a successful import.
src/containers/Form/FormLayout.tsx (1)

343-355: ⚠️ Potential issue | 🟠 Major

Credential shortcode routes are still skipped here.

variables switches to { shortcode: params.type } for credentials, but skip is still tied to itemId. On shortcode-only routes the query never runs, so fetchedItem stays null and the form falls through the create path.

💡 Suggested fix
-  let variables: any = itemId ? { [idType]: itemId } : false;
+  let variables: any = itemId ? { [idType]: itemId } : undefined;
   if (listItem === 'credential') {
-    variables = params.type ? { shortcode: params.type } : false;
+    variables = params.type ? { shortcode: params.type } : undefined;
   }
+  const shouldFetchItem = Boolean(variables);

   const { loading, error, data: itemData, refetch } = useQuery(getItemQuery, {
     variables,
-    skip: !itemId,
+    skip: !shouldFetchItem,
     fetchPolicy: getQueryFetchPolicy,
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/Form/FormLayout.tsx` around lines 343 - 355, The query is
being skipped on shortcode-only credential routes because skip is tied only to
itemId; update the logic that builds variables and the skip condition so
getItemQuery runs when either itemId exists or when listItem === 'credential'
and params.type (shortcode) is present. Specifically, ensure the variables
assignment (variables = itemId ? { [idType]: itemId } : false; and the
credential branch variables = params.type ? { shortcode: params.type } : false;)
is preserved and change the useQuery option skip from skip: !itemId to skip:
!(itemId || (listItem === 'credential' && params?.type)), so the query executes
for shortcode routes and fetchedItem is populated.
🧹 Nitpick comments (1)
src/containers/HSM/HSMList/HSMList.tsx (1)

372-384: Restrict the picker to CSVs too.

ImportButton already supports fileType, so passing .csv here prevents unsupported files before FileReader runs and avoids the loading flash for obviously invalid selections.

💡 Suggested refactor
-        <ImportButton title={t('Bulk apply')} onImport={() => setImporting(true)} afterImport={handleBulkApply} />
+        <ImportButton
+          title={t('Bulk apply')}
+          fileType=".csv"
+          onImport={() => setImporting(true)}
+          afterImport={handleBulkApply}
+        />
...
         <ImportButton
           title={t('Import templates')}
+          fileType=".csv"
           onImport={() => setImporting(true)}
           afterImport={handleImportTemplates}
         />
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/HSM/HSMList/HSMList.tsx` around lines 372 - 384, The
ImportButton usage for template import should restrict selectable files to CSVs;
update the ImportButton component(s) (e.g., the instance with title 'Import
templates' in HSMList where setImporting and handleImportTemplates are used) to
pass fileType=".csv" (and also add fileType=".csv" to any other ImportButton
instances used for importing templates such as the 'Bulk apply' ImportButton if
applicable) so the file picker only allows .csv files and prevents unsupported
files before FileReader runs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/containers/Form/FormLayout.tsx`:
- Around line 223-243: The new user-facing strings inside the FormLayout
success/error branch should be localized with i18next: replace hard-coded
messages such as "Failed to compile code. Please check again", the success
message constructed from capitalListItemName ("${capitalListItemName} edited
successfully!"), the copyNotification value usage, and "Your changes have been
autosaved" by wrapping them in t(...) and use interpolation for
capitalListItemName (e.g., t('...',{ name: capitalListItemName })); update
usages around updatedItem.isValid/customError.setErrors, the success branch that
calls setLink/additionalQuery/setFormSubmitted/setNotification, and any similar
strings at the other occurrences mentioned (lines ~264-279 and ~618) so all
user-facing messages are extracted for translation.
- Around line 348-376: The create form is mounting before the USER_LANGUAGES
query (organization) is resolved which causes languageId to start as '' then
flip and can wipe Formik state; update the logic around the organization
useQuery and form initialization so the form (or any Formik reinitialization
that relies on languageId) is gated until organization.data is loaded or
errored: use the existing USER_LANGUAGES query result (the organization const)
to compute a stable isLoadedOrg flag and only initialize the form/state (and
call setStates) when isLoadedOrg is true, surface organization.error to the
UI/error handling path, and ensure languageId returns null (or undefined) rather
than '' before org resolves so Number('') is not sent as 0; adjust the
languageId computation and the useEffect that calls setStates (and any
isLoadedData logic) to depend on organization.data/loading/error and fetchedItem
appropriately.

---

Duplicate comments:
In `@src/containers/Form/FormLayout.tsx`:
- Around line 343-355: The query is being skipped on shortcode-only credential
routes because skip is tied only to itemId; update the logic that builds
variables and the skip condition so getItemQuery runs when either itemId exists
or when listItem === 'credential' and params.type (shortcode) is present.
Specifically, ensure the variables assignment (variables = itemId ? { [idType]:
itemId } : false; and the credential branch variables = params.type ? {
shortcode: params.type } : false;) is preserved and change the useQuery option
skip from skip: !itemId to skip: !(itemId || (listItem === 'credential' &&
params?.type)), so the query executes for shortcode routes and fetchedItem is
populated.

In `@src/containers/HSM/HSMList/HSMList.tsx`:
- Around line 237-245: The importTemplatesMutation success branch currently does
not notify the user; update the try block in HSMList (where
importTemplatesMutation is awaited) to call setNotification with a success
message (e.g. t('Templates imported successfully')) when
data?.importTemplates?.errors is empty or undefined, keeping the existing
warning call when errors exist and preserving the catch warning behavior; ensure
you use the same setNotification and i18n t() pattern as elsewhere so the UI
shows a success toast on a successful import.

---

Nitpick comments:
In `@src/containers/HSM/HSMList/HSMList.tsx`:
- Around line 372-384: The ImportButton usage for template import should
restrict selectable files to CSVs; update the ImportButton component(s) (e.g.,
the instance with title 'Import templates' in HSMList where setImporting and
handleImportTemplates are used) to pass fileType=".csv" (and also add
fileType=".csv" to any other ImportButton instances used for importing templates
such as the 'Bulk apply' ImportButton if applicable) so the file picker only
allows .csv files and prevents unsupported files before FileReader runs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 04f01fed-d61b-4ac1-b683-5d8a5696c020

📥 Commits

Reviewing files that changed from the base of the PR and between 9b5cc51 and 8c98323.

📒 Files selected for processing (4)
  • src/containers/Form/FormLayout.tsx
  • src/containers/HSM/HSMList/HSMList.tsx
  • src/containers/Trigger/Trigger.tsx
  • src/i18n/en/en.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/i18n/en/en.json
  • src/containers/Trigger/Trigger.tsx

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
src/containers/Form/FormLayout.tsx (3)

223-242: ⚠️ Potential issue | 🟡 Minor

Localize the new toast and validation copy.

The literals at Lines 225, 236-242, 266-278, and 623 bypass t(...), so they will not be extracted or translated. Please wrap the local strings in t(...) and interpolate capitalListItemName instead of building English messages inline.

As per coding guidelines, "Use i18next for internationalization with string extraction to Lokalise via yarn extract-translations."

Also applies to: 264-279, 623-623

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/Form/FormLayout.tsx` around lines 223 - 242, The hard-coded
user-facing strings in the success/validation paths need to be wrapped with the
i18next translator and use interpolation instead of concatenation; update the
branches around updatedItem handling (references: customError.setErrors,
setLink, additionalQuery, setFormSubmitted, setNotification, copyNotification,
capitalListItemName) to call t(...) for messages and pass capitalListItemName as
an interpolation variable, and replace the static codeErrors/code message with
t(...) as well so all toast and validation text is extractable for localization.

343-360: ⚠️ Potential issue | 🟠 Major

Shortcode-based credential forms are still skipped.

variables already supports { shortcode: params.type }, but Line 359 still ties the query to itemId. On shortcode-only routes this query never runs, so the form never hydrates from the existing credential.

💡 Suggested fix
-  let variables: any = itemId ? { [idType]: itemId } : false;
+  let variables: any = itemId ? { [idType]: itemId } : undefined;
   if (listItem === 'credential') {
-    variables = params.type ? { shortcode: params.type } : false;
+    variables = params.type ? { shortcode: params.type } : undefined;
   }
+  const shouldFetchItem = Boolean(variables);

   const {
     loading,
     error,
     data: itemData,
     refetch,
   } = useQuery(getItemQuery, {
     variables,
-    skip: !itemId,
+    skip: !shouldFetchItem,
     fetchPolicy: getQueryFetchPolicy,
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/Form/FormLayout.tsx` around lines 343 - 360, The query for
getItemQuery is being skipped when itemId is falsy even though credential forms
can be identified by params.type (shortcode); update the variables and skip
logic so the useQuery runs for shortcode-based credentials: keep the existing
variables assignment (variables = itemId ? { [idType]: itemId } : false; and
variables = params.type ? { shortcode: params.type } : false when listItem ===
'credential') and change the useQuery option skip from skip: !itemId to skip:
!itemId && !(listItem === 'credential' && params.type), ensuring getItemQuery
executes when params.type is present even if itemId is absent.

348-381: ⚠️ Potential issue | 🟠 Major

Hold create-mode rendering until USER_LANGUAGES resolves.

On create routes Line 381 initializes languageId to '' and later replaces it with the org default. With enableReinitialize on Line 389, that can wipe in-progress edits, and the empty state can still be serialized as 0 on submit. organization.error is also ignored right now.

💡 One way to stabilize initialization
   const organization = useQuery(USER_LANGUAGES, {
     skip: !languageSupport,
   });
+  const isOrganizationLoading = languageSupport && !itemId && organization.loading;

   const languageId = fetchedItem
     ? languageSupport
       ? (fetchedItem.language?.id ?? '')
       : null
     : !itemId && organization.data
       ? organization.data.currentUser.user.organization.defaultLanguage.id
-      : '';
+      : undefined;

 ...
-  if (loading) return <Loading />;
+  if (loading || isOrganizationLoading) return <Loading />;
+  if (organization.error) {
+    setErrorMessage(organization.error);
+    return null;
+  }

I’d also avoid serializing languageId until it is a real value; otherwise '' becomes 0 and undefined becomes NaN.

Also applies to: 383-389, 451-455

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/containers/Form/FormLayout.tsx` around lines 348 - 381, The create-mode
can initialize languageId to an empty string before USER_LANGUAGES resolves
which, combined with enableReinitialize, can wipe edits and serialize to invalid
values; change the logic around USER_LANGUAGES/organization and languageId so
the form waits for organization to finish (check organization.loading and
organization.error) before providing a default language, only call
setStates/fetch initialization when fetchedItem or organization is settled, and
keep languageId undefined (not '') until a real id is available; update uses of
languageId, the useEffect that calls setStates, and any enableReinitialize
gating to only run reinitialization when organization.data or fetchedItem is a
real value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/containers/Form/FormLayout.tsx`:
- Around line 297-299: The submit path currently uses isLoadedData (set to
Boolean(fetchedItem)) to decide update vs create, allowing a missing edit record
to fall through to createItem; change this by introducing a distinct "query
resolved for edit" guard (e.g., isEditResolved or hasFetchedItem) and use it in
performTask to block submit when itemId is present but fetchedItem is
null/undefined: if itemId exists and the edit-query has resolved without a
fetchedItem, return or surface a not-found error instead of calling createItem;
ensure the same clear guard replaces uses of isLoadedData in the edit-flow
(including the logic around fetchedItem at lines referenced) so updateItem is
only attempted when fetchedItem exists and createItem only when itemId is
absent.

---

Duplicate comments:
In `@src/containers/Form/FormLayout.tsx`:
- Around line 223-242: The hard-coded user-facing strings in the
success/validation paths need to be wrapped with the i18next translator and use
interpolation instead of concatenation; update the branches around updatedItem
handling (references: customError.setErrors, setLink, additionalQuery,
setFormSubmitted, setNotification, copyNotification, capitalListItemName) to
call t(...) for messages and pass capitalListItemName as an interpolation
variable, and replace the static codeErrors/code message with t(...) as well so
all toast and validation text is extractable for localization.
- Around line 343-360: The query for getItemQuery is being skipped when itemId
is falsy even though credential forms can be identified by params.type
(shortcode); update the variables and skip logic so the useQuery runs for
shortcode-based credentials: keep the existing variables assignment (variables =
itemId ? { [idType]: itemId } : false; and variables = params.type ? {
shortcode: params.type } : false when listItem === 'credential') and change the
useQuery option skip from skip: !itemId to skip: !itemId && !(listItem ===
'credential' && params.type), ensuring getItemQuery executes when params.type is
present even if itemId is absent.
- Around line 348-381: The create-mode can initialize languageId to an empty
string before USER_LANGUAGES resolves which, combined with enableReinitialize,
can wipe edits and serialize to invalid values; change the logic around
USER_LANGUAGES/organization and languageId so the form waits for organization to
finish (check organization.loading and organization.error) before providing a
default language, only call setStates/fetch initialization when fetchedItem or
organization is settled, and keep languageId undefined (not '') until a real id
is available; update uses of languageId, the useEffect that calls setStates, and
any enableReinitialize gating to only run reinitialization when
organization.data or fetchedItem is a real value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a6aec6a8-6f49-48d5-8638-8d5307fe043b

📥 Commits

Reviewing files that changed from the base of the PR and between 8c98323 and eddb8a7.

📒 Files selected for processing (2)
  • src/containers/Form/FormLayout.tsx
  • src/containers/Trigger/Trigger.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/containers/Trigger/Trigger.tsx

…ist component by removing unused import and import templates logic; fix formatting in SettingList test helper
@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 06:38 Inactive
@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 06:47 Inactive
@github-actions github-actions bot temporarily deployed to pull request March 18, 2026 07:15 Inactive
@github-actions github-actions bot temporarily deployed to pull request March 23, 2026 02:42 Inactive
@akanshaaa19 akanshaaa19 requested a review from mdshamoon March 23, 2026 03:04
@github-actions github-actions bot temporarily deployed to pull request March 23, 2026 03:09 Inactive
@akanshaaa19 akanshaaa19 requested a review from rvignesh89 March 23, 2026 09:34
@github-actions github-actions bot temporarily deployed to pull request March 26, 2026 06:33 Inactive
Copy link
Copy Markdown
Member

@mdshamoon mdshamoon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check the following comments. Rest looks good

const handleImport = async (result: string) => {
try {
const { data } = await importFlow({ variables: { flow: result } });
const { status } = data.importFlow;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we sure status will always be there?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yess


const handleUpdateCompleted = (data: any, isSaveClick: boolean) => {
setShowConfirmationDialog(false);
let itemUpdatedObject: any = Object.keys(data)[0];
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we sure in all cases we will get it in the first key. Sometimes we also get __typename

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is how it was done earlier also see line 353 in the old code

Comment on lines +229 to +253
if (errors) {
if (customHandler) {
customHandler(errors);
} else {
setErrorMessage(errors[0]);
}
} else if (updatedItem && typeof updatedItem.isValid === 'boolean' && !updatedItem.isValid) {
if (customError) {
const codeErrors = { code: 'Failed to compile code. Please check again' };
customError.setErrors(codeErrors);
}
} else {
if (type === 'copy') setLink(updatedItem[linkParameter]);
if (additionalQuery) {
additionalQuery(itemId);
}

if (saveOnPageChange || isSaveClick) {
setFormSubmitted(true);
let notificationMessage = `${capitalListItemName} edited successfully!`;
if (type === 'copy') {
notificationMessage = copyNotification;
}
setNotification(notificationMessage);
} else {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We havent touched this code base in a long time. See if these conditions can be optimized.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can pick this later #3870

@codacy-production
Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 2 high · 1 medium

Alerts:
⚠ 3 issues (≤ 0 issues of at least minor severity)

Results:
3 new issues

Category Results
BestPractice 1 medium
1 high
ErrorProne 1 high

View in Codacy

🟢 Metrics 1 complexity

Metric Results
Complexity 1

View in Codacy

TIP This summary will be updated as you push new changes. Give us feedback

@github-actions github-actions bot temporarily deployed to pull request April 6, 2026 03:26 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Upgrade apollo to latest versions

2 participants