Skip to content

get element names from directory server#1095

Merged
thangqp merged 13 commits into
mainfrom
get-element-names
May 12, 2026
Merged

get element names from directory server#1095
thangqp merged 13 commits into
mainfrom
get-element-names

Conversation

@carojeandat
Copy link
Copy Markdown
Contributor

PR Summary

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 13, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cdfa661f-67e1-4b3b-818c-3eea6003f2ae

📥 Commits

Reviewing files that changed from the base of the PR and between 632ccfd and 218419e.

📒 Files selected for processing (3)
  • src/components/parameters/common/contingency-table/columns-definitions.ts
  • src/components/parameters/common/contingency-table/contingency-table.tsx
  • src/components/parameters/common/contingency-table/types.ts
✅ Files skipped from review due to trivial changes (1)
  • src/components/parameters/common/contingency-table/contingency-table.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/parameters/common/contingency-table/columns-definitions.ts
  • src/components/parameters/common/contingency-table/types.ts

📝 Walkthrough

Walkthrough

Enriched parameter variants were introduced across contingency, PCC‑Min, sensitivity, and security domains. Services now enrich fetched ID-only parameters with element names via a directory lookup; UI hooks/components consume enriched types and map enriched form data back to ID-only payloads when calling backend update endpoints. A directory name lookup and PCC‑Min / sensitivity type utilities were added and re-exported.

Changes

Contingency Table Types & Wiring

Layer / File(s) Summary
Data Shape
src/components/parameters/common/contingency-table/types.ts
Adds ContingencyListsInfosEnriched ([CONTINGENCY_LISTS]: IdName[]) and keeps ContingencyListsInfos as ID-only (UUID[]).
Conversion Utility
src/components/parameters/common/contingency-table/columns-definitions.ts
toFormValuesContingencyListsInfos now accepts ContingencyListsInfosEnriched[] and maps entries to the same form shape.
Component Usage
src/components/parameters/common/contingency-table/contingency-table.tsx
Component treats form getValues results as ContingencyListsInfosEnriched[] for contingency-count effects.

PCC‑Min Parameters

Layer / File(s) Summary
New Types & Transforms
src/utils/types/pcc-min.type.ts
Introduces PccMinParametersEnriched (filters as FilterIdentifier[]), ID-only PccMinParameters (filters as UUID[]), mapPccMinParameters and enrichPccMinParameters (uses fetchElementNames).
Form Mappings
src/components/parameters/pcc-min/pcc-min-form-utils.ts
Adds fromPccMinParametersFormToParamValuesEnriched and preserves fromPccMinParametersFormToParamValues which returns the ID-array payload.
Component Props / Wiring
src/components/parameters/pcc-min/pcc-min-parameters-inline.tsx, src/components/parameters/pcc-min/use-pcc-min-parameters-form.ts
Props and hook types updated to PccMinParametersEnriched; inline-save uses enriched conversion and then maps to ID-only for update.
Service Layer
src/services/pcc-min.ts
Fetch/get now return enriched form via enrichPccMinParameters; update serializes with mapPccMinParameters when sending to backend.

Sensitivity Analysis Parameters

Layer / File(s) Summary
Generic Data Shape
src/utils/types/sensitivity-analysis.type.ts
Refactors sensitivity types to be generic over equipment info, adds SensitivityAnalysisParametersInfosEnriched (enriched containers) and ID-only alias, plus mapSensitivityAnalysisParameters and enrichSensitivityAnalysisParameters.
Service Enrichment
src/services/sensitivity-analysis.ts
Fetch/get return enriched parameters via enrichSensitivityAnalysisParameters; setters and factor-count calls serialize with mapSensitivityAnalysisParameters.
Form / Hook Wiring
src/components/parameters/sensi/use-sensitivity-analysis-parameters.ts
Hook API and return types updated to enriched types; save path maps enriched -> ID-only before update.
Component Usage
src/components/parameters/sensi/sensitivity-analysis-parameters-inline.tsx
Promise handlers typed to enriched infos; CreateParameterDialog formatting maps enriched -> ID-only payloads.

Security Analysis Parameters

Layer / File(s) Summary
Types & Helpers
src/components/parameters/security-analysis/types.ts
Converts SAParameters to a type, adds SAParametersEnriched, mapSecurityAnalysisParameters, and enrichSecurityAnalysisParameters.
Conversion Utility
src/components/parameters/security-analysis/columns-definitions.ts
toFormValueSaParameters now accepts SAParametersEnriched.
Service Layer
src/services/security-analysis.ts
Fetch/get return enriched parameters via enrichSecurityAnalysisParameters; set/update serialize with mapSecurityAnalysisParameters.
Form / Component Wiring
src/components/parameters/security-analysis/use-security-analysis-parameters-form.ts, src/components/parameters/security-analysis/security-analysis-parameters-inline.tsx, src/components/parameters/security-analysis/security-analysis-parameters-selector.tsx
Hooks and components updated to accept enriched types; save/update paths map enriched -> ID-only before sending.

Directory Service & Utility Re-exports

Layer / File(s) Summary
Name Lookup Service
src/services/directory.ts
Adds exported fetchElementNames(elementUuids: Set<string>) which queries /v1/explore/elements/name with repeated ids params and returns backend JSON.
Services Index
src/services/index.ts
Re-exports ./sensitivity-analysis.
Types Re-exports
src/utils/types/index.ts
Re-exports ./pcc-min.type to expose PCC‑Min types/transforms.
Parameters Conditional Types
src/utils/types/parameters.type.ts
ParametersInfos<T> mapping now resolves sensitivity and security branches to their enriched variants for the corresponding computing types.

Sequence Diagram(s)

sequenceDiagram
    participant UI as Client UI
    participant Hook as Form Hook
    participant Svc as Service
    participant Dir as Directory Service
    participant BE as Backend API

    UI->>Hook: request load parameters (uuid)
    Hook->>Svc: fetchParameters(uuid)
    Svc->>BE: GET /parameters/:uuid
    BE-->>Svc: returns ID-only parameters
    Svc->>Dir: fetchElementNames(setOfIds) (if any)
    Dir->>BE: GET /v1/explore/elements/name?ids=...
    BE-->>Dir: element id->name map
    Dir-->>Svc: element names
    Svc-->>Hook: enriched parameters (IDs + names)
    Hook-->>UI: reset form with enriched values
    UI->>Hook: save form
    Hook->>Hook: formatNewParams(formData) -> enriched shape
    Hook->>Svc: updateParameter(uuid, mapToIdOnly(enriched))
    Svc->>BE: PUT /parameters/:uuid with ID-only payload
    BE-->>Svc: ack
    Svc-->>Hook: result
Loading

Suggested reviewers

  • achour94
  • antoinebhs
  • khouadrired
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description provided is empty/placeholder text with no meaningful details about the changes, making it impossible to assess relevance to the changeset. Provide a non-empty description explaining the changes, their purpose, and any important context for reviewers.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'get element names from directory server' directly and clearly summarizes the main technical change: adding functionality to fetch element names from a directory server.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


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.

@carojeandat carojeandat marked this pull request as ready for review April 15, 2026 14:57
# Conflicts:
#	src/components/parameters/common/contingency-table/columns-definitions.ts
#	src/components/parameters/common/contingency-table/contingency-table.tsx
#	src/components/parameters/security-analysis/use-security-analysis-parameters-form.ts
#	src/components/parameters/sensi/use-sensitivity-analysis-parameters.ts
#	src/utils/types/parameters.type.ts
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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/components/parameters/common/contingency-table/contingency-table.tsx (1)

89-93: ⚠️ Potential issue | 🟡 Minor

flatMap callback may return undefined.

lists[CONTINGENCY_LISTS]?.map(...) can evaluate to undefined, which flatMap treats as a single non-array element, yielding undefined entries in the resulting UUID[] passed to fetchContingencyCount. Since CONTINGENCY_LISTS on ContingencyListsInfosEnriched is required (IdName[]), drop the optional chaining, or guard with ?? [].

🔧 Proposed fix
-                .flatMap((lists) => lists[CONTINGENCY_LISTS]?.map((contingencyList) => contingencyList[ID])),
+                .flatMap((lists) => (lists[CONTINGENCY_LISTS] ?? []).map((contingencyList) => contingencyList[ID])),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/parameters/common/contingency-table/contingency-table.tsx`
around lines 89 - 93, The callback passed to flatMap can return undefined
because of the optional chain on lists[CONTINGENCY_LISTS]; update the expression
that builds the UUID[] for fetchContingencyCount to guarantee an array by
removing the optional chaining or coalescing to an empty array (e.g., use
lists[CONTINGENCY_LISTS] or lists[CONTINGENCY_LISTS] ?? []) so flatMap always
receives an array of map results; adjust the call site referencing
contingencyListsInfos, ACTIVATED, CONTINGENCY_LISTS, and ID accordingly to
ensure no undefined values are produced.
src/services/sensitivity-analysis.ts (1)

98-109: ⚠️ Potential issue | 🟡 Minor

Tighten type and fix misleading log message.

Two issues on this function:

  1. newParams: any bypasses the enriched-type contract enforced elsewhere. Since body calls mapSensitivityAnalysisParameters(newParams), the parameter should be typed as SensitivityAnalysisParametersInfosEnriched | null to match backendUpdateParameters in ParametersInfos<SENSITIVITY_ANALYSIS>.
  2. The log reads 'set security analysis parameters' — copy-paste from the security-analysis service. It should reference sensitivity analysis.
🛠 Proposed fix
-export function updateSensitivityAnalysisParameters(parameterUuid: UUID, newParams: any) {
-    console.info('set security analysis parameters');
-    const setSecurityAnalysisParametersUrl = `${getSensiUrl()}parameters/${parameterUuid}`;
-    console.debug(setSecurityAnalysisParametersUrl);
-    return backendFetch(setSecurityAnalysisParametersUrl, {
+export function updateSensitivityAnalysisParameters(
+    parameterUuid: UUID,
+    newParams: SensitivityAnalysisParametersInfosEnriched | null
+) {
+    console.info('set sensitivity analysis parameters');
+    const url = `${getSensiUrl()}parameters/${parameterUuid}`;
+    console.debug(url);
+    return backendFetch(url, {
         method: 'PUT',
         headers: {
             Accept: 'application/json',
             'Content-Type': 'application/json',
         },
         body: newParams ? JSON.stringify(mapSensitivityAnalysisParameters(newParams)) : null,
     });
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/services/sensitivity-analysis.ts` around lines 98 - 109, The function
updateSensitivityAnalysisParameters currently accepts newParams: any and logs a
misleading message; change the parameter type to
SensitivityAnalysisParametersInfosEnriched | null (matching
backendUpdateParameters / ParametersInfos<SENSITIVITY_ANALYSIS>) and ensure the
body still calls mapSensitivityAnalysisParameters(newParams) when non-null, and
update the console.info message from 'set security analysis parameters' to
something like 'set sensitivity analysis parameters' so the log matches the
function purpose; adjust any imports/types if needed to reference
SensitivityAnalysisParametersInfosEnriched and keep the existing backendFetch
call intact.
src/utils/types/sensitivity-analysis.type.ts (1)

23-26: ⚠️ Potential issue | 🟡 Minor

containerName should allow null to match enrichment behavior.

enrichSensitivityAnalysisParameters writes containerName: elementNames?.[id] ?? null (line 224), but the interface declares containerName: string. Any consumer reading these values (e.g., UI renderers, form defaults) that has been strictly typed on EquipmentsContainer will be working against a lie when the directory lookup fails to return a name. Either widen the field or default to ''.

🛡️ Suggested fix
 interface EquipmentsContainer {
     containerId: string;
-    containerName: string;
+    containerName: string | null;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/types/sensitivity-analysis.type.ts` around lines 23 - 26, The
EquipmentsContainer interface currently declares containerName as string but
enrichSensitivityAnalysisParameters sets containerName to elementNames?.[id] ??
null, so update the type to reflect actual values by changing
EquipmentsContainer.containerName to string | null (or alternatively change
enrichSensitivityAnalysisParameters to default to ''), and ensure any consumers
handle the nullable case; reference the EquipmentsContainer interface and
enrichSensitivityAnalysisParameters function when making the change.
🧹 Nitpick comments (8)
src/components/parameters/security-analysis/types.ts (1)

51-56: Misleading helper name.

getEquipmentsContainerIds does not deal with equipment containers — it extracts contingency list IDs. Rename (e.g. getContingencyListIds) to match the domain and avoid copy-paste confusion.

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

In `@src/components/parameters/security-analysis/types.ts` around lines 51 - 56,
Rename the misleading helper function getEquipmentsContainerIds to
getContingencyListIds across the module and update all references; the function
currently takes SAParameters and reads
params.contingencyListsInfos.flatMap((cli) => cli.contingencyLists ?? []) to
build the Set of contingency list IDs, so keep the implementation but change the
function identifier (and any exported/imported names) to getContingencyListIds
and adjust any typings/usages to match the new name to avoid copy-paste
confusion.
src/utils/types/pcc-min.type.ts (1)

29-47: Duplication with enrichSecurityAnalysisParameters.

The enrichment pattern (collect UUIDs → fetchElementNames → map IDs to {id, name}) is repeated almost verbatim here and in src/components/parameters/security-analysis/types.ts. Consider extracting a generic helper (e.g. enrichIdsWithNames(ids: Set<UUID>): Promise<Record<UUID, string> | null>) to reduce drift as more parameter types adopt the pattern.

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

In `@src/utils/types/pcc-min.type.ts` around lines 29 - 47, enrichPccMinParameters
duplicates the pattern used in enrichSecurityAnalysisParameters (collect UUIDs
-> fetchElementNames -> map ids to {filterId, filterName}); extract a shared
helper (e.g. enrichIdsWithNames or fetchNamesForIds) that takes a Set<UUID> or
UUID[] and returns Promise<Record<UUID,string>|null>, then replace the local
call to fetchElementNames/getFilterIdentifierIds in enrichPccMinParameters and
in enrichSecurityAnalysisParameters to use that helper; update the mapping logic
in enrichPccMinParameters (the mapIdsToFilterIdentifiers closure that uses
FILTERS and getFilterIdentifierIds) to consume the helper's result
(elementNames) instead of calling fetchElementNames directly so both functions
share the same enrichment path.
src/services/directory.ts (1)

79-91: Missing return type and inconsistent log level.

fetchElementNames returns Promise<any>, which propagates untyped data into enrichPccMinParameters / enrichSecurityAnalysisParameters (where elementNames?.[id] is indexed blindly). Declare the expected backend shape (a UUID → name mapping) so consumers get compile-time safety. Also, console.log is inconsistent with the rest of this file, which uses console.debug for URLs.

🔧 Proposed fix
-export function fetchElementNames(elementUuids: Set<string>) {
+export function fetchElementNames(elementUuids: Set<string>): Promise<Record<UUID, string>> {
     console.info('fetch directory element names');

     const params = new URLSearchParams();
     elementUuids.forEach((id) => {
         params.append('ids', id);
     });

     const url = `${PREFIX_EXPLORE_SERVER_QUERIES}/v1/explore/elements/name?${params.toString()}`;
-    console.log(url);
+    console.debug(url);

     return backendFetchJson(url);
 }

Please confirm the actual response shape returned by GET /v1/explore/elements/name?ids=... (e.g. { [uuid]: name } vs array of {id, name}); the current consumers assume the former via elementNames?.[id].

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

In `@src/services/directory.ts` around lines 79 - 91, fetchElementNames currently
returns untyped Promise<any> and uses console.log for the URL; declare and
return the concrete backend shape (e.g. Promise<Record<string, string>> if the
API returns a mapping UUID→name, or adjust to
Promise<Array<{id:string,name:string}>> and convert to a Record if the API
returns an array) so callers like
enrichPccMinParameters/enrichSecurityAnalysisParameters can index safely, and
replace the console.log(url) with console.debug(url) for consistency; update the
fetchElementNames signature and the call to backendFetchJson (and add a small
mapping step if needed) to ensure compile-time safety and correct runtime shape.
src/components/parameters/pcc-min/pcc-min-form-utils.ts (1)

26-42: Consolidate the two identical form-value converters.

fromPccMinParamsDataToFormValues and fromStudyPccMinParamsDataToFormValues have identical signatures and bodies. Either drop the study-specific variant and reuse the generic one at call sites, or have one delegate to the other to avoid divergence. This matches SonarCloud's warning on line 36.

♻️ Proposed refactor
 export const fromPccMinParamsDataToFormValues = (parameters: PccMinParametersEnriched | null): Record<string, any> => ({
     [FILTERS]:
         parameters?.[FILTERS]?.map((filter) => ({
             [ID]: filter[FILTER_ID],
             [NAME]: filter[FILTER_NAME],
         })) ?? [],
 });

-export const fromStudyPccMinParamsDataToFormValues = (
-    parameters: PccMinParametersEnriched | null
-): Record<string, any> => ({
-    [FILTERS]:
-        parameters?.[FILTERS]?.map((filter) => ({
-            [ID]: filter[FILTER_ID],
-            [NAME]: filter[FILTER_NAME],
-        })) ?? [],
-});
+export const fromStudyPccMinParamsDataToFormValues = fromPccMinParamsDataToFormValues;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/parameters/pcc-min/pcc-min-form-utils.ts` around lines 26 -
42, The two functions fromPccMinParamsDataToFormValues and
fromStudyPccMinParamsDataToFormValues are identical; remove duplication by
keeping one canonical implementation (e.g., fromPccMinParamsDataToFormValues)
and update usages of fromStudyPccMinParamsDataToFormValues to call/delegate to
the canonical function (or replace call sites to use
fromPccMinParamsDataToFormValues directly); ensure the exported API stays
compatible by either exporting the alias (export const
fromStudyPccMinParamsDataToFormValues = fromPccMinParamsDataToFormValues) or
removing the duplicate export and refactoring call sites accordingly, preserving
the same parameter signature and return shape.
src/utils/types/sensitivity-analysis.type.ts (2)

125-282: Significant code duplication across map* and enrich* helpers.

Each of the 5 sensitivity sub-structures repeats nearly identical map/enrich logic in both mapSensitivityAnalysisParameters and enrichSensitivityAnalysisParameters. Consider driving them from a small field-list descriptor keyed by structure name to reduce surface area and future drift (e.g., a new field missed in one branch but not the other).

♻️ Sketch
const SUBSTRUCT_FIELDS = {
    sensitivityInjectionsSet: ['monitoredBranches', 'injections', 'contingencies'],
    sensitivityInjection:     ['monitoredBranches', 'injections', 'contingencies'],
    sensitivityHVDC:          ['monitoredBranches', 'hvdcs', 'contingencies'],
    sensitivityPST:           ['monitoredBranches', 'psts', 'contingencies'],
    sensitivityNodes:         ['monitoredVoltageLevels', 'equipmentsInVoltageRegulation', 'contingencies'],
} as const;

Iterate over that descriptor in both map and enrich to apply the same field-level transform.

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

In `@src/utils/types/sensitivity-analysis.type.ts` around lines 125 - 282, The
code duplicates nearly identical mapping/enrichment logic across
mapSensitivityAnalysisParameters and enrichSensitivityAnalysisParameters for the
five sensitivity sub-structures; refactor by introducing a shared descriptor
(e.g., const SUBSTRUCT_FIELDS = { sensitivityInjectionsSet:
['monitoredBranches','injections','contingencies'], sensitivityInjection: [...],
sensitivityHVDC: [...], sensitivityPST: [...], sensitivityNodes: [...] } as
const) and iterate over its entries in both functions to apply the appropriate
transform (use the existing helper mapEquipmentsContainerToIds in
mapSensitivityAnalysisParameters and mapIdsToEquipmentsContainer /
fetchElementNames flow in enrichSensitivityAnalysisParameters), dispatching
per-field transforms by name to eliminate the repeated per-structure blocks
while preserving existing return shapes and null/empty-array fallbacks.

128-130: Unsafe as UUID[] cast.

containerId is typed as string, not UUID. The as UUID[] cast silently accepts any string shape. Since downstream types (SensitivityAnalysisParameters<UUID>) rely on this invariant, prefer either typing containerId as UUID on EquipmentsContainer (since it always originates from a UUID in the backend) or validating the id before casting.

 interface EquipmentsContainer {
-    containerId: string;
+    containerId: UUID;
     containerName: string | null;
 }

Then mapEquipmentsContainerToIds no longer needs the cast.

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

In `@src/utils/types/sensitivity-analysis.type.ts` around lines 128 - 130, The
mapEquipmentsContainerToIds function currently force-casts strings to UUID[];
change the source typing or validate instead: update the EquipmentsContainer
type's containerId from string to UUID so mapEquipmentsContainerToIds can simply
return containers?.map(c => c.containerId) without an unsafe as-cast, and ensure
SensitivityAnalysisParameters<UUID> consumers remain consistent; alternatively,
if you cannot change the model, add a validation step inside
mapEquipmentsContainerToIds to parse/validate each c.containerId as a UUID and
only return validated ids (or throw/skip invalid ones) rather than using the as
UUID[] cast.
src/components/parameters/pcc-min/use-pcc-min-parameters-form.ts (1)

86-117: Inconsistent error-handling helper between inline and dialog save paths.

onSaveInline calls snackError directly while onSaveDialog uses snackWithFallback. For consistency (and to benefit from the fallback message when error.message is missing), consider using snackWithFallback in both branches.

♻️ Proposed tweak
-                updatePccMinParameters(studyUuid, fromPccMinParametersFormToParamValuesEnriched(formData)).catch(
-                    (error) => {
-                        snackError({
-                            messageTxt: error.message,
-                            headerId: 'updatePccMinParametersError',
-                        });
-                    }
-                );
+                updatePccMinParameters(studyUuid, fromPccMinParametersFormToParamValuesEnriched(formData)).catch(
+                    (error) => {
+                        snackWithFallback(snackError, error, { headerId: 'updatePccMinParametersError' });
+                    }
+                );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/parameters/pcc-min/use-pcc-min-parameters-form.ts` around
lines 86 - 117, The inline save path in onSaveInline uses snackError directly
while onSaveDialog uses snackWithFallback; change onSaveInline's catch to call
snackWithFallback(snackError, error, { headerId: 'updatePccMinParametersError'
}) so it mirrors the dialog behavior and provides fallback messaging, and update
the useCallback dependency array for onSaveInline to include snackWithFallback
(in addition to snackError and studyUuid) to avoid stale closures.
src/components/parameters/sensi/use-sensitivity-analysis-parameters.ts (1)

447-462: mapSensitivityAnalysisParameters wrap before updateParameter is the right asymmetry.

The generic updateParameter service cannot know the enriched shape, so converting here is correct. Note the intentional asymmetry with onSaveInline at line 435, where setSensitivityAnalysisParameters performs the mapping internally — worth a brief JSDoc on the service (or the hook) to make that contract explicit for future callers.

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

In `@src/components/parameters/sensi/use-sensitivity-analysis-parameters.ts`
around lines 447 - 462, The code is correct to call
mapSensitivityAnalysisParameters before updateParameter (the generic
updateParameter expects the enriched shape already), but the asymmetry with
onSaveInline (which lets setSensitivityAnalysisParameters do the mapping) should
be documented; add a brief JSDoc on the updateParameter service (or on the hook
that wraps it) describing the contract: updateParameter expects
already-mapped/enriched parameter payloads (caller responsibility), and note
that setSensitivityAnalysisParameters performs mapping internally while
onSaveDialog must call mapSensitivityAnalysisParameters first; reference
mapSensitivityAnalysisParameters, updateParameter, onSaveInline, and
setSensitivityAnalysisParameters in the comment.
🤖 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/components/parameters/security-analysis/types.ts`:
- Around line 63-72: The mapIdsToIdNames closure returns IdName objects with
[NAME] possibly set to null which violates IdName.name:string; update
mapIdsToIdNames in the elementNamesPromise.then block to coerce
elementNames?.[id] to a string (e.g., elementNames?.[id] ?? '') so [NAME] is
always a string, preserving the IdName type (alternatively, if you prefer a type
change, update the IdName declaration to allow string | null across usages, but
the quick fix is to use the empty-string fallback).

In `@src/services/directory.ts`:
- Around line 79-91: fetchElementNames currently builds a long GET URL by
appending many ids query params which can hit 414 limits; change
fetchElementNames to send the UUIDs in the request body instead (POST) or
implement client-side batching: build an array from elementUuids and call the
same endpoint with a POST to
`${PREFIX_EXPLORE_SERVER_QUERIES}/v1/explore/elements/name` using JSON body {
ids: [...] } and Content-Type: application/json (or, if POST is not allowed,
split elementUuids into chunks and perform multiple GET requests and merge
results). Update the call site to use backendFetchJson with method:'POST',
appropriate headers and JSON.stringify(body) (or loop over chunks and aggregate
responses) and keep function name fetchElementNames unchanged.

In `@src/services/pcc-min.ts`:
- Around line 18-32: The enrichment step can throw (fetchElementNames failure)
and currently bubbles up, so wrap the call to enrichPccMinParameters in a
rejection handler and return a sensible fallback so the base parameters still
resolve; specifically, in both getPccMinStudyParameters and
fetchPccMinParameters replace the direct .then(enrichPccMinParameters) with
.then(params => { try { return enrichPccMinParameters(params); } catch (err) {
return enrichPccMinParameters({ ...params, elementNames: {} }); } }) or
equivalent Promise.catch-based logic that catches enrichment errors and returns
the original parameters enriched with an empty elementNames map (reference
enrichPccMinParameters and the fact it calls fetchElementNames) so the form can
render even if fetchElementNames fails.

In `@src/utils/types/pcc-min.type.ts`:
- Around line 34-47: The mapIdsToFilterIdentifiers closure returns filterName as
elementNames?.[id] ?? null which can be null but FilterIdentifier.filterName is
declared as string; change the code so filterName is always a string (e.g.
elementNames?.[id] ?? id or elementNames?.[id] ?? '') or update the
FilterIdentifier type to allow string | null; locate the mapper in the
elementNamesPromise.then block (mapIdsToFilterIdentifiers, FILTERS,
FilterIdentifier) and implement the chosen fix consistently so the returned
object matches the FilterIdentifier definition.
- Around line 11-23: mapPccMinParameters uses optional chaining on a field that
the input type PccMinParametersEnriched marks as required, which can yield
undefined for the required PccMinParameters[FILTERS]; fix by ensuring FILTERS is
always an array: in mapPccMinParameters convert parametersInfos.filters to an
array (e.g. parametersInfos.filters ? parametersInfos.filters.map(f =>
f.filterId) : []) or remove the optional chaining and rely on the required type
(parametersInfos.filters.map(...)); reference mapPccMinParameters,
PccMinParametersEnriched, PccMinParameters and FILTERS when changing the
implementation or types.

In `@src/utils/types/sensitivity-analysis.type.ts`:
- Around line 219-281: The enrichSensitivityAnalysisParameters function
currently coerces undefined sensitivity sub-fields into empty arrays (e.g.,
sensitivityInjectionsSet, sensitivityInjection, sensitivityHVDC, sensitivityPST,
sensitivityNodes) by using ternaries that return []; change these to preserve
undefined using optional chaining or nullish checks so the function returns
undefined when the input was undefined (mirroring
mapSensitivityAnalysisParameters). Specifically, update the mapping logic that
uses mapIdsToEquipmentsContainer and the ternary patterns on
parameters.sensitivityInjectionsSet, parameters.sensitivityInjection,
parameters.sensitivityHVDC, parameters.sensitivityPST, and
parameters.sensitivityNodes to use optional chaining (e.g.,
parameters.sensitivityInjectionsSet?.map(...)) or return undefined instead of []
so round-trip semantics are preserved.

---

Outside diff comments:
In `@src/components/parameters/common/contingency-table/contingency-table.tsx`:
- Around line 89-93: The callback passed to flatMap can return undefined because
of the optional chain on lists[CONTINGENCY_LISTS]; update the expression that
builds the UUID[] for fetchContingencyCount to guarantee an array by removing
the optional chaining or coalescing to an empty array (e.g., use
lists[CONTINGENCY_LISTS] or lists[CONTINGENCY_LISTS] ?? []) so flatMap always
receives an array of map results; adjust the call site referencing
contingencyListsInfos, ACTIVATED, CONTINGENCY_LISTS, and ID accordingly to
ensure no undefined values are produced.

In `@src/services/sensitivity-analysis.ts`:
- Around line 98-109: The function updateSensitivityAnalysisParameters currently
accepts newParams: any and logs a misleading message; change the parameter type
to SensitivityAnalysisParametersInfosEnriched | null (matching
backendUpdateParameters / ParametersInfos<SENSITIVITY_ANALYSIS>) and ensure the
body still calls mapSensitivityAnalysisParameters(newParams) when non-null, and
update the console.info message from 'set security analysis parameters' to
something like 'set sensitivity analysis parameters' so the log matches the
function purpose; adjust any imports/types if needed to reference
SensitivityAnalysisParametersInfosEnriched and keep the existing backendFetch
call intact.

In `@src/utils/types/sensitivity-analysis.type.ts`:
- Around line 23-26: The EquipmentsContainer interface currently declares
containerName as string but enrichSensitivityAnalysisParameters sets
containerName to elementNames?.[id] ?? null, so update the type to reflect
actual values by changing EquipmentsContainer.containerName to string | null (or
alternatively change enrichSensitivityAnalysisParameters to default to ''), and
ensure any consumers handle the nullable case; reference the EquipmentsContainer
interface and enrichSensitivityAnalysisParameters function when making the
change.

---

Nitpick comments:
In `@src/components/parameters/pcc-min/pcc-min-form-utils.ts`:
- Around line 26-42: The two functions fromPccMinParamsDataToFormValues and
fromStudyPccMinParamsDataToFormValues are identical; remove duplication by
keeping one canonical implementation (e.g., fromPccMinParamsDataToFormValues)
and update usages of fromStudyPccMinParamsDataToFormValues to call/delegate to
the canonical function (or replace call sites to use
fromPccMinParamsDataToFormValues directly); ensure the exported API stays
compatible by either exporting the alias (export const
fromStudyPccMinParamsDataToFormValues = fromPccMinParamsDataToFormValues) or
removing the duplicate export and refactoring call sites accordingly, preserving
the same parameter signature and return shape.

In `@src/components/parameters/pcc-min/use-pcc-min-parameters-form.ts`:
- Around line 86-117: The inline save path in onSaveInline uses snackError
directly while onSaveDialog uses snackWithFallback; change onSaveInline's catch
to call snackWithFallback(snackError, error, { headerId:
'updatePccMinParametersError' }) so it mirrors the dialog behavior and provides
fallback messaging, and update the useCallback dependency array for onSaveInline
to include snackWithFallback (in addition to snackError and studyUuid) to avoid
stale closures.

In `@src/components/parameters/security-analysis/types.ts`:
- Around line 51-56: Rename the misleading helper function
getEquipmentsContainerIds to getContingencyListIds across the module and update
all references; the function currently takes SAParameters and reads
params.contingencyListsInfos.flatMap((cli) => cli.contingencyLists ?? []) to
build the Set of contingency list IDs, so keep the implementation but change the
function identifier (and any exported/imported names) to getContingencyListIds
and adjust any typings/usages to match the new name to avoid copy-paste
confusion.

In `@src/components/parameters/sensi/use-sensitivity-analysis-parameters.ts`:
- Around line 447-462: The code is correct to call
mapSensitivityAnalysisParameters before updateParameter (the generic
updateParameter expects the enriched shape already), but the asymmetry with
onSaveInline (which lets setSensitivityAnalysisParameters do the mapping) should
be documented; add a brief JSDoc on the updateParameter service (or on the hook
that wraps it) describing the contract: updateParameter expects
already-mapped/enriched parameter payloads (caller responsibility), and note
that setSensitivityAnalysisParameters performs mapping internally while
onSaveDialog must call mapSensitivityAnalysisParameters first; reference
mapSensitivityAnalysisParameters, updateParameter, onSaveInline, and
setSensitivityAnalysisParameters in the comment.

In `@src/services/directory.ts`:
- Around line 79-91: fetchElementNames currently returns untyped Promise<any>
and uses console.log for the URL; declare and return the concrete backend shape
(e.g. Promise<Record<string, string>> if the API returns a mapping UUID→name, or
adjust to Promise<Array<{id:string,name:string}>> and convert to a Record if the
API returns an array) so callers like
enrichPccMinParameters/enrichSecurityAnalysisParameters can index safely, and
replace the console.log(url) with console.debug(url) for consistency; update the
fetchElementNames signature and the call to backendFetchJson (and add a small
mapping step if needed) to ensure compile-time safety and correct runtime shape.

In `@src/utils/types/pcc-min.type.ts`:
- Around line 29-47: enrichPccMinParameters duplicates the pattern used in
enrichSecurityAnalysisParameters (collect UUIDs -> fetchElementNames -> map ids
to {filterId, filterName}); extract a shared helper (e.g. enrichIdsWithNames or
fetchNamesForIds) that takes a Set<UUID> or UUID[] and returns
Promise<Record<UUID,string>|null>, then replace the local call to
fetchElementNames/getFilterIdentifierIds in enrichPccMinParameters and in
enrichSecurityAnalysisParameters to use that helper; update the mapping logic in
enrichPccMinParameters (the mapIdsToFilterIdentifiers closure that uses FILTERS
and getFilterIdentifierIds) to consume the helper's result (elementNames)
instead of calling fetchElementNames directly so both functions share the same
enrichment path.

In `@src/utils/types/sensitivity-analysis.type.ts`:
- Around line 125-282: The code duplicates nearly identical mapping/enrichment
logic across mapSensitivityAnalysisParameters and
enrichSensitivityAnalysisParameters for the five sensitivity sub-structures;
refactor by introducing a shared descriptor (e.g., const SUBSTRUCT_FIELDS = {
sensitivityInjectionsSet: ['monitoredBranches','injections','contingencies'],
sensitivityInjection: [...], sensitivityHVDC: [...], sensitivityPST: [...],
sensitivityNodes: [...] } as const) and iterate over its entries in both
functions to apply the appropriate transform (use the existing helper
mapEquipmentsContainerToIds in mapSensitivityAnalysisParameters and
mapIdsToEquipmentsContainer / fetchElementNames flow in
enrichSensitivityAnalysisParameters), dispatching per-field transforms by name
to eliminate the repeated per-structure blocks while preserving existing return
shapes and null/empty-array fallbacks.
- Around line 128-130: The mapEquipmentsContainerToIds function currently
force-casts strings to UUID[]; change the source typing or validate instead:
update the EquipmentsContainer type's containerId from string to UUID so
mapEquipmentsContainerToIds can simply return containers?.map(c =>
c.containerId) without an unsafe as-cast, and ensure
SensitivityAnalysisParameters<UUID> consumers remain consistent; alternatively,
if you cannot change the model, add a validation step inside
mapEquipmentsContainerToIds to parse/validate each c.containerId as a UUID and
only return validated ids (or throw/skip invalid ones) rather than using the as
UUID[] cast.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 93bdbe37-35ea-4750-b6e3-94aebf809967

📥 Commits

Reviewing files that changed from the base of the PR and between 3499211 and 3ab6fcd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (22)
  • src/components/parameters/common/contingency-table/columns-definitions.ts
  • src/components/parameters/common/contingency-table/contingency-table.tsx
  • src/components/parameters/common/contingency-table/types.ts
  • src/components/parameters/pcc-min/pcc-min-form-utils.ts
  • src/components/parameters/pcc-min/pcc-min-parameters-inline.tsx
  • src/components/parameters/pcc-min/use-pcc-min-parameters-form.ts
  • src/components/parameters/security-analysis/columns-definitions.ts
  • src/components/parameters/security-analysis/security-analysis-parameters-inline.tsx
  • src/components/parameters/security-analysis/security-analysis-parameters-selector.tsx
  • src/components/parameters/security-analysis/types.ts
  • src/components/parameters/security-analysis/use-security-analysis-parameters-form.ts
  • src/components/parameters/sensi/sensitivity-analysis-parameters-inline.tsx
  • src/components/parameters/sensi/use-sensitivity-analysis-parameters.ts
  • src/services/directory.ts
  • src/services/index.ts
  • src/services/pcc-min.ts
  • src/services/security-analysis.ts
  • src/services/sensitivity-analysis.ts
  • src/utils/types/index.ts
  • src/utils/types/parameters.type.ts
  • src/utils/types/pcc-min.type.ts
  • src/utils/types/sensitivity-analysis.type.ts

Comment on lines +63 to +72
return elementNamesPromise.then((elementNames) => {
const mapIdsToIdNames = (ids: UUID[] | undefined): IdName[] => {
return ids
? ids.map((id) => ({
[ID]: id,
[NAME]: elementNames?.[id] ?? null,
}))
: [];
};
return {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Type violation: [NAME]: null breaks IdName.

IdName[NAME] is declared as string (see src/components/parameters/common/contingency-table/types.ts), but elementNames?.[id] ?? null returns string | null. Same defect as in pcc-min.type.ts. Either widen IdName.name to string | null or fall back to ''.

🔧 Proposed fix
-                      [ID]: id,
-                      [NAME]: elementNames?.[id] ?? null,
+                      [ID]: id,
+                      [NAME]: elementNames?.[id] ?? '',
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/parameters/security-analysis/types.ts` around lines 63 - 72,
The mapIdsToIdNames closure returns IdName objects with [NAME] possibly set to
null which violates IdName.name:string; update mapIdsToIdNames in the
elementNamesPromise.then block to coerce elementNames?.[id] to a string (e.g.,
elementNames?.[id] ?? '') so [NAME] is always a string, preserving the IdName
type (alternatively, if you prefer a type change, update the IdName declaration
to allow string | null across usages, but the quick fix is to use the
empty-string fallback).

Comment thread src/services/directory.ts
Comment on lines +79 to +91
export function fetchElementNames(elementUuids: Set<string>) {
console.info('fetch directory element names');

const params = new URLSearchParams();
elementUuids.forEach((id) => {
params.append('ids', id);
});

const url = `${PREFIX_EXPLORE_SERVER_QUERIES}/v1/explore/elements/name?${params.toString()}`;
console.log(url);

return backendFetchJson(url);
}
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot Apr 17, 2026

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Potential 414 URI Too Long with large UUID sets.

All IDs are sent as repeated ids query params on a GET. With many contingency lists/filters, the URL can exceed server/proxy limits (commonly 4–8 KB). Consider switching to POST with a JSON body, or batching the UUIDs client-side.

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

In `@src/services/directory.ts` around lines 79 - 91, fetchElementNames currently
builds a long GET URL by appending many ids query params which can hit 414
limits; change fetchElementNames to send the UUIDs in the request body instead
(POST) or implement client-side batching: build an array from elementUuids and
call the same endpoint with a POST to
`${PREFIX_EXPLORE_SERVER_QUERIES}/v1/explore/elements/name` using JSON body {
ids: [...] } and Content-Type: application/json (or, if POST is not allowed,
split elementUuids into chunks and perform multiple GET requests and merge
results). Update the call site to use backendFetchJson with method:'POST',
appropriate headers and JSON.stringify(body) (or loop over chunks and aggregate
responses) and keep function name fetchElementNames unchanged.

Copy link
Copy Markdown
Contributor

@thangqp thangqp May 7, 2026

Choose a reason for hiding this comment

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

in reality, we have not much uuids, not reached a hundred elements.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@thangqp, understood — thanks for the context! With fewer than a hundred UUIDs, the URL length will stay well within typical server and proxy limits (each UUID is ~36 chars, so even 100 IDs only adds ~4 KB at most). The current GET-with-query-params approach is fine for this scale, and no change is needed.

Comment thread src/services/pcc-min.ts
Comment on lines +18 to 32
export function getPccMinStudyParameters(studyUuid: UUID): Promise<PccMinParametersEnriched | null> {
console.info('get pcc min study parameters');
const getPccMintParams = `${getStudyUrl(studyUuid)}/pcc-min/parameters`;
console.debug(getPccMintParams);
return backendFetchJson(getPccMintParams);
const url = `${getStudyUrl(studyUuid)}/pcc-min/parameters`;
console.debug(url);
const parametersPromise: Promise<PccMinParameters> = backendFetchJson(url);
return parametersPromise.then((parameters) => enrichPccMinParameters(parameters));
}

export function fetchPccMinParameters(parameterUuid: UUID): Promise<PccMinParameters> {
export function fetchPccMinParameters(parameterUuid: UUID): Promise<PccMinParametersEnriched> {
console.info('fetch pcc min parameters');
const url = `${getPccMinUrl()}parameters/${encodeURIComponent(parameterUuid)}`;
console.debug(url);
return backendFetchJson(url);
const parametersPromise: Promise<PccMinParameters> = backendFetchJson(url);
return parametersPromise.then((parameters) => enrichPccMinParameters(parameters));
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Unhandled backend failure during enrichment.

enrichPccMinParameters now issues a network call inside getPccMinStudyParameters / fetchPccMinParameters. If fetchElementNames fails (directory server down, 4xx/5xx, timeout), the whole parameters load rejects even though the base parameters were successfully fetched. Consider catching the enrichment error and falling back to an empty-names mapping so the form can still render.

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

In `@src/services/pcc-min.ts` around lines 18 - 32, The enrichment step can throw
(fetchElementNames failure) and currently bubbles up, so wrap the call to
enrichPccMinParameters in a rejection handler and return a sensible fallback so
the base parameters still resolve; specifically, in both
getPccMinStudyParameters and fetchPccMinParameters replace the direct
.then(enrichPccMinParameters) with .then(params => { try { return
enrichPccMinParameters(params); } catch (err) { return enrichPccMinParameters({
...params, elementNames: {} }); } }) or equivalent Promise.catch-based logic
that catches enrichment errors and returns the original parameters enriched with
an empty elementNames map (reference enrichPccMinParameters and the fact it
calls fetchElementNames) so the form can render even if fetchElementNames fails.

Comment on lines +11 to +23
export type PccMinParametersEnriched = {
[FILTERS]: FilterIdentifier[];
};
export type PccMinParameters = {
[FILTERS]: UUID[];
};

export function mapPccMinParameters(parametersInfos: PccMinParametersEnriched): PccMinParameters {
return {
...parametersInfos,
[FILTERS]: parametersInfos.filters?.map((filter) => filter.filterId),
};
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

mapPccMinParameters: optional chaining + required field mismatch.

PccMinParametersEnriched.filters is non-optional, yet parametersInfos.filters?.map(...) can produce undefined, which is assigned to PccMinParameters.filters: UUID[] (required). Either tighten the types to optional or coalesce to [].

🔧 Proposed fix
-        [FILTERS]: parametersInfos.filters?.map((filter) => filter.filterId),
+        [FILTERS]: parametersInfos.filters?.map((filter) => filter.filterId) ?? [],
📝 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.

Suggested change
export type PccMinParametersEnriched = {
[FILTERS]: FilterIdentifier[];
};
export type PccMinParameters = {
[FILTERS]: UUID[];
};
export function mapPccMinParameters(parametersInfos: PccMinParametersEnriched): PccMinParameters {
return {
...parametersInfos,
[FILTERS]: parametersInfos.filters?.map((filter) => filter.filterId),
};
}
export type PccMinParametersEnriched = {
[FILTERS]: FilterIdentifier[];
};
export type PccMinParameters = {
[FILTERS]: UUID[];
};
export function mapPccMinParameters(parametersInfos: PccMinParametersEnriched): PccMinParameters {
return {
...parametersInfos,
[FILTERS]: parametersInfos.filters?.map((filter) => filter.filterId) ?? [],
};
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/types/pcc-min.type.ts` around lines 11 - 23, mapPccMinParameters
uses optional chaining on a field that the input type PccMinParametersEnriched
marks as required, which can yield undefined for the required
PccMinParameters[FILTERS]; fix by ensuring FILTERS is always an array: in
mapPccMinParameters convert parametersInfos.filters to an array (e.g.
parametersInfos.filters ? parametersInfos.filters.map(f => f.filterId) : []) or
remove the optional chaining and rely on the required type
(parametersInfos.filters.map(...)); reference mapPccMinParameters,
PccMinParametersEnriched, PccMinParameters and FILTERS when changing the
implementation or types.

Comment on lines +34 to +47
return elementNamesPromise.then((elementNames) => {
const mapIdsToFilterIdentifiers = (ids: UUID[] | undefined): FilterIdentifier[] => {
return ids
? ids.map((id) => ({
filterId: id,
filterName: elementNames?.[id] ?? null,
}))
: [];
};
return {
...parameters,
[FILTERS]: mapIdsToFilterIdentifiers(parameters[FILTERS]),
};
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Type violation: filterName can be null but FilterIdentifier.filterName is string.

elementNames?.[id] ?? null produces UUID | null, which does not match FilterIdentifier (see src/utils/constants/filterConstant.ts where filterName: string). This will either fail type-checking or silently leak null into UI code that assumes a string. Either widen the type (filterName: string | null) or fall back to an empty string / the UUID.

🔧 Proposed fix
-                      filterId: id,
-                      filterName: elementNames?.[id] ?? null,
+                      filterId: id,
+                      filterName: elementNames?.[id] ?? '',
📝 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.

Suggested change
return elementNamesPromise.then((elementNames) => {
const mapIdsToFilterIdentifiers = (ids: UUID[] | undefined): FilterIdentifier[] => {
return ids
? ids.map((id) => ({
filterId: id,
filterName: elementNames?.[id] ?? null,
}))
: [];
};
return {
...parameters,
[FILTERS]: mapIdsToFilterIdentifiers(parameters[FILTERS]),
};
});
return elementNamesPromise.then((elementNames) => {
const mapIdsToFilterIdentifiers = (ids: UUID[] | undefined): FilterIdentifier[] => {
return ids
? ids.map((id) => ({
filterId: id,
filterName: elementNames?.[id] ?? '',
}))
: [];
};
return {
...parameters,
[FILTERS]: mapIdsToFilterIdentifiers(parameters[FILTERS]),
};
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/types/pcc-min.type.ts` around lines 34 - 47, The
mapIdsToFilterIdentifiers closure returns filterName as elementNames?.[id] ??
null which can be null but FilterIdentifier.filterName is declared as string;
change the code so filterName is always a string (e.g. elementNames?.[id] ?? id
or elementNames?.[id] ?? '') or update the FilterIdentifier type to allow string
| null; locate the mapper in the elementNamesPromise.then block
(mapIdsToFilterIdentifiers, FILTERS, FilterIdentifier) and implement the chosen
fix consistently so the returned object matches the FilterIdentifier definition.

Comment on lines +219 to +281
return elementNamesPromise.then((elementNames) => {
const mapIdsToEquipmentsContainer = (ids: UUID[] | undefined): EquipmentsContainer[] => {
return ids
? ids.map((id) => ({
containerId: id,
containerName: elementNames?.[id] ?? null,
}))
: [];
};
return {
...parameters,
sensitivityInjectionsSet: parameters.sensitivityInjectionsSet
? parameters.sensitivityInjectionsSet.map((is) => {
return {
...is,
monitoredBranches: mapIdsToEquipmentsContainer(is.monitoredBranches),
injections: mapIdsToEquipmentsContainer(is.injections),
contingencies: mapIdsToEquipmentsContainer(is.contingencies),
};
})
: [],
sensitivityInjection: parameters.sensitivityInjection
? parameters.sensitivityInjection.map((i) => {
return {
...i,
monitoredBranches: mapIdsToEquipmentsContainer(i.monitoredBranches),
injections: mapIdsToEquipmentsContainer(i.injections),
contingencies: mapIdsToEquipmentsContainer(i.contingencies),
};
})
: [],
sensitivityHVDC: parameters.sensitivityHVDC
? parameters.sensitivityHVDC.map((hvdc) => {
return {
...hvdc,
monitoredBranches: mapIdsToEquipmentsContainer(hvdc.monitoredBranches),
hvdcs: mapIdsToEquipmentsContainer(hvdc.hvdcs),
contingencies: mapIdsToEquipmentsContainer(hvdc.contingencies),
};
})
: [],
sensitivityPST: parameters.sensitivityPST
? parameters.sensitivityPST.map((pst) => {
return {
...pst,
monitoredBranches: mapIdsToEquipmentsContainer(pst.monitoredBranches),
psts: mapIdsToEquipmentsContainer(pst.psts),
contingencies: mapIdsToEquipmentsContainer(pst.contingencies),
};
})
: [],
sensitivityNodes: parameters.sensitivityNodes
? parameters.sensitivityNodes.map((n) => {
return {
...n,
monitoredVoltageLevels: mapIdsToEquipmentsContainer(n.monitoredVoltageLevels),
equipmentsInVoltageRegulation: mapIdsToEquipmentsContainer(n.equipmentsInVoltageRegulation),
contingencies: mapIdsToEquipmentsContainer(n.contingencies),
};
})
: [],
};
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find backend contract for sensitivity-analysis parameters to see whether
# omitted fields and empty arrays are handled equivalently.
rg -nP --type=ts -C3 '\bsensitivityInjectionsSet\b|\bsensitivityInjection\b|\bsensitivityHVDC\b' -g '!**/*.test.*'

Repository: gridsuite/commons-ui

Length of output: 13141


Asymmetry in undefined handling between enrich and map functions causes silent round-trip conversion.

The enrichSensitivityAnalysisParameters function converts undefined fields to empty arrays (undefined[]), while its complement mapSensitivityAnalysisParameters preserves undefined values using optional chaining. This creates a semantic loss during round-tripping: a field omitted by the backend becomes an empty array when the form is sent back, which backends may interpret differently from truly absent fields (important for partial updates).

Suggested fix (apply to all sensitivity sub-structures)
-            sensitivityInjectionsSet: parameters.sensitivityInjectionsSet
-                ? parameters.sensitivityInjectionsSet.map((is) => {
+            sensitivityInjectionsSet: parameters.sensitivityInjectionsSet?.map((is) => {
                     return {
                         ...is,
                         monitoredBranches: mapIdsToEquipmentsContainer(is.monitoredBranches),
                         injections: mapIdsToEquipmentsContainer(is.injections),
                         contingencies: mapIdsToEquipmentsContainer(is.contingencies),
                     };
-                  })
-                : [],
+                }),

Use optional chaining throughout to preserve undefined and maintain consistency with mapSensitivityAnalysisParameters.

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

In `@src/utils/types/sensitivity-analysis.type.ts` around lines 219 - 281, The
enrichSensitivityAnalysisParameters function currently coerces undefined
sensitivity sub-fields into empty arrays (e.g., sensitivityInjectionsSet,
sensitivityInjection, sensitivityHVDC, sensitivityPST, sensitivityNodes) by
using ternaries that return []; change these to preserve undefined using
optional chaining or nullish checks so the function returns undefined when the
input was undefined (mirroring mapSensitivityAnalysisParameters). Specifically,
update the mapping logic that uses mapIdsToEquipmentsContainer and the ternary
patterns on parameters.sensitivityInjectionsSet,
parameters.sensitivityInjection, parameters.sensitivityHVDC,
parameters.sensitivityPST, and parameters.sensitivityNodes to use optional
chaining (e.g., parameters.sensitivityInjectionsSet?.map(...)) or return
undefined instead of [] so round-trip semantics are preserved.

import { ContingencyListsInfos, ContingencyListsInfosEnriched, IdName } from '../common/contingency-table/types';
import { ILimitReductionsByVoltageLevel } from '../common/limitreductions/columns-definitions';
import { fetchElementNames } from '../../../services/directory';
import { ID, NAME } from '../common/parameter-table/constants';
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
import { ID, NAME } from '../common/parameter-table/constants';
import { ID, NAME } from '../common/parameter-table-field/constants';

Comment thread package-lock.json
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

to remove the diff of this file in the PR

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Copy link
Copy Markdown
Contributor

@thangqp thangqp left a comment

Choose a reason for hiding this comment

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

EquipmentsContainer with be removed in the next PR:
#1125

return new Set(allContainerIds);
}

export function enrichSecurityAnalysisParameters(parameters: SAParameters): Promise<SAParametersEnriched> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@thangqp is it ok to add these functions in the file "types.ts"?!

Copy link
Copy Markdown
Contributor

@thangqp thangqp May 12, 2026

Choose a reason for hiding this comment

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

it is not Top but if a transformation between the API backend DTO and a derived of this DTO is co-located with the dervied type, IMO it is acceptable. The best is separating to a new file security-analysis-utils.ts in utils/types and create a new file security-analysis.type.ts in the same directory.

Note that the transformation is performed at service level, i.e. /services/security-analysis.ts so it should not depend on components/parameters/security-analysis

I will note it for the next rework PR

return new Set(params[FILTERS]);
}

export function enrichPccMinParameters(parameters: PccMinParameters): Promise<PccMinParametersEnriched> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why in type.ts?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

allVariableIds?: string[];
};

export function mapSensitivityAnalysisParameters(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

outch!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Signed-off-by: Thang PHAM <phamthang37@gmail.com>
@sonarqubecloud
Copy link
Copy Markdown

@thangqp thangqp merged commit e8410f1 into main May 12, 2026
6 checks passed
@thangqp thangqp deleted the get-element-names branch May 12, 2026 14:16
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.

3 participants