-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Hcmpre 866 #1547
Hcmpre 866 #1547
Conversation
📝 Walkthrough📝 WalkthroughWalkthroughThis pull request introduces several changes across multiple components in the campaign management module. Key modifications include the addition of null checks, restructuring of data handling, introduction of new utility functions, and enhancements in state management. Notably, the Changes
Possibly related PRs
Suggested reviewers
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Caution
Inline review comments failed to post
Actionable comments posted: 25
🧹 Outside diff range comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (1)
Line range hint
532-537
: LGTM! Improved reactivity for campaign data generation.The updated
useEffect
hook now correctly depends oncycleData
, ensuring that campaign data is regenerated whenever the cycle configuration changes. This improves the component's reactivity and data consistency.Consider memoizing the
cycleData.cycleConfgureDate
object to optimize performance, especially if it's derived from props or complex calculations:const memoizedCycleConfigureDate = useMemo(() => cycleData?.cycleConfgureDate, [cycleData]); useEffect(() => { if (memoizedCycleConfigureDate) { dispatchCampaignData({ type: "GENERATE_CAMPAIGN_DATA", cycle: memoizedCycleConfigureDate.cycle, deliveries: memoizedCycleConfigureDate.deliveries, }); } }, [memoizedCycleConfigureDate, dispatchCampaignData]);This approach can help prevent unnecessary re-renders if
cycleData
changes frequently butcycleConfgureDate
remains the same.
🛑 Comments failed to post (25)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignUpdateSummary.js (2)
217-217: 🧹 Nitpick (assertive)
LGTM! Consider adding keyboard accessibility.
The changes to the
handleRedirect
function and the addition ofupdateUrlParams
improve URL handling and code maintainability. Great job!To enhance accessibility, consider adding keyboard event handlers (onKeyUp, onKeyDown, or onKeyPress) alongside the onClick events for the edit buttons. This ensures that keyboard-only users can also interact with these elements. For example:
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(4)} onKeyDown={(e) => e.key === 'Enter' && handleRedirect(4)} tabIndex={0} role="button" > <span>{t(`CAMPAIGN_EDIT`)}</span> <EditIcon /> </div>Apply this pattern to all similar div elements acting as buttons.
Also applies to: 237-237, 257-257
🧰 Tools
🪛 Biome
[error] 217-217: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.
Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.
(lint/a11y/useKeyWithClickEvents)
217-217: 💡 Codebase verification
Error handling for
summaryErrors
is incomplete after removal of theuseEffect
block.The
CampaignUpdateSummary.js
component initializessummaryErrors
but does not actively manage or update them due to the commented-outsetSummaryErrors
calls. Please ensure that error handling forsummaryErrors
is implemented appropriately, either within this component or elsewhere in the codebase.🔗 Analysis chain
Verify error handling after removal of commented-out code.
The removal of the commented-out
useEffect
block improves code cleanliness. However, please ensure that the error handling functionality previously managed by this code is now handled elsewhere or is no longer needed.To confirm that error handling is still properly managed, please run the following script:
Also applies to: 237-237, 257-257
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for error handling related to summaryErrors echo "Searching for summaryErrors usage in the codebase..." rg --type js 'summaryErrors' echo "Searching for error state management in the CampaignUpdateSummary component..." rg --type js '(setDeliveryErrors|setTargetErrors|setFacilityErrors|setUserErrors|setCycleDatesError|setSummaryErrors)' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignUpdateSummary.js echo "Please review the output to ensure that error handling related to summaryErrors is still properly managed in the codebase."Length of output: 12693
🧰 Tools
🪛 Biome
[error] 217-217: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.
Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.
(lint/a11y/useKeyWithClickEvents)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js (1)
304-310: 🧹 Nitpick (assertive)
LGTM! Improved null checks for better robustness.
The addition of optional chaining operators (?.) enhances the code's resilience against potential runtime errors when accessing properties of potentially undefined objects. This is a good practice, especially when dealing with data that might not always be present.
Consider using nullish coalescing operator (??) for providing default values, which can make the code even more concise. For example:
if ((cycle?.deliveries?.length ?? 0) > subTabs) { cycle?.deliveries?.splice(subTabs); } if (subTabs > (cycle?.deliveries?.length ?? 0)) { // ... rest of the code }This approach handles both
undefined
andnull
cases elegantly.health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (4)
105-105:
⚠️ Potential issuePotential confusion with nested
deliveries
property.In line 105,
conditionConfig
is created by mapping overdelivery.deliveries
. This could be confusing since you are iterating overdeliveries
, and eachdelivery
has adeliveries
property. Verify thatdelivery.deliveries
is the correct property and consider renaming variables or restructuring the data to improve readability.
124-128: 🧹 Nitpick (assertive)
Remove commented-out code for cleaner codebase.
The code in lines 124-128 is commented out. If this code is no longer needed, consider removing it to maintain code cleanliness and prevent confusion.
147-147:
⚠️ Potential issueIncorrect function call to
generateMRDNConfig
.The
generateMRDNConfig
function has been updated to accept only one parameter(deliveries)
, but at line 147, it is called with two arguments:data?.cycles
andprojectType
. This mismatch will lead to a runtime error.Apply this diff to fix the function call:
- return generateMRDNConfig(data?.cycles, projectType); + return generateMRDNConfig(data?.cycles);📝 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.return generateMRDNConfig(data?.cycles);
101-142:
⚠️ Potential issueEnsure proper handling of
fromValue
andtoValue
inattributeConfig
.In the
generateMRDNConfig
function, within theattributeConfig
,fromValue
andtoValue
are assigned usingvalue.minValue
andvalue.maxValue
without considering theoperatorValue
. IfoperatorValue
is not"IN_BETWEEN"
,value
may not haveminValue
andmaxValue
, leading toundefined
values.Consider adding logic to handle different
operatorValue
cases, similar to what's done in thegenerateBednetConfig
function.Apply this diff to address the issue:
+ let fromValue = null; + let toValue = null; + if (operatorValue === "IN_BETWEEN") { + fromValue = Number(value.minValue); + toValue = Number(value.maxValue); + } else { + fromValue = Number(value.comparisonValue); + toValue = null; + } return { key: `${conditionIndex + 1}-${attrIndex + 1}`, label: "Custom", attrType: criteria.attrType || "dropdown", attrValue: value.variable, operatorValue, - fromValue: Number(value.minValue), - toValue: Number(value.maxValue) - 1 + fromValue, + toValue };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const generateMRDNConfig = (deliveries) => { const deliveryConfig = deliveries.map((delivery, deliveryIndex) => { return { delivery: delivery.id, conditionConfig: delivery.deliveries.map((deliveryItem, conditionIndex) => { return { disableDeliveryType: deliveryItem.deliveryStrategy === "DIRECT", deliveryType: deliveryItem.deliveryStrategy, attributeConfig: deliveryItem.doseCriteria.map((criteria, attrIndex) => { const { operatorValue, value } = parseCondition(criteria.condition); let fromValue = null; let toValue = null; if (operatorValue === "IN_BETWEEN") { fromValue = Number(value.minValue); toValue = Number(value.maxValue); } else { fromValue = Number(value.comparisonValue); toValue = null; } return { key: `${conditionIndex + 1}-${attrIndex + 1}`, label: "Custom", attrType: criteria.attrType || "dropdown", attrValue: value.variable, operatorValue, fromValue, toValue }; }), productConfig: deliveryItem.doseCriteria.flatMap((criteria, prodIndex) => { return criteria.ProductVariants.map((variant, varIndex) => { // if(variant?.productVariantId){ // productName = useProductVariantSearch({ variantId: variant.productVariantId, tenantId: "mz" }); // } // const productName = useProductVariantSearch({ variantId: variant.productVariantId, tenantId: "mz" }); return { key: `${conditionIndex + 1}-${varIndex + 1}`, count: variant.quantity, value: variant.productVariantId, name: variant.name }; }); }) }; }) }; }); return deliveryConfig; };
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DeliveryDetailsSummary.js (3)
111-111:
⚠️ Potential issueUse
const
instead oflet
for variables that are not reassigned.Variables
rules
(line 111) andattributes
(line 115) are declared withlet
but are never reassigned after their initial assignment. Usingconst
for such variables enhances code readability and prevents accidental reassignment.Apply this diff to fix the issue:
// Line 111 - let rules = []; + const rules = []; // Line 115 - let attributes = []; + const attributes = [];Also applies to: 115-115
🧰 Tools
🪛 Biome
[error] 111-111: This let declares a variable that is only assigned once.
'rules' is never reassigned.
Safe fix: Use const instead.
(lint/style/useConst)
89-97:
⚠️ Potential issueQuote the key
'IN_BETWEEN'
inoperatorMapping
to prevent referencing an undefined variable.In the
operatorMapping
object, the keyIN_BETWEEN
is not enclosed in quotes. This could lead to an undefined variable error since unquoted keys are treated as variables. Object keys intended as strings should be enclosed in quotes.Apply this diff to fix the issue:
const operatorMapping = { "<=": "LESS_THAN_EQUAL_TO", ">=": "GREATER_THAN_EQUAL_TO", "<": "LESS_THAN", ">": "GREATER_THAN", "==": "EQUAL_TO", "!=": "NOT_EQUAL_TO", - IN_BETWEEN: "IN_BETWEEN", + "IN_BETWEEN": "IN_BETWEEN", };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const operatorMapping = { "<=": "LESS_THAN_EQUAL_TO", ">=": "GREATER_THAN_EQUAL_TO", "<": "LESS_THAN", ">": "GREATER_THAN", "==": "EQUAL_TO", "!=": "NOT_EQUAL_TO", "IN_BETWEEN": "IN_BETWEEN", };
410-412: 🛠️ Refactor suggestion
Ensure consistent code formatting for better readability.
The
else
block is misaligned, which can lead to confusion. It's recommended to use braces consistently for all conditional branches to improve code clarity and maintainability.Apply this diff to improve code formatting:
const onStepClick = (currentStep) => { if (currentStep === 0) { setKey(7); } else if (currentStep === 2) { setKey(9); } else { setKey(8); } };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if (currentStep === 0) { setKey(7); } else if (currentStep === 2) { setKey(9); } else { setKey(8); }
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js (6)
95-95:
⚠️ Potential issueEnclose 'IN_BETWEEN' in quotes
In the
operatorMapping
object, the keyIN_BETWEEN
is not enclosed in quotes, which could lead to unexpected behavior ifIN_BETWEEN
is not a defined variable. To ensure it's treated as a string key, enclose it in quotes.Apply this diff to fix the issue:
- IN_BETWEEN: "IN_BETWEEN", + "IN_BETWEEN": "IN_BETWEEN",📝 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."IN_BETWEEN": "IN_BETWEEN",
692-692: 🧹 Nitpick (assertive)
Simplify condition with optional chaining
Use optional chaining to streamline the condition when accessing nested properties.
Apply this diff:
- if (section.props && section.props.data) { + if (section.props?.data) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if (section.props?.data) {
🧰 Tools
🪛 Biome
[error] 692-692: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
686-686: 🧹 Nitpick (assertive)
Simplify condition with optional chaining
You can simplify the condition by using optional chaining to check if
card.name
exists before callingstartsWith
.Apply this diff:
- if (card.name && card.name.startsWith("CYCLE_")) { + if (card.name?.startsWith("CYCLE_")) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if (card.name?.startsWith("CYCLE_")) {
🧰 Tools
🪛 Biome
[error] 686-686: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
426-426: 🧹 Nitpick (assertive)
Simplify string concatenation using template literals
You're concatenating strings inside a template literal using the
+
operator. You can simplify this by utilizing template literals entirely.Apply this diff to improve the code:
- cardHeader: { value: `${t((hierarchyType + "_" + item?.type).toUpperCase())}`, inlineStyles: { color: "#0B4B66" } }, + cardHeader: { value: `${t(`${hierarchyType}_${item?.type}`.toUpperCase())}`, inlineStyles: { color: "#0B4B66" } },📝 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.cardHeader: { value: `${t(`${hierarchyType}_${item?.type}`.toUpperCase())}`, inlineStyles: { color: "#0B4B66" } },
🧰 Tools
🪛 Biome
[error] 426-426: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
114-114: 🧹 Nitpick (assertive)
Use 'const' instead of 'let' for 'attributes'
The variable
attributes
is declared withlet
but is never reassigned. Consider usingconst
to make the intent clearer.Apply this diff to fix the issue:
- let attributes = []; + const attributes = [];📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const attributes = [];
🧰 Tools
🪛 Biome
[error] 114-114: This let declares a variable that is only assigned once.
'attributes' is never reassigned.
Safe fix: Use const instead.
(lint/style/useConst)
110-110: 🧹 Nitpick (assertive)
Use 'const' instead of 'let' for 'rules'
The variable
rules
is declared withlet
but is never reassigned. Usingconst
is preferred for variables that are not reassigned to enhance code readability and prevent accidental reassignments.Apply this diff to fix the issue:
- let rules = []; + const rules = [];📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const rules = [];
🧰 Tools
🪛 Biome
[error] 110-110: This let declares a variable that is only assigned once.
'rules' is never reassigned.
Safe fix: Use const instead.
(lint/style/useConst)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js (2)
618-619: 🛠️ Refactor suggestion
Consider refactoring duplicated code for 'selectedStructureCodes'.
The declaration of
selectedStructureCodes
at lines 618-619 is duplicated at lines 922-923. Extracting this logic into a shared utility function can improve maintainability and reduce redundancy.
922-923:
⚠️ Potential issueMissing optional chaining operator may cause runtime errors.
At line 923, the optional chaining operator
?.
is missing beforemap
onattributes
. Ifrule?.attributes
is null or undefined, callingmap
will result in a runtime error. Please add the optional chaining operator to prevent potential errors.Apply this diff to fix the issue:
- cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes.map((attribute) => attribute?.value))) + cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const selectedStructureCodes = campaignData?.flatMap((cycle) => cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (7)
649-649:
⚠️ Potential issueEnsure
projectType
is provided when callingrestructureData
The
restructureData
function expects aprojectType
parameter. Omitting it may lead to unexpected behavior or errors, especially since it's used to find the appropriate delivery configuration.Please update the function calls to include
projectType
:// Example at line 649 - const temp = restructureData(..., DeliveryConfig); + const temp = restructureData(..., DeliveryConfig, totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.code);Also applies to: 721-721, 786-786, 850-850
722-722:
⚠️ Potential issueMaintain consistent assignment to
payloadData.deliveryRules
payloadData.deliveryRules
is assigned differently in various places—once as an array containingtemp[0]
and once directly astemp[0]
. This inconsistency can cause issues if other parts of the code expectdeliveryRules
to be of a specific type.Please standardize the assignment:
If
deliveryRules
should be an array:// At line 787 - payloadData.deliveryRules = temp?.[0]; + payloadData.deliveryRules = [temp?.[0]];Or if it should be an object:
// At lines 650 and 851 - payloadData.deliveryRules = [temp?.[0]]; + payloadData.deliveryRules = temp?.[0];Also applies to: 787-787
186-186: 🧹 Nitpick (assertive)
Remove debugging statement
The
console.log
statement is likely used for debugging purposes and should be removed to clean up the console output in production.Suggested change:
- console.log("t" , data);
📝 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.
277-277: 🧹 Nitpick (assertive)
Remove debugging statement
The
console.log
statement can clutter console output and reveal internal data structures. It's advisable to remove it before deploying.Suggested change:
- console.log("tttttttttt" , transformedCycles);
📝 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.
86-149: 🧹 Nitpick (assertive)
Remove large blocks of commented-out code
Having large sections of commented-out code can reduce code readability and increase maintenance overhead. It's better to remove unused code and rely on version control systems to retrieve previous versions if needed.
Suggested change:
- // function restructureData(data, cycleData, DeliveryConfig, projectType) { - // const tt = DeliveryConfig?.find((e) => e.code === String(projectType)); - // ... - // return [tt]; - // }📝 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.
514-514: 🧹 Nitpick (assertive)
Remove debugging statement
Removing unnecessary
console.log
statements improves performance and reduces potential exposure of sensitive information.Suggested change:
- console.log("delivery" , delivery);
📝 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.
155-156:
⚠️ Potential issueAvoid using the
delete
operator; consider setting properties toundefined
ornull
insteadUsing the
delete
operator can negatively impact JavaScript engine optimizations and overall performance. It's recommended to set the properties toundefined
ornull
to indicate they are no longer needed.Suggested change:
- delete deliveryConfig.cycles; - delete deliveryConfig.resources; + deliveryConfig.cycles = undefined; + deliveryConfig.resources = undefined;📝 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.deliveryConfig.cycles = undefined; deliveryConfig.resources = undefined;
🧰 Tools
🪛 Biome
[error] 155-155: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
[error] 156-156: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🧹 Outside diff range comments (2)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (2)
Line range hint
155-160
: Verify the Correctness of Cycle Dates Assignment.In the
restructureData
function, thestartDate
andendDate
for each cycle are being set usingcycleData.cycleData[0]
, which means all cycles will have the same dates:const cycleStartDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.fromDate); const cycleEndDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.toDate);Please verify if this is intended. If each cycle should have its own start and end dates, consider updating the code to use the corresponding index:
const cycles = data.map((cycle, index) => { - const cycleStartDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.fromDate); - const cycleEndDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[0]?.toDate); + const cycleStartDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[index]?.fromDate); + const cycleEndDate = Digit.Utils.pt.convertDateToEpoch(cycleData?.cycleData?.[index]?.toDate); // rest of the code... });
Line range hint
316-320
: Enhance Age Extraction Logic inextractAgesFromConditions
.The
extractAgesFromConditions
function uses a regular expression that matches any number in the condition string:const agePattern = /\b(\d+)\b/g;Consider refining the regex to specifically match age-related numbers to avoid capturing unintended numbers that are not related to age.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
📒 Files selected for processing (4)
- health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BoundarySummary.js (1 hunks)
- health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (3 hunks)
- health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js (2 hunks)
- health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BoundarySummary.js (1)
Pattern
**/*.js
: checkhealth/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js (1)
Pattern
**/*.js
: checkhealth/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js (1)
Pattern
**/*.js
: checkhealth/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1)
Pattern
**/*.js
: check
🔇 Additional comments (2)
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BoundarySummary.js (1)
Line range hint
1-38
: Overall, the change improves robustness without altering core functionality.The addition of the null check in the
boundaryDataGrp
function enhances the component's resilience to unexpected data structures. This change:
- Prevents potential runtime errors when processing boundary data.
- Maintains the existing data flow and component functionality.
- Slightly improves code maintainability.
To ensure this change doesn't mask any underlying issues, please verify that
boundaryData
is expected to be potentially undefined in some valid scenarios. Run the following script to check for other usages ofboundaryData
:✅ Verification successful
Change Verified: The null check added to the
boundaryDataGrp
function aligns with existing code practices whereboundaryData
may be undefined. This enhancement ensures greater resilience without affecting the component's core functionality.
boundaryData
is appropriately handled across various components, indicating that it can be undefined in valid scenarios.- The added null check prevents potential runtime errors during data processing.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other usages of boundaryData to ensure consistency rg --type js 'boundaryData' health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/srcLength of output: 12050
health/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/getDeliveryConfig.js (1)
133-134
: Verify thatvariant.name
is reliably definedThe updated code assigns
variant.name
directly to thename
property:name: variant.namePreviously, there was a commented-out implementation using the
useProductVariantSearch
hook to retrieve the product name. This suggests thatvariant.name
may not always have the necessary data. Please verify thatvariant.name
is consistently defined and contains the correct product name for all variants. If there are cases wherevariant.name
might be undefined or incorrect, consider handling these cases or reverting to using theuseProductVariantSearch
hook.
@@ -13,7 +13,7 @@ function boundaryDataGrp(boundaryData) { | |||
const groupedData = {}; | |||
|
|||
// Iterate through each boundary item in the data | |||
boundaryData.forEach((item) => { | |||
boundaryData?.forEach((item) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick (assertive)
Approve the null check, but consider adding a fallback.
The addition of the optional chaining operator ?.
is a good defensive programming practice. It prevents potential runtime errors when boundaryData
is null or undefined.
Consider adding a fallback to make the behavior more explicit:
- boundaryData?.forEach((item) => {
+ (boundaryData || []).forEach((item) => {
This change ensures that an empty array is used if boundaryData
is falsy, making the intention clearer and maintaining consistent behavior.
📝 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.
boundaryData?.forEach((item) => { | |
(boundaryData || []).forEach((item) => { |
|
||
const selectedStructureCodes = campaignData?.flatMap((cycle) => |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Refactor duplicated logic for selectedStructureCodes
into a helper function
The computation of selectedStructureCodes
at lines 618-619 is duplicated elsewhere in the code (lines 923-924). To improve maintainability and reduce code duplication, consider extracting this logic into a reusable helper function.
Here's how you can refactor the code:
+ const getSelectedStructureCodes = (campaignData) =>
+ campaignData?.flatMap((cycle) =>
+ cycle?.deliveries?.flatMap((delivery) =>
+ delivery?.deliveryRules?.flatMap((rule) =>
+ rule?.attributes?.map((attribute) => attribute?.value)
+ )
+ )
+ );
...
- const selectedStructureCodes = campaignData?.flatMap((cycle) =>
- cycle?.deliveries?.flatMap((delivery) =>
- delivery?.deliveryRules?.flatMap((rule) =>
- rule?.attributes?.map((attribute) => attribute?.value)
- )
- )
- );
+ const selectedStructureCodes = getSelectedStructureCodes(campaignData);
Then, replace other occurrences of this computation with getSelectedStructureCodes(campaignData)
.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const selectedStructureCodes = campaignData?.flatMap((cycle) => | |
const getSelectedStructureCodes = (campaignData) => | |
campaignData?.flatMap((cycle) => | |
cycle?.deliveries?.flatMap((delivery) => | |
delivery?.deliveryRules?.flatMap((rule) => | |
rule?.attributes?.map((attribute) => attribute?.value) | |
) | |
) | |
); | |
const selectedStructureCodes = getSelectedStructureCodes(campaignData); |
const selectedStructureCodes = campaignData?.flatMap((cycle) => | ||
cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes.map((attribute) => attribute?.value))) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add missing optional chaining to prevent potential runtime errors
At lines 923-924, the optional chaining operator ?.
is missing before attributes
. If attributes
is undefined
, this could cause a runtime error when attempting to call .map()
on undefined
. Please add optional chaining for safer property access.
Apply this diff to fix the issue:
- cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule.attributes.map((attribute) => attribute?.value)))
+ cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value)))
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const selectedStructureCodes = campaignData?.flatMap((cycle) => | |
cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes.map((attribute) => attribute?.value))) | |
const selectedStructureCodes = campaignData?.flatMap((cycle) => | |
cycle?.deliveries?.flatMap((delivery) => delivery?.deliveryRules?.flatMap((rule) => rule?.attributes?.map((attribute) => attribute?.value))) |
attributes.push({ | ||
key: attributes.length + 1, | ||
value, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix Order of fromValue
and toValue
in IN_BETWEEN
Condition Construction.
In the processDoseCriteria
function, when handling the IN_BETWEEN
operator, the condition string appears to have fromValue
and toValue
swapped:
return `${attr.toValue} <= ${attr.attribute.code} < ${attr.fromValue}`;
This might be incorrect, as usually fromValue
should be less than toValue
. The correct condition should be:
- return `${attr.toValue} <= ${attr.attribute.code} < ${attr.fromValue}`;
+ return `${attr.fromValue} <= ${attr.attribute.code} < ${attr.toValue}`;
const fromValue = parts[4]; | ||
attributes.push({ | ||
key: 1, | ||
operator: { code: operatorMapping["IN_BETWEEN"] }, | ||
attribute: { code: parts[2] }, | ||
fromValue, | ||
toValue, | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct fromValue
and toValue
Assignment in reverseDeliveryRemap
.
In the parseConditionAndCreateRules
function within reverseDeliveryRemap
, the fromValue
and toValue
may be incorrectly assigned when parsing IN_BETWEEN
conditions:
const toValue = parts[0];
const fromValue = parts[4];
This assignment seems reversed. The correct assignment should be:
- const toValue = parts[0];
- const fromValue = parts[4];
+ const fromValue = parts[0];
+ const toValue = parts[4];
Summary by CodeRabbit
New Features
Bug Fixes
Refactor