Lemon Squeezy Importer - #4214
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe PR adds Lemon Squeezy partner, customer, and commission imports with validated API access, queued processing, cron dispatch, server actions, and UI controls. It also centralizes Dub customer ID extraction across Stripe webhook flows. ChangesLemon Squeezy import
Stripe metadata resolution
Estimated code review effort: 5 (Critical) | ~90 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant ImportLemonSqueezyModal
participant ServerActions
participant LemonSqueezyApi
participant lemonSqueezyImporter
participant CronRoute
participant Importers
User->>ImportLemonSqueezyModal: enter API key and select store
ImportLemonSqueezyModal->>ServerActions: validate credentials and store
ServerActions->>LemonSqueezyApi: list stores
LemonSqueezyApi-->>ServerActions: return stores
ServerActions->>lemonSqueezyImporter: queue import job
lemonSqueezyImporter->>CronRoute: send import payload
CronRoute->>Importers: dispatch import stage
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/web/ui/modals/modal-provider.tsx (1)
50-64: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winKeep one owner for
ImportLemonSqueezyModal.
PartnersMenuPopoveralso mountsImportLemonSqueezyModal. Both instances observe?import=lemonsqueezy, so one import selection opens two dialogs and renders duplicate form controls. Remove this provider integration to match the existing partner-import pattern, or remove the menu integration and make the provider the only owner.Also applies to: 120-121, 208-223
🤖 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 `@apps/web/ui/modals/modal-provider.tsx` around lines 50 - 64, Ensure ImportLemonSqueezyModal has a single owner by removing its modal-provider integration: delete the setShowImportLemonSqueezyModal context state, default, provider wiring, and related render block around the provider symbols, while preserving the PartnersMenuPopover-owned modal and existing import behavior.
🧹 Nitpick comments (1)
apps/web/lib/lemonsqueezy/import-commissions.ts (1)
76-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
toDubStatusnever returnsnull.The
defaultbranch returns"pending", so the| nullreturn type and theif (!status) return;guard at lines 407-410 are unreachable. Either dropnullfrom the signature and remove the guard, or returnnullfor unknown statuses if you want to skip them.♻️ Proposed change
-const toDubStatus = (status: string): CommissionStatus | null => { +const toDubStatus = (status: string): CommissionStatus => {🤖 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 `@apps/web/lib/lemonsqueezy/import-commissions.ts` around lines 76 - 93, Update toDubStatus so its return type and behavior agree: either remove null from the return type and delete the unreachable !status guard in the caller, or return null for unknown statuses so that guard can skip them. Preserve the existing mappings for recognized statuses.
🤖 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 `@apps/web/lib/lemonsqueezy/import-commissions.ts`:
- Around line 566-609: Update the import flow around the per-page sale-event
processing and the sale handling shown here to group events by
customerExternalId, process each customer’s events sequentially in createdAt
order, and mark only the earliest event as eligible for first-conversion and
firstSaleAt updates. Ensure later events for the same customer do not reuse
stale customer state to increment link conversions or overwrite firstSaleAt,
while preserving normal sale and amount increments for every event.
In `@apps/web/lib/lemonsqueezy/import-customers.ts`:
- Around line 119-141: Update the customer processing loop in importCustomers to
use Promise.allSettled instead of Promise.all, preserving processing of all
chunks and allowing the importer queue to run when an individual createCustomer
call fails. Also update the recordClick result handling so its nullable return
is guarded before constructing the clickEventSchemaTB payload, including the
required bot and qr fields only when a valid result exists.
- Around line 74-80: Scope both affiliate-by-domain link lookups to the current
program by adding program.id to the where filters in
apps/web/lib/lemonsqueezy/import-customers.ts lines 74-80 and
apps/web/lib/lemonsqueezy/import-commissions.ts lines 333-340. Update the
findMany calls in both import flows so matching requires the domain, affiliate
key, and programId.
In `@apps/web/lib/lemonsqueezy/import-partners.ts`:
- Around line 221-226: Update the duplicate-link log in the partner import flow
to stop including partner.email, and report the partner’s id instead while
preserving the existing affiliate key and skip behavior.
- Around line 101-114: Inspect the results returned by Promise.allSettled in the
activeAffiliates import flow and log each rejected createPartnerAndLinks
operation with its rejection reason. Preserve successful imports and ensure
failures from any stage, including database upserts, produce an import-error log
identifying the affected affiliate.
In `@apps/web/lib/lemonsqueezy/importer.ts`:
- Around line 13-37: Update setCredentials, getCredentials, and
deleteCredentials to scope cached Lemon Squeezy credentials to each import
rather than only the workspace. Add or propagate importId through these methods
and include it in the Redis key, preserving the existing expiry,
missing-credential error, and deletion behavior so concurrent imports do not
overwrite or remove one another’s credentials.
In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx`:
- Around line 140-143: Update the stores-loading flow around setStores and
setStep("select-store") to verify data.stores contains at least one store before
advancing. Keep the token form open for an empty array, and display the existing
error UI/message for API keys with no accessible stores.
---
Outside diff comments:
In `@apps/web/ui/modals/modal-provider.tsx`:
- Around line 50-64: Ensure ImportLemonSqueezyModal has a single owner by
removing its modal-provider integration: delete the
setShowImportLemonSqueezyModal context state, default, provider wiring, and
related render block around the provider symbols, while preserving the
PartnersMenuPopover-owned modal and existing import behavior.
---
Nitpick comments:
In `@apps/web/lib/lemonsqueezy/import-commissions.ts`:
- Around line 76-93: Update toDubStatus so its return type and behavior agree:
either remove null from the return type and delete the unreachable !status guard
in the caller, or return null for unknown statuses so that guard can skip them.
Preserve the existing mappings for recognized statuses.
🪄 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: 0c243eba-cba5-4793-88a6-0116d385786b
📒 Files selected for processing (21)
apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.tsapps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsapps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsapps/web/app/(ee)/api/stripe/integration/webhook/utils/get-dub-customer-external-id-from-metadata.tsapps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.tsapps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-menu-popover.tsxapps/web/lib/actions/partners/set-lemonsqueezy-token.tsapps/web/lib/actions/partners/start-lemonsqueezy-import.tsapps/web/lib/constants/program.tsapps/web/lib/lemonsqueezy/api.tsapps/web/lib/lemonsqueezy/import-commissions.tsapps/web/lib/lemonsqueezy/import-customers.tsapps/web/lib/lemonsqueezy/import-partners.tsapps/web/lib/lemonsqueezy/importer.tsapps/web/lib/lemonsqueezy/schemas.tsapps/web/lib/lemonsqueezy/types.tsapps/web/lib/zod/schemas/import-error-log.tsapps/web/lib/zod/schemas/sales.tsapps/web/ui/modals/import-lemonsqueezy-modal.tsxapps/web/ui/modals/modal-provider.tsxpackages/email/src/templates/program-imported.tsx
|
@coderabbitai full review. any breaking changes or security issues? |
|
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (2)
apps/web/ui/modals/import-lemonsqueezy-modal.tsx (1)
253-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExpose the selection state to assistive technology.
The store list behaves like a radio group, but the markup uses plain buttons. The selected store is communicated only by the visual
Check2icon. Addrole="radiogroup"to the container androle="radio"witharia-checked={checked}to each button, so screen readers announce which store is selected.♻️ Proposed change
- <div className="flex w-full flex-col gap-1 p-1"> + <div role="radiogroup" aria-label="Choose a store to import" className="flex w-full flex-col gap-1 p-1"> {stores.map((store) => { const checked = selectedStoreId === store.id; return ( <button key={store.id} type="button" + role="radio" + aria-checked={checked} onClick={() => setSelectedStoreId(store.id)}🤖 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 `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx` around lines 253 - 297, Update the store selection markup in the ScrollContainer to expose its radio-group semantics: add role="radiogroup" to the list container and role="radio" with aria-checked={checked} to each store button generated in the stores.map callback.apps/web/lib/lemonsqueezy/api.ts (1)
100-116: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider retrying on 429 instead of only reporting
Retry-After.The client reads
Retry-Afterbut only embeds it in the error message. A single rate-limited page then throws and aborts the current import batch. Add a bounded retry that waits forRetry-Afterbefore failing, so long imports survive normal rate limiting.🤖 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 `@apps/web/lib/lemonsqueezy/api.ts` around lines 100 - 116, Update the non-OK response handling in the Lemon Squeezy request flow to retry 429 responses a bounded number of times, waiting for the duration specified by Retry-After before each retry. After the retry limit is reached, preserve the existing error construction and reporting behavior; non-429 responses should continue failing immediately.
🤖 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 `@apps/web/lib/constants/program.ts`:
- Around line 40-45: Update the helpUrl for the lemonsqueezy entry in the
program constants and the corresponding import-modal occurrence to a currently
published, non-404 help article URL; keep both references consistent.
In `@apps/web/lib/lemonsqueezy/import-commissions.ts`:
- Around line 76-93: Update toDubStatus so its behavior and return type agree:
either return null for unrecognized Lemon Squeezy statuses and retain the
existing null guard while logging skipped commissions, or keep the pending
fallback and change the return type to CommissionStatus while removing the dead
guard at the commission import call site. Choose the intended policy and apply
it consistently.
- Around line 186-214: Move the lemonSqueezyImporter.deleteCredentials call in
the completed import flow to after the workspaceUser lookup and conditional
sendEmail call. Keep credential deletion as the final step so retries can still
retrieve credentials if the lookup or completion email fails.
- Around line 366-380: Update the commission processing loop in
processSaleEvents to use Promise.allSettled instead of Promise.all when invoking
createCommission for each saleChunk, matching the pattern used by
importCustomers. Preserve processing of all sale events, chunks, and subsequent
continuation or subscription-invoices handoffs even when an individual
createCommission call rejects.
In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx`:
- Around line 147-149: Both action error handlers in
import-lemonsqueezy-modal.tsx can pass undefined to toast.error; update the
handlers at lines 147-149 and 228-230 to fall back from error.serverError to
“Failed to fetch Lemon Squeezy stores.” and “Failed to start the Lemon Squeezy
import.” respectively.
---
Nitpick comments:
In `@apps/web/lib/lemonsqueezy/api.ts`:
- Around line 100-116: Update the non-OK response handling in the Lemon Squeezy
request flow to retry 429 responses a bounded number of times, waiting for the
duration specified by Retry-After before each retry. After the retry limit is
reached, preserve the existing error construction and reporting behavior;
non-429 responses should continue failing immediately.
In `@apps/web/ui/modals/import-lemonsqueezy-modal.tsx`:
- Around line 253-297: Update the store selection markup in the ScrollContainer
to expose its radio-group semantics: add role="radiogroup" to the list container
and role="radio" with aria-checked={checked} to each store button generated in
the stores.map callback.
🪄 Autofix
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: 49f0143b-31cd-4ce9-a1e2-58a1d46193dd
📒 Files selected for processing (21)
apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.tsapps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsapps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsapps/web/app/(ee)/api/stripe/integration/webhook/utils/get-dub-customer-external-id-from-metadata.tsapps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.tsapps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-menu-popover.tsxapps/web/lib/actions/partners/set-lemonsqueezy-token.tsapps/web/lib/actions/partners/start-lemonsqueezy-import.tsapps/web/lib/constants/program.tsapps/web/lib/lemonsqueezy/api.tsapps/web/lib/lemonsqueezy/import-commissions.tsapps/web/lib/lemonsqueezy/import-customers.tsapps/web/lib/lemonsqueezy/import-partners.tsapps/web/lib/lemonsqueezy/importer.tsapps/web/lib/lemonsqueezy/schemas.tsapps/web/lib/lemonsqueezy/types.tsapps/web/lib/zod/schemas/import-error-log.tsapps/web/lib/zod/schemas/sales.tsapps/web/ui/modals/import-lemonsqueezy-modal.tsxapps/web/ui/modals/modal-provider.tsxpackages/email/src/templates/program-imported.tsx
Summary by CodeRabbit