Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(billing): anchor monthly quotas to the subscription period, not the calendar month (#500)
Gökhan Geyikfec807e66b1b
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.jsindex 96c0ad6c6..07e4a1a16 100644--- a/server/src/lib/plan-guard.js+++ b/server/src/lib/plan-guard.js@@ -6,6 +6,7 @@ import {isCloud,isSubscriptionActive,} from '../config/plans.js';+import { anchoredPeriodStart } from './quota-period.js';export class PlanLimitError extends Error {constructor(message, statusCode = 403) {@@ -135,20 +136,18 @@ export async function enforceVolumeQuota(userId) {throw new PlanLimitError('No organization found for user.', 400);}- const startOfMonth = new Date();- startOfMonth.setUTCDate(1);- startOfMonth.setUTCHours(0, 0, 0, 0);+ const periodStart = await quotaPeriodStart(profile.organization_id);const { count } = await supabaseAdmin.from('volume_usage').select('*', { count: 'exact', head: true }).eq('organization_id', profile.organization_id)- .gte('used_at', startOfMonth.toISOString());+ .gte('used_at', periodStart.toISOString());const used = count || 0;if (used >= maxAnalyses) {throw new PlanLimitError(- `Monthly volume analysis limit reached (${used}/${maxAnalyses}). Resets on the 1st of next month.`,+ `Monthly volume analysis limit reached (${used}/${maxAnalyses}). Resets when your subscription renews.`,);}@@ -172,15 +171,13 @@ export async function getVolumeQuotaStatus(userId) {if (!profile?.organization_id) return { used: 0, limit: maxAnalyses, remaining: maxAnalyses };- const startOfMonth = new Date();- startOfMonth.setUTCDate(1);- startOfMonth.setUTCHours(0, 0, 0, 0);+ const periodStart = await quotaPeriodStart(profile.organization_id);const { count } = await supabaseAdmin.from('volume_usage').select('*', { count: 'exact', head: true }).eq('organization_id', profile.organization_id)- .gte('used_at', startOfMonth.toISOString());+ .gte('used_at', periodStart.toISOString());const used = count || 0;return { used, limit: maxAnalyses, remaining: maxAnalyses - used };@@ -193,12 +190,41 @@ function startOfCurrentMonth() {return start;}+/**+ * Start of the monthly quota window containing `now`, anchored to the+ * subscription's billing day (`subscription_ends_at` = Stripe's+ * current_period_end, kept fresh by the webhook). Quotas renew when the+ * customer's payment renews — not on the 1st of the calendar month, which+ * made a renewal day feel like a limit that never reset (#500).+ *+ * Orgs without an active subscription (free, incomplete, self-host paths+ * that still reach here) fall back to the calendar month. Window math lives+ * in quota-period.js.+ */+export async function quotaPeriodStart(orgId, now = new Date()) {+ if (!isCloud() || !orgId) return startOfCurrentMonth();++ const { data: org } = await supabaseAdmin+ .from('organizations')+ .select('subscription_ends_at, subscription_status')+ .eq('id', orgId)+ .maybeSingle();++ const endsAt = org?.subscription_ends_at ? new Date(org.subscription_ends_at) : null;+ if (!endsAt || Number.isNaN(endsAt.getTime()) || !isSubscriptionActive(org.subscription_status)) {+ return startOfCurrentMonth();+ }++ return anchoredPeriodStart(endsAt, now);+}+async function countBriefUsageThisMonth(orgId) {+ const periodStart = await quotaPeriodStart(orgId);const { count } = await supabaseAdmin.from('brief_usage').select('*', { count: 'exact', head: true }).eq('organization_id', orgId)- .gte('used_at', startOfCurrentMonth().toISOString());+ .gte('used_at', periodStart.toISOString());return count || 0;}@@ -216,7 +242,7 @@ export async function enforceBriefQuota(orgId) {const used = await countBriefUsageThisMonth(orgId);if (used >= max) {throw new PlanLimitError(- `Monthly content brief limit reached (${used}/${max}) on the ${plan.name} plan. Resets on the 1st of next month — upgrade for more.`,+ `Monthly content brief limit reached (${used}/${max}) on the ${plan.name} plan. Resets when your subscription renews — upgrade for more.`,);}@@ -237,11 +263,12 @@ export async function getBriefQuotaStatus(orgId) {}async function countSiteAuditUsageThisMonth(orgId) {+ const periodStart = await quotaPeriodStart(orgId);const { count } = await supabaseAdmin.from('site_audit_usage').select('*', { count: 'exact', head: true }).eq('organization_id', orgId)- .gte('used_at', startOfCurrentMonth().toISOString());+ .gte('used_at', periodStart.toISOString());return count || 0;}@@ -259,7 +286,7 @@ export async function enforceSiteAuditQuota(orgId) {const used = await countSiteAuditUsageThisMonth(orgId);if (used >= max) {throw new PlanLimitError(- `Monthly Site Audit limit reached (${used}/${max}) on the ${plan.name} plan. Resets on the 1st of next month — upgrade for more.`,+ `Monthly Site Audit limit reached (${used}/${max}) on the ${plan.name} plan. Resets when your subscription renews — upgrade for more.`,429,);}diff --git a/server/src/lib/quota-period.js b/server/src/lib/quota-period.jsnew file mode 100644index 000000000..e4aed075b--- /dev/null+++ b/server/src/lib/quota-period.js@@ -0,0 +1,36 @@+/**+ * Billing-anchored quota window math (#500). Pure functions — no I/O — so+ * they can be unit-tested without the supabase config (which exits the+ * process when env vars are missing).+ */++/** Add `delta` months with Stripe-style day clamping (Mar 31 − 1mo → Feb 28/29). */+export function shiftMonthClamped(date, delta) {+ const d = new Date(date);+ const day = d.getUTCDate();+ d.setUTCDate(1);+ d.setUTCMonth(d.getUTCMonth() + delta);+ const daysInMonth = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate();+ d.setUTCDate(Math.min(day, daysInMonth));+ return d;+}++/**+ * Start of the monthly window containing `now`, anchored to the billing day+ * of `endsAt` (Stripe's current_period_end). Walks month-by-month so it also+ * lands on the right window under webhook lag (endsAt briefly in the past+ * right after renewal) or annual billing (endsAt far in the future).+ */+export function anchoredPeriodStart(endsAt, now = new Date()) {+ let end = endsAt;+ let start = shiftMonthClamped(end, -1);+ for (let i = 0; start > now && i < 24; i++) {+ end = start;+ start = shiftMonthClamped(end, -1);+ }+ for (let i = 0; end <= now && i < 24; i++) {+ start = end;+ end = shiftMonthClamped(start, 1);+ }+ return start;+}diff --git a/server/src/lib/quota-period.test.js b/server/src/lib/quota-period.test.jsnew file mode 100644index 000000000..a858eeb74--- /dev/null+++ b/server/src/lib/quota-period.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';+import { anchoredPeriodStart, shiftMonthClamped } from './quota-period.js';++const iso = (s) => new Date(s);++describe('shiftMonthClamped', () => {+ it('shifts by whole months on plain days', () => {+ expect(shiftMonthClamped(iso('2026-08-21T10:00:00Z'), -1).toISOString()).toBe(+ '2026-07-21T10:00:00.000Z',+ );+ expect(shiftMonthClamped(iso('2026-07-21T10:00:00Z'), 1).toISOString()).toBe(+ '2026-08-21T10:00:00.000Z',+ );+ });++ it('clamps to the shorter month instead of overflowing', () => {+ // Mar 31 − 1 month → Feb 28 (2026 is not a leap year), NOT Mar 3.+ expect(shiftMonthClamped(iso('2026-03-31T00:00:00Z'), -1).toISOString()).toBe(+ '2026-02-28T00:00:00.000Z',+ );+ expect(shiftMonthClamped(iso('2024-03-31T00:00:00Z'), -1).toISOString()).toBe(+ '2024-02-29T00:00:00.000Z',+ );+ expect(shiftMonthClamped(iso('2026-01-31T00:00:00Z'), 1).toISOString()).toBe(+ '2026-02-28T00:00:00.000Z',+ );+ });++ it('crosses year boundaries', () => {+ expect(shiftMonthClamped(iso('2026-01-15T00:00:00Z'), -1).toISOString()).toBe(+ '2025-12-15T00:00:00.000Z',+ );+ });+});++describe('anchoredPeriodStart', () => {+ it('returns the current billing period start for a monthly subscription', () => {+ // Renewed today: period ends Aug 21, so the window started Jul 21.+ const start = anchoredPeriodStart(iso('2026-08-21T09:00:00Z'), iso('2026-07-21T12:00:00Z'));+ expect(start.toISOString()).toBe('2026-07-21T09:00:00.000Z');+ });++ it('mid-period: now well inside the window', () => {+ const start = anchoredPeriodStart(iso('2026-08-21T09:00:00Z'), iso('2026-08-10T00:00:00Z'));+ expect(start.toISOString()).toBe('2026-07-21T09:00:00.000Z');+ });++ it('webhook lag: ends_at still in the past right after renewal', () => {+ // Renewal fired but the webhook has not updated ends_at yet — the+ // current window must start today, not last month.+ const start = anchoredPeriodStart(iso('2026-07-21T09:00:00Z'), iso('2026-07-21T12:00:00Z'));+ expect(start.toISOString()).toBe('2026-07-21T09:00:00.000Z');+ });++ it('annual billing: ends_at far in the future still yields a monthly window', () => {+ const start = anchoredPeriodStart(iso('2027-07-21T09:00:00Z'), iso('2026-11-05T00:00:00Z'));+ expect(start.toISOString()).toBe('2026-10-21T09:00:00.000Z');+ });++ it('anchor day clamping across short months', () => {+ // Billing day 31: the window containing mid-March starts on Feb 28.+ const start = anchoredPeriodStart(iso('2026-03-31T00:00:00Z'), iso('2026-03-15T00:00:00Z'));+ expect(start.toISOString()).toBe('2026-02-28T00:00:00.000Z');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex a84eb3e45..3ba9d69f1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -1359,7 +1359,7 @@ export default function PromptsPage() {</Button>{quotaExhausted && (<p className="text-xs text-red-500">- Monthly analysis limit reached. Resets on the 1st.+ Monthly analysis limit reached. Resets when your subscription renews.</p>)}{quota && quota.limit !== -1 && !quotaExhausted && (