Skip to content

fix: code quality and safety improvements - #743

Open
saurabhhhcodes wants to merge 1 commit into
roshankumar0036singh:mainfrom
saurabhhhcodes:fix/Uni-Event-19707
Open

fix: code quality and safety improvements#743
saurabhhhcodes wants to merge 1 commit into
roshankumar0036singh:mainfrom
saurabhhhcodes:fix/Uni-Event-19707

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling when calendar requests fail.
    • Added safer handling and logging for push notification registration errors.
    • Added error logging when attendance data cannot be loaded.
  • Tests
    • Updated critical-flow test setup and error handling for more reliable test execution.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The changes add HTTP failure checks to calendar requests, add logging for rejected push registration and attendance fetch operations, remove push notification listeners and returned state, and replace Cypress mock-user setup with error logging.

Changes

Error handling updates

Layer / File(s) Summary
Calendar request validation
app/src/lib/CalendarService.js
createMeetEvent and addToCalendar now throw "Request failed" before parsing unsuccessful responses.
Application error handling
app/src/lib/usePushNotifications.js, app/src/screens/AttendanceDashboard.js
Push registration and attendance event loading now log errors. Push notification listeners, cleanup, and returned state were removed.
Cypress setup handling
app/cypress/e2e/critical_flows.cy.js
The mock-user setup was removed. Setup errors are logged with console.error.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: quality:clean, type:refactor

Suggested reviewers: atul-upadhyay-7, roshankumar0036singh

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title broadly refers to the changes but uses generic terms and does not identify the error-handling or behavior changes. Use a specific title, such as "fix: add fetch error handling and simplify notification setup".
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Biome (2.5.5)
app/src/lib/usePushNotifications.js

File contains syntax errors that prevent linting: Line 55: Expected a statement but instead found '.catch(err => console.error(err))'.; Line 55: expected } but instead the file ends

app/cypress/e2e/critical_flows.cy.js

File contains syntax errors that prevent linting: Line 6: Expected a statement but instead found '.catch(err => console.error(err))'.; Line 6: expected } but instead the file ends

app/src/screens/AttendanceDashboard.js

File contains syntax errors that prevent linting: Line 167: Expected a statement but instead found '.catch(err => console.error(err))'.; Line 167: expected } but instead the file ends

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

app/cypress/e2e/critical_flows.cy.js

ESLint skipped: missing config or dependency (missing-dependency). The ESLint configuration references a package that is not available in the sandbox.

app/src/lib/CalendarService.js

ESLint skipped: the ESLint configuration for this file references a package that is not available in the sandbox.

app/src/lib/usePushNotifications.js

ESLint skipped: the ESLint configuration for this file references a package that is not available in the sandbox.

  • 1 others

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.

Warning

⚠️ This pull request has been flagged as potential spam (vandalism) by CodeRabbit slop detection and should be reviewed carefully.

@sonarqubecloud

sonarqubecloud Bot commented Aug 1, 2026

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/cypress/e2e/critical_flows.cy.js`:
- Line 6: Restore authenticated mock-user setup in the protected flow tests by
calling globalThis.setMockUser(...) after cy.visit('/') in the critical flow
setup. Ensure the mock user is configured before the flow assertions execute,
preserving the existing test sequence and error handling.
- Line 6: Fix the cy.window() setup in the beforeEach hook by completing or
removing the .then(win => { callback; do not attach .catch(...) as a Cypress
command-chain API. Ensure the beforeEach and describe blocks are properly closed
so the spec parses successfully.

In `@app/src/lib/CalendarService.js`:
- Around line 87-88: Update the calendar response mocks used by the affected
tests to include ok: true for body-error scenarios, preserving their expected
“API Failure” and “Calendar Failure” results. Add a separate mock with ok: false
to cover the HTTP-failure branch introduced by the response.ok guard in the
calendar request functions.

In `@app/src/lib/usePushNotifications.js`:
- Line 55: Complete the promise chains and closing braces at
app/src/lib/usePushNotifications.js:55 by attaching catch to the registration
promise, then closing useEffect and usePushNotifications; at
app/src/screens/AttendanceDashboard.js:167, close the event-document then
callback, attach catch to the promise chain, and close useEffect and the
component.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d3a7e698-1974-47bc-a95a-2dbf65718f72

📥 Commits

Reviewing files that changed from the base of the PR and between ecf85dc and 4060bac.

📒 Files selected for processing (4)
  • app/cypress/e2e/critical_flows.cy.js
  • app/src/lib/CalendarService.js
  • app/src/lib/usePushNotifications.js
  • app/src/screens/AttendanceDashboard.js

cy.get('[data-testid="clear-search-button"]').should('exist');
});
});
.catch(err => console.error(err)) No newline at end of file

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg '(^|/)critical_flows\.cy\.js$|(^|/)AuthContext\.js$|(^|/).*[Ll]og[Ll]og|setMockUser|cy\.visit|cy\.getLogin' || true

echo "== target file outlint/section =="
if [ -f app/cypress/e2e/critical_flows.cy.js ]; then
  wc -l app/cypress/e2e/critical_flows.cy.js
  cat -n app/cypress/e2e/critical_flows.cy.js
fi

echo "== AuthContext section =="
if [ -f app/src/lib/AuthContext.js ]; then
  wc -l app/src/lib/AuthContext.js
  cat -n app/src/lib/AuthContext.js | sed -n '1,140p'
fi

echo "== usages in cypress =="
rg -n "setMockUser|mock(user|User)|cy\.visit|beforeEach|AuthContext|cy\.login|login" app/cypress app/src -S || true

echo "== diff stat =="
git diff --stat || true
git diff -- app/cypress/e2e/critical_flows.cy.js app/src/lib/AuthContext.js || true

Repository: roshankumar0036singh/Uni-Event

Length of output: 13105


Restore the mock-user setup for protected flow tests.

app/cypress/e2e/critical_flows.cy.js now visits / without calling setMockUser, so these assertions can run with no authenticated user state. Call globalThis.setMockUser(...) after cy.visit('/') or add another authenticated setup before the flow tests.

🧰 Tools
🪛 Biome (2.5.5)

[error] 6-6: Expected a statement but instead found '.catch(err => console.error(err))'.

(parse)


[error] 6-6: expected } but instead the file ends

(parse)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/cypress/e2e/critical_flows.cy.js` at line 6, Restore authenticated
mock-user setup in the protected flow tests by calling
globalThis.setMockUser(...) after cy.visit('/') in the critical flow setup.
Ensure the mock user is configured before the flow assertions execute,
preserving the existing test sequence and error handling.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file exists and size =="
git ls-files | grep -F 'app/cypress/e2e/critical_flows.cy.js' || true
wc -l app/cypress/e2e/critical_flows.cy.js

echo "== relevant file contents =="
cat -n app/cypress/e2e/critical_flows.cy.js

echo "== search for mock user/window context =="
rg -n "setMockUser|beforeEach|describe|cy\.window|window" app/cypress/e2e app -S || true

Repository: roshankumar0036singh/Uni-Event

Length of output: 7621


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== JS parse/check for critical_flows =="
node - <<'JS'
const fs = require('fs');
const path = 'app/cypress/e2e/critical_flows.cy.js';
const src = fs.readFileSync(path, 'utf8');
try {
  new Function(src);
  console.log('node parses: ok');
} catch (err) {
  console.log(`node parse error: ${err.name}: ${err.message}`);
  console.log(err.stack.split('\n').slice(0, 3).join('\n'));
}
JS

echo "== package/cypress tooling availability =="
node - <<'JS'
for (const mod of ['cypress']) {
  try {
    const p = require.resolve(mod);
    console.log(`${mod}: ${p}`);
  } catch (err) {
    console.log(`${mod}: not resolvable`);
  }
}
JS

echo "== Cypress package files mentioning catch handling / .then signatures =="
fd -a 'package.json|CHANGELOG.md|dist|src' app 2>/dev/null | sed 's#^\./##' | head -50 || true

Repository: roshankumar0036singh/Uni-Event

Length of output: 551


Fix the malformed Cypress chain before merging.

Line 5 opens a .then(win => { callback, but line 6 starts with .catch(...) instead of using catch inside that callback. The beforeEach and describe blocks are also not closed, so this spec cannot be parsed.

Complete or remove the cy.window() setup, then close beforeEach and describe; .catch is not a command-chain API and should not attach here if command failures are being handled.

🧰 Tools
🪛 Biome (2.5.5)

[error] 6-6: Expected a statement but instead found '.catch(err => console.error(err))'.

(parse)


[error] 6-6: expected } but instead the file ends

(parse)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/cypress/e2e/critical_flows.cy.js` at line 6, Fix the cy.window() setup in
the beforeEach hook by completing or removing the .then(win => { callback; do
not attach .catch(...) as a Cypress command-chain API. Ensure the beforeEach and
describe blocks are properly closed so the spec parses successfully.

Source: Linters/SAST tools

Comment on lines +87 to +88
if (!response.ok) throw new Error("Request failed");
const data = await response.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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg 'app/src/lib/(CalendarService\.js|__tests__/CalendarService\.test\.js)$' || true

echo "== CalendarService outline =="
ast-grep outline app/src/lib/CalendarService.js || true

echo "== CalendarService relevant lines =="
sed -n '1,140p' app/src/lib/CalendarService.js

echo "== CalendarService tests relevant lines =="
sed -n '1,220p' app/src/lib/__tests__/CalendarService.test.js

echo "== fetch resolvers in tests =="
python3 - <<'PY'
from pathlib import Path
p=Path('app/src/lib/__tests__/CalendarService.test.js')
s=p.read_text()
for i,line in enumerate(s.splitlines(),1):
    if 'mockResolvedValueOnce' in line or 'mockRejectedValueOnce' in line:
        print(f"{i}: {line}")
PY

Repository: roshankumar0036singh/Uni-Event

Length of output: 8698


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== deterministic probe for response.ok guard behavior =="
python3 - <<'PY'
def read_error_mock_without_ok(body_error='API Failure'):
    response = {
        "ok": None,
        "status": None,
        "json": lambda: {"error": body_error}
    }
    try:
        if not response["ok"]:
            raise Exception("Request failed")
        data = response["json"]()
        return ("parsed", data)
    except Exception as e:
        return ("raised", str(e))

for body in ["API Failure", "Calendar Failure"]:
    print({body: read_error_mock_without_ok(body)})
PY

Repository: roshankumar0036singh/Uni-Event

Length of output: 322


Update the calendar response mocks for the new response.ok guard.

Both failing calendar tests return mock responses without ok, and both functions now check if (!response.ok) before parsing response bodies. As written, these tests throw "Request failed" instead of "API Failure" or "Calendar Failure". Add ok: true to the body-error mocks and add a separate ok: false HTTP-failure path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/lib/CalendarService.js` around lines 87 - 88, Update the calendar
response mocks used by the affected tests to include ok: true for body-error
scenarios, preserving their expected “API Failure” and “Calendar Failure”
results. Add a separate mock with ok: false to cover the HTTP-failure branch
introduced by the response.ok guard in the calendar request functions.


return { expoPushToken, notification };
};
.catch(err => console.error(err)) No newline at end of file

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Locate files =="
git ls-files | rg '(^|/)usePushNotifications\.js$|(^|/)AttendanceDashboard\.js$' || true

echo "== Show relevant slices with line numbers =="
for f in app/src/lib/usePushNotifications.js app/src/screens/AttendanceDashboard.js; do
  if [ -f "$f" ]; then
    echo "--- $f ($(wc -l < "$f") lines) ---"
    sed -n '1,120p' "$f" | cat -n
  else
    echo "missing $f"
  fi
done

echo "== Parse check with Node parser (read-only) =="
python3 - <<'PY'
from pathlib import Path
files = Path('app/src/lib/usePushNotifications.js').resolve(), Path('app/src/screens/AttendanceDashboard.js').resolve()
for p in files:
    if p.exists():
        print(p)
        print(open(p, encoding='utf-8').read()[-1200:])
PY

Repository: roshankumar0036singh/Uni-Event

Length of output: 10110


🌐 Web query:

AttendanceDashboard.js 167 getDoc doc(db COLLECTIONS.EVENTS eventId) then catch

💡 Result:

In the Firebase Modular SDK (v9+), the getDoc function returns a Promise that resolves to a DocumentSnapshot [1]. You can handle this operation using either the.then.catch pattern or async/await syntax [2][3]. Based on your query regarding AttendanceDashboard.js, the following implementation shows how to use getDoc with a promise chain and error handling: import { doc, getDoc } from "firebase/firestore"; // Assuming db and COLLECTIONS.EVENTS are defined correctly const docRef = doc(db, COLLECTIONS.EVENTS, eventId); getDoc(docRef).then((docSnap) => { if (docSnap.exists) { console.log("Document data:", docSnap.data); } else { console.log("No such document!"); } }).catch((error) => { console.error("Error getting document:", error); }); Key points for this implementation: 1. Document Reference: Use the doc function to create a reference to the specific document, passing the database instance, collection name, and document ID [2][4]. 2. Fetching: getDoc is an asynchronous operation that returns a Promise [1]. 3. Existence Check: Always check if the document exists using the.exists method on the returned snapshot before attempting to access its data with.data [2][5][6]. 4. Error Handling: The.catch block will capture errors related to the fetch operation, such as permission issues or network failures [2][3]. Alternatively, many developers prefer async/await for cleaner syntax: try { const docSnap = await getDoc(docRef); if (docSnap.exists) { console.log("Document data:", docSnap.data); } else { console.log("No such document!"); } } catch (error) { console.error("Error getting document:", error); }

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== AttendanceDashboard remaining lines =="
sed -n '140,180p' app/src/screens/AttendanceDashboard.js | cat -n

echo "== usePushNotifications remaining lines =="
sed -n '50,70p' app/src/lib/usePushNotifications.js | cat -n

echo "== Deterministic JS parse probe for dangling catch syntax =="
node - <<'JS'
const snippet = `
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
.catch(err => console.error(err))
`;
try {
  Function(snippet);
  console.log("Parses as", true);
} catch (err) {
  console.log("Parses as", false, err.message);
}
JS

Repository: roshankumar0036singh/Uni-Event

Length of output: 1732


Complete the broken promise chains and closures.

Both changed files stop before the useEffect, hook, or component closing braces, and each leaves .catch as an invalid standalone statement.

  • app/src/lib/usePushNotifications.js#L55: attach .catch to the registration promise, close useEffect, and close usePushNotifications.
  • app/src/screens/AttendanceDashboard.js#L167: close the event-document then, then attach .catch, close useEffect, and close the component.
🧰 Tools
🪛 Biome (2.5.5)

[error] 55-55: Expected a statement but instead found '.catch(err => console.error(err))'.

(parse)


[error] 55-55: expected } but instead the file ends

(parse)

📍 Affects 2 files
  • app/src/lib/usePushNotifications.js#L55-L55 (this comment)
  • app/src/screens/AttendanceDashboard.js#L167-L167
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/lib/usePushNotifications.js` at line 55, Complete the promise chains
and closing braces at app/src/lib/usePushNotifications.js:55 by attaching catch
to the registration promise, then closing useEffect and usePushNotifications; at
app/src/screens/AttendanceDashboard.js:167, close the event-document then
callback, attach catch to the promise chain, and close useEffect and the
component.

Source: Linters/SAST tools

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