Skip to content

fix: add dynamic rate limits - #2892

Merged
dguyen merged 8 commits into
mainfrom
fix/add-dynamic-rate-limits
May 30, 2026
Merged

dguyen merged 8 commits into
mainfrom
fix/add-dynamic-rate-limits

Conversation

@dguyen

@dguyen dguyen commented May 30, 2026

Copy link
Copy Markdown
Collaborator

Description

Add dynamic rate limiting and quotas.

Copilot AI review requested due to automatic review settings May 30, 2026 11:57
@vercel

vercel Bot commented May 30, 2026 •

Copy link
Copy Markdown

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

3 Skipped Deployments
Project Deployment Actions Updated (UTC)
prd-docs Ignored Ignored May 30, 2026 2:13pm
prd-openpage-api Ignored Ignored May 30, 2026 2:13pm
stg-docs Skipped Skipped May 30, 2026 2:13pm

Request Review

@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b63b0b0e-3a65-438e-b5cb-50e2103259a7

📥 Commits

Reviewing files that changed from the base of the PR and between d7c2d66 and 3306f9f.

📒 Files selected for processing (1)
  • packages/lib/types/subscription.ts

📝 Walkthrough

Walkthrough

Adds organisation-scoped windowed rate limits, monthly quotas, and recipient-count limits with DB schema, enforcement helpers, service integration, admin APIs/UI, notification job, and E2E tests.

Changes

Organisation Rate Limits and Quotas

Layer / File(s) Summary
Database schema, migration, and type definitions
packages/prisma/migrations/20260529132406_add_org_rate_limits/migration.sql, packages/prisma/schema.prisma, packages/lib/server-only/rate-limit/types.ts
OrganisationMonthlyStat created; SubscriptionClaim and OrganisationClaim extended with recipientCount, *RateLimits JSON arrays, and *Quota fields; Zod rate-limit schemas and related type exports added.
Rate limiting infrastructure and enforcement
packages/lib/server-only/rate-limit/assert-organisation-rates-and-limits.ts, packages/lib/server-only/rate-limit/check-organisation-rate-limits.ts, packages/lib/server-only/rate-limit/check-monthly-quota.ts, packages/lib/server-only/rate-limit/current-monthly-period.ts, packages/lib/server-only/rate-limit/rate-limit.ts
Core helpers enforce windowed organisation rate limits and monthly quotas (atomic increments, threshold detection, notification job); generic limiter supports configurable count consumption.
Subscription claim retrieval and persistence
packages/lib/server-only/subscription/get-subscription-claim.ts, packages/lib/server-only/organisation/create-organisation.ts, packages/lib/types/subscription.ts, packages/lib/utils/organisations-claims.ts
Adds getSubscriptionClaim(); refactors claim upsert mapping to accept Prisma SubscriptionClaim shape including rate-limit arrays and quotas; internalClaims expanded to include recipientCount and quota/rate-limit metadata; defaults updated.
Document and email operation enforcement
packages/lib/server-only/envelope/create-envelope.ts, packages/lib/server-only/envelope/duplicate-envelope.ts, packages/lib/server-only/template/create-document-from-template.ts, packages/lib/server-only/template/create-document-from-direct-template.ts, packages/lib/server-only/document/send-document.ts, packages/lib/server-only/document/resend-document.ts, packages/lib/jobs/definitions/emails/send-signing-email.handler.ts
Integrates assertions: document creation/duplication and template flows call assertOrganisationRatesAndLimits; sendDocument and resend flows enforce recipientCount (0 = unlimited) and quota/rate checks; old email-only helper removed and replaced by unified assertions.
API token validation and public-API rate limiting
packages/lib/server-only/public-api/get-api-token-by-token.ts, packages/lib/server-only/embedding-presign/create-embedding-presign-token.ts, packages/lib/server-only/webhooks/zapier/validateApiToken.ts
getApiTokenByToken gains bypassRateLimit option and owner/user disabled checks; presign and Zapier flows bypass org rate limits as trusted operations.
Limit-exceeded email notifications
packages/email/templates/organisation-limit-exceeded.tsx, packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.ts, packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.handler.ts, packages/lib/jobs/client.ts
New email template and job (definition + handler) that renders localized notifications to organisation managers when monthly quotas cross threshold; job registered in jobs client.
Admin endpoints for claim and organisation management
packages/trpc/server/admin-router/get-admin-organisation.ts, packages/trpc/server/admin-router/get-admin-organisation.types.ts, packages/trpc/server/admin-router/create-admin-organisation.ts, packages/trpc/server/admin-router/swap-organisation-subscription.ts, packages/trpc/server/admin-router/create-subscription-claim.ts, packages/trpc/server/admin-router/create-subscription-claim.types.ts, packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts, packages/trpc/server/admin-router/reset-organisation-monthly-stat.types.ts, packages/trpc/server/admin-router/router.ts, packages/trpc/server/organisation-router/create-organisation.ts
getAdminOrganisation returns monthlyStats; free claim loaded via getSubscriptionClaim() where needed; new resetOrganisationMonthlyStat mutation resets monthly counters; admin request/response schemas extended for rate-limit/quota fields.
Admin UI for limit configuration and usage monitoring
apps/remix/app/components/general/claim-limit-fields.tsx, apps/remix/app/components/general/rate-limit-array-input.tsx, apps/remix/app/components/general/organisation-usage-panel.tsx, apps/remix/app/components/general/organisation-usage-reset-button.tsx, apps/remix/app/components/forms/subscription-claim-form.tsx, apps/remix/app/routes/_authenticated+/admin+/organisations.$id.tsx
New React components: ClaimLimitFields, RateLimitArrayInput, OrganisationUsagePanel, and OrganisationUsageResetButton. Subscription form adds recipientCount and renders ClaimLimitFields; organisation admin page shows usage panel and reset actions.
API v1 middleware 429 response handling
packages/api/v1/middleware/authenticated.ts
Middleware now logs via apiLogger.info and returns HTTP 429 with headers for AppErrorCode.TOO_MANY_REQUESTS instead of default 401 handling.
E2E tests for API v1 and v2
packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts, packages/app-tests/e2e/api/v2/organisation-rate-limits.spec.ts, packages/app-tests/e2e/api/v2/recipient-count-limit.spec.ts
Comprehensive Playwright suites validating windowed and monthly enforcement for api/document/email counters, header/body semantics, monthly counter behaviors, and recipient-count distribution boundaries with deterministic helpers and DB assertions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • Mythie
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/add-dynamic-rate-limits

@github-actions github-actions Bot added apps: web Issues related to the webapp 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR 🚨 e2e changes 🚨 Be advised: PR changes E2E tests - Auto-Generated by GitHub Actions on raising a PR pkg: ee changes labels May 30, 2026
@dguyen dguyen changed the title Fix/add dynamic rate limits fix: add dynamic rate limits May 30, 2026

@roshboi roshboi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds organisation-level, dynamically configurable rate limiting and monthly quotas (API/document/email) backed by new claim fields and a monthly usage table, with admin UI + API support to view/manage limits and reset counters.

Changes:

  • Extend SubscriptionClaim/OrganisationClaim with per-counter *RateLimits and *Quota, plus a recipientCount cap.
  • Enforce document/email/api limits in key server flows (API token validation, envelope/document creation, resend, etc.) and track monthly quota usage in OrganisationMonthlyStat.
  • Add admin tooling/UI to view usage, edit limits, and reset monthly counters; add E2E coverage for recipient limits and org rate limits/quotas.

Reviewed changes

Copilot reviewed 54 out of 54 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
packages/trpc/server/organisation-router/create-organisation.ts Fetches FREE claim from DB via getSubscriptionClaim when creating orgs.
packages/trpc/server/admin-router/update-admin-organisation.types.ts Expands admin update schema to include new claim limit/quota fields.
packages/trpc/server/admin-router/swap-organisation-subscription.ts Swaps org subscription while carrying new claim fields; uses DB-backed FREE claim.
packages/trpc/server/admin-router/router.ts Registers new resetMonthlyStat admin endpoint.
packages/trpc/server/admin-router/reset-organisation-monthly-stat.types.ts Defines request/response schemas for resetting a monthly stat counter.
packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts Implements admin mutation to reset current month counters.
packages/trpc/server/admin-router/get-admin-organisation.types.ts Adds monthlyStats to admin organisation response schema.
packages/trpc/server/admin-router/get-admin-organisation.ts Loads organisation monthly stats for admin view.
packages/trpc/server/admin-router/find-subscription-claims.types.ts Returns new claim fields in admin claim search results.
packages/trpc/server/admin-router/create-subscription-claim.types.ts Allows creating claims with recipient limit + rate limits + quotas.
packages/trpc/server/admin-router/create-subscription-claim.ts Persists new claim fields on claim creation.
packages/trpc/server/admin-router/create-admin-organisation.ts Uses DB-backed FREE claim when creating orgs via admin.
packages/prisma/schema.prisma Adds claim fields, introduces OrganisationMonthlyStat, and links it to Organisation.
packages/prisma/migrations/20260529132406_add_org_rate_limits/migration.sql Backfills and adds new columns + creates OrganisationMonthlyStat table.
packages/lib/utils/organisations-claims.ts Updates default subscription claim generator with new fields.
packages/lib/universal/id.ts Adds org_monthly_stat ID prefix.
packages/lib/types/subscription.ts Introduces Zod schemas/types for rate-limit arrays; extends internal claims with new fields.
packages/lib/server-only/webhooks/zapier/validateApiToken.ts Bypasses org API rate-limit checks during Zapier token validation.
packages/lib/server-only/template/create-document-from-template.ts Asserts org document counter limits before creating a doc from template.
packages/lib/server-only/template/create-document-from-direct-template.ts Enforces recipient cap + asserts document limits for direct-template flow.
packages/lib/server-only/subscription/get-subscription-claim.ts Adds helper to fetch subscription claim from DB with FREE fallback.
packages/lib/server-only/rate-limit/types.ts Adds shared types for org counters and rate-limit entry window typing.
packages/lib/server-only/rate-limit/rate-limits.ts Removes temporary recipient-email rate limit entries.
packages/lib/server-only/rate-limit/rate-limit.ts Adds count consumption to rate-limit checks and DB increments.
packages/lib/server-only/rate-limit/current-monthly-period.ts Adds helper to compute current UTC YYYY-MM period.
packages/lib/server-only/rate-limit/check-organisation-rate-limits.ts Implements per-org windowed rate-limit enforcement with 429 headers.
packages/lib/server-only/rate-limit/check-monthly-quota.ts Implements monthly quota tracking/enforcement + notification job trigger.
packages/lib/server-only/rate-limit/assert-organisation-rates-and-limits.ts Central assertion combining windowed limits + monthly quotas.
packages/lib/server-only/public-api/get-api-token-by-token.ts Enforces org API limits during token validation (optional bypass).
packages/lib/server-only/organisation/create-organisation.ts Uses DB-backed FREE claim; upserts org claim with new limit/quota fields.
packages/lib/server-only/envelope/duplicate-envelope.ts Enforces org document limits when duplicating as a document.
packages/lib/server-only/envelope/create-envelope.ts Enforces org document limits before creating document envelopes.
packages/lib/server-only/embedding-presign/create-embedding-presign-token.ts Bypasses org API limits when creating embedding presign token.
packages/lib/server-only/email/assert-org-email-send-allowed.ts Removes old temporary per-org recipient email limiter helper.
packages/lib/server-only/document/send-document.ts Enforces per-document recipient count cap at distribution/send time.
packages/lib/server-only/document/resend-document.ts Replaces old email limiter with org email rate/quota assertions.
packages/lib/jobs/definitions/emails/send-signing-email.handler.ts Applies org email rate/quota limits (drop job when exceeded).
packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.ts Adds job definition for notifying org admins when limits are exceeded.
packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.handler.ts Sends “limit exceeded” emails to authorised org members.
packages/lib/jobs/client.ts Registers the new “organisation limit exceeded” email job.
packages/email/templates/organisation-limit-exceeded.tsx Adds email template content for org limit/quota exceeded notifications.
packages/ee/server-only/stripe/webhook/on-subscription-deleted.ts Uses DB-backed FREE claim when reverting org claim on subscription deletion.
packages/ee/server-only/limits/constants.ts Adds DEFAULT_RECIPIENT_COUNT for initial frontend state.
packages/app-tests/e2e/api/v2/recipient-count-limit.spec.ts Adds E2E coverage for recipient count cap on distribute.
packages/app-tests/e2e/api/v2/organisation-rate-limits.spec.ts Adds extensive v2 E2E coverage for org rate limits/quotas (skips when bypass enabled).
packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts Adds v1 E2E coverage for org rate limits/quotas (accounts for v1 handler behavior).
packages/api/v1/middleware/authenticated.ts Returns 429 on org rate/quota rejection and logs errors via structured logger.
apps/remix/app/routes/_authenticated+/admin+/organisations.$id.tsx Adds admin UI sections for usage + editing claim limits/quotas.
apps/remix/app/components/general/rate-limit-array-input.tsx Adds UI input for editing rate-limit windows/max entries.
apps/remix/app/components/general/organisation-usage-reset-button.tsx Adds button to call admin reset-monthly-stat mutation.
apps/remix/app/components/general/organisation-usage-panel.tsx Displays monthly usage against quotas + reset controls.
apps/remix/app/components/general/claim-limit-fields.tsx Reusable form fields for quotas and rate-limit arrays.
apps/remix/app/components/forms/subscription-claim-form.tsx Extends claim form UI with recipientCount + quota/rate limit editors.
.vscode/settings.json Changes JSON formatter setting for VS Code workspace.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 13

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/remix/app/components/general/claim-limit-fields.tsx`:
- Line 44: The placeholder string "Unlimited" is hardcoded; import the t macro
(e.g., import { t } from '`@lingui/react/macro`') if not already present and
replace the literal placeholder="Unlimited" with a localized expression using
the t macro (placeholder={t`Unlimited`}) in the ClaimLimitFields JSX so the
user-facing string is localized.

In `@apps/remix/app/components/general/organisation-usage-panel.tsx`:
- Line 44: The visible label in OrganisationUsagePanel currently contains a
developer note and promises conditional behavior that the component doesn't
implement; update the <Trans> string (the line with "Usage this month (Will only
show if there are quota/rates set)") to a real user-facing label (e.g., "Usage
this month") and either remove the parenthetical or implement gating: check the
component's props/state (e.g., quota/rate fields on the organisation or props
used by OrganisationUsagePanel) and only render the usage rows (the three
unconditional rows rendered in the component) when a quota or rate is actually
set; adjust the JSX accordingly so the label matches the real rendering behavior
or make the rows conditional to match the parenthetical.

In `@apps/remix/app/components/general/organisation-usage-reset-button.tsx`:
- Line 17: The mutation hook
trpc.admin.organisation.resetMonthlyStat.useMutation currently destructures
mutateAsync as reset and is invoked in the onClick handler without awaiting,
causing unhandled promise rejections; change the destructuring to use mutate
(e.g., const { mutate: reset, isPending } =
trpc.admin.organisation.resetMonthlyStat.useMutation({...})) so the click can
fire-and-forget safely, leaving the onClick={() => reset({ organisationId,
counter })} calls unchanged (apply the same change for the other occurrence
referenced at the second use).

In `@packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts`:
- Around line 87-223: Extract duplicated types and helpers into a shared test
utility module and import them from both v1 and v2 specs: move RateLimitEntry,
ClaimLimits, MonthlyCounter, currentMonthlyPeriod, getOrganisationClaim,
setClaimLimits, getMonthlyStat, expectMonthlyCounter, alignToFreshWindowBucket,
and ensureWindowHeadroom into e2e/helpers/rate-limit-test-utils.ts and update
both specs to import those symbols; keep resetUsage in each spec but refactor it
to call a shared resetUsageBase(organisation, action) helper (or accept the
action as a parameter) so v1 passes 'api.v1' and v2 passes 'api.v2' and only the
action string differs.
- Around line 236-309: Duplicate HTTP helper functions (isOrgLimited,
expectOrgLimited, expectNoOrgRateLimitHeader, expectNotGlobalLimited) need to be
extracted into a shared test utility module; move the implementations into a new
exported helpers file (e.g., create a test utils module), export the four
functions, replace the duplicated definitions in both spec files with imports
from that module, and update any references to call the imported helpers (keep
function names identical to avoid changing call sites); ensure the new module
has appropriate types (ApiErrorBody, APIResponse) imported/ re-exported or
re-used so tests compile.

In
`@packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.handler.ts`:
- Around line 60-85: Hoist the email rendering and i18n initialization out of
the organisation.members loop: create the emailContent using
OrganisationLimitExceededEmailTemplate and compute html and text once via
renderEmailWithI18N, and get the i18n instance once with getI18nInstance before
iterating; then loop over organisation.members only to call io.runTask and
mailer.sendMail (using the precomputed html, text, i18n, senderEmail and
subject) so renderEmailWithI18N,
createElement(OrganisationLimitExceededEmailTemplate) and getI18nInstance are
not executed per member.

In `@packages/lib/jobs/definitions/emails/send-signing-email.handler.ts`:
- Around line 167-184: The warning swallows the caught error from
assertOrganisationRatesAndLimits; capture the error (replace _err with err) and
include its details in the io.logger.warn payload so observability improves —
e.g., pass err.message and err.stack (or the whole err) alongside
organisationId, recipientId (recipient.id) and envelopeId (envelope.id); keep
the same control flow (log then return) in the catch block of
send-signing-email.handler.ts.

In `@packages/lib/server-only/rate-limit/assert-organisation-rates-and-limits.ts`:
- Around line 71-83: The current call order (checkOrganisationRateLimits before
checkMonthlyQuota) must be preserved because the v2 E2E suite depends on
windowed enforcement happening first; therefore do not reorder the calls in
assertOrganisationRatesAndLimits (keep checkOrganisationRateLimits({ ... })
followed by checkMonthlyQuota({ ... })), and add a short clarifying comment
above these calls referencing the E2E expectation; if you intend to change
semantics so quota wins over windowed limits, add/adjust E2E tests to cover that
behavior before making any reorder in the checkOrganisationRateLimits /
checkMonthlyQuota invocation order.

In `@packages/lib/server-only/subscription/get-subscription-claim.ts`:
- Around line 8-10: The query in get-subscription-claim.ts uses
prisma.subscriptionClaim.findFirst to look up by primary key id; replace it with
prisma.subscriptionClaim.findUnique and pass the id in the where clause (i.e.,
use findUnique({ where: { id: claimId } })) so Prisma can optimize the PK lookup
and preserve the same null-handling behavior in the surrounding function.
- Line 19: Replace the generic Error thrown in getSubscriptionClaim (the line
throwing `Subscription claim ${claimId} not found`) with the project’s AppError:
import AppError if not already imported, and throw an AppError instance that
includes the same message and appropriate metadata/status (e.g., 404 or a
not-found code) and the claimId for debugging; update the throw site in
get-subscription-claim.ts to use AppError instead of Error.

In `@packages/lib/server-only/template/create-document-from-template.ts`:
- Around line 507-512: The organisation rate/limit assertion
(assertOrganisationRatesAndLimits) is run too late and wastes work—move the call
to immediately after getTeamSettings returns (i.e., right after the
getTeamSettings invocation/variable) so the function fails fast before any file
I/O or PDF processing, and then remove the duplicate
assertOrganisationRatesAndLimits call currently present near the document
creation block (the block that creates documentData). Ensure you pass the same
payload ({ organisationId: callerTeam.organisationId, type: 'document', count: 1
}) when relocating the check.

In `@packages/lib/types/subscription.ts`:
- Around line 142-169: The FREE plan in internalClaims sets recipientCount: 0
but there's no explanation whether 0 means "unlimited" or "none"; add a short
inline comment next to recipientCount in the INTERNAL_CLAIM_ID.FREE object
(inside internalClaims) clarifying the convention (e.g., "0 means unlimited" or
"0 means no recipients") so future maintainers understand the semantics relative
to other plans.

In `@packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts`:
- Around line 28-31: The reset route currently calls
prisma.organisationMonthlyStat.update with the composite key
organisationId_period which throws Prisma P2025 if the (organisationId, period)
row doesn't exist; change this to either prisma.organisationMonthlyStat.upsert
(preferred) or prisma.organisationMonthlyStat.updateMany so the operation is
idempotent and won't 500—use the same where data ({ organisationId, period })
and provide create and update payloads for upsert (or the equivalent data for
updateMany) in reset-organisation-monthly-stat.ts to match other paths like
check-monthly-quota.ts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c9388d9c-3922-44d4-a5d0-d6b1bee20111

📥 Commits

Reviewing files that changed from the base of the PR and between 22ceff4 and 55554aa.

⛔ Files ignored due to path filters (1)
  • .vscode/settings.json is excluded by !**/*.json
📒 Files selected for processing (53)
  • apps/remix/app/components/forms/subscription-claim-form.tsx
  • apps/remix/app/components/general/claim-limit-fields.tsx
  • apps/remix/app/components/general/organisation-usage-panel.tsx
  • apps/remix/app/components/general/organisation-usage-reset-button.tsx
  • apps/remix/app/components/general/rate-limit-array-input.tsx
  • apps/remix/app/routes/_authenticated+/admin+/organisations.$id.tsx
  • packages/api/v1/middleware/authenticated.ts
  • packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts
  • packages/app-tests/e2e/api/v2/organisation-rate-limits.spec.ts
  • packages/app-tests/e2e/api/v2/recipient-count-limit.spec.ts
  • packages/ee/server-only/limits/constants.ts
  • packages/ee/server-only/stripe/webhook/on-subscription-deleted.ts
  • packages/email/templates/organisation-limit-exceeded.tsx
  • packages/lib/jobs/client.ts
  • packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.handler.ts
  • packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.ts
  • packages/lib/jobs/definitions/emails/send-signing-email.handler.ts
  • packages/lib/server-only/document/resend-document.ts
  • packages/lib/server-only/document/send-document.ts
  • packages/lib/server-only/email/assert-org-email-send-allowed.ts
  • packages/lib/server-only/embedding-presign/create-embedding-presign-token.ts
  • packages/lib/server-only/envelope/create-envelope.ts
  • packages/lib/server-only/envelope/duplicate-envelope.ts
  • packages/lib/server-only/organisation/create-organisation.ts
  • packages/lib/server-only/public-api/get-api-token-by-token.ts
  • packages/lib/server-only/rate-limit/assert-organisation-rates-and-limits.ts
  • packages/lib/server-only/rate-limit/check-monthly-quota.ts
  • packages/lib/server-only/rate-limit/check-organisation-rate-limits.ts
  • packages/lib/server-only/rate-limit/current-monthly-period.ts
  • packages/lib/server-only/rate-limit/rate-limit.ts
  • packages/lib/server-only/rate-limit/rate-limits.ts
  • packages/lib/server-only/rate-limit/types.ts
  • packages/lib/server-only/subscription/get-subscription-claim.ts
  • packages/lib/server-only/template/create-document-from-direct-template.ts
  • packages/lib/server-only/template/create-document-from-template.ts
  • packages/lib/server-only/webhooks/zapier/validateApiToken.ts
  • packages/lib/types/subscription.ts
  • packages/lib/universal/id.ts
  • packages/lib/utils/organisations-claims.ts
  • packages/prisma/migrations/20260529132406_add_org_rate_limits/migration.sql
  • packages/prisma/schema.prisma
  • packages/trpc/server/admin-router/create-admin-organisation.ts
  • packages/trpc/server/admin-router/create-subscription-claim.ts
  • packages/trpc/server/admin-router/create-subscription-claim.types.ts
  • packages/trpc/server/admin-router/find-subscription-claims.types.ts
  • packages/trpc/server/admin-router/get-admin-organisation.ts
  • packages/trpc/server/admin-router/get-admin-organisation.types.ts
  • packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts
  • packages/trpc/server/admin-router/reset-organisation-monthly-stat.types.ts
  • packages/trpc/server/admin-router/router.ts
  • packages/trpc/server/admin-router/swap-organisation-subscription.ts
  • packages/trpc/server/admin-router/update-admin-organisation.types.ts
  • packages/trpc/server/organisation-router/create-organisation.ts
💤 Files with no reviewable changes (2)
  • packages/lib/server-only/email/assert-org-email-send-allowed.ts
  • packages/lib/server-only/rate-limit/rate-limits.ts

Comment thread packages/lib/types/subscription.ts Resolved
@vercel
vercel Bot temporarily deployed to Preview – stg-docs May 30, 2026 12:43 Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/remix/app/components/general/organisation-usage-panel.tsx`:
- Line 40: The component currently assumes monthlyStats[0] exists, causing reset
buttons to disappear and counts to show 0 when there's no data; update the
OrganisationUsagePanel to check monthlyStats?.[0] (or a helper like
hasMonthlyStats) and render a clear empty-state hint (e.g. "No usage data for
this month") instead of defaulting counts to 0, and explicitly hide or disable
the reset buttons and related actions when monthlyStats[0] is absent so the UI
isn't misleading; update all usages of monthlyStats[0] and any code paths that
compute counts or render reset buttons to branch on the presence of monthlyStats
first.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 16c9da6b-cb8e-44f8-af10-697744561cda

📥 Commits

Reviewing files that changed from the base of the PR and between 55554aa and c975147.

📒 Files selected for processing (7)
  • apps/remix/app/components/general/claim-limit-fields.tsx
  • apps/remix/app/components/general/organisation-usage-panel.tsx
  • packages/email/templates/organisation-limit-exceeded.tsx
  • packages/lib/jobs/definitions/emails/send-organisation-limit-exceeded-email.handler.ts
  • packages/lib/server-only/document/resend-document.ts
  • packages/lib/server-only/rate-limit/assert-organisation-rates-and-limits.ts
  • packages/lib/server-only/subscription/get-subscription-claim.ts

},
];

// Todo: This may not show if the organisation has no usage data for the current month.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Dangling TODO — usage rows hidden when no monthly stats exist.

This Todo flags a real gap: with no monthlyStats[0], the panel still renders limits but the reset buttons vanish and counts fall back to 0, which can mislead admins into thinking usage is genuinely zero.

Want me to open a tracking issue or sketch a fix (e.g. an empty-state hint when monthlyStats[0] is absent)?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/remix/app/components/general/organisation-usage-panel.tsx` at line 40,
The component currently assumes monthlyStats[0] exists, causing reset buttons to
disappear and counts to show 0 when there's no data; update the
OrganisationUsagePanel to check monthlyStats?.[0] (or a helper like
hasMonthlyStats) and render a clear empty-state hint (e.g. "No usage data for
this month") instead of defaulting counts to 0, and explicitly hide or disable
the reset buttons and related actions when monthlyStats[0] is absent so the UI
isn't misleading; update all usages of monthlyStats[0] and any code paths that
compute counts or render reset buttons to branch on the presence of monthlyStats
first.

@vercel
vercel Bot temporarily deployed to Preview – stg-docs May 30, 2026 13:38 Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts (1)

79-215: 🧹 Nitpick | 🔵 Trivial | ⚖️ Poor tradeoff

Duplicate test helpers across v1 and v2 specs.

The types (RateLimitEntry, ClaimLimits, MonthlyCounter), claim/usage helpers (currentMonthlyPeriod, getOrganisationClaim, setClaimLimits, getMonthlyStat, expectMonthlyCounter, alignToFreshWindowBucket, ensureWindowHeadroom), and HTTP helpers (isOrgLimited, expectOrgLimited, expectNoOrgRateLimitHeader, expectNotGlobalLimited) are duplicated verbatim in v2/organisation-rate-limits.spec.ts. Extract these to a shared e2e/helpers/rate-limit-test-utils.ts module, parameterizing only the divergent parts (resetUsage action string).

Also applies to: 228-301

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts` around lines
79 - 215, The tests duplicate many helpers and types across v1 and v2; extract
RateLimitEntry, ClaimLimits, MonthlyCounter and the helper functions
currentMonthlyPeriod, getOrganisationClaim, setClaimLimits, getMonthlyStat,
expectMonthlyCounter, alignToFreshWindowBucket, ensureWindowHeadroom and the
HTTP helpers (isOrgLimited, expectOrgLimited, expectNoOrgRateLimitHeader,
expectNotGlobalLimited) into a new shared module
e2e/helpers/rate-limit-test-utils.ts and import it from both spec files;
refactor resetUsage to accept the divergent piece (the global limiter action
string, e.g. 'api.v1' or 'api.v2') or accept a small strategy callback so each
spec calls resetUsage(organisation, { globalAction: 'api.v1' }) (or
resetUsage(organisation, strategy)) and update calls in v1/v2 specs to use the
shared helpers instead of the duplicated local implementations.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/lib/server-only/rate-limit/check-monthly-quota.ts`:
- Around line 28-29: The user-facing literal error strings in checkMonthlyQuota
(the object with the message property and the other strings around lines 88-94)
must be wrapped with the t`...` macro from `@lingui/react/macro`; import { t }
from '`@lingui/react/macro`' at the top of the module, replace the plain message:
'Your request could not be completed...' with t`Your request could not be
completed at this time due to your account exceeding the fair use limits of your
current plan. Please contact support.`, and similarly wrap the other string
literals referenced around lines 88-94 using t`...` so all user-facing messages
are translatable (ensure you update all occurrences in the file such as the
message property in the checkMonthlyQuota response and any other error/notice
strings).

---

Duplicate comments:
In `@packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts`:
- Around line 79-215: The tests duplicate many helpers and types across v1 and
v2; extract RateLimitEntry, ClaimLimits, MonthlyCounter and the helper functions
currentMonthlyPeriod, getOrganisationClaim, setClaimLimits, getMonthlyStat,
expectMonthlyCounter, alignToFreshWindowBucket, ensureWindowHeadroom and the
HTTP helpers (isOrgLimited, expectOrgLimited, expectNoOrgRateLimitHeader,
expectNotGlobalLimited) into a new shared module
e2e/helpers/rate-limit-test-utils.ts and import it from both spec files;
refactor resetUsage to accept the divergent piece (the global limiter action
string, e.g. 'api.v1' or 'api.v2') or accept a small strategy callback so each
spec calls resetUsage(organisation, { globalAction: 'api.v1' }) (or
resetUsage(organisation, strategy)) and update calls in v1/v2 specs to use the
shared helpers instead of the duplicated local implementations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a238fdd4-85be-42b1-b0ba-c11130b6aa01

📥 Commits

Reviewing files that changed from the base of the PR and between c975147 and d7c2d66.

📒 Files selected for processing (3)
  • packages/app-tests/e2e/api/v1/organisation-rate-limits.spec.ts
  • packages/app-tests/e2e/api/v2/organisation-rate-limits.spec.ts
  • packages/lib/server-only/rate-limit/check-monthly-quota.ts

Comment on lines +28 to +29
message:
'Your request could not be completed at this time due to your account exceeding the fair use limits of your current plan. Please contact support.',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Error messages should use the t macro for translations.

Per coding guidelines, string constants and user-friendly messages should use the tstring`` macro from @lingui/react/macro. These error messages are user-facing and should be translatable.

♻️ Proposed fix
+import { t } from '`@lingui/core/macro`';
+
 // In the quota === 0 case (lines 28-29):
-      message:
-        'Your request could not be completed at this time due to your account exceeding the fair use limits of your current plan. Please contact support.',
+      message: t`Your request could not be completed at this time due to your account exceeding the fair use limits of your current plan. Please contact support.`,

 // In the over-quota case (line 91):
-      message:
-        'Your request could not be completed at this time due to your account exceeding the fair use limits of your current plan. Please contact support.',
+      message: t`Your request could not be completed at this time due to your account exceeding the fair use limits of your current plan. Please contact support.`,

As per coding guidelines: "String constants should use the tstring macro from @lingui/react/macro".

Also applies to: 88-94

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/lib/server-only/rate-limit/check-monthly-quota.ts` around lines 28 -
29, The user-facing literal error strings in checkMonthlyQuota (the object with
the message property and the other strings around lines 88-94) must be wrapped
with the t`...` macro from `@lingui/react/macro`; import { t } from
'`@lingui/react/macro`' at the top of the module, replace the plain message: 'Your
request could not be completed...' with t`Your request could not be completed at
this time due to your account exceeding the fair use limits of your current
plan. Please contact support.`, and similarly wrap the other string literals
referenced around lines 88-94 using t`...` so all user-facing messages are
translatable (ensure you update all occurrences in the file such as the message
property in the checkMonthlyQuota response and any other error/notice strings).

@vercel
vercel Bot temporarily deployed to Preview – stg-docs May 30, 2026 14:13 Inactive
@dguyen
dguyen merged commit 61138cd into main May 30, 2026
9 checks passed
@dguyen
dguyen deleted the fix/add-dynamic-rate-limits branch May 30, 2026 14:34
scoobs-mystery-bytes pushed a commit to scoobs-mystery-bytes/documenso that referenced this pull request May 30, 2026

This branch was previously deployed

1 inactive deployment
Preview – stg-docs — 3306f9fa Deployed May 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apps: web Issues related to the webapp coderabbit 🚨 e2e changes 🚨 Be advised: PR changes E2E tests - Auto-Generated by GitHub Actions on raising a PR 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR pkg: ee changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants