Skip to content

feat(eai): add handleRefundAndRemoveFromCalendar function for processing refunds and updating calendar events #477

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

Merged
merged 2 commits into from
May 17, 2025

Conversation

vojtaholik
Copy link
Member

@vojtaholik vojtaholik commented May 16, 2025

gif

Summary by CodeRabbit

  • New Features
    • Users who receive a refund for a live product will now be automatically removed from the associated Google Calendar event.
  • Chores
    • Updated the support email address in the development environment configuration.

@vojtaholik vojtaholik requested a review from joelhooks May 16, 2025 10:42
Copy link

vercel bot commented May 16, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
ai-hero ❌ Failed (Inspect) May 17, 2025 5:17am
astro-party ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
course-builder-egghead ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
course-builder-poc ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
craft-of-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
cursor-pro ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
epic-react-builder ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
epic-web-builder ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
epicai-pro ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am
go-local-first ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 17, 2025 5:17am

Copy link
Contributor

coderabbitai bot commented May 16, 2025

Walkthrough

A new event-driven workflow is introduced to handle refunds by removing refunded users from Google Calendar events associated with live products. This involves defining a new refund event schema, emitting the event after a refund is processed, and implementing an Inngest function to process the event and remove the user from the calendar. Supporting configuration and type definitions are also updated.

Changes

File(s) Change Summary
apps/epicdev-ai/.env.development Updated support email address from "[email protected]" to "[email protected]".
apps/epicdev-ai/src/inngest/functions/calendar-sync.ts Added handleRefundAndRemoveFromCalendar Inngest function to remove refunded users from calendars.
apps/epicdev-ai/src/inngest/inngest.config.ts Imported and registered handleRefundAndRemoveFromCalendar in the Inngest functions array.
packages/core/src/inngest/commerce/event-refund-processed.ts Introduced refund processed event constant, schema, and types.
packages/core/src/inngest/index.ts Added refund processed event and type to the core events union.
packages/core/src/lib/actions/process-refund.ts Emitted refund processed event after refunding, with error logging for event emission.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant System
    participant Inngest
    participant GoogleCalendar

    User->>System: Initiates refund
    System->>System: Process refund logic
    System->>Inngest: Emit REFUND_PROCESSED_EVENT (with merchantChargeId)
    Inngest->>System: Trigger handleRefundAndRemoveFromCalendar
    System->>System: Lookup charge, purchase, product, user, event
    alt Product is live and event found
        System->>GoogleCalendar: Remove user from event (by email)
        GoogleCalendar-->>System: Confirmation
    else Product not live or event missing
        System->>System: Skip removal
    end
    System->>Inngest: Report outcome (success, error, or skipped)
Loading

Poem

Refunds are processed, the bunnies are quick,
Now users are whisked from calendars slick.
With emails updated and logic so neat,
No more stray carrots in a Google Meet!
🥕✨

— A rabbit who loves clean calendars

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.

🔧 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.

Scope: all 3 workspace projects
 WARN  Ignoring not compatible lockfile at /tmp/eslint/pnpm-lock.yaml
Progress: resolved 1, reused 0, downloaded 0, added 0
 WARN  deprecated [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
/tmp/eslint/packages/config/eslint-config:
 ERR_PNPM_WORKSPACE_PKG_NOT_FOUND  In packages/config/eslint-config: "@coursebuilder/eslint-plugin@workspace:*" is in the dependencies but no package named "@coursebuilder/eslint-plugin" is present in the workspace

This error happened while installing a direct dependency of /tmp/eslint/packages/config/eslint-config

Packages found in the workspace:

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • 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.

Base automatically changed from vh/feat/eai/sync-calendar-invites-on-purchase-transfer to main May 17, 2025 04:57
@kodiakhq kodiakhq bot merged commit daf0b2a into main May 17, 2025
14 of 25 checks passed
@kodiakhq kodiakhq bot deleted the vh/feat/eai/remove-attendee-from-calendar-on-refund branch May 17, 2025 04:59
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

🧹 Nitpick comments (4)
packages/core/src/inngest/index.ts (1)

23-26: Prefer splitting value vs type imports for consistency & tree-shaking

Throughout the file we import runtime constants and purely‐compile-time types in separate statements, e.g.:

import {
  NEW_PURCHASE_CREATED_EVENT,
  NewPurchaseCreated,
} from './commerce/event-new-purchase-created'

For the newly added refund event you again mix the two in one import. Consider:

-import {
-  REFUND_PROCESSED_EVENT,
-  RefundProcessed,
-} from './commerce/event-refund-processed'
+import { REFUND_PROCESSED_EVENT } from './commerce/event-refund-processed'
+import type { RefundProcessed } from './commerce/event-refund-processed'

Benefits
• keeps the pattern consistent with the earlier import type blocks in the file
• guarantees that the RefundProcessed symbol is fully erased from JS output, yielding slightly leaner bundles.

apps/epicdev-ai/src/inngest/functions/calendar-sync.ts (3)

14-15: Type safety TODO can be resolved right away

GetFunctionInput is already imported. You can give the handler strong typing without waiting:

-// TODO: Define a more specific type for the event data if available
-// type RefundProcessedEvent = GetFunctionInput<typeof REFUND_PROCESSED_EVENT>['data']
+type RefundProcessedEvent = GetFunctionInput<typeof REFUND_PROCESSED_EVENT>['data']

and then

-async ({ event, step, logger }) => {
+async (
+  { event, step, logger }: { event: { name: typeof REFUND_PROCESSED_EVENT; data: RefundProcessedEvent } } ,
+) => {

This prevents accidental any leaks and gives autocomplete for merchantChargeId.


480-486: Log message typo may confuse debugging

getEvent.getProduct does not exist; the message should simply reference getEvent.

-`Event resource ${eventResourceId} not found or failed validation via getEvent.getProduct`,
+`Event resource ${eventResourceId} not found or failed validation via getEvent`,

Tiny, but log hygiene matters when you’re triaging incidents.


293-307: Adapter method presence check can be simplified

You test each adapter property individually, but if any are missing you throw the same error.
A helper promotes DRY and makes future additions safer:

const required = [
  'getMerchantCharge',
  'getPurchaseForStripeCharge',
  'getUser',
  'getProduct',
  'getContentResource',
] as const

for (const fn of required) {
  if (typeof (courseBuilderAdapter as any)[fn] !== 'function') {
    logger.error(`CourseBuilderAdapter missing method ${fn}`)
    throw new NonRetriableError('Adapter incomplete for calendar removal')
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between c40a50c and 2382c71.

📒 Files selected for processing (6)
  • apps/epicdev-ai/.env.development (1 hunks)
  • apps/epicdev-ai/src/inngest/functions/calendar-sync.ts (2 hunks)
  • apps/epicdev-ai/src/inngest/inngest.config.ts (2 hunks)
  • packages/core/src/inngest/commerce/event-refund-processed.ts (1 hunks)
  • packages/core/src/inngest/index.ts (2 hunks)
  • packages/core/src/lib/actions/process-refund.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/core/src/lib/actions/process-refund.ts (1)
packages/core/src/inngest/commerce/event-refund-processed.ts (1)
  • REFUND_PROCESSED_EVENT (3-3)
apps/epicdev-ai/src/inngest/inngest.config.ts (1)
apps/epicdev-ai/src/inngest/functions/calendar-sync.ts (1)
  • handleRefundAndRemoveFromCalendar (273-547)
packages/core/src/inngest/index.ts (1)
packages/core/src/inngest/commerce/event-refund-processed.ts (2)
  • REFUND_PROCESSED_EVENT (3-3)
  • RefundProcessed (5-8)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: format
  • GitHub Check: build
🔇 Additional comments (7)
packages/core/src/inngest/commerce/event-refund-processed.ts (1)

1-14: Well-structured event schema with proper validation.

This is a clean implementation of the refund processed event schema. The use of Zod for validation ensures type safety and runtime validation for the event data.

apps/epicdev-ai/.env.development (1)

6-6: Support email updated to match product branding.

The support email has been updated from "[email protected]" to "[email protected]", which aligns with the product branding.

packages/core/src/lib/actions/process-refund.ts (2)

1-1: LGTM! Appropriate import for the refund event.

The import for the refund processed event constant is correctly added.


36-45: Well-implemented event emission with proper error handling.

The event emission is correctly wrapped in a try-catch block, ensuring that any errors during event sending won't affect the main refund flow. The event includes the necessary merchantChargeId data, which will be used by the calendar sync function to locate the relevant user and product.

apps/epicdev-ai/src/inngest/inngest.config.ts (2)

17-20: Clean import of the new calendar function.

The import has been properly updated to include the new handleRefundAndRemoveFromCalendar function.


59-59: Correct registration of the new Inngest function.

The handleRefundAndRemoveFromCalendar function has been properly added to the Inngest configuration, ensuring it will be triggered when refund events occur.

packages/core/src/inngest/index.ts (1)

91-91: Remember to re-export the new event type if external packages rely on it

You added the mapping in CourseBuilderCoreEvents, 👍.
If downstream packages cast/extend this union they may need to re-export RefundProcessed alongside the constant so consumers can narrow on the type. Double-check @coursebuilder/core barrel exports.

Comment on lines +418 to +436
'find-event-resource-id-for-product',
async () => {
const resources = purchasedProduct.resources

if (!Array.isArray(resources)) {
logger.warn(
`Product ${purchasedProductId} does not have a 'resources' array or it's not an array. Cannot find event resource.`,
)
return null
}

// Use .find() as seen in post-event-purchase.ts
const foundEventResource = resources.find(
(item) => item.resource?.type === 'event',
)?.resource

return foundEventResource?.id || null
},
)
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 null-access on nested resource objects

resources.find((item) => item.resource?.type === 'event') assumes every resources element has a resource property.
If an element is null/undefined, the optional-chaining won’t guard the earlier item.resource access itself and could still raise if item is nullish.

A slightly safer variant:

const found = resources.find(
  (r): r is { resource: { type: string; id: string } } =>
    !!r?.resource && r.resource.type === 'event',
)

or use a for … of loop with explicit checks.

🤖 Prompt for AI Agents
In apps/epicdev-ai/src/inngest/functions/calendar-sync.ts between lines 418 and
436, the code uses resources.find with a callback accessing item.resource?.type
but does not check if item itself is null or undefined, which can cause runtime
errors. To fix this, update the find callback to first check that the item is
not nullish before accessing its resource property, either by using a type guard
with a condition like !!item?.resource && item.resource.type === 'event' or by
replacing the find with a for...of loop that explicitly checks each item and its
resource property before accessing type.

Comment on lines +522 to +545
// Step 7: Remove User from Google Calendar Event
try {
await step.run('remove-user-from-google-event', async () => {
await removeUserFromGoogleCalendarEvent(calendarId, user.email)
})
logger.info(
`Successfully removed user ${user.email} from calendar event ${calendarId}`,
)
return {
outcome: 'success',
userId,
email: user.email,
calendarId,
eventResourceId,
}
} catch (error: any) {
logger.error(
`Failed to remove user ${user.email} from calendar event ${calendarId}: ${error.message}`,
{ error },
)
// Depending on the error, you might want to retry.
// For now, assume most GCal API errors might be retriable if not handled by removeUserFromGoogleCalendarEvent itself.
throw error
}
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

Gracefully handle “attendee already removed / not found” errors

removeUserFromGoogleCalendarEvent will throw on any non-2xx Google error.
For refunds it’s common that the user was never on the guest list (manual removal, previous retries, etc.).

Consider inspecting the error code (usually 404 or Google’s status === 'failedPrecondition') and returning a NonRetriableError rather than re-throwing, to avoid noisy retries that can never succeed.

-} catch (error: any) {
+} catch (error: any) {
+  if (isNotFoundOrAlreadyRemoved(error)) {
+    logger.warn(`User ${user.email} not present on event ${calendarId}, skipping retry`)
+    return { outcome: 'skipped', reason: 'attendee absent', calendarId, userId }
+  }
   logger.error(

(Implement isNotFoundOrAlreadyRemoved to parse Google error responses.)

📝 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
// Step 7: Remove User from Google Calendar Event
try {
await step.run('remove-user-from-google-event', async () => {
await removeUserFromGoogleCalendarEvent(calendarId, user.email)
})
logger.info(
`Successfully removed user ${user.email} from calendar event ${calendarId}`,
)
return {
outcome: 'success',
userId,
email: user.email,
calendarId,
eventResourceId,
}
} catch (error: any) {
logger.error(
`Failed to remove user ${user.email} from calendar event ${calendarId}: ${error.message}`,
{ error },
)
// Depending on the error, you might want to retry.
// For now, assume most GCal API errors might be retriable if not handled by removeUserFromGoogleCalendarEvent itself.
throw error
}
// Step 7: Remove User from Google Calendar Event
try {
await step.run('remove-user-from-google-event', async () => {
await removeUserFromGoogleCalendarEvent(calendarId, user.email)
})
logger.info(
`Successfully removed user ${user.email} from calendar event ${calendarId}`,
)
return {
outcome: 'success',
userId,
email: user.email,
calendarId,
eventResourceId,
}
} catch (error: any) {
if (isNotFoundOrAlreadyRemoved(error)) {
logger.warn(
`User ${user.email} not present on event ${calendarId}, skipping retry`
)
return {
outcome: 'skipped',
reason: 'attendee absent',
userId,
calendarId,
}
}
logger.error(
`Failed to remove user ${user.email} from calendar event ${calendarId}: ${error.message}`,
{ error },
)
// Depending on the error, you might want to retry.
// For now, assume most GCal API errors might be retriable if not handled by removeUserFromGoogleCalendarEvent itself.
throw error
}
🤖 Prompt for AI Agents
In apps/epicdev-ai/src/inngest/functions/calendar-sync.ts around lines 522 to
545, the catch block for removeUserFromGoogleCalendarEvent currently re-throws
all errors, causing unnecessary retries for cases where the user is already
removed or not found. Implement a helper function isNotFoundOrAlreadyRemoved to
detect these specific Google API errors (e.g., 404 status or
failedPrecondition). In the catch block, check the error with this helper and if
it matches, throw a NonRetriableError instead of the original error to prevent
retries; otherwise, re-throw as usual.

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.

2 participants