-
Notifications
You must be signed in to change notification settings - Fork 34
feat(aih): invoke post cohort purchase workflow when redeeming a full price coupon #471
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
feat(aih): invoke post cohort purchase workflow when redeeming a full price coupon #471
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis update introduces a new event, Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Adapter
participant Core
participant Inngest
participant Workflow
User->>Adapter: Redeem full-price coupon
Adapter->>Core: createPurchase({ ..., organizationId })
Core->>Inngest: Emit FullPriceCouponRedeemed (purchaseId, productType, orgId)
Inngest->>Workflow: Trigger postCohortPurchaseWorkflow (on event)
Workflow->>Core: Fetch product details and process cohort logic
Suggested reviewers
Poem
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
Scope: all 3 workspace projects This error happened while installing a direct dependency of /tmp/eslint/packages/config/eslint-config Packages found in the workspace: Tip ⚡️ Faster reviews with caching
Enjoy the performance boost—your workflow just got faster. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
const userMemberships = await adapter.getMembershipsForUser(user.id) | ||
const organizationId = userMemberships[0].organizationId |
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.
@joelhooks I'm not 100% sure if this is the right way to get user's org id. it needs to be passed down to createPurchase
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.
for a redemption we need to look at the coupon, which should have an org id and join the user to that org
- team purchase
- create bulk coupon w/ org id (this happens below in
createMerchantChargeAndPurchase
) - redeem coupon
- use coupon org id for redemption purchase
- join user to org as
learner
you can fallback to the personal org of the user as a last resort, but we probably want to ensure all coupons get created with an org id?
I made the personal org id lookup a little "safer" versus index[0] access
…nd redeem actions
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: 1
🔭 Outside diff range comments (2)
packages/core/src/inngest/index.ts (1)
89-99
: 💡 Verification agent🧩 Analysis chain
Missing event handler in core functions array.
While the new event type is added to the
CourseBuilderCoreEvents
type, there appears to be no corresponding handler added to thecourseBuilderCoreFunctions
array. If the event requires a specific handler, it should be added here.Run the following script to check if the event has a handler defined elsewhere:
🏁 Script executed:
#!/bin/bash # Check for handlers for the FullPriceCouponRedeemed event echo "Searching for event definitions:" rg -A 3 "FULL_PRICE_COUPON_REDEEMED_EVENT" --type ts echo "Searching for event handlers:" rg -A 5 "fullPriceCouponRedeemed|FullPriceCouponRedeemed.*=>|'commerce/full-price-coupon-redeemed'" --type tsLength of output: 3828
Add handler for FullPriceCouponRedeemed event
I searched the core package and confirmed that while
FULL_PRICE_COUPON_REDEEMED_EVENT
and its type are defined, there’s no corresponding handler function exported or included in thecourseBuilderCoreFunctions
array. If this event needs to be handled at the core level, please:• In
packages/core/src/inngest/commerce/event-full-price-coupon-redeemed.ts
, implement and export a handler function (e.g.fullPriceCouponRedeemed
)
• Inpackages/core/src/inngest/index.ts
, import that handler:import { fullPriceCouponRedeemed } from './commerce/event-full-price-coupon-redeemed'• Add it to the
courseBuilderCoreFunctions
array alongside the other handlers:export const courseBuilderCoreFunctions = [ ...coreVideoProcessingFunctions, sendPostPurchaseEmail, /* … */ updatePurchaseStatus, + fullPriceCouponRedeemed, ]
This ensures the new event type has its handler registered in the core functions list.
packages/adapter-drizzle/src/lib/mysql/index.ts (1)
374-465
: 🛠️ Refactor suggestionConsider adding error handling for missing organization memberships.
The implementation assumes that every user has at least one organization membership, but this might not always be the case. If a user somehow doesn't have any memberships, the code could throw an error when trying to access
userMemberships[0]
.Consider adding a fallback mechanism or more robust error handling:
async redeemFullPriceCoupon(options) { const { email: baseEmail, couponId, productIds, currentUserId, redeemingProductId, } = options const email = String(baseEmail).replace(' ', '+') // Rest of the existing code... const purchaseId = `purchase-${v4()}` const userMemberships = await adapter.getMembershipsForUser(user.id) - const organizationId = userMemberships[0].organizationId + let organizationId: string | undefined + + if (userMemberships.length > 0) { + organizationId = userMemberships[0].organizationId + } else { + console.warn(`User ${user.id} has no organization memberships. Creating purchase without organization.`) + } await adapter.createPurchase({ id: purchaseId, userId: user.id, couponId: bulkCouponRedemption ? null : coupon.id, redeemedBulkCouponId: bulkCouponRedemption ? coupon.id : null, productId, totalAmount: '0', organizationId, metadata: { couponUsedId: bulkCouponRedemption ? null : coupon.id, }, }) // Rest of the existing code... }🧰 Tools
🪛 Biome (1.9.4)
[error] 431-431: This code is unreachable
... because this statement will return from the function beforehand
(lint/correctness/noUnreachable)
🧹 Nitpick comments (3)
.changeset/sixty-eggs-doubt.md (1)
1-7
: Changeset description could be more descriptive.While the changeset correctly identifies the affected packages, the description "create FullPriceCouponRedeemed event,pass orgId" is quite minimal. Consider providing more context about the purpose of this event and how it integrates with the existing purchase workflow.
-create FullPriceCouponRedeemed event,pass orgId +create FullPriceCouponRedeemed event that includes organization ID to support post-cohort purchase workflow when redeeming full price couponspackages/core/src/lib/actions/redeem.ts (1)
44-44
: Consider removing this debug log statement before shipping to production.Debug logs like this should typically be removed or replaced with proper structured logging for production code.
-console.log('createdPurchase', createdPurchase) +// Consider using structured logging if needed for productionapps/ai-hero/src/inngest/functions/post-cohort-purchase-workflow.ts (1)
43-43
: Consider removing this debug log or enhancing it for production.Similar to the previous file, consider removing debug logs or enhancing them with structured logging for production.
-console.log(`product`, product) +// Replace with structured logging if needed for production
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
.changeset/sixty-eggs-doubt.md
(1 hunks)apps/ai-hero/src/inngest/functions/post-cohort-purchase-workflow.ts
(2 hunks)packages/adapter-drizzle/src/lib/mysql/index.ts
(2 hunks)packages/core/src/adapters.ts
(1 hunks)packages/core/src/inngest/commerce/event-full-price-coupon-redeemed.ts
(1 hunks)packages/core/src/inngest/index.ts
(2 hunks)packages/core/src/lib/actions/redeem.ts
(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/core/src/inngest/index.ts (1)
packages/core/src/inngest/commerce/event-full-price-coupon-redeemed.ts (2)
FULL_PRICE_COUPON_REDEEMED_EVENT
(3-4)FullPriceCouponRedeemed
(6-9)
packages/core/src/lib/actions/redeem.ts (1)
packages/core/src/inngest/commerce/event-full-price-coupon-redeemed.ts (1)
FULL_PRICE_COUPON_REDEEMED_EVENT
(3-4)
apps/ai-hero/src/inngest/functions/post-cohort-purchase-workflow.ts (2)
packages/core/src/inngest/commerce/event-new-purchase-created.ts (1)
NEW_PURCHASE_CREATED_EVENT
(3-3)packages/core/src/inngest/commerce/event-full-price-coupon-redeemed.ts (1)
FULL_PRICE_COUPON_REDEEMED_EVENT
(3-4)
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: typecheck
- GitHub Check: format
- GitHub Check: e2e-node (course-builder-web)
- GitHub Check: lint
- GitHub Check: build
🔇 Additional comments (9)
packages/core/src/adapters.ts (1)
44-56
: NeworganizationId
parameter correctly extends the interface.The addition of the optional
organizationId
parameter to thecreatePurchase
options interface allows associating purchases with specific organizations. This change properly supports the introduction of theFullPriceCouponRedeemed
event that includes organizational context.packages/core/src/inngest/index.ts (2)
6-9
: Clean import of new event types.The imports for the new event type and interface are properly structured and follow the established pattern for event definitions in the system.
85-86
: Event type properly added to the core events map.The
FullPriceCouponRedeemed
event is correctly added to theCourseBuilderCoreEvents
type, allowing it to be properly typed throughout the system when event handling is performed.packages/adapter-drizzle/src/lib/mysql/index.ts (1)
438-446
: Organization ID correctly passed to createPurchase.The organization ID is properly passed to the
createPurchase
method, utilizing the new parameter added to the adapter interface. This ensures purchases created during coupon redemption are associated with the correct organization.packages/core/src/lib/actions/redeem.ts (2)
2-2
: Good import statement for the new event.The import is correctly added to support the new feature for invoking the post cohort purchase workflow on full price coupon redemption.
56-71
: Good implementation of event dispatching for full price coupon redemption.The code correctly:
- Fetches the product associated with the purchase
- Checks if the product exists before dispatching the event
- Uses the product type or falls back to a default type
- Includes error handling with appropriate logging and error message
The implementation aligns well with the feature goal of invoking the post cohort purchase workflow when redeeming a full price coupon.
apps/ai-hero/src/inngest/functions/post-cohort-purchase-workflow.ts (2)
12-12
: Good import for the new event constant.Correctly imports the new event constant needed for the workflow function.
20-29
: Well-structured event trigger configuration.The workflow function now properly listens for both purchase creation and coupon redemption events, with appropriate filtering for cohort-type products. The array structure allows for clean extension if more event types need to be added in the future.
packages/core/src/inngest/commerce/event-full-price-coupon-redeemed.ts (1)
1-19
: Well-structured event definition with proper type safety.The new event is:
- Clearly named and consistently follows existing conventions
- Properly typed with TypeScript for compile-time validation
- Schema-validated with Zod for runtime validation
- Includes appropriate enum values for product types
The event definition is concise, type-safe, and follows best practices for event-driven architectures.
…flow-when-redeeming-full-price-coupon
Summary by CodeRabbit