Skip to content

feat(content): show and enforce the monthly content opportunity quota - #1019

Merged
gkhngyk merged 9 commits into
ansvisor:mainfrom
cihan-gyk:feature/content-monthly-quota
Oct 14, 2026
Merged

gkhngyk merged 9 commits into
ansvisor:mainfrom
cihan-gyk:feature/content-monthly-quota

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

CONTENT-001. The Content page only showed all-time totals, so users couldn't tell how much of their plan they had used this month. The plan also had no limit on how many opportunities the system created.

Product decisions for this task:

  • The quota renews with the billing period, not the calendar month.
  • New opportunities and briefs are two separate counters, each Starter 10 / Growth 50 per month.

What changed

  • Plans: new maxOpportunitiesPerMonth in server/src/config/plans.js and web/src/config/plans.ts.
    • Starter 10, Growth 50, Enterprise and self-hosted unlimited.
    • Enterprise can override it through plan_overrides.
    • The existing maxBriefGenerations (10 / 50) stays as the brief counter.
  • Usage table: new opportunity_usage (migration 00125), modelled on brief_usage.
    • One row per opportunity created, with opportunity_id ON DELETE SET NULL.
    • Dismissed and deleted opportunities still count.
  • Atomic claim: claim_opportunity_usage(org, since, limit, count) takes a per-organization advisory lock, counts the period's usage and inserts at most the remaining slots.
    • Several brands of one org generating at once can't push it past its limit. CONTENT-003's "+ New" will use the same function.
  • Generation (opportunity-generator.js):
    • It claims slots before the model call.
    • It links each slot to the opportunity it created.
    • It hands back slots for merged or skipped clusters, and all of them if the model call or the insert fails.
    • With no slots left it returns { limited: true } without calling the model.
  • API: GET /api/content/usage returns { plan, planName, periodStart, periodEnd, opportunities, briefs }, each counter as { used, limit, remaining } with -1 meaning unlimited. The MCP server and agents can read the same figures.
  • Content page: a "This billing period" card leads the stat row.
    • One bar per counter: green below 80%, amber from 80%, red with "Limit reached" at 100%.
    • Plan name and "Resets {date}".
    • "Upgrade plan" (Starter) when a counter is exhausted.
    • An ⓘ explains what counts.
    • The card is hidden when neither counter is limited (self-hosted, unlimited Enterprise).
  • Brief panel: "wait until the 1st when your quota resets" was wrong since fix(billing): anchor monthly quotas to the subscription period, not the calendar month #500; it now says the quota resets when the subscription renews.

Notes for reviewers

Related issue

CONTENT-001 (internal product task)

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply migration 00125.
  2. Set IS_CLOUD=true (server) and NEXT_PUBLIC_IS_CLOUD=true (web).
  3. Give your org plan='starter' with an active subscription and a subscription_ends_at in the future, then restart both servers.
  4. Insert some usage, e.g. 8 rows: insert into opportunity_usage (organization_id) select '<org>' from generate_series(1,8);
  5. Open /dashboard/content. The card shows New opportunities 8 / 10 (amber), Content briefs x / 10, "Starter plan · Resets {billing day}".
  6. Add 2 more rows. The card shows 10 / 10, red, "Limit reached" and "Upgrade plan".
  7. Switch to growth and refresh. The card shows x / 50.
  8. select count(*) from claim_opportunity_usage('<org>', now() - interval '30 days', 10, 3); returns 0 once the quota is full.
  9. Check light and dark mode, and 1024px.

I ran steps 1–9 locally and reverted the test data afterwards.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): 0 errors; the 7 warnings are in files this PR doesn't touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

Check Result
yarn test 470/470
yarn build passed
server: npm run format && npm run lint && npm test 1037/1037
npm run version:check passed
bash supabase/build-schema.sh run

🤖 Generated with Claude Code

Plans get a monthly limit on new content opportunities (Starter 10,
Growth 50, Enterprise/self-hosted unlimited), counted separately from the
existing brief quota and renewing with the subscription. Usage is recorded
in opportunity_usage, so dismissed and deleted opportunities still count.

The nightly generation claims slots atomically per organization
(claim_opportunity_usage) before calling the model and hands back the ones
it doesn't use. The Content page leads its stat row with a usage card for
both counters, and GET /api/content/usage exposes the same figures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk CONTENT-001 is ready for review: a monthly limit on new content opportunities (Starter 10 / Growth 50, separate from the existing brief quota, renewing with the billing period), enforced atomically in the nightly generation, plus a usage card on the Content page and GET /api/content/usage. Migration 00125 adds opportunity_usage and claim_opportunity_usage.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 13, 2026
cihan-gyk and others added 2 commits October 13, 2026 19:32
…isor#1009)

The Tracked Prompts page showed only "All Prompts (N)", with no sign of the
plan limit or how many slots were left, so users found out at save time.
The header now shows "used / limit prompt locations · <plan> plan" with a
progress bar and the slots left (amber from 80%, red when full or over).
When the limit is reached, Add prompt explains it with Upgrade plan
(Starter) or Contact us (Growth / Enterprise) instead of the form.

The numbers come from getLocationQuota, the same org-wide prompt-location
count the plan-limit guard enforces, so the counter can't promise a slot a
save would reject. getPromptsPageData returns it in the page's single
round trip.

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
…ansvisor#1010)

The Positions panel was fixed to the table's range, so checking a prompt
over another period meant changing the whole table. The panel now has its
own 24h / 7d / 30d / 90d / Custom control. It opens on the table's range,
and changing it reloads only the panel. The open prompt and the panel's
range are mirrored to the URL (?positions=<id>&positionsRange=7d) so the
view can be shared. A custom range no longer spells its dates twice in
the header.

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
cihan-gyk and others added 2 commits October 13, 2026 21:34
…gestions (ansvisor#1011)

* feat(prompts): pick the Positions panel's date range inside the panel

The Positions panel was fixed to the table's range, so checking a prompt
over another period meant changing the whole table. The panel now has its
own 24h / 7d / 30d / 90d / Custom control. It opens on the table's range,
and changing it reloads only the panel. The open prompt and the panel's
range are mirrored to the URL (?positions=<id>&positionsRange=7d) so the
view can be shared. A custom range no longer spells its dates twice in
the header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): add an Improve tab with platform-specific position suggestions

For one prompt and the panel's range, the Positions panel gets an Improve
tab: per AI platform where the brand is not mentioned, mentioned late, or
mentioned early but not cited, AI-generated suggestions grounded in that
platform's own evidence (fan-out sub-queries, cited domains, competitor
URLs, the answer text). The server checks every source against that
evidence and drops invented ones, so each card names something real.
Suggestions are editable drafts: check, edit, remove (undoable) or add
your own.

Generation is always the user's click and is metered: each call's real
token cost is charged against a monthly budget of 1% of the plan price
(Growth $2.49, Enterprise $4.99 or 1% of plan_overrides.contractMonthlyUsd),
so the share holds whichever model IMPROVE_SUGGESTION_MODEL points at.
Sets are cached per prompt, range and location; newer runs show a
"Regenerate" notice instead of rebuilding automatically. Growth+ only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prompts): address review on the Improve tab

- Treat a platform mentioned in fewer than half its runs as not mentioned,
  and show "mentioned in X of Y runs" in each platform header.
- Retry on a failed read re-reads the cache instead of generating; a failed
  generate keeps the set already on screen.
- Charge every model attempt, including schema misses withRetry repeats,
  and log a failed usage insert.
- Price openrouter/ model ids as the model they route to.
- Classify platforms from every answer in the window, like the Positions
  tab; keep the newest 600 for evidence only.
- Fix the stale budget name in server/.env.example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
…svisor#1012)

* feat(prompts): pick the Positions panel's date range inside the panel

The Positions panel was fixed to the table's range, so checking a prompt
over another period meant changing the whole table. The panel now has its
own 24h / 7d / 30d / 90d / Custom control. It opens on the table's range,
and changing it reloads only the panel. The open prompt and the panel's
range are mirrored to the URL (?positions=<id>&positionsRange=7d) so the
view can be shared. A custom range no longer spells its dates twice in
the header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): add an Improve tab with platform-specific position suggestions

For one prompt and the panel's range, the Positions panel gets an Improve
tab: per AI platform where the brand is not mentioned, mentioned late, or
mentioned early but not cited, AI-generated suggestions grounded in that
platform's own evidence (fan-out sub-queries, cited domains, competitor
URLs, the answer text). The server checks every source against that
evidence and drops invented ones, so each card names something real.
Suggestions are editable drafts: check, edit, remove (undoable) or add
your own.

Generation is always the user's click and is metered: each call's real
token cost is charged against a monthly budget of 1% of the plan price
(Growth $2.49, Enterprise $4.99 or 1% of plan_overrides.contractMonthlyUsd),
so the share holds whichever model IMPROVE_SUGGESTION_MODEL points at.
Sets are cached per prompt, range and location; newer runs show a
"Regenerate" notice instead of rebuilding automatically. Growth+ only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): send selected Improve suggestions to Action Center

The Improve tab's footer gets Send Actions: the checked suggestions, exactly
as edited, become one Action Center action (kind prompt_improve, category
compete). Each suggestion is a task with its body, platform and evidence
in the new action_tasks.details column. The action's why and goal are
written from the platform states at send time, its impact from the
prompt's demand and the size of the gap, and its baseline keeps the
positions per platform for PROMPT-008. Validation measures it on its own
prompt.

After a send the button turns into Open in Actions, the footer shows the
action id, and the sent suggestions are marked. The send is recorded on
the cached set, so this survives a reload, and is dropped once the action
is dismissed. An idempotency key per send makes a double click create one
action.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prompts): address review on the Improve tab

- Treat a platform mentioned in fewer than half its runs as not mentioned,
  and show "mentioned in X of Y runs" in each platform header.
- Retry on a failed read re-reads the cache instead of generating; a failed
  generate keeps the set already on screen.
- Charge every model attempt, including schema misses withRetry repeats,
  and log a failed usage insert.
- Price openrouter/ model ids as the model they route to.
- Classify platforms from every answer in the window, like the Positions
  tab; keep the newest 600 for evidence only.
- Fix the stale budget name in server/.env.example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prompts): measure Improve action citations on the pages it names

Citations are counted on a basket's pages, and the action's payload had
none, so the metric was always null. Carry the selected suggestions'
brand_page sources as payload.pages, and list citations in kpi_keys only
when there are pages to measure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
cihan-gyk and others added 3 commits October 13, 2026 22:04
…stions to Action Center (ansvisor#1014)

* feat(prompts): pick the Positions panel's date range inside the panel

The Positions panel was fixed to the table's range, so checking a prompt
over another period meant changing the whole table. The panel now has its
own 24h / 7d / 30d / 90d / Custom control. It opens on the table's range,
and changing it reloads only the panel. The open prompt and the panel's
range are mirrored to the URL (?positions=<id>&positionsRange=7d) so the
view can be shared. A custom range no longer spells its dates twice in
the header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): add an Improve tab with platform-specific position suggestions

For one prompt and the panel's range, the Positions panel gets an Improve
tab: per AI platform where the brand is not mentioned, mentioned late, or
mentioned early but not cited, AI-generated suggestions grounded in that
platform's own evidence (fan-out sub-queries, cited domains, competitor
URLs, the answer text). The server checks every source against that
evidence and drops invented ones, so each card names something real.
Suggestions are editable drafts: check, edit, remove (undoable) or add
your own.

Generation is always the user's click and is metered: each call's real
token cost is charged against a monthly budget of 1% of the plan price
(Growth $2.49, Enterprise $4.99 or 1% of plan_overrides.contractMonthlyUsd),
so the share holds whichever model IMPROVE_SUGGESTION_MODEL points at.
Sets are cached per prompt, range and location; newer runs show a
"Regenerate" notice instead of rebuilding automatically. Growth+ only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): send selected Improve suggestions to Action Center

The Improve tab's footer gets Send Actions: the checked suggestions, exactly
as edited, become one Action Center action (kind prompt_improve, category
compete). Each suggestion is a task with its body, platform and evidence
in the new action_tasks.details column. The action's why and goal are
written from the platform states at send time, its impact from the
prompt's demand and the size of the gap, and its baseline keeps the
positions per platform for PROMPT-008. Validation measures it on its own
prompt.

After a send the button turns into Open in Actions, the footer shows the
action id, and the sent suggestions are marked. The send is recorded on
the cached set, so this survives a reload, and is dropped once the action
is dismissed. An idempotency key per send makes a double click create one
action.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(mcp): add a create_improve_action tool for sending Improve suggestions to Action Center

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prompts): address review on the Improve tab

- Treat a platform mentioned in fewer than half its runs as not mentioned,
  and show "mentioned in X of Y runs" in each platform header.
- Retry on a failed read re-reads the cache instead of generating; a failed
  generate keeps the set already on screen.
- Charge every model attempt, including schema misses withRetry repeats,
  and log a failed usage insert.
- Price openrouter/ model ids as the model they route to.
- Classify platforms from every answer in the window, like the Positions
  tab; keep the newest 600 for evidence only.
- Fix the stale budget name in server/.env.example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prompts): measure Improve action citations on the pages it names

Citations are counted on a basket's pages, and the action's payload had
none, so the metric was always null. Carry the selected suggestions'
brand_page sources as payload.pages, and list citations in kpi_keys only
when there are pages to measure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
…visor#1015)

* feat(prompts): pick the Positions panel's date range inside the panel

The Positions panel was fixed to the table's range, so checking a prompt
over another period meant changing the whole table. The panel now has its
own 24h / 7d / 30d / 90d / Custom control. It opens on the table's range,
and changing it reloads only the panel. The open prompt and the panel's
range are mirrored to the URL (?positions=<id>&positionsRange=7d) so the
view can be shared. A custom range no longer spells its dates twice in
the header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): add an Improve tab with platform-specific position suggestions

For one prompt and the panel's range, the Positions panel gets an Improve
tab: per AI platform where the brand is not mentioned, mentioned late, or
mentioned early but not cited, AI-generated suggestions grounded in that
platform's own evidence (fan-out sub-queries, cited domains, competitor
URLs, the answer text). The server checks every source against that
evidence and drops invented ones, so each card names something real.
Suggestions are editable drafts: check, edit, remove (undoable) or add
your own.

Generation is always the user's click and is metered: each call's real
token cost is charged against a monthly budget of 1% of the plan price
(Growth $2.49, Enterprise $4.99 or 1% of plan_overrides.contractMonthlyUsd),
so the share holds whichever model IMPROVE_SUGGESTION_MODEL points at.
Sets are cached per prompt, range and location; newer runs show a
"Regenerate" notice instead of rebuilding automatically. Growth+ only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): send selected Improve suggestions to Action Center

The Improve tab's footer gets Send Actions: the checked suggestions, exactly
as edited, become one Action Center action (kind prompt_improve, category
compete). Each suggestion is a task with its body, platform and evidence
in the new action_tasks.details column. The action's why and goal are
written from the platform states at send time, its impact from the
prompt's demand and the size of the gap, and its baseline keeps the
positions per platform for PROMPT-008. Validation measures it on its own
prompt.

After a send the button turns into Open in Actions, the footer shows the
action id, and the sent suggestions are marked. The send is recorded on
the cached set, so this survives a reload, and is dropped once the action
is dismissed. An idempotency key per send makes a double click create one
action.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(prompts): replace the row's Edit icon with a ⋯ actions menu

The last column of the Tracked Prompts table was a single pencil. It is
now a ⋯ menu (Base UI, so it opens from mouse and keyboard and closes on
Esc and outside clicks) with:
- Edit: the existing dialog
- Pause tracking / Resume tracking: one click, with a toast
- Improve position…: opens the Positions panel on its Improve tab
- Delete: confirms "Delete prompt and its history?", removes the row and
  its count at once, and offers Undo for 10 s

Prompts have no soft delete (a delete drops their history), so the undo
window is a delayed delete: the row is hidden at once and deleted when the
window ends, or right away if the table unmounts first. Closing the page
inside the window leaves the prompt in place.

Suggest Content and the bulk action bar from the task are follow-ups.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(prompts): import the row menu icons apart from the limit counter's

Keeps this branch merging cleanly with the tracked prompt limit counter
(feature/prompts-tracked-limit-counter), which adds an icon to the same list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(prompts): import the dropdown menu apart from the bulk import's

Keeps this branch merging cleanly with bulk import
(feature/prompts-bulk-import), which adds imports at the same spot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
…er view (ansvisor#1016)

* feat(prompts): make Prompts an expandable sidebar menu with a route per view

The sidebar had a single Prompts link, and the page's views lived behind
?tab= / ?view= query params. Prompts now expands in the sidebar to:
- Tracked Prompts, with the brand's prompt count
- Prompt Suggestions
- Query Fan-outs
- Insights

Each has its own route: /dashboard/prompts/{tracked,suggestions,fan-outs,
insights}. Each route renders the same page, which reads its view from the
path. The page's tabs stay, and switching them rewrites the path in place,
so the sidebar and the tabs always show the same view. Moving between views
from the sidebar keeps the date range and location; location is now in the
URL as well.

/dashboard/prompts and its old ?tab= / ?view= links redirect to the matching
route (next.config redirects). The submenu's open state is remembered in
localStorage and opens on any Prompts route. Arrow keys move through the
sidebar links (right/left open, enter or leave the submenu), the parent
carries aria-expanded, and a collapsed sidebar opens on keyboard focus as it
already does on hover. The mobile nav lists the four views under Prompts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(prompts): define the tracked prompt count apart from bulk import's action

Keeps this branch merging cleanly with bulk import
(feature/prompts-bulk-import), which adds a function at the same spot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk
gkhngyk previously approved these changes Oct 14, 2026

@gkhngyk gkhngyk 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.

Looks good, thanks. I merged main into the branch and kept both sides of the plan and plan-guard conflicts (improveMonthlyBudgetUsd from #1011 next to maxOpportunitiesPerMonth), then regenerated schema.sql. Migration 00125 is applied to production.

Follow-ups, none blocking:

  • Claimed slots can leak. The slots are handed back on the basket, model and insert failures, but any other throw between the claim and the insert keeps them. A try/finally around that stretch would cover every path, which matters with Starter's 10.
  • A limited run is silent. When the quota is used up, generation returns limited: true, but the worker and the page don't surface it. A run that hits the limit looks like one that found nothing.

@cihan-gyk
cihan-gyk dismissed gkhngyk’s stale review October 14, 2026 09:27

The merge-base changed after approval.

@gkhngyk
gkhngyk merged commit 7a1c9b8 into ansvisor:main Oct 14, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants