-
Notifications
You must be signed in to change notification settings - Fork 514
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
Fix state & district autofill & multiple other small issues in Patient Registration page #9711
base: develop
Are you sure you want to change the base?
Fix state & district autofill & multiple other small issues in Patient Registration page #9711
Conversation
WalkthroughThe pull request introduces enhancements to the patient registration process by implementing automatic state and district selection based on the entered pincode. Key modifications are made to the Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
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 (
|
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
async function fetchOrganizationByName(name: string, parentId?: string) { | ||
try { | ||
const data = await query(organizationApi.list, { | ||
queryParams: { | ||
org_type: "govt", | ||
parent: parentId || "", | ||
name, | ||
}, | ||
})({ signal: new AbortController().signal }); | ||
return data.results?.[0]; | ||
} catch (error) { | ||
toast.error("Error fetching organization"); | ||
return undefined; | ||
} | ||
} |
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.
At some point, we may need to extract this into a separate hook
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.
Yea, go ahead and do that since same logic is being used in #9662.
Also check Rithvik's comment below.
cc: @Mahendar0701
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: 0
🧹 Nitpick comments (6)
src/pages/Organization/components/OrganizationSelector.tsx (2)
23-24
: Add documentation for new props.
Prefer adding a short explanation or a JSDoc comment forparentSelectedLevels
anderrorMessage
to guide future maintainers on their usage.
170-171
: Push only meaningful errors.
errors={[props.errorMessage || ""]}
might cause an empty string to appear if there's no actual error. Consider conditionally passing an empty array instead to avoid confusing UI.-errors={[props.errorMessage || ""]} +errors={props.errorMessage ? [props.errorMessage] : []}src/components/Patient/PatientRegistration.tsx (4)
6-6
: Confirm i18n usage for toast messages.
Since you are using translations in other notifications, consider localizing toast errors to maintain a consistent user experience.
208-213
: Consider grouping pincode org fetch logic.
The logic fetches the state org first, then setsselectedLevels
to[]
early if state org is not found. Consider returning a partial selection if the state is found but not the district – or add a fallback mechanism.
326-340
: Add robust error details.
toast.error("Error fetching organization")
might leave users uncertain about the exact cause. Consider including the organization name in the error text or using a more descriptive message.
625-625
: Improve UX for disabled text area.
You correctly remove editing withcursor-not-allowed
if addresses match. Optionally, add a tooltip or note explaining why the field is disabled for clarity.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/components/Patient/PatientRegistration.tsx
(7 hunks)src/pages/Organization/components/OrganizationSelector.tsx
(5 hunks)
🔇 Additional comments (6)
src/pages/Organization/components/OrganizationSelector.tsx (3)
33-36
: Initialize state thoughtfully.
UsingparentSelectedLevels || []
is fine. Consider logging or handling scenarios whereparentSelectedLevels
might be empty due to unexpected data, ensuring robust default behaviors.
112-124
: Validate data removal edge cases.
When the user removes all levels (newLevels.length === 0
), you reset the selection. This is correct for typical usage. Confirm that removing the top-level organization doesn't break parent-child flows if the parent-level has siblings or alternative branches.
127-132
: Avoid re-initialization loops.
TheuseEffect
reassigns state whenparentSelectedLevels
changes. This is correct but be aware of potential repeated updates if parent-level changes are frequent.src/components/Patient/PatientRegistration.tsx (3)
85-85
: Validate usage of local org state.
selectedLevels
is used to maintain hierarchical organization data derived from the pincode. Ensure that clearing it in one place does not inadvertently disrupt other parts of registration.
219-222
: Handle partial fetch failures.
If the district API fails, current logic omits selecting the state org. Evaluate whether you want to preserve the state org even if the district is not found.
676-683
: Check null-safety for error message.
You passerrorMessage={errors.geo_organization?.[0]}
but ifgeo_organization
is missing or empty, it may show an undefined or empty string inOrganizationSelector
. Confirm the UI reflects a real error only when relevant.
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.
not a fan of this approach. how about we stick with how dependent queries are made as per tanstacks docs?
this way we wouldn't need to try catch either and stick with the simplicity.
cc @bodhish
👋 Hi, @yash-learner, This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there. |
|
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: 0
🧹 Nitpick comments (12)
src/hooks/useOrganization.ts (2)
7-12
: Add User Facing Documentation Comment forUseOrganizationParams
Though this interface is self-explanatory, adding a short JSDoc comment or code comment could clarify the accepted parameters for future maintainers and reduce confusion about which fields are optional.
20-31
: Ensure error handling is robustWhile
isError
is returned, there is no specialized error handling in thequeryFn
or anonError
callback for the query. If additional failover or fallback logic is required when the API call fails, consider adding a customonError
in theuseQuery
options or a shared error boundary.src/hooks/useStateAndDistrictFromPincode.ts (3)
14-16
: Clarify hook naming or add doc commentThe function name
useStateAndDistrictFromPincode
is descriptive, but consider adding inline documentation about how it fetches pincode details, extracts the state and district, and loads the corresponding organizations. This can improve maintainability.
43-53
: Consider concurrency or caching benefitsThe second organization query is nested behind the first's result for
stateOrg?.id
. This is logical. If you anticipate repeated lookups or the same pincodes, ensure that React Query’s caching strategy is adequately configured to minimize network calls.
56-61
: CombineisError
states carefullyThis hook merges three possible error states into one, which is correct for a simplified approach. However, distinct error messages can help users identify which step failed (e.g., the pincode fetch vs. the state org fetch). Consider returning more granular error states if needed.
src/components/Patient/PatientRegistration.tsx (7)
6-6
: Check the usage ofCareIcon
importThe
CareIcon
import is newly added. Verify whether all necessary icons are being efficiently imported. For performance, you might consider a dynamic icon library approach if your codebase loads many icons.
30-30
: Mention the custom hook in documentation or inline comments
useStateAndDistrictFromPincode
is introduced here. A short comment indicating its purpose in the patient registration flow (e.g., “Auto-fills state and district based on pincode”) could guide future contributors.
79-79
: Refactor state management for clarity
selectedLevels
andsetSelectedLevels
hold the acquired organizations. Consider whether these should be combined or abstracted to a single object (likegeoOrganization
) if there’s no plan to scale beyond two levels. This might simplify future expansions.
189-191
: Decouple logic from the UI effectThe
useStateAndDistrictFromPincode
hook is invoked inline here. If you anticipate using the same logic in other forms, it might be beneficial to centralize or abstract the effect of pincode changes, e.g., in a custom reducer or separate function for clarity.
194-206
: Enhance user feedback for partial auto-fillIf some part of the data can’t be automatically derived from the pincode (e.g., the district wasn’t found), the
pincode_autofill
message still appears iflevels.length > 0
. Consider either partial messages or fallback for missing details.
580-580
: UI clarity for disabled text areaWhen
sameAddress
is true, the permanent address is disabled. Thecursor-not-allowed
is good, but consider adding a tooltip or helper text to clarify that the permanent address matches the current address. This could improve UX.
Line range hint
596-606
: Refine timed feedback approachYou’re displaying
_showAutoFilledPincode
for 2 seconds to highlight auto-filling. This is a subtle user experience detail. If users need more time or have accessibility needs, consider a more stable or dismissible notification.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/components/Patient/PatientRegistration.tsx
(8 hunks)src/hooks/useOrganization.ts
(1 hunks)src/hooks/useStateAndDistrictFromPincode.ts
(1 hunks)
🔇 Additional comments (5)
src/hooks/useOrganization.ts (1)
14-19
: Confirm default parameter usage logicCurrently, the default values for
orgType
,parentId
, andname
are all empty strings. If the intended scenario requires no query to run until a validname
is provided, this setup is fine. Otherwise, you might consider enabling queries based on other parameter conditions (likeorgType
).src/hooks/useStateAndDistrictFromPincode.ts (2)
17-25
: Validate pincode more thoroughly
validatePincode(pincode)
is used to control theenabled
property, but ensure it returnsfalse
for invalid or partial input. If user input can be partially typed, consider whether the query should wait until the pincode is a specific length (e.g., 6 digits in India).
30-40
: Check for fallback behavior whenstateName
is missingIf
pincodeDetails.statename
is an empty string, the state query is disabled, which is correct. Just confirm that this is the desired behavior. If there is a possibility of partial matches or alternate naming, you might need more robust fallback or alias logic forstateName
.src/components/Patient/PatientRegistration.tsx (2)
43-46
: Validate usage of new or changed importsWith the introduction of
OrganizationSelector
from@/pages/Organization/components/OrganizationSelector
, ensure no cyclical imports exist and confirm version compatibility. This is more of a housekeeping check.
631-638
: Verify theOrganizationSelector
usage
OrganizationSelector
is receivingparentSelectedLevels
and anerrorMessage
. Ensure that the error logic is consistent with your form validation approach. If you have an external form library or inline validation, confirm that the error message updates as expected.
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: 0
🧹 Nitpick comments (3)
src/pages/Organization/components/OrganizationSelector.tsx (3)
33-36
: Consider optimizing for reference stability.While the implementation is functionally correct, consider adding a deep comparison to prevent unnecessary re-renders when only the reference of
parentSelectedLevels
changes but the content remains the same.useEffect(() => { if (parentSelectedLevels) { + const hasChanged = JSON.stringify(parentSelectedLevels) !== JSON.stringify(selectedLevels); + if (hasChanged) { setSelectedLevels(parentSelectedLevels); + } } }, [parentSelectedLevels]);Also applies to: 123-127
108-120
: Consider simplifying the control flow.While the logic is correct, the nested if-else structure could be simplified for better readability.
const handleEdit = (level: number) => { const newLevels = selectedLevels.slice(0, level); setSelectedLevels(newLevels); - if (!newLevels.length) { - onChange(""); - } else { - const lastOrg = newLevels[newLevels.length - 1]; - if (!lastOrg.has_children) { - onChange(lastOrg.id); - } else { - onChange(""); - } - } + const lastOrg = newLevels[newLevels.length - 1]; + const newValue = lastOrg && !lastOrg.has_children ? lastOrg.id : ""; + onChange(newValue); };
170-171
: Simplify required prop and improve error handling.Two minor improvements could be made:
- The double negation (
!!
) is unnecessary sincerequired
is already boolean- Consider passing undefined instead of an empty string array when there's no error
- required={!!required} - errors={[props.errorMessage || ""]} + required={required} + errors={props.errorMessage ? [props.errorMessage] : undefined}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/pages/Organization/components/OrganizationSelector.tsx
(5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: cypress-run (1)
- GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
src/pages/Organization/components/OrganizationSelector.tsx (2)
22-23
: LGTM! Well-structured prop additions.The new optional props enhance the component's flexibility while maintaining type safety.
31-31
: Address the TODO comment for component renaming.The TODO comment suggests renaming to
GovtOrganizationSelector
. This would indeed better reflect the component's specific purpose, as it's currently hardcoded to handle government organizations (org_type: "govt"
).Would you like me to help create a GitHub issue to track this renaming task? This would include:
- Renaming the component
- Updating all imports
- Updating documentation
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: 0
🧹 Nitpick comments (6)
src/hooks/useOrganization.ts (2)
23-24
: Consider enhancing the query key specificity.The current query key
["organization", orgType, name, parentId]
could potentially cause cache collisions. Consider adding a more specific prefix.- queryKey: ["organization", orgType, name, parentId], + queryKey: ["organization", "list", orgType, name, parentId],
37-37
: Enhance error toast message with more context.The generic error message could be more helpful by including the context of what failed.
- isError && toast.error(t("organizations_fetch_error")); + isError && toast.error(t("organizations_fetch_error", { context: `${orgType}${parentId ? ' for parent ' + parentId : ''}` }));src/hooks/useStateAndDistrictFromPincode.ts (2)
58-62
: Consider combining error notifications.Multiple toast notifications for state and district errors might overwhelm the user. Consider combining them into a single notification.
- isStateError && toast.info(t("pincode_state_auto_fill_error")); - - isDistrictError && - !isStateError && - toast.info(t("pincode_district_auto_fill_error")); + useEffect(() => { + if (isStateError || isDistrictError) { + const errors = []; + if (isStateError) errors.push(t("pincode_state_auto_fill_error")); + if (isDistrictError && !isStateError) errors.push(t("pincode_district_auto_fill_error")); + toast.info(errors.join(". ")); + } + }, [isStateError, isDistrictError, t]);
34-56
: Consider combining state and district queries.The separate queries for state and district organizations could be combined using a single useQuery to reduce network requests.
+ const { data: orgs, isLoading, isError } = useQuery({ + queryKey: ["organizations", "state-district", stateName, districtName], + queryFn: async () => { + const stateOrg = await organizationApi.list({ + org_type: "govt", + name: stateName + }); + if (stateOrg.results?.[0]) { + const districtOrg = await organizationApi.list({ + org_type: "govt", + parent: stateOrg.results[0].id, + name: districtName + }); + return { + stateOrg: stateOrg.results[0], + districtOrg: districtOrg.results[0] + }; + } + return { stateOrg: null, districtOrg: null }; + }, + enabled: !!stateName && !!districtName + });src/components/Patient/PatientRegistration.tsx (2)
189-206
: Consider extracting form management logic into a custom hook.The form management logic, including the pincode-based autofill functionality, could be extracted into a custom hook to improve maintainability and reusability.
// usePatientRegistrationForm.ts export function usePatientRegistrationForm(initialData?: Partial<PatientModel>) { const [form, setForm] = useState<Partial<PatientModel>>(initialData || { nationality: "India", phone_number: "+91", emergency_phone_number: "+91", }); const { stateOrg, districtOrg } = useStateAndDistrictFromPincode({ pincode: form.pincode?.toString() || "", }); const [selectedLevels, setSelectedLevels] = useState<Organization[]>([]); const [showAutoFilledPincode, setShowAutoFilledPincode] = useState(false); useEffect(() => { const levels: Organization[] = []; if (stateOrg) levels.push(stateOrg); if (districtOrg) levels.push(districtOrg); setSelectedLevels(levels); if (levels.length === 2) { setShowAutoFilledPincode(true); const timer = setTimeout(() => { setShowAutoFilledPincode(false); }, 2000); return () => clearTimeout(timer); } }, [stateOrg, districtOrg]); return { form, setForm, selectedLevels, showAutoFilledPincode }; }
Line range hint
596-606
: Extract autofill notification into a separate component.The autofill notification UI could be extracted into a reusable component.
// AutofillNotification.tsx interface AutofillNotificationProps { show: boolean; message: string; } function AutofillNotification({ show, message }: AutofillNotificationProps) { if (!show) return null; return ( <div> <CareIcon icon="l-check-circle" className="mr-2 text-sm text-green-500" /> <span className="text-sm text-primary-500"> {message} </span> </div> ); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
public/locale/en.json
(2 hunks)src/components/Patient/PatientRegistration.tsx
(8 hunks)src/hooks/useOrganization.ts
(1 hunks)src/hooks/useStateAndDistrictFromPincode.ts
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/hooks/useOrganization.ts (1)
31-31
: LGTM! Smart query enablement condition.The query is enabled only when both conditions are met:
enabled && !!name
. This prevents unnecessary API calls.src/hooks/useStateAndDistrictFromPincode.ts (1)
26-26
: LGTM! Smart validation before query.Using
validatePincode
before enabling the query prevents unnecessary API calls with invalid pincodes.src/components/Patient/PatientRegistration.tsx (1)
631-638
: LGTM! Proper prop passing to OrganizationSelector.The component correctly passes both
parentSelectedLevels
anderrorMessage
props to handle the organization selection and validation.public/locale/en.json (1)
1305-1305
: LGTM! Error messages are clear and well-structured.The new error messages for organization fetching and pincode-based autofill failures are user-friendly and provide specific feedback without exposing technical details.
Also applies to: 1396-1397
Proposed Changes
auto_fill_state_._district_based_on_pincode.webm
@ohcnetwork/care-fe-code-reviewers
Merge Checklist
Summary by CodeRabbit
New Features
Bug Fixes
Improvements