Skip to content

outlook sub history#938

Merged
elie222 merged 3 commits intomainfrom
feat/outlook-sub-history
Nov 10, 2025
Merged

outlook sub history#938
elie222 merged 3 commits intomainfrom
feat/outlook-sub-history

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 10, 2025

Summary by CodeRabbit

  • New Features

    • Added subscription history tracking for Outlook email accounts, preserving prior subscription records.
  • Improvements

    • Webhook lookup now searches historical subscription records to locate accounts when current subscription IDs change.
    • Subscription updates now maintain and clean up historical entries automatically.
  • Tests

    • Expanded tests to cover history parsing, retention, cleanup, and update behavior.
  • Chores

    • Bumped version to v2.18.14.

@vercel
Copy link

vercel bot commented Nov 10, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Nov 10, 2025 8:25am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 10, 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.

Walkthrough

Adds Outlook subscription history support: a JSONB column on EmailAccount, a new subscription-history utility, integration into subscription update flow to append/cleanup history, webhook lookup fallback that searches historical subscription IDs, tests, and a patch version bump.

Changes

Cohort / File(s) Summary
Database & Schema
apps/web/prisma/migrations/20251110013724_add_outlook_subscription_history/migration.sql, apps/web/prisma/schema.prisma, version.txt
Adds watchEmailsSubscriptionHistory (JSONB) to EmailAccount via migration and schema; bumps version to v2.18.14.
Subscription History Utilities
apps/web/utils/outlook/subscription-history.ts, apps/web/utils/outlook/subscription-history.test.ts
New module providing types and functions to parse, validate, clean, query, and append subscription history entries (entries with subscriptionId, createdAt, replacedAt) and accompanying unit tests.
Subscription Manager
apps/web/utils/outlook/subscription-manager.ts, apps/web/utils/outlook/subscription-manager.test.ts
Integrates history parsing/cleanup into subscription update flow; appends previous subscription to history when ID changes; persists watchEmailsSubscriptionHistory with updates; tests updated to cover history behavior.
Webhook Validation
apps/web/utils/webhook/validate-webhook-account.ts
Extends webhook account lookup to include watchEmailsSubscriptionHistory in projection; if no current match, searches watchEmailsSubscriptionHistory JSONB for the subscriptionId and refetches account on historical match.

Sequence Diagram(s)

sequenceDiagram
    participant Webhook as Webhook Handler
    participant Validate as validateWebhookAccount()
    participant DB as Database
    participant History as History Utils

    Webhook->>Validate: incoming subscriptionId
    Validate->>DB: query EmailAccount by watchEmailsSubscriptionId (select history)
    alt Found by current ID
        DB-->>Validate: EmailAccount (includes history)
        Validate-->>Webhook: Account found
    else Not found
        Validate->>History: isSubscriptionInHistory(subscriptionId, watchEmailsSubscriptionHistory)
        activate History
        History-->>Validate: match? (true/false)
        deactivate History
        alt Found in history
            Validate->>DB: query EmailAccount by id (log historical match)
            DB-->>Validate: EmailAccount
            Validate-->>Webhook: Account found via history
        else Not found
            Validate-->>Webhook: Account not found (error)
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Focus review on:
    • apps/web/utils/outlook/subscription-manager.ts — correctness of history parsing, createdAt/replacedAt handling, update payload shape, and race conditions.
    • apps/web/utils/webhook/validate-webhook-account.ts — safety and correctness of JSONB search and projection changes.
    • apps/web/utils/outlook/subscription-history.ts — robust parsing, date handling, and cleanup logic.
    • Migration SQL — ensure IF NOT EXISTS guard and type consistency with Prisma schema.

Possibly related PRs

  • Reduce diff in schema #636 — Related changes to the EmailAccount model; both PRs touch schema.prisma and the new watchEmailsSubscriptionHistory field.
  • Fix e2e test #904 — Related modifications to validate-webhook-account.ts; both PRs adjust webhook account lookup and logging paths.

Poem

🐰
I tuck old IDs in JSON hay,
Replaced subscriptions cozy, tucked away.
If an ID wanders and can't be found,
I hop through history, turn it around.
A tidy trail for each email day. 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'outlook sub history' is vague and abbreviated, lacking specificity about what subscription history functionality is being added. Use a more descriptive title such as 'Add Outlook subscription history tracking' to clearly convey the feature being implemented.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/outlook-sub-history

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

🧹 Nitpick comments (2)
apps/web/utils/outlook/subscription-history.ts (2)

14-48: Consider validating ISO date format in parsed entries.

The function properly validates that createdAt and replacedAt are strings, but doesn't verify they're valid ISO date strings. This could cause issues downstream when these values are passed to new Date() (e.g., in cleanupOldHistoryEntries).

Consider adding date format validation in the type guard:

       const hasRequiredFields =
         typeof entry === "object" &&
         entry !== null &&
         "subscriptionId" in entry &&
         "createdAt" in entry &&
         "replacedAt" in entry &&
         typeof entry.subscriptionId === "string" &&
         typeof entry.createdAt === "string" &&
-        typeof entry.replacedAt === "string";
+        typeof entry.replacedAt === "string" &&
+        !isNaN(Date.parse(entry.createdAt)) &&
+        !isNaN(Date.parse(entry.replacedAt));

90-100: Consider automatic cleanup to prevent unbounded growth.

The function appends entries without cleanup. While cleanupOldHistoryEntries exists, callers must remember to invoke it separately. Consider calling cleanup automatically within this function to prevent unbounded history growth.

 export function addToHistory(
   currentHistory: unknown,
   subscriptionId: string,
   createdAt: string,
   replacedAt: string,
   logger?: Logger,
 ): SubscriptionHistory {
   const parsed = parseSubscriptionHistory(currentHistory, logger);
   const newEntry = createHistoryEntry(subscriptionId, createdAt, replacedAt);
-  return [...parsed, newEntry];
+  const updated = [...parsed, newEntry];
+  return cleanupOldHistoryEntries(updated);
 }
📜 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 38f10fe and 74665d0.

📒 Files selected for processing (6)
  • apps/web/prisma/migrations/20251110013724_add_outlook_subscription_history/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (2 hunks)
  • apps/web/utils/outlook/subscription-history.ts (1 hunks)
  • apps/web/utils/outlook/subscription-manager.ts (4 hunks)
  • apps/web/utils/webhook/validate-webhook-account.ts (2 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
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/webhook/validate-webhook-account.ts
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • version.txt
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/prisma/migrations/20251110013724_add_outlook_subscription_history/migration.sql
  • apps/web/prisma/schema.prisma
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/utils/outlook/subscription-history.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/webhook/validate-webhook-account.ts
  • version.txt
  • apps/web/utils/outlook/subscription-manager.ts
  • apps/web/prisma/migrations/20251110013724_add_outlook_subscription_history/migration.sql
  • apps/web/prisma/schema.prisma
  • apps/web/utils/outlook/subscription-history.ts
apps/web/prisma/schema.prisma

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

The Prisma schema file must be located at apps/web/prisma/schema.prisma

Files:

  • apps/web/prisma/schema.prisma
🧠 Learnings (3)
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operations

Applied to files:

  • apps/web/utils/webhook/validate-webhook-account.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer existing helpers from @/__tests__/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Applied to files:

  • apps/web/utils/webhook/validate-webhook-account.ts
📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Applied to files:

  • apps/web/utils/outlook/subscription-history.ts
🧬 Code graph analysis (2)
apps/web/utils/outlook/subscription-manager.ts (1)
apps/web/utils/outlook/subscription-history.ts (3)
  • parseSubscriptionHistory (14-48)
  • cleanupOldHistoryEntries (68-74)
  • addCurrentSubscriptionToHistory (105-126)
apps/web/utils/outlook/subscription-history.ts (1)
apps/web/utils/logger.ts (1)
  • Logger (5-5)
⏰ 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). (4)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Jit Security
  • GitHub Check: test
🔇 Additional comments (5)
apps/web/utils/outlook/subscription-history.ts (5)

1-9: LGTM! Clean type definitions.

The import and type definitions follow best practices, using import type for the Logger and providing clear, simple type structures for the subscription history.


53-63: LGTM! Simple and clear.

The factory function is straightforward and appropriate for creating history entries. Since callers typically use .toISOString(), the date format should be consistent.


68-74: LGTM! Defensive filtering behavior.

The function correctly filters old entries. Note that if entry.replacedAt is an invalid date string, new Date() returns an Invalid Date which fails the comparison and gets filtered out—this is acceptable defensive behavior. Consider applying the date validation from the previous comment to prevent invalid entries from entering the history.


79-85: LGTM! Clean implementation.

The function properly delegates parsing to parseSubscriptionHistory and uses a simple array search. Error handling is appropriately handled by the parser.


105-126: LGTM! Smart estimation logic.

The function correctly estimates the createdAt timestamp by using the last entry's replacedAt time, which aligns with the subscription replacement flow. This provides accurate tracking of subscription lifecycles.

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.

2 issues found across 6 files

Prompt for AI agents (all 2 issues)

Understand the root cause of the following 2 issues and fix them.


<file name="apps/web/prisma/migrations/20251110013724_add_outlook_subscription_history/migration.sql">

<violation number="1" location="apps/web/prisma/migrations/20251110013724_add_outlook_subscription_history/migration.sql:2">
`IF NOT EXISTS` lets this Prisma migration silently skip applying the JSONB column even if an environment already has the column with the wrong type, leaving the DB schema out of sync and causing Prisma JSON writes to fail. Let the migration fail fast instead of masking drift.</violation>
</file>

<file name="apps/web/utils/webhook/validate-webhook-account.ts">

<violation number="1" location="apps/web/utils/webhook/validate-webhook-account.ts:74">
The JSON history lookup uses array_contains with a bare object; for PostgreSQL JSON arrays this will not match elements. Wrap the object in an array so the containment check can correctly find entries by subscriptionId</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

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 (1)
apps/web/utils/outlook/subscription-history.test.ts (1)

1-267: Consider adding beforeEach for consistency.

While the current tests work correctly, adding a beforeEach block with vi.clearAllMocks() would improve consistency with coding guidelines and the other test file. This would also future-proof the tests if more mocks are added later.

+import { describe, it, expect, vi, beforeEach } from "vitest";
-import { describe, it, expect, vi } from "vitest";
 import {
   parseSubscriptionHistory,
   createHistoryEntry,
   cleanupOldHistoryEntries,
   isSubscriptionInHistory,
   addCurrentSubscriptionToHistory,
 } from "./subscription-history";

 describe("subscription-history", () => {
+  beforeEach(() => {
+    vi.clearAllMocks();
+  });
+
   describe("parseSubscriptionHistory", () => {

Based on coding guidelines

📜 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 2c528da and 33215f0.

📒 Files selected for processing (2)
  • apps/web/utils/outlook/subscription-history.test.ts (1 hunks)
  • apps/web/utils/outlook/subscription-manager.test.ts (2 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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.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/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.test.ts
**/*.test.{ts,tsx}

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

**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock the server-only module with vi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it with vi.mock("@/utils/prisma") and use the mock from @/utils/__mocks__/prisma
Use provided helpers for mocks: import { getEmail, getEmailAccount, getRule } from @/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g., vi.clearAllMocks() in beforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger

Files:

  • apps/web/utils/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.test.ts
🧠 Learnings (11)
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer existing helpers from @/__tests__/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Applied to files:

  • apps/web/utils/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats

Applied to files:

  • apps/web/utils/outlook/subscription-manager.test.ts
  • apps/web/utils/outlook/subscription-history.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/utils/outlook/subscription-manager.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : When testing code that uses Prisma, mock it with `vi.mock("@/utils/prisma")` and use the mock from `@/utils/__mocks__/prisma`

Applied to files:

  • apps/web/utils/outlook/subscription-manager.test.ts
📚 Learning: 2025-06-23T12:26:53.882Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.

Applied to files:

  • apps/web/utils/outlook/subscription-manager.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Clean up mocks between tests (e.g., `vi.clearAllMocks()` in `beforeEach`)

Applied to files:

  • apps/web/utils/outlook/subscription-manager.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Avoid testing implementation details; focus on observable behavior

Applied to files:

  • apps/web/utils/outlook/subscription-history.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI paths, including cases where no AI processing is required

Applied to files:

  • apps/web/utils/outlook/subscription-history.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Create helper functions for common test data (e.g., getUser, getTestData) to reduce duplication

Applied to files:

  • apps/web/utils/outlook/subscription-history.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use descriptive test names

Applied to files:

  • apps/web/utils/outlook/subscription-history.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"

Applied to files:

  • apps/web/utils/outlook/subscription-history.test.ts
🧬 Code graph analysis (2)
apps/web/utils/outlook/subscription-manager.test.ts (1)
apps/web/utils/outlook/subscription-history.ts (1)
  • SubscriptionHistoryEntry (3-7)
apps/web/utils/outlook/subscription-history.test.ts (1)
apps/web/utils/outlook/subscription-history.ts (5)
  • parseSubscriptionHistory (14-48)
  • createHistoryEntry (53-63)
  • cleanupOldHistoryEntries (68-74)
  • isSubscriptionInHistory (79-85)
  • addCurrentSubscriptionToHistory (105-126)
⏰ 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 (12)
apps/web/utils/outlook/subscription-manager.test.ts (6)

5-5: LGTM: Proper type import.

The type import for SubscriptionHistoryEntry follows TypeScript best practices and coding guidelines.


136-158: LGTM: Initial subscription update test.

The test correctly validates the behavior when no prior subscription exists. It properly mocks the initial state and verifies that an empty history array is created.


160-191: LGTM: History entry creation validated.

This test correctly verifies that when a subscription changes, the old subscription is moved to history with proper timestamps. The test validates the structure of the history entry and ensures the new subscription ID is updated.


193-227: LGTM: History preservation validated.

This test ensures that existing history entries are not lost when adding a new subscription. Good coverage of the append behavior.


229-273: LGTM: Temporal cleanup logic validated.

This test correctly validates the 30-day cleanup threshold. The test setup with entries at different ages (31 days vs 29 days) effectively demonstrates the cleanup behavior.


275-294: LGTM: No-op scenario covered.

This test correctly validates that when the subscription ID hasn't changed, no history entry is added. This prevents unnecessary history pollution.

apps/web/utils/outlook/subscription-history.test.ts (6)

1-9: LGTM: Proper test setup.

Imports are clean and follow coding guidelines. All necessary functions are imported for testing.


12-58: LGTM: Comprehensive parseSubscriptionHistory tests.

Excellent coverage of edge cases including:

  • Valid input handling
  • Null/undefined handling
  • Invalid entry filtering with logger warnings
  • Non-array input handling

The logger mock is properly used to verify warning behavior.


62-74: LGTM: createHistoryEntry test.

Simple and effective test for a straightforward utility function.


78-148: LGTM: Comprehensive cleanup tests.

Good coverage of the temporal cleanup logic:

  • Custom days threshold
  • Default 30-day threshold
  • All-recent entries preservation

The test setup with different time offsets effectively validates the cutoff logic.


152-190: LGTM: Comprehensive lookup tests.

Excellent edge case coverage for the isSubscriptionInHistory function, including invalid input handling.


194-265: LGTM: Comprehensive history addition tests.

These tests effectively validate:

  • Empty history initialization
  • Timestamp chaining (using last entry's replacedAt as next createdAt)
  • History preservation

Good coverage of the core history management logic.

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.

No issues found across 3 files

@elie222 elie222 merged commit dc3774a into main Nov 10, 2025
16 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 13, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 17, 2025
@elie222 elie222 deleted the feat/outlook-sub-history branch December 18, 2025 23:03
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

Comments