Files
classroomio/packages/db
Rotimi Best fd8bec3e70 feat(billing): enforce free-plan student cap across the app (#733)
* feat(billing): enforce free-plan student cap across the app

Free (BASIC) plan orgs were able to exceed the advertised 20-student
limit because the cap existed only as dashboard cosmetic copy with no
server-side enforcement.

Add a single source of truth (getStudentLimit / STUDENT_LIMITS) and a
central guard (assertStudentCapacityOrThrow) wired into every path that
creates a new student-role org member: self-enrolment, course-invite
acceptance, bulk audience import, and org-invite acceptance. The guard
throws UPGRADE_REQUIRED (403) and notifies org admins by email (throttled
to once per org per day) when the limit is hit.

Surface the limit in the UI: disable the audience import button and the
course new-student invite section with upgrade banners for admins, and
show a "contact your administrator" message on the public enrol page for
students (who cannot upgrade). Expose a studentLimitReached flag from the
public course endpoint so the enrol button can be disabled proactively.

Add a one-time (manual, non-cron) db script,
db:notify-students-over-limit, to email admins of orgs already over the
limit at rollout.

* feat(billing): guard remaining student-creating paths against the cap

The initial cap enforcement missed several service entry points that also
create a new student-role org member. Add the capacity guard to:

- autoEnrollStudent (public org self-join on a tenant site)
- cohort enrollment (bulk group enrollment and single member accept)
- ensureProgramCourseAccess (program/cohort-granted course access)

For the cohort and program paths, only genuinely new members are counted
(existing org members are skipped) so re-enrolling current students is
never falsely blocked. The core path enforces via the shared limit check;
it throws UPGRADE_REQUIRED without the admin email since the queue lives
in the api layer.

* fix(billing): don't show cap block to existing org members on enroll page

The public course-by-slug endpoint is unauthenticated, so the enroll
page's studentLimitReached flag is org-wide and can't tell whether the
current viewer is already an org member. An existing student of a full
BASIC org would see Join disabled even though the backend correctly lets
existing members enroll without consuming a new seat.

Only pre-block anonymous visitors (would-be new joiners). Logged-in users
are governed by the membership-aware backend, which allows existing
members and returns UPGRADE_REQUIRED (surfaced via the enroll onError
mapping) for genuinely new students.

* feat(billing): deliver org plan-limits via /account with an extensible registry

Replace the ad-hoc, per-surface audience fetches (each calling getOrgAudience
just to read a count) with a single, future-proof delivery of org usage +
limits on the /account payload, gated to admin/tutor members (students never
receive limit data; a plain COUNT, no student rows).

Model it generically so future org limits (courses, etc.) drop in without
reshaping the payload or re-plumbing the frontend:
- New packages/utils plan-limits registry: PLAN_LIMIT_RESOURCES, PLAN_LIMITS
  (reuses STUDENT_LIMITS), getPlanLimit, and a JSON-safe ResourceUsage /
  OrgUsageLimits shape with isResourceLimitReached / resourceLimitRemaining.
- getAccountData attaches a per-org `limits` map for admin/tutor orgs.
- Store selectors currentOrgLimits / studentUsage / isStudentLimitReached;
  sidebars, upgrade card, People pages, and invite modals read these instead
  of fetching audience rows.

Bring cohort surfaces to parity with course: cohort People page banner and
cohort sidebar People upgrade icon, matching the course equivalents.

Also: close the upgrade modal that opened over the invite modal (drop the
`add` param via openUpgradeModalOver), redesign the sidebar upgrade card
(progress toward the student limit), add a Progress `variant`, and document
the no-complex-expressions-in-object-literals rule in AGENTS.md.

* refactor(billing): address PR review on the limits work

- Dedupe new student profile IDs before the cohort seat check so duplicate
  batch entries can't overcount against the cap (Greptile P1).
- Drive the org-sidebar upgrade indicator from a dynamic nav-item `upgrade`
  flag (audience config declares `upgradeResource: 'students'`; groups set it
  from a `limitsReached` map) instead of a hardcoded path check.
- Collapse the audience Import button into a single button with ternary
  `disabled`/`href`.
- Simplify the notify-students-over-limit upgrade link to app.classroomio.com.
- Drop the comment on the org `limits` field.
- Add .greptile/rules.md documenting the manual one-time db/src/scripts
  convention (operator-controlled reruns) so idempotency isn't reflagged.

* fix(billing): name the org in the enroll capacity message

Change the enroll-page student-limit message from "This course has reached
its student capacity" to "{orgName} has reached its student capacity", since
the cap is org-wide, not course-specific. Pass orgName from the loaded org on
the page and from the currentOrg store in the enroll onError snackbar.

* style(billing): use PremiumIcon for the Authentication upgrade indicator

Replace the RocketIcon on paid settings sub-items (e.g. Authentication) with
the PremiumIcon used on the Audience item, right-aligned (ml-auto) to match.
2026-07-12 11:33:04 +01:00
..
2026-05-19 04:32:32 +01:00
2025-11-01 15:49:29 +01:00
2026-04-27 11:40:38 +01:00

@cio/db

This package handles everything related to the database, schema, migrations and connection.

Stack

  1. Postgres - We use postgres for the database
  2. Drizzle ORM - For managing and querying the database
  3. Better Auth - For managing the auth tables (users, account, session).

Workflow

We used Supabase in the past for managing the supabase but have now moved on to use postgres directly and auth managed by our backend. This means the workflow is a mix of the Database First approach (Option 1) and the Codebase First approach (Option 2). Learn more about each approach from the drizzle migration docs.

Here is how I do it:

1. Local DB to Drizzle Schema TS file

I have a postgres tool where I can make changes to the db as I want. I am not so familiar with drizzle that much so I am sticking with this for now.

```bash
pnpm db pull # this does sql -> drizzle ts code
```

2. Drizzle Schema file to Prod SQL

Now when I am ready to deploy the feature, I can use option 2 which is makes the typescript schema the source of truth. This command will only run on CI on every merge on a condition that there was a change to the schema file packages/db/src/schema.ts

```bash
pnpm db push # this does drizzle ts code to prod db
```

OR

I can make changes directly to the schema file and run pnpm db push to push the changes to the source db.

Setting up a new DB on Railway

Once you setup a Postgres DB on Railway, you should copyt the DATABASE_PUBLIC_URL and paste into your .env. In the .env we expect DATABASE_URL:

```.env
DATABASE_URL=what-you-copied-from-railway
```

Commands

db:setup

Prepares the database so the application can run. Run this for new databases or after provisioning Postgres.

pnpm db:setup

It performs three steps in order:

  1. Schema sync – Runs drizzle-kit push to apply the TypeScript schema to the database (creates/updates tables, enums, etc.).
  2. PostgreSQL roles – Creates the authenticated and anon roles if missing (used by RLS policies).
  3. Essential seed data – Inserts required reference data: roles (ADMIN, TUTOR, STUDENT), submission statuses, and question types.

Optional: Add --seed (or -s) to run the full seed, including demo users, organizations, courses, and other example data.

Requires DATABASE_URL or PRIVATE_DATABASE_URL in the environment. The scripts load .env from this package directory, so bootstrap it once from the template:

cp .env.example .env   # then set DATABASE_URL for your DB

db:backfill-profile-email-verification

Repairs stale profile.is_email_verified rows where the auth user is already verified (user.email_verified = true) or has a linked OAuth/SSO account, but the profile flag was never synced. Use after the auth/profile verification mismatch fix, or when users are blocked by the verify-email modal while send-verification-email returns EMAIL_IS_ALREADY_VERIFIED.

Dry run (lists affected count and a sample; makes no changes):

pnpm db:backfill-profile-email-verification
# or from repo root:
pnpm --filter @cio/db db:backfill-profile-email-verification

Apply updates:

pnpm db:backfill-profile-email-verification -- --execute

The script prints how many profiles were updated and verifies zero mismatches remain.

Seeding

The seed script populates the database with demo data for local development. It is idempotent — running it multiple times is safe; existing records are skipped.

Run all seeds

pnpm seed
# or explicitly
pnpm seed --all

Run individual seeds

Pass one or more flags to run only specific steps:

pnpm seed --users --profiles
pnpm seed --organizations --organization-members --organization-plan
Flag What it seeds
--roles ADMIN, TUTOR, STUDENT roles
--submissions Submission statuses
--question-types Question types
--users Auth users (from users.json)
--profiles User profiles
--accounts User accounts
--organizations Demo organizations
--organization-members Org membership records
--organization-plan Organization plan records (enterprise + early adopter)
--groups Course groups
--group-members Group membership records
--courses Demo courses
--sections Course sections
--lessons Lessons
--exercises Exercises
--questions Questions
--templates Exercise templates

Demo accounts

Email Password Role Plan
admin@test.com 123456 Admin Basic (free)
student@test.com 123456 Student Basic (free)
enterprise@test.com 123456 Admin Enterprise
enterprise-student@test.com 123456 Student Enterprise
early-adopter@test.com 123456 Admin Early Adopter
early-adopter-student@test.com 123456 Student Early Adopter

Mock user credentials are defined in users.json. The demo accounts above use the password 123456.