Skip to content

Conversation

@REHAAANNN
Copy link

@REHAAANNN REHAAANNN commented Dec 13, 2025

Closes #

πŸ“ Description

πŸ”§ Changes Made

πŸ“· Screenshots or Visual Changes (if applicable)

🀝 Collaboration

Collaborated with: @username (optional)

βœ… Checklist

  • I have read the contributing guidelines.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added necessary documentation (if applicable).
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

Release Notes

  • New Features
    • Users can now mark medicines as taken or not taken directly from the medicine history screen.
    • Visual status indicators display whether each medicine entry has been marked as taken, with distinct styling applied for taken entries.
    • Tap the status icon next to each medicine to quickly toggle the taken state.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 13, 2025

Walkthrough

A new feature is added to mark medicines as taken or not taken. The backend introduces a PATCH endpoint at /medicine/<int:id>/taken to update the taken field and refresh the cache. The frontend adds a handler to send the request and UI elements (toggle icon and conditional text styling) to display and interact with the taken status.

Changes

Cohort / File(s) Summary
Backend API Endpoint
Backend/routes/medicine.py
Adds PATCH endpoint /medicine/<int:id>/taken to update medicine taken status, with authentication, database commit, cache refresh, and success response
Frontend Handler & UI
Frontend/src/Screens/MedicineScreen.jsx
Adds handleMarkAsTaken() handler to send PATCH request; introduces toggle icon (check-circle/radio-button-unchecked) and conditional text styling for taken entries

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Verify the PATCH endpoint correctly handles the taken field update and default value (true)
  • Confirm cache refresh mechanism executes after database commit
  • Validate frontend error handling and state synchronization after successful API response
  • Review UI state consistency between toggle icon and text styling
  • Ensure authentication protection is properly applied to the new endpoint

Poem

🐰 A little click, a toggle bright,
To mark each dose as taken right,
With icons dancing, check and blank,
The medicine tracker earned its rank!
πŸ’Šβœ¨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
βœ… Passed checks (2 passed)
Check name Status Explanation
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title clearly summarizes the main change: adding mark as taken functionality for the medicine tracker, which is confirmed by both backend and frontend changes.
✨ Finishing touches
  • πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (3)
Backend/routes/medicine.py (1)

163-163: Validate the taken field type for robustness.

The taken_status is extracted without type validation. While the frontend sends a boolean, a malformed request could pass a non-boolean value (e.g., string, number, null), which SQLite might coerce unexpectedly.

Apply this diff to add type validation:

-    taken_status = data.get('taken', True)  # Default to True if not specified
+    taken_status = data.get('taken', True)
+    if not isinstance(taken_status, bool):
+        return jsonify({"error": "Taken status must be a boolean"}), 400
Frontend/src/Screens/MedicineScreen.jsx (2)

129-141: Add response validation and consider optimistic updates.

The function doesn't validate the response status before refreshing. If the backend returns an error (e.g., 404, 500), the history is still refreshed, potentially showing stale data.

Apply this diff to validate the response:

 const handleMarkAsTaken = async (id, currentStatus) => {
   try {
-    await fetch(`${BASE_URL}/medicine/${id}/taken`, {
+    const response = await fetch(`${BASE_URL}/medicine/${id}/taken`, {
       method: 'PATCH',
       headers: {'Content-Type': 'application/json'},
       body: JSON.stringify({taken: !currentStatus}),
     });
+    if (!response.ok) {
+      throw new Error(`Server responded with ${response.status}`);
+    }
     fetchMedicineHistory();
   } catch (err) {
     console.error('Failed to mark medicine:', err);
     Alert.alert('Error', 'Failed to update medicine status.');
   }
 };

Alternatively, consider implementing optimistic updates to improve perceived responsiveness.


216-222: Consider debouncing to prevent race conditions.

Rapid clicks on the icon could trigger multiple concurrent PATCH requests, leading to inconsistent state or unexpected toggle behavior.

Add a loading state or debounce the handler:

const [updatingMedicine, setUpdatingMedicine] = useState(null);

const handleMarkAsTaken = async (id, currentStatus) => {
  if (updatingMedicine === id) return; // Prevent concurrent updates
  setUpdatingMedicine(id);
  
  try {
    const response = await fetch(`${BASE_URL}/medicine/${id}/taken`, {
      method: 'PATCH',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({taken: !currentStatus}),
    });
    if (!response.ok) {
      throw new Error(`Server responded with ${response.status}`);
    }
    fetchMedicineHistory();
  } catch (err) {
    console.error('Failed to mark medicine:', err);
    Alert.alert('Error', 'Failed to update medicine status.');
  } finally {
    setUpdatingMedicine(null);
  }
};

Conditionally disable the icon while updating:

<TouchableOpacity 
  onPress={() => handleMarkAsTaken(entry.id, entry.taken)}
  disabled={updatingMedicine === entry.id}>
  <Icon
    name={entry.taken ? 'check-circle' : 'radio-button-unchecked'}
    size={24}
    color={updatingMedicine === entry.id ? '#bdc3c7' : (entry.taken ? '#27ae60' : '#95a5a6')}
    style={styles.checkIcon}
  />
</TouchableOpacity>
πŸ“œ Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between a76d240 and b2fa48a.

πŸ“’ Files selected for processing (2)
  • Backend/routes/medicine.py (1 hunks)
  • Frontend/src/Screens/MedicineScreen.jsx (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
Backend/routes/medicine.py (3)
Backend/db/db.py (1)
  • open_db (8-13)
Backend/agent/agent.py (2)
  • get_agent (97-102)
  • update_cache (63-72)
Backend/agent/cache.py (1)
  • update_cache (270-364)
πŸ”‡ Additional comments (3)
Frontend/src/Screens/MedicineScreen.jsx (2)

372-378: LGTM!

The styling for taken entries is clear and appropriate. The line-through decoration and muted color effectively communicate the taken state.


216-222: > Likely an incorrect or invalid review comment.

Backend/routes/medicine.py (1)

152-174: The database schema correctly includes the taken column.

The weekly_medicine table in Backend/schema.sql defines taken as a BOOLEAN column with a default value of 0, confirming the endpoint implementation is properly supported by the schema.

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.

1 participant