Skip to content

Comments

Fix merging with premium#761

Merged
elie222 merged 5 commits intomainfrom
fix/merge-premium
Sep 10, 2025
Merged

Fix merging with premium#761
elie222 merged 5 commits intomainfrom
fix/merge-premium

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 9, 2025

Summary by CodeRabbit

  • New Features

    • Premium subscriptions and admin roles now automatically transfer to the primary account during Google and Outlook account merges.
  • Bug Fixes

    • Prevents scenarios where premium access could be lost or split between merged accounts; tier comparisons ensure the higher-tier subscription prevails.
  • Tests

    • Added comprehensive tests covering premium and admin transfer scenarios across merge cases.
  • Chores

    • Bumped app version to v2.9.7.

@vercel
Copy link

vercel bot commented Sep 9, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Error Error Sep 10, 2025 10:20am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 9, 2025

Note

Other AI code review bot(s) detected

CodeRabbit 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 failed

The pull request is closed.

Walkthrough

Adds a premium-transfer step to Google and Outlook account-merge flows by calling a new utility transferPremiumDuringMerge before the existing Prisma transaction; adds the transfer utility and unit tests; bumps version to v2.9.7. No public API signature changes.

Changes

Cohort / File(s) Summary of Changes
Linking callback routes
apps/web/app/api/google/linking/callback/route.ts, apps/web/app/api/outlook/linking/callback/route.ts
Import and call transferPremiumDuringMerge({ sourceUserId: existingAccount.userId, targetUserId }) in the merge branch immediately before the Prisma transaction that reassigns accounts and deletes the source user; integrated into existing try/catch without altering other flow.
Premium transfer utility
apps/web/utils/user/merge-premium.ts
New exported async transferPremiumDuringMerge({ sourceUserId, targetUserId }) that reads source/target premium and admin state, decides transfer/assign/disconnect/update operations (including tier comparisons), schedules Prisma updates (connect/disconnect/update), and logs decisions; errors are caught and logged (no rethrow).
Tests for utility
apps/web/utils/user/merge-premium.test.ts
New test suite mocking Prisma scenarios covering combinations of source/target premium and admin states, tier comparisons, no-op cases, transfers, and admin connections; asserts appropriate Prisma update/connect calls.
Version
version.txt
Bump version from v2.9.6 to v2.9.7.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I hopped between accounts with careful cheer,
Shuffling premium carrots from far to near.
Admins connected, tiers checked with delight,
Two nests now one, everything set right.
v2.9.7 — a tidy hop, and all snug tonight. 🥕🐇


📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9967f59 and de33281.

📒 Files selected for processing (1)
  • apps/web/utils/user/merge-premium.test.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/merge-premium

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 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 params

Passing 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 in withAuth (or withEmailAccount) and assert decodedState.userId === ctx.auth.userId before proceeding, to prevent unauthorized merges (IDOR).

🧹 Nitpick comments (4)
apps/web/utils/user/merge-premium.ts (4)

66-66: Type the operations for transaction safety

Annotate 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 condition

You 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 consistency

When 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 update premiumAdminId accordingly. Otherwise the field may not reflect actual admin memberships.


10-16: Consider accepting a TransactionClient to ensure end‑to‑end atomic merge

To 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

📥 Commits

Reviewing files that changed from the base of the PR and between afbfa56 and 2943a8e.

📒 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.txt
  • apps/web/utils/user/merge-premium.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/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.txt
  • apps/web/utils/user/merge-premium.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/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.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/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.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/api/google/linking/callback/route.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import 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.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/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 use elements 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.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/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.ts
  • apps/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: Use withAuth for user-level operations
Use withEmailAccount for 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 with withAuth or withEmailAccount middleware 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.ts
  • apps/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).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and 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.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma 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.ts
  • apps/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.ts
  • apps/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 LGTM

v2.9.7 looks consistent with the PR scope.

apps/web/app/api/google/linking/callback/route.ts (1)

8-8: Import looks good

Path alias and utils placement comply with guidelines.

apps/web/app/api/outlook/linking/callback/route.ts (1)

8-8: Import LGTM

Utility import via "@/utils/…" is correct and scoped.

Comment on lines +138 to +143
// Transfer premium subscription before deleting the source user
await transferPremiumDuringMerge({
sourceUserId: existingAccount.userId,
targetUserId,
});

Copy link
Contributor

Choose a reason for hiding this comment

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

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

Suggested change
// 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.

Comment on lines +223 to +228
// Transfer premium subscription before deleting the source user
await transferPremiumDuringMerge({
sourceUserId: existingAccount.userId,
targetUserId,
});

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 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 transferPremiumDuringMerge plus the account updates and user deletion in a single
    await prisma.$transaction(async (tx) => {
      await transferPremiumDuringMerge({ sourceUserId, targetUserId }, tx);
      // tx.account.update…
      // tx.emailAccount.update…
      // tx.user.delete…
    });
    passing tx into the helper.
  • Refactor transferPremiumDuringMerge (apps/web/utils/user/merge-premium.ts) to accept a Prisma.TransactionClient (default prisma) 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).

Comment on lines 164 to 173
// Execute all premium transfer operations
if (operations.length > 0) {
logger.info("Executing premium transfer operations", {
operationCount: operations.length,
sourceUserId,
targetUserId,
});

await Promise.all(operations);

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

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.

Suggested change
// 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.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

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({
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 9, 2025

Choose a reason for hiding this comment

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

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) =&gt; {
     });
+
+    // Transfer premium subscription before deleting the source user
+    await transferPremiumDuringMerge({
+      sourceUserId: existingAccount.userId,
+      targetUserId,
</file context>
Fix with Cubic

});

// Transfer premium subscription before deleting the source user
await transferPremiumDuringMerge({
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 9, 2025

Choose a reason for hiding this comment

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

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&#39;s current premium rather than &quot;maintain access to both&quot;</comment>

<file context>
@@ -218,6 +219,13 @@ export const GET = withError(async (request: NextRequest) =&gt; {
     });
+
+    // Transfer premium subscription before deleting the source user
+    await transferPremiumDuringMerge({
+      sourceUserId: existingAccount.userId,
+      targetUserId,
</file context>
Fix with Cubic

);

// Transfer premium subscription before deleting the source user
await transferPremiumDuringMerge({
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 9, 2025

Choose a reason for hiding this comment

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

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) =&gt; {
     );
+
+    // Transfer premium subscription before deleting the source user
+    await transferPremiumDuringMerge({
+      sourceUserId: existingAccount.userId,
+      targetUserId,
</file context>
Fix with Cubic

targetUserId,
});

await Promise.all(operations);
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 9, 2025

Choose a reason for hiding this comment

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

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(&quot;Premium transfer completed successfully&quot;, {
</file context>

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: 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 scenario

Also 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2943a8e and 80da827.

📒 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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/web/utils/user/merge-premium.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import 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
  • apps/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.ts and dir/format.test.ts)
Use vi.mock("server-only", () => ({})); to mock the server-only module in tests
Mock @/utils/prisma in tests using vi.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/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.ts
  • apps/web/utils/user/merge-premium.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Don't use elements 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
  • apps/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.ts
  • apps/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 the prisma.premium.update disconnect assertion if you’ve consolidated to a single prisma.user.update. Remove the disconnect check in apps/web/utils/user/merge-premium.test.ts (lines 145–154) and only assert the reassignment to sourcePremiumId.

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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 80da827 and 9967f59.

📒 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}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import 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.ts and dir/format.test.ts)
Use vi.mock("server-only", () => ({})); to mock the server-only module in tests
Mock @/utils/prisma in tests using vi.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 use elements 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: Use pnpm test (not pnpm -w vitest run) and update the test to expect resolution
Replace the rejects.toThrow expectation with a resolves.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 -i

to verify the suite passes.

@elie222 elie222 merged commit 2e1dddd into main Sep 10, 2025
6 of 8 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 14, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 18, 2025
@elie222 elie222 deleted the fix/merge-premium branch December 18, 2025 23:06
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.

1 participant