Skip to content

Comments

refactor: add logging in getCalEventResponses#23420

Merged
Ryukemeister merged 2 commits intomainfrom
refactor/add-logging
Aug 29, 2025
Merged

refactor: add logging in getCalEventResponses#23420
Ryukemeister merged 2 commits intomainfrom
refactor/add-logging

Conversation

@Udit-takkar
Copy link
Contributor

@Udit-takkar Udit-takkar commented Aug 28, 2025

What does this PR do?

  • Fixes #XXXX (GitHub issue number)
  • Fixes CAL-XXXX (Linear issue number - should be visible at the bottom of the GitHub issue description)

Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • N/A I have updated the developer docs in /docs if this PR makes changes that would require a documentation change. If N/A, write N/A here and check the checkbox.
  • N/A I confirm automated tests are in place that prove my fix is effective or that my feature works.

How should this be tested?

@Udit-takkar Udit-takkar requested a review from a team as a code owner August 28, 2025 10:07
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 28, 2025

Walkthrough

The change updates getCalEventResponses in packages/features/bookings/lib/getCalEventResponses.ts. It adds structured logging via a sub-logger prefixed "[getCalEventResponses]". The function’s input object now optionally includes responses (typed as z.infer) and seatsEnabled. Response selection prefers the provided responses, falling back to booking data. If email is absent and attendeePhoneNumber is not a string, it logs an error with context and throws a 400 HttpError. If attendeePhoneNumber is a string, email is constructed from it.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/add-logging

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@graphite-app graphite-app bot requested a review from a team August 28, 2025 10:07
@github-actions
Copy link
Contributor

github-actions bot commented Aug 28, 2025

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.

Details:

Unknown release type "refactro" found in pull request title "refactro: add logging in getCalEventResponses". 

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

@keithwillcode keithwillcode added core area: core, team members only enterprise area: enterprise, audit log, organisation, SAML, SSO labels Aug 28, 2025
@Ryukemeister Ryukemeister changed the title refactro: add logging in getCalEventResponses refactor: add logging in getCalEventResponses Aug 28, 2025
@dosubot dosubot bot added bookings area: bookings, availability, timezones, double booking 💻 refactor labels Aug 28, 2025
@vercel
Copy link

vercel bot commented Aug 28, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

2 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
cal Ignored Ignored Aug 28, 2025 10:09am
cal-eu Ignored Ignored Aug 28, 2025 10:09am

@Ryukemeister Ryukemeister enabled auto-merge (squash) August 28, 2025 10:09
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: 2

Caution

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

⚠️ Outside diff range comments (1)
packages/features/bookings/lib/getCalEventResponses.ts (1)

15-40: Clone input responses to prevent unintended mutations
Wrap the resolved backwardCompatibleResponses in a shallow copy before assigning to email (and any other fields), e.g.:

// before mutation
const original = responses ?? getBookingWithResponses(booking!).responses;
const backwardCompatibleResponses = { ...original }; // clone

// then safely set placeholder email
if (!backwardCompatibleResponses.email) {
  backwardCompatibleResponses.email = constructEmailFromPhoneNumber(
    backwardCompatibleResponses.attendeePhoneNumber
  );
}
🧹 Nitpick comments (1)
packages/features/bookings/lib/getCalEventResponses.ts (1)

61-63: Trim phone before deriving email (minor hardening).

Apply:

-    backwardCompatibleResponses["attendeePhoneNumber"]
+    backwardCompatibleResponses["attendeePhoneNumber"].trim()
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f1d7d7f and 639bb95.

📒 Files selected for processing (1)
  • packages/features/bookings/lib/getCalEventResponses.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/features/bookings/lib/getCalEventResponses.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/features/bookings/lib/getCalEventResponses.ts
**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.

Files:

  • packages/features/bookings/lib/getCalEventResponses.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: Udit-takkar
PR: calcom/cal.com#22919
File: packages/features/calAIPhone/providers/retellAI/services/PhoneNumberService.ts:212-220
Timestamp: 2025-08-08T10:26:13.362Z
Learning: In calcom/cal.com PR #22919, packages/features/calAIPhone/providers/retellAI/services/PhoneNumberService.ts should include the phone number in client-facing HttpError messages (e.g., in updatePhoneNumber/getPhoneNumber catch blocks). Do not suggest redacting the phone number from these errors unless requirements change (per maintainer: Udit-takkar).
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Tests / Unit
  • GitHub Check: Type check / check-types
  • GitHub Check: Linters / lint
🔇 Additional comments (3)
packages/features/bookings/lib/getCalEventResponses.ts (3)

13-13: Good: scoped sub-logger with clear prefix.

Helps grep-ability and isolates noise.


74-76: Use strict equality and clear guests when seats are enabled
Replaced == with ===. Clearing guests to [] when seatsEnabled is true aligns with the UI’s behavior of disabling the guests field and won’t regress other flows.


9-9: No action needed; default import is correct.
packages/lib/logger.ts uses export default logger, so importing with import logger from "@calcom/lib/logger" matches the module signature and won’t cause a runtime mismatch.

Comment on lines 45 to 47
const backwardCompatibleResponses =
responses ?? (booking ? getBookingWithResponses(booking).responses : null);
if (!backwardCompatibleResponses) throw new Error("Couldn't get responses");
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use HttpError and add context; avoid mutating the source by cloning.

Throwing a bare Error is inconsistent with the rest of this function and loses context. Also clone to avoid mutating inputs.

Apply:

-  const backwardCompatibleResponses =
-    responses ?? (booking ? getBookingWithResponses(booking).responses : null);
-  if (!backwardCompatibleResponses) throw new Error("Couldn't get responses");
+  const baseResponses =
+    responses ?? (booking ? getBookingWithResponses(booking).responses : null);
+  if (!baseResponses) {
+    log.error("Could not derive booking responses", {
+      hasResponsesParam: !!responses,
+      hasBooking: !!booking,
+    });
+    throw new HttpError({ statusCode: 400, message: "Couldn't derive booking responses" });
+  }
+  const backwardCompatibleResponses = { ...baseResponses };

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 50 to +60
if (!!!backwardCompatibleResponses.email) {
if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string")
if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string") {
log.error(`backwardCompatibleResponses: ${JSON.stringify(backwardCompatibleResponses)}`, {
responses,
bookingResponses: booking?.responses,
});
throw new HttpError({
statusCode: 400,
message: "Both Phone and Email are missing",
});

}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Reduce PII in logs and simplify triple-bang; improve error copy.

  • !!!x hurts readability; prefer !x.
  • Logging the full responses object and booking responses risks leaking PII. Log metadata only.
  • Error message: use a clearer, action-oriented sentence.

Apply:

-  if (!!!backwardCompatibleResponses.email) {
+  if (!backwardCompatibleResponses.email) {
     if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string") {
-      log.error(`backwardCompatibleResponses: ${JSON.stringify(backwardCompatibleResponses)}`, {
-        responses,
-        bookingResponses: booking?.responses,
-      });
-      throw new HttpError({
-        statusCode: 400,
-        message: "Both Phone and Email are missing",
-      });
+      log.error("Missing both phone and email in booking responses", {
+        keys: Object.keys(backwardCompatibleResponses),
+        attendeePhoneNumberType: typeof backwardCompatibleResponses["attendeePhoneNumber"],
+        hasResponsesParam: !!responses,
+        hasBookingResponses: !!booking?.responses,
+      });
+      throw new HttpError({ statusCode: 400, message: "Either phone or email is required." });
     }
📝 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
if (!!!backwardCompatibleResponses.email) {
if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string")
if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string") {
log.error(`backwardCompatibleResponses: ${JSON.stringify(backwardCompatibleResponses)}`, {
responses,
bookingResponses: booking?.responses,
});
throw new HttpError({
statusCode: 400,
message: "Both Phone and Email are missing",
});
}
if (!backwardCompatibleResponses.email) {
if (typeof backwardCompatibleResponses["attendeePhoneNumber"] !== "string") {
log.error("Missing both phone and email in booking responses", {
keys: Object.keys(backwardCompatibleResponses),
attendeePhoneNumberType: typeof backwardCompatibleResponses["attendeePhoneNumber"],
hasResponsesParam: !!responses,
hasBookingResponses: !!booking?.responses,
});
throw new HttpError({ statusCode: 400, message: "Either phone or email is required." });
}
🤖 Prompt for AI Agents
In packages/features/bookings/lib/getCalEventResponses.ts around lines 50–60,
simplify the visibility check by replacing the confusing triple-bang with a
single negation (use !backwardCompatibleResponses.email), stop logging full
response objects to avoid PII leaks (log only non-PII metadata such as
booking?.id, responses?.length, and whether attendeePhoneNumber is present), and
update the thrown error message to a clear, action-oriented sentence like
"Please provide either a valid email or a phone number." Ensure the log and
error changes are used in the same conditional branch where the phone/email
validation occurs.

Copy link
Contributor

@hbjORbj hbjORbj left a comment

Choose a reason for hiding this comment

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

Looks safe

@Ryukemeister Ryukemeister merged commit b332d98 into main Aug 29, 2025
62 of 63 checks passed
@Ryukemeister Ryukemeister deleted the refactor/add-logging branch August 29, 2025 08:06
@github-actions
Copy link
Contributor

E2E results are ready!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bookings area: bookings, availability, timezones, double booking core area: core, team members only enterprise area: enterprise, audit log, organisation, SAML, SSO ready-for-e2e 💻 refactor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants