Skip to content

feat: add admin org stats - #2904

Merged
dguyen merged 2 commits into
mainfrom
feat/add-org-stats
Jun 1, 2026
Merged

dguyen merged 2 commits into
mainfrom
feat/add-org-stats

Conversation

@dguyen

@dguyen dguyen commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

Description

Add ability to view the monthly org stats

Copilot AI review requested due to automatic review settings June 1, 2026 05:34
@vercel

vercel Bot commented Jun 1, 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 Jun 1, 2026 6:23am
prd-openpage-api Ignored Ignored Jun 1, 2026 6:23am
stg-docs Skipped Skipped Jun 1, 2026 6:23am

Request Review

@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an admin organisation statistics page, a TRPC endpoint returning paginated per-organisation monthly counts, a Remix page with debounced search/claim/period filters synced to URL, and a DataTable component with URL-driven sorting and pagination.

Changes

Organisation Stats Feature

Layer / File(s) Summary
Monthly Period Module Consolidation
packages/lib/server-only/rate-limit/check-monthly-quota.ts, packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts
Import of currentMonthlyPeriod consolidated to the universal monthly-period module.
Organisation Stats Schema & Types
packages/trpc/server/admin-router/find-organisation-stats.types.ts
Adds request schema (optional period YYYY‑MM, claimId, orderByColumn, orderByDirection) and response schema with stat records and pagination types.
Organisation Stats TRPC Endpoint
packages/trpc/server/admin-router/find-organisation-stats.ts
New findOrganisationStats route: resolves period default, joins monthly stats with organisations and claims, supports claimId and query filters (including org_ prefix lookup), computes totals with windowed count, applies ordering and pagination, and returns paginated results.
Admin Router Wiring & Navigation
packages/trpc/server/admin-router/router.ts, apps/remix/app/routes/_authenticated+/admin+/_layout.tsx
Registers findOrganisationStatsRoute as organisation.findStats and adds "Organisation Stats" sidebar button with LineChartIcon linking to /admin/organisation-stats.
Organisation Stats Page & Filters
apps/remix/app/routes/_authenticated+/admin+/organisation-stats._index.tsx
Adds admin route: debounced search synced to URL (clears page on change), claim select populated via TRPC, generated period select (earliest→current month), handlers that update URL and clear pagination, and an informational alert about attempted-action metrics.
Organisation Stats Data Table
apps/remix/app/components/tables/admin-organisation-stats-table.tsx
New AdminOrganisationStatsTable component: reads URL params for page/perPage/order, queries admin.organisation.findStats, memoizes sortable columns (organisation link, claim fallback, period, document/email/API/total counts), toggles sort direction and resets page, and renders loading skeleton/error and pagination with visible count.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add admin org stats' directly describes the main change: adding a new admin feature for viewing organisation statistics.
Description check ✅ Passed The description 'Add ability to view the monthly org stats' accurately describes the changeset, which introduces monthly organisation statistics viewing functionality.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 feat/add-org-stats

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.

@github-actions github-actions Bot added the apps: web Issues related to the webapp label Jun 1, 2026

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 an admin-facing “Organisation Stats” view to browse monthly organisation usage, including server-side filtering/sorting and a small shared utility for deriving the current UTC month period.

Changes:

  • Add a new admin TRPC route (admin.organisation.findStats) backed by a Kysely query over OrganisationMonthlyStat with filters (period/query/claim) and sortable columns.
  • Add a new Remix admin page (/admin/organisation-stats) plus navigation entry and a data table UI with sorting/pagination.
  • Introduce currentMonthlyPeriod() as a shared universal helper and update existing callers to use it.

Reviewed changes

Copilot reviewed 8 out of 9 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
packages/trpc/server/admin-router/router.ts Wires the new organisation.findStats admin endpoint into the admin router.
packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts Switches to the new shared currentMonthlyPeriod() helper.
packages/trpc/server/admin-router/find-organisation-stats.types.ts Defines request/response schemas for the new org stats endpoint.
packages/trpc/server/admin-router/find-organisation-stats.ts Implements the new org stats query (filters, ordering, pagination).
packages/lib/universal/monthly-period.ts Adds currentMonthlyPeriod() helper returning UTC YYYY-MM.
packages/lib/server-only/rate-limit/check-monthly-quota.ts Switches to the new shared currentMonthlyPeriod() helper.
apps/remix/app/routes/_authenticated+/admin+/organisation-stats._index.tsx Adds the new admin page with period/claim filters and search param syncing.
apps/remix/app/routes/_authenticated+/admin+/_layout.tsx Adds nav link entry for the new “Organisation Stats” page.
apps/remix/app/components/tables/admin-organisation-stats-table.tsx Adds the sortable/paginated stats table using the new TRPC endpoint.

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

Comment on lines +5 to +9
period: z
.string()
.regex(/^\d{4}-\d{2}$/, 'Period must be in YYYY-MM format.')
.describe('Filter stats by UTC calendar month in `YYYY-MM` form, e.g. "2026-05".')
.optional(),

@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/routes/_authenticated`+/admin+/organisation-stats._index.tsx:
- Around line 71-86: The search effect currently updates query but doesn't reset
pagination, which can leave users on an invalid page; inside the useEffect that
builds params from searchParams, compare the current query value
(searchParams.get('query') || '') to debouncedSearchQuery and if they differ,
call params.delete('page') before calling setSearchParams; keep the existing
guard that returns when params.toString() === searchParams?.toString() and still
only call setSearchParams(params) when something actually changed (use the
existing debouncedSearchQuery, searchParams, setSearchParams, pathname,
useEffect symbols).
🪄 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: 4727eaa3-cb71-4790-b838-c00f0ff5d431

📥 Commits

Reviewing files that changed from the base of the PR and between 44c4826 and 99a740b.

📒 Files selected for processing (9)
  • apps/remix/app/components/tables/admin-organisation-stats-table.tsx
  • apps/remix/app/routes/_authenticated+/admin+/_layout.tsx
  • apps/remix/app/routes/_authenticated+/admin+/organisation-stats._index.tsx
  • packages/lib/server-only/rate-limit/check-monthly-quota.ts
  • packages/lib/universal/monthly-period.ts
  • packages/trpc/server/admin-router/find-organisation-stats.ts
  • packages/trpc/server/admin-router/find-organisation-stats.types.ts
  • packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts
  • packages/trpc/server/admin-router/router.ts

@vercel
vercel Bot temporarily deployed to Preview – stg-docs June 1, 2026 05:48 Inactive
@dguyen
dguyen force-pushed the feat/add-org-stats branch from c97bcfa to 1ac51c9 Compare June 1, 2026 06:22
@vercel
vercel Bot temporarily deployed to Preview – stg-docs June 1, 2026 06:23 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 `@packages/trpc/server/admin-router/find-organisation-stats.ts`:
- Around line 116-138: The current pagination loses the total when rows is empty
because count is read from the windowed totalRows of the first row; update the
logic in find-organisation-stats.ts so that if rows.length === 0 you run a
dedicated cheap count query (reusing the same filter conditions used to build
dataQuery) to populate count (or alternatively always run that separate COUNT(*)
query alongside dataQuery), then compute totalPages = Math.ceil(count / perPage)
and return the response (the relevant symbols: dataQuery, rows, count, page,
perPage, totalPages, FindResultResponse) so an empty data page still reports the
correct total.
🪄 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: 8c361608-de31-46a0-89b4-33bf8aa25e5e

📥 Commits

Reviewing files that changed from the base of the PR and between c97bcfa and 1ac51c9.

📒 Files selected for processing (9)
  • apps/remix/app/components/tables/admin-organisation-stats-table.tsx
  • apps/remix/app/routes/_authenticated+/admin+/_layout.tsx
  • apps/remix/app/routes/_authenticated+/admin+/organisation-stats._index.tsx
  • packages/lib/server-only/rate-limit/check-monthly-quota.ts
  • packages/lib/universal/monthly-period.ts
  • packages/trpc/server/admin-router/find-organisation-stats.ts
  • packages/trpc/server/admin-router/find-organisation-stats.types.ts
  • packages/trpc/server/admin-router/reset-organisation-monthly-stat.ts
  • packages/trpc/server/admin-router/router.ts

Comment on lines +116 to +138
const rows = await dataQuery.execute();

const count = rows.length > 0 ? Number(rows[0].totalRows) : 0;

const data = rows.map((row) => ({
id: row.id,
organisationId: row.organisationId,
organisationName: row.organisationName,
originalClaimId: row.originalClaimId,
period: row.period,
documentCount: Number(row.documentCount),
emailCount: Number(row.emailCount),
apiCount: Number(row.apiCount),
totalCount: Number(row.totalCount),
}));

return {
data,
count,
currentPage: Math.max(page, 1),
perPage,
totalPages: Math.ceil(count / perPage),
} satisfies FindResultResponse<typeof data>;

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Total count is lost on empty pages, breaking pagination.

count is read from the windowed totalRows of the first returned row. When offset exceeds available rows (e.g. direct navigation to an out-of-range page, or a larger perPage after filtering), rows is empty, so count collapses to 0 and totalPages to 0 — the footer then misreports totals and the user can get stranded on an empty page with no way back via pagination.

Run a dedicated count query (cheap, no window function) when the data page is empty, or always derive count separately.

🐛 Proposed fix sketch
   const rows = await dataQuery.execute();

-  const count = rows.length > 0 ? Number(rows[0].totalRows) : 0;
+  let count = rows.length > 0 ? Number(rows[0].totalRows) : 0;
+
+  // The windowed totalRows is only available on returned rows. For an
+  // out-of-range page the result set is empty, so fall back to a count query.
+  if (rows.length === 0 && offset > 0) {
+    const { total } = await baseQuery
+      .select((eb) => eb.fn.countAll().as('total'))
+      .executeTakeFirstOrThrow();
+
+    count = Number(total);
+  }
🤖 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/trpc/server/admin-router/find-organisation-stats.ts` around lines
116 - 138, The current pagination loses the total when rows is empty because
count is read from the windowed totalRows of the first row; update the logic in
find-organisation-stats.ts so that if rows.length === 0 you run a dedicated
cheap count query (reusing the same filter conditions used to build dataQuery)
to populate count (or alternatively always run that separate COUNT(*) query
alongside dataQuery), then compute totalPages = Math.ceil(count / perPage) and
return the response (the relevant symbols: dataQuery, rows, count, page,
perPage, totalPages, FindResultResponse) so an empty data page still reports the
correct total.

@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

@dguyen
dguyen merged commit 536142b into main Jun 1, 2026
9 checks passed
@dguyen
dguyen deleted the feat/add-org-stats branch June 1, 2026 07:26
@coderabbitai coderabbitai Bot mentioned this pull request Jun 1, 2026

This branch was previously deployed

1 inactive deployment
Preview – stg-docs — 1ac51c9b Deployed Jun 1, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants