Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Caution Review failedThe pull request is closed. WalkthroughAdds a premium-transfer step to Google and Outlook account-merge flows by calling a new utility Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User
participant OP as OAuth Provider
participant R as Linking Callback Route
participant PU as transferPremiumDuringMerge
participant DB as Prisma
U->>OP: Complete OAuth linking
OP-->>R: Redirect with auth code
R->>R: Detect merge (existing account + target user)
R->>PU: transferPremiumDuringMerge(sourceUserId, targetUserId)
Note right of PU #E8F6EF: Read source/target premium & admin\nDecide transfer/connect/disconnect ops
PU->>DB: Read source & target users
PU->>DB: Execute prepared updates (connect/disconnect/update)
PU-->>R: Resolve (or log error)
alt Transfer succeeded
R->>DB: Transaction: reassign account, update emailAccount, delete source user
DB-->>R: Commit
R-->>U: Redirect success
else Transfer error
R->>R: Map/log error
R-->>U: Redirect with error
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
✨ Finishing Touches
🧪 Generate unit tests
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: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/web/app/api/outlook/linking/callback/route.ts (2)
266-271: Avoid leaking internal error messages via query paramsPassing error.message to clients can expose internal details. Only surface sanitized messages (e.g., SafeError) or rely on the error code.
- redirectUrl.searchParams.set( - "error_description", - error.message || "Unknown error", - ); + if (error instanceof SafeError) { + redirectUrl.searchParams.set("error_description", error.message); + }
12-15: Authenticate and authorize the GET handler
Wrap the exported GET handler inwithAuth(orwithEmailAccount) and assertdecodedState.userId === ctx.auth.userIdbefore proceeding, to prevent unauthorized merges (IDOR).
🧹 Nitpick comments (4)
apps/web/utils/user/merge-premium.ts (4)
66-66: Type the operations for transaction safetyAnnotate operations as Prisma promises to play nicely with
$transaction.- const operations: Promise<unknown>[] = []; + const operations: ReturnType<typeof prisma.$executeRaw>[] | Parameters<typeof prisma.$transaction>[0] = [];Alternatively, if you import Prisma types:
+ // at top of file + import type { Prisma } from "@prisma/client"; ... - const operations: Promise<unknown>[] = []; + const operations: Prisma.PrismaPromise<unknown>[] = [];
22-44: Trim unnecessary selects; simplify conditionYou load emails and nested users/admins but don’t use them. Reduce payload and simplify the premium check.
- const sourceUser = await prisma.user.findUnique({ + const sourceUser = await prisma.user.findUnique({ where: { id: sourceUserId }, select: { id: true, - email: true, premiumId: true, premiumAdminId: true, - premium: { - select: { - id: true, - users: { select: { id: true, email: true } }, - admins: { select: { id: true, email: true } }, - }, - }, - premiumAdmin: { - select: { - id: true, - users: { select: { id: true, email: true } }, - admins: { select: { id: true, email: true } }, - }, - }, }, }); ... - } else if (sourceUser.premiumId && sourceUser.premium) { + } else if (sourceUser.premiumId) {Also applies to: 93-93
126-162: Premium admin transfer consistencyWhen the target already has
premiumAdminId, you add them as admin to the source’s premium too (now admin of two). If that’s intended, fine; if not, decide which one should be “primary” and updatepremiumAdminIdaccordingly. Otherwise the field may not reflect actual admin memberships.
10-16: Consider accepting a TransactionClient to ensure end‑to‑end atomic mergeTo make the premium transfer atomic with account reassignment + source deletion, accept an optional
tx(Prisma.TransactionClient) and use it for all reads/writes and$transaction.Example signature and usage:
// utils export async function transferPremiumDuringMerge( { sourceUserId, targetUserId }: { sourceUserId: string; targetUserId: string }, opts?: { tx?: Prisma.TransactionClient } ) { const db = opts?.tx ?? prisma; // ... use db.* and db.$transaction(...) }Then in the route, wrap everything in one interactive transaction and pass
tx(see route comment).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/web/app/api/google/linking/callback/route.ts(2 hunks)apps/web/app/api/outlook/linking/callback/route.ts(2 hunks)apps/web/utils/user/merge-premium.ts(1 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
!{.cursor/rules/*.mdc}
📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)
Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location
Files:
version.txtapps/web/utils/user/merge-premium.tsapps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
!pages/_document.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.
Files:
version.txtapps/web/utils/user/merge-premium.tsapps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use@/for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX
Files:
apps/web/utils/user/merge-premium.tsapps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)
**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod
Files:
apps/web/utils/user/merge-premium.tsapps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport Prisma in the project using
import prisma from "@/utils/prisma";
**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.
Files:
apps/web/utils/user/merge-premium.tsapps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
apps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logic
Files:
apps/web/utils/user/merge-premium.ts
apps/web/utils/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size
Files:
apps/web/utils/user/merge-premium.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...
Files:
apps/web/utils/user/merge-premium.tsapps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
apps/web/app/**
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
NextJS app router structure with (app) directory
Files:
apps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
apps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/route.ts: UsewithAuthfor user-level operations
UsewithEmailAccountfor email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes
apps/web/app/api/**/route.ts: Wrap all GET API route handlers withwithAuthorwithEmailAccountmiddleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.
Files:
apps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
**/api/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
UsewithEmailAccountmiddleware for API routes that operate on a specific email account (i.e., use or requireemailAccountId).
UsewithAuthmiddleware for API routes that operate at the user level (i.e., use or require onlyuserId).
UsewithErrormiddleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST usewithErrormiddleware and validate the cron secret usinghasCronSecret(request)orhasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts withcaptureExceptionand return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
AllfindUniqueandfindFirstPrisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
AllfindManyPrisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...
Files:
apps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
apps/web/app/api/**/*.{ts,js}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.
Files:
apps/web/app/api/outlook/linking/callback/route.tsapps/web/app/api/google/linking/callback/route.ts
🧬 Code graph analysis (3)
apps/web/utils/user/merge-premium.ts (1)
apps/web/utils/logger.ts (1)
createScopedLogger(17-67)
apps/web/app/api/outlook/linking/callback/route.ts (1)
apps/web/utils/user/merge-premium.ts (1)
transferPremiumDuringMerge(10-181)
apps/web/app/api/google/linking/callback/route.ts (1)
apps/web/utils/user/merge-premium.ts (1)
transferPremiumDuringMerge(10-181)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: cubic · AI code reviewer
🔇 Additional comments (3)
version.txt (1)
1-1: Version bump LGTMv2.9.7 looks consistent with the PR scope.
apps/web/app/api/google/linking/callback/route.ts (1)
8-8: Import looks goodPath alias and utils placement comply with guidelines.
apps/web/app/api/outlook/linking/callback/route.ts (1)
8-8: Import LGTMUtility import via "@/utils/…" is correct and scoped.
| // Transfer premium subscription before deleting the source user | ||
| await transferPremiumDuringMerge({ | ||
| sourceUserId: existingAccount.userId, | ||
| targetUserId, | ||
| }); | ||
|
|
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Run premium transfer inside the same transaction as reassignment/deletion
Calling the transfer before a separate $transaction risks partial merges if later steps fail. Wrap all steps in a single interactive transaction and pass a tx into the utility.
Example:
await prisma.$transaction(async (tx) => {
await transferPremiumDuringMerge(
{ sourceUserId: existingAccount.userId, targetUserId },
{ tx },
);
await tx.account.update({
where: { id: existingAccount.id },
data: { userId: targetUserId },
});
await tx.emailAccount.update({
where: { accountId: existingAccount.id },
data: {
userId: targetUserId,
name: existingAccount.user.name,
email: existingAccount.user.email,
},
});
await tx.user.delete({ where: { id: existingAccount.userId } });
});Optional: Apply the same change to the Outlook linking route for parity.
🏁 Script executed:
#!/bin/bash
# Verify the Outlook route also wraps merge + premium transfer in one transaction
rg -nC2 -g 'apps/web/app/api/**/linking/**/route.ts' -P 'transferPremiumDuringMerge\(|\$transaction\('Length of output: 1666
Wrap premium transfer and merge steps in a single transaction
Move the call to transferPremiumDuringMerge into the same prisma.$transaction block as the account/user updates and deletion, passing in the transaction client. Apply this change in both:
- apps/web/app/api/google/linking/callback/route.ts (lines 138–143 & 144–146)
- apps/web/app/api/outlook/linking/callback/route.ts (lines 223–227 & 229–231)
- await transferPremiumDuringMerge({ sourceUserId, targetUserId });
- await prisma.$transaction([ …updates…, …deletion… ]);
+ await prisma.$transaction(async (tx) => {
+ await transferPremiumDuringMerge(
+ { sourceUserId, targetUserId },
+ { tx },
+ );
+ await tx.account.update({ … });
+ await tx.emailAccount.update({ … });
+ await tx.user.delete({ … });
+ });📝 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.
| // Transfer premium subscription before deleting the source user | |
| await transferPremiumDuringMerge({ | |
| sourceUserId: existingAccount.userId, | |
| targetUserId, | |
| }); | |
| // Transfer premium subscription before deleting the source user | |
| await prisma.$transaction(async (tx) => { | |
| // first, move premium over using the same transaction client | |
| await transferPremiumDuringMerge( | |
| { sourceUserId: existingAccount.userId, targetUserId }, | |
| { tx }, | |
| ); | |
| // then perform the merge updates and deletion atomically | |
| await tx.account.update({ | |
| /* …existing account.update parameters… */ | |
| }); | |
| await tx.emailAccount.update({ | |
| /* …existing emailAccount.update parameters… */ | |
| }); | |
| await tx.user.delete({ | |
| /* …existing user.delete parameters… */ | |
| }); | |
| }); |
🤖 Prompt for AI Agents
In apps/web/app/api/google/linking/callback/route.ts around lines 138-143 (and
144-146) and apps/web/app/api/outlook/linking/callback/route.ts around lines
223-227 (and 229-231), the call to transferPremiumDuringMerge is executed
outside the prisma.$transaction; move that call into the same
prisma.$transaction block that performs the account/user updates and deletion,
remove the standalone call, and pass the transaction client (e.g., tx) into
transferPremiumDuringMerge so it uses the transactional Prisma client for any DB
operations.
| // Transfer premium subscription before deleting the source user | ||
| await transferPremiumDuringMerge({ | ||
| sourceUserId: existingAccount.userId, | ||
| targetUserId, | ||
| }); | ||
|
|
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Make premium transfer atomic with the merge transaction
Running transferPremiumDuringMerge before the $transaction risks partial state (premium moved but merge fails or vice‑versa). Execute the premium transfer inside the same Prisma transaction using an interactive transaction and pass a TransactionClient to the helper.
Apply this refactor:
- // Transfer premium subscription before deleting the source user
- await transferPremiumDuringMerge({
- sourceUserId: existingAccount.userId,
- targetUserId,
- });
-
- await prisma.$transaction([
- prisma.account.update({
- where: { id: existingAccount.id },
- data: { userId: targetUserId },
- }),
- prisma.emailAccount.update({
- where: { accountId: existingAccount.id },
- data: {
- userId: targetUserId,
- name: existingAccount.user.name,
- email: existingAccount.user.email,
- },
- }),
- prisma.user.delete({
- where: { id: existingAccount.userId },
- }),
- ]);
+ await prisma.$transaction(async (tx) => {
+ // Transfer premium subscription before deleting the source user
+ await transferPremiumDuringMerge(
+ { sourceUserId: existingAccount.userId, targetUserId },
+ tx,
+ );
+
+ await tx.account.update({
+ where: { id: existingAccount.id },
+ data: { userId: targetUserId },
+ });
+
+ await tx.emailAccount.update({
+ where: { accountId: existingAccount.id },
+ data: {
+ userId: targetUserId,
+ name: existingAccount.user.name,
+ email: existingAccount.user.email,
+ },
+ });
+
+ await tx.user.delete({
+ where: { id: existingAccount.userId },
+ });
+ });Update the helper to accept a transaction client (outside this file):
// apps/web/utils/user/merge-premium.ts
import type { Prisma } from "@prisma/client";
import prisma from "@/utils/prisma";
export async function transferPremiumDuringMerge(
params: { sourceUserId: string; targetUserId: string },
db: Prisma.TransactionClient = prisma,
) {
// use `db` instead of `prisma` for all queries
}Optional: consider isolationLevel: "Serializable" (Postgres) if concurrent merges are possible.
To verify other call sites also run inside a transaction:
🏁 Script executed:
#!/bin/bash
rg -n -C3 'transferPremiumDuringMerge\('Length of output: 1677
Make premium transfer atomic in merge transactions
- In apps/web/app/api/outlook/linking/callback/route.ts (≈line 223) and apps/web/app/api/google/linking/callback/route.ts (≈line 139), wrap
transferPremiumDuringMergeplus the account updates and user deletion in a singlepassingawait prisma.$transaction(async (tx) => { await transferPremiumDuringMerge({ sourceUserId, targetUserId }, tx); // tx.account.update… // tx.emailAccount.update… // tx.user.delete… });
txinto the helper. - Refactor
transferPremiumDuringMerge(apps/web/utils/user/merge-premium.ts) to accept aPrisma.TransactionClient(defaultprisma) and use it for all queries.
(Optional) consider isolationLevel: "Serializable" for stricter concurrency control.
🤖 Prompt for AI Agents
In apps/web/app/api/outlook/linking/callback/route.ts around lines 223-228 (and
similarly apps/web/app/api/google/linking/callback/route.ts around line 139),
the call to transferPremiumDuringMerge and the subsequent account updates and
user deletion must be executed inside a single prisma transaction; wrap those
operations in await prisma.$transaction(async (tx) => { ... }) and pass tx into
transferPremiumDuringMerge so it uses the transaction client for its queries;
update apps/web/utils/user/merge-premium.ts to accept an optional
Prisma.TransactionClient parameter (defaulting to prisma) and replace all
prisma.* calls inside the helper with the passed tx to ensure the premium
transfer is atomic with the account updates and user deletion (optionally add
isolationLevel: "Serializable" to the transaction call for stricter
concurrency).
apps/web/utils/user/merge-premium.ts
Outdated
| // Execute all premium transfer operations | ||
| if (operations.length > 0) { | ||
| logger.info("Executing premium transfer operations", { | ||
| operationCount: operations.length, | ||
| sourceUserId, | ||
| targetUserId, | ||
| }); | ||
|
|
||
| await Promise.all(operations); | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Execute updates in a single DB transaction (avoid partial state)
Running these updates with Promise.all risks partial writes if one op fails. Use a Prisma transaction.
Apply this diff:
- await Promise.all(operations);
+ await prisma.$transaction(operations as Parameters<typeof prisma.$transaction>[0]);Follow-up: If we later pass a TransactionClient (see separate comment), use tx.$transaction(ops) for full atomicity with the caller’s merge.
📝 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.
| // Execute all premium transfer operations | |
| if (operations.length > 0) { | |
| logger.info("Executing premium transfer operations", { | |
| operationCount: operations.length, | |
| sourceUserId, | |
| targetUserId, | |
| }); | |
| await Promise.all(operations); | |
| // Execute all premium transfer operations | |
| if (operations.length > 0) { | |
| logger.info("Executing premium transfer operations", { | |
| operationCount: operations.length, | |
| sourceUserId, | |
| targetUserId, | |
| }); | |
| await prisma.$transaction(operations as Parameters<typeof prisma.$transaction>[0]); |
🤖 Prompt for AI Agents
In apps/web/utils/user/merge-premium.ts around lines 164 to 173, the code
currently runs updates with await Promise.all(operations), which can produce
partial writes if one op fails; replace this with a Prisma transaction call to
ensure atomicity: if a TransactionClient (tx) is provided call await
tx.$transaction(operations), otherwise call await
prisma.$transaction(operations). Ensure the items in operations are raw Prisma
query functions (not already-executed promises) so they run inside the
transaction, and keep the existing logging and error propagation (catch, log,
rethrow) as needed.
There was a problem hiding this comment.
4 issues found across 4 files
Since this is your first cubic review, here's how it works:
- cubic automatically reviews your code and comments on bugs and improvements
- Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
- Ask questions if you need clarification on any suggestion
React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.
| }); | ||
|
|
||
| // Transfer premium subscription before deleting the source user | ||
| await transferPremiumDuringMerge({ |
There was a problem hiding this comment.
Premium updates are executed outside the merge transaction, risking partial state if $transaction later fails; consider performing all writes in a single interactive transaction
Prompt for AI agents
Address the following comment on apps/web/app/api/outlook/linking/callback/route.ts at line 224:
<comment>Premium updates are executed outside the merge transaction, risking partial state if $transaction later fails; consider performing all writes in a single interactive transaction</comment>
<file context>
@@ -218,6 +219,13 @@ export const GET = withError(async (request: NextRequest) => {
});
+
+ // Transfer premium subscription before deleting the source user
+ await transferPremiumDuringMerge({
+ sourceUserId: existingAccount.userId,
+ targetUserId,
</file context>
| }); | ||
|
|
||
| // Transfer premium subscription before deleting the source user | ||
| await transferPremiumDuringMerge({ |
There was a problem hiding this comment.
transferPremiumDuringMerge assumes a user can belong to multiple premiums; schema enforces a single premiumId per user, so connecting here will overwrite the target's current premium rather than "maintain access to both"
Prompt for AI agents
Address the following comment on apps/web/app/api/outlook/linking/callback/route.ts at line 224:
<comment>transferPremiumDuringMerge assumes a user can belong to multiple premiums; schema enforces a single premiumId per user, so connecting here will overwrite the target's current premium rather than "maintain access to both"</comment>
<file context>
@@ -218,6 +219,13 @@ export const GET = withError(async (request: NextRequest) => {
});
+
+ // Transfer premium subscription before deleting the source user
+ await transferPremiumDuringMerge({
+ sourceUserId: existingAccount.userId,
+ targetUserId,
</file context>
| ); | ||
|
|
||
| // Transfer premium subscription before deleting the source user | ||
| await transferPremiumDuringMerge({ |
There was a problem hiding this comment.
Premium transfer runs outside the surrounding DB transaction, risking inconsistent state if later merge operations fail.
Prompt for AI agents
Address the following comment on apps/web/app/api/google/linking/callback/route.ts at line 139:
<comment>Premium transfer runs outside the surrounding DB transaction, risking inconsistent state if later merge operations fail.</comment>
<file context>
@@ -133,6 +134,13 @@ export const GET = withError(async (request: NextRequest) => {
);
+
+ // Transfer premium subscription before deleting the source user
+ await transferPremiumDuringMerge({
+ sourceUserId: existingAccount.userId,
+ targetUserId,
</file context>
apps/web/utils/user/merge-premium.ts
Outdated
| targetUserId, | ||
| }); | ||
|
|
||
| await Promise.all(operations); |
There was a problem hiding this comment.
Multiple related DB updates are executed without a transaction, risking partial updates and inconsistent state if any operation fails.
Prompt for AI agents
Address the following comment on apps/web/utils/user/merge-premium.ts at line 172:
<comment>Multiple related DB updates are executed without a transaction, risking partial updates and inconsistent state if any operation fails.</comment>
<file context>
@@ -0,0 +1,181 @@
+ targetUserId,
+ });
+
+ await Promise.all(operations);
+
+ logger.info("Premium transfer completed successfully", {
</file context>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
apps/web/utils/user/merge-premium.ts (1)
201-211: Execute writes atomically in a transaction (duplicate of earlier feedback).Promise.all risks partial state if one write fails. Use Prisma $transaction with the array API.
- await Promise.all(operations); + await prisma.$transaction( + operations as Parameters<typeof prisma.$transaction>[0], + );
🧹 Nitpick comments (5)
apps/web/utils/user/merge-premium.ts (3)
23-46: Trim over-selected fields to reduce load and PII surface.users/admins lists aren’t used for decision-making; only tier (and optional admin ids if guarding duplicates) are needed.
premium: { - select: { - id: true, - tier: true, - users: { select: { id: true, email: true } }, - admins: { select: { id: true, email: true } }, - }, + select: { id: true, tier: true }, }, - premiumAdmin: { - select: { - id: true, - users: { select: { id: true, email: true } }, - admins: { select: { id: true, email: true } }, - }, - }, + premiumAdmin: { select: { id: true, admins: { select: { id: true } } } },Also applies to: 60-66
171-199: Guard against duplicate admin connect to avoid unique constraint errors.If target is already an admin of sourceUser.premiumAdmin, connect can fail. Use the selected admins ids to skip.
- // Connect target user as admin to source premium admin - operations.push( - prisma.premium.update({ - where: { id: sourceUser.premiumAdminId }, - data: { - admins: { - connect: { id: targetUserId }, - }, - }, - }), - ); + // Connect target user as admin (skip if already connected) + const alreadyAdmin = + sourceUser.premiumAdmin?.admins?.some((a) => a.id === targetUserId); + if (!alreadyAdmin) { + operations.push( + prisma.premium.update({ + where: { id: sourceUser.premiumAdminId }, + data: { admins: { connect: { id: targetUserId } } }, + }), + ); + }
11-17: Consider accepting a TransactionClient to run reads+writes in the caller’s merge transaction.Pre-merge reads can go stale before writes. Optionally add tx?: Prisma.TransactionClient and use tx for both reads and writes when provided.
apps/web/utils/user/merge-premium.test.ts (2)
140-142: Add transaction assertion once writes are wrapped.After switching to prisma.$transaction, assert it was called and that individual updates weren’t awaited directly.
Example:
expect(prisma.$transaction).toHaveBeenCalled(); // Optionally: expect(prisma.user.update).toHaveBeenCalledTimes(1) // depending on scenarioAlso applies to: 232-240
357-400: Add a test for duplicate admin connect.Simulate target already being an admin of sourceUser.premiumAdmin and expect no prisma.premium.update with admins.connect.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/utils/user/merge-premium.test.ts(1 hunks)apps/web/utils/user/merge-premium.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use@/for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
!{.cursor/rules/*.mdc}
📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)
Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)
**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport Prisma in the project using
import prisma from "@/utils/prisma";
**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
**/*.test.{ts,js}
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
Include security tests in your test suites to verify authentication, authorization, and error handling.
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.test.{ts,js,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,js,tsx,jsx}: Tests are colocated next to the tested file (e.g.,dir/format.tsanddir/format.test.ts)
Usevi.mock("server-only", () => ({}));to mock theserver-onlymodule in tests
Mock@/utils/prismain tests usingvi.mock("@/utils/prisma")and use the provided prisma mock
Mock external dependencies in tests
Clean up mocks between tests
Do not mock the Logger
Files:
apps/web/utils/user/merge-premium.test.ts
apps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logic
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
apps/web/utils/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
!pages/_document.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.
Files:
apps/web/utils/user/merge-premium.test.tsapps/web/utils/user/merge-premium.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.
Files:
apps/web/utils/user/merge-premium.test.ts
🧠 Learnings (3)
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Include standard cases: happy path, error handling, edge cases (empty/null), different user configs, and various input formats
Applied to files:
apps/web/utils/user/merge-premium.test.ts
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Create helper functions for common test data (e.g., getUser, getTestData(overrides))
Applied to files:
apps/web/utils/user/merge-premium.test.ts
📚 Learning: 2025-06-23T12:27:30.570Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/__mocks__/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.
Applied to files:
apps/web/utils/user/merge-premium.test.ts
🧬 Code graph analysis (2)
apps/web/utils/user/merge-premium.test.ts (1)
apps/web/utils/user/merge-premium.ts (1)
transferPremiumDuringMerge(11-218)
apps/web/utils/user/merge-premium.ts (2)
apps/web/utils/logger.ts (1)
createScopedLogger(17-67)apps/web/utils/premium/index.ts (1)
isOnHigherTier(105-113)
🔇 Additional comments (4)
apps/web/utils/user/merge-premium.ts (2)
76-99: Tier decision logic reads correctly (1→many schema aligned).Using isOnHigherTier(targetTier, sourceTier) negated to prefer the source when target is not higher is correct; handling “same premiumId” short-circuits unnecessary writes. Nice.
69-73: Good not-found handling for target user.Logging + throwing a specific error message is appropriate here.
apps/web/utils/user/merge-premium.test.ts (2)
1-8: Mocks and setup look correct and follow project conventions.Prisma is mocked via "@/utils/mocks/prisma", server-only is stubbed, and mocks are cleared per test.
145-161: Drop theprisma.premium.updatedisconnect assertion if you’ve consolidated to a singleprisma.user.update. Remove the disconnect check in apps/web/utils/user/merge-premium.test.ts (lines 145–154) and only assert the reassignment tosourcePremiumId.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
apps/web/utils/user/merge-premium.test.ts (2)
10-12: Prefer resetAllMocks for stronger isolation (optional).Using vi.resetAllMocks() also resets mock implementations between tests and can prevent cross-test leakage if defaults are ever set.
Apply this diff:
- beforeEach(() => { - vi.clearAllMocks(); - }); + beforeEach(() => { + vi.resetAllMocks(); + });
21-35: Reduce repetition with small test data helpers (optional).Repeated inline user/premium objects make tests verbose. Consider factory helpers (per retrieved learnings) to cut duplication and improve readability.
Example helper (add near top of file):
const makeUser = (overrides: Partial<any> = {}) => ({ id: "user-id", email: "user@example.com", premiumId: null, premiumAdminId: null, premium: null, premiumAdmin: null, ...overrides, }); const makePremium = (id: string, tier: PremiumTier, extra: Partial<any> = {}) => ({ id, tier, users: [], admins: [], ...extra, });Also applies to: 67-81, 106-120, 151-168, 194-207, 234-242, 267-275, 298-310, 347-360, 411-419
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/utils/user/merge-premium.test.ts(1 hunks)apps/web/utils/user/merge-premium.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/utils/user/merge-premium.ts
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use@/for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX
Files:
apps/web/utils/user/merge-premium.test.ts
!{.cursor/rules/*.mdc}
📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)
Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)
**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport Prisma in the project using
import prisma from "@/utils/prisma";
**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.test.{ts,js}
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
Include security tests in your test suites to verify authentication, authorization, and error handling.
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.test.{ts,js,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,js,tsx,jsx}: Tests are colocated next to the tested file (e.g.,dir/format.tsanddir/format.test.ts)
Usevi.mock("server-only", () => ({}));to mock theserver-onlymodule in tests
Mock@/utils/prismain tests usingvi.mock("@/utils/prisma")and use the provided prisma mock
Mock external dependencies in tests
Clean up mocks between tests
Do not mock the Logger
Files:
apps/web/utils/user/merge-premium.test.ts
apps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logic
Files:
apps/web/utils/user/merge-premium.test.ts
apps/web/utils/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...
Files:
apps/web/utils/user/merge-premium.test.ts
!pages/_document.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.
Files:
apps/web/utils/user/merge-premium.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.
Files:
apps/web/utils/user/merge-premium.test.ts
🧠 Learnings (3)
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Include standard cases: happy path, error handling, edge cases (empty/null), different user configs, and various input formats
Applied to files:
apps/web/utils/user/merge-premium.test.ts
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Create helper functions for common test data (e.g., getUser, getTestData(overrides))
Applied to files:
apps/web/utils/user/merge-premium.test.ts
📚 Learning: 2025-06-23T12:27:30.570Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/__mocks__/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.
Applied to files:
apps/web/utils/user/merge-premium.test.ts
🧬 Code graph analysis (1)
apps/web/utils/user/merge-premium.test.ts (1)
apps/web/utils/user/merge-premium.ts (1)
transferPremiumDuringMerge(11-218)
🪛 GitHub Check: test
apps/web/utils/user/merge-premium.test.ts
[failure] 424-424: utils/user/merge-premium.test.ts > transferPremiumDuringMerge > error handling > should throw error when target user is not found
AssertionError: promise resolved "undefined" instead of rejecting
- Expected:
Error {
"message": "rejected promise",
}
- Received:
undefined
❯ utils/user/merge-premium.test.ts:424:7
🪛 GitHub Actions: Run Tests
apps/web/utils/user/merge-premium.test.ts
[error] 424-424: Test failed in step: 'pnpm -F inbox-zero-ai test' (Vitest). In utils/user/merge-premium.test.ts, 'transferPremiumDuringMerge' -> 'error handling' -> 'should throw error when target user is not found' failed: promise resolved to undefined instead of rejecting.
🔇 Additional comments (7)
apps/web/utils/user/merge-premium.test.ts (7)
1-8: Mocks are set up correctly.Good job mocking server-only and Prisma with the project’s provided prisma mock; colocated tests align with guidelines.
14-186: Tier-resolution scenarios look solid.Good coverage for source-higher, target-higher, equal-tier, and shared-premium cases; assertions match the utility’s intended idempotency.
188-260: One-sided premium ownership paths are covered.The “only source” transfer and “only target keeps” behaviors are validated properly.
262-290: No-premium case is exercised.Correctly asserts no writes when neither user has premium.
292-385: Admin-rights transfer logic is well tested.Assertions align with connecting target as admin and avoiding redundant premiumAdminId updates when already present.
387-405: Source-missing early return matches implementation.No updates asserted; consistent with utility’s non-throwing behavior on early exit.
407-425: Usepnpm test(notpnpm -w vitest run) and update the test to expect resolution
Replace therejects.toThrowexpectation with aresolves.toBeUndefined()and assert no writes:- await expect( - transferPremiumDuringMerge({ sourceUserId, targetUserId }), - ).rejects.toThrow(`Target user ${targetUserId} not found`); + // Function swallows errors; expect resolution and no writes + await expect( + transferPremiumDuringMerge({ sourceUserId, targetUserId }), + ).resolves.toBeUndefined(); + expect(prisma.premium.update).not.toHaveBeenCalled(); + expect(prisma.user.update).not.toHaveBeenCalled();Then run
pnpm test apps/web/utils/user/merge-premium.test.ts -ito verify the suite passes.
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores