Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions compute/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Composer.
| [`personal-site`](./personal-site) | Astro personal site with no database. |
| [`room-booking-prisma-template`](./room-booking-prisma-template) | Next.js room booking app: Resource Scheduler timeline, row locks and an exclusion constraint against double booking. |
| [`scalable-indexing-platform-template`](./scalable-indexing-platform-template) | Next.js resource directory (DevShelf): full-text search, filters, cursor pagination and batched bulk seeding. |
| [`revenue-metrics`](./revenue-metrics) | Next.js revenue dashboard: MRR, active subscriptions and revenue from Stripe tables, each metric one typed SQL query. |

Each example includes a Composer module and a GitHub Actions deployment
workflow. The database-backed examples also include a Prisma 8 contract,
Expand Down
9 changes: 9 additions & 0 deletions compute/revenue-metrics/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Local settings for `bun run dev` and the db:* scripts. Copy this file to
# .env.local (not .env: `next build` copies .env into the bundle that a deploy
# uploads) and set your own value. Not needed on Prisma Compute, where the app
# gets its database from Prisma Composer.
#
# With Prisma Postgres, use the direct host db.prisma.io. The pooled host
# (pooled.db.prisma.io) refuses a setting Prisma ORM 8 sends while connecting,
# until prisma/orm#31081 ships.
DATABASE_URL="postgresql://USER:PASSWORD@db.prisma.io:5432/postgres?sslmode=require"
2 changes: 2 additions & 0 deletions compute/revenue-metrics/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
src/prisma/contract.json linguist-generated
src/prisma/contract.d.ts linguist-generated
42 changes: 42 additions & 0 deletions compute/revenue-metrics/.github/workflows/prisma-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: prisma-deploy

on:
push:
delete:

concurrency:
group: prisma-deploy-${{ github.event_name == 'delete' && github.event.ref || github.ref_name }}
cancel-in-progress: false

permissions:
contents: read
id-token: write
pull-requests: write

jobs:
deploy:
if: github.event_name == 'push' && github.ref_type == 'branch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.4.0
- uses: oven-sh/setup-bun@v2.2.0
- uses: actions/setup-node@v4.4.0
with:
node-version: 22.23.2
- uses: prisma/cloud-deploy-action@v1
with:
build-command: bun run build

teardown:
if: github.event_name == 'delete' && github.event.ref_type == 'branch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.4.0
- uses: oven-sh/setup-bun@v2.2.0
- uses: actions/setup-node@v4.4.0
with:
node-version: 22.23.2
- uses: prisma/cloud-deploy-action@v1
with:
mode: destroy
stage: ${{ github.event.ref }}
9 changes: 9 additions & 0 deletions compute/revenue-metrics/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
node_modules
.next
.env
.prisma
.prisma-composer
.alchemy
next-env.d.ts
.env.local
*.tsbuildinfo
1 change: 1 addition & 0 deletions compute/revenue-metrics/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
24
12 changes: 12 additions & 0 deletions compute/revenue-metrics/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## This project

A revenue metrics dashboard template: Next.js 16 App Router, Prisma ORM 8, Prisma Postgres, Prisma Compute via Prisma Composer. Each metric is one SQL query, typed with `.returnsRow()`. See README.md.

- Node.js 22.18 or newer (`.nvmrc` selects Node 24) and Bun. `prisma dev` does not run on Windows (`DEV.PLATFORM_UNSUPPORTED`); use `bun run dev` with a database URL in `.env.local`.
- The four queries live in `src/queries.ts`. Cast every computed column in SQL (`::int8`, `::int4`) to match its codec in `.returnsRow()`: codecs read values, they do not convert them. The SQL panel shows each query via `db.toSql()`, so keep the SQL readable.
- The tables match the Stripe tables Codeless Sync creates (same columns, types and nulls). Do not rename or drop columns in `src/prisma/contract.prisma`, or synced data stops fitting. Extra columns and indexes are fine.
- Schema changes: edit `src/prisma/contract.prisma`, then `bun run contract:emit`, `bun run migration:plan --name <name>`, `bun run db:migrate`. Never hand-edit `ops.json`, `contract.json` or `contract.d.ts`.
- Demo rows have ids containing `_seed_`. `bun run db:seed` replaces them, `bun run db:seed --remove` deletes them; other rows are never touched.
- Local settings go in `.env.local`, never `.env` (`next build` copies `.env` into the deployed bundle). With Prisma Postgres use the direct host `db.prisma.io`, not `pooled.db.prisma.io` (prisma/orm#31081).
- Deploy is `bun run deploy` (`next build`, then `prisma deploy`). On Windows, `bunx prisma deploy` fails (its deploy engine relaunches itself through `bunx.exe`); `bun run deploy` works. A deploy is production; ask first.
- Before committing: `bun run typecheck`, `bun run build`.
21 changes: 21 additions & 0 deletions compute/revenue-metrics/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Ilshaad Kheerdali

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
134 changes: 134 additions & 0 deletions compute/revenue-metrics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Revenue Metrics with Prisma

A small dashboard of SaaS revenue metrics: MRR, active subscriptions, revenue in the last 30 days and revenue by month, from Stripe billing tables. Every metric is one SQL query, computed in Postgres and typed end to end with Prisma ORM 8, and the page shows you each query next to its result.

- **[Prisma ORM](https://www.prisma.io/orm)** 8 for the contract, the migration and typed raw SQL.
- **[Prisma Postgres](https://www.prisma.io/postgres)** for the data, with demo data on the first visit.
- **[Prisma Compute](https://www.prisma.io/compute)** to host it, declared with Prisma Composer.

<a href="https://console.prisma.io/apps/revenue-metrics"><img src="https://www.prisma.io/docs/img/deploy-button.svg" alt="Deploy with Prisma" width="172" height="36" /></a>

<img src="docs/screenshot.png" alt="The Revenue Metrics dashboard: cards for MRR, active subscriptions and revenue in the last 30 days, a 12-month revenue bar chart, and a dark side panel showing the SQL behind MRR" width="1280" />

## What it shows

| Card | What it is | Reads |
| --- | --- | --- |
| **MRR** | Monthly recurring revenue of active subscriptions. Each price is turned into a monthly amount (a yearly price is divided by 12) and multiplied by its quantity. | `stripe_subscriptions`, `stripe_subscription_items`, `stripe_prices` |
| **Active subscriptions** | Subscriptions with status `active`. `trialing` and `past_due` are left out. | `stripe_subscriptions` |
| **Revenue, last 30 days** | Cash from paid invoices created in the last 30 days. | `stripe_invoices` |
| **Revenue by month** | Paid invoices of the last 12 months, grouped by month in UTC. A month with no invoices shows as $0. | `stripe_invoices` |

Each card also shows its change from 30 days earlier, from a second column of the same query. **View SQL** opens the query behind a card in the side panel, with the `.returnsRow()` spec that types it; **Copy** copies the SQL, which runs as is in any SQL client connected to the database. The panel text comes from `db.toSql()`, so it is the SQL that ran, not a copy of it.

Good to know:

- **Amounts are in cents**, as Stripe stores them, and the template assumes one currency (USD in the demo data). The queries do not convert or filter currencies.
- **The previous MRR and subscription counts are approximate.** A subscription counts as active 30 days ago if it was created before then and is active now or has ended since, and MRR uses today's prices. Revenue's previous value is exact.
- **Invoices are dated by `created`.** Stripe's paid date is only inside the `data` JSON column, and subscription invoices are usually paid within about an hour of creation.
- **Results are cached for 60 seconds**, because Prisma Postgres bills per query and the page runs four of them. The page reads the database at request time, never during the build.

## Run it locally

You need **Node.js 22.18 or newer** (`.nvmrc` selects Node 24 for `nvm use`), **[Bun](https://bun.sh)**, and a PostgreSQL database. For Prisma Postgres, create a database in the [Prisma Console](https://console.prisma.io) and copy its connection string.

```bash
bun install
cp .env.example .env.local # then set DATABASE_URL in .env.local
bun run contract:emit
bun run db:migrate # creates the four Stripe tables
bun run db:seed # adds the demo data (optional: the first visit does it)
bun run dev
```

- **Use `.env.local`, not `.env`:** `next build` copies `.env` into the bundle that a deploy uploads.
- **Prisma Postgres: use the direct host `db.prisma.io`.** If your connection string has `pooled.db.prisma.io`, change it to `db.prisma.io`. The pooled host refuses a setting Prisma ORM 8 sends while connecting, and commands fail with `Failed to connect to upstream database` ([prisma/orm#31081](https://github.com/prisma/orm/pull/31081)).

Open [http://localhost:3000](http://localhost:3000). You see the three cards and the chart with about a year of demo data: around 600 active subscriptions and $39k MRR. Click **View SQL** on any card to see its query and types in the side panel, and open **How it works** under the title for where the data and the queries come from.

## Deploy to Prisma Compute

The **Deploy with Prisma** button above copies this template to your GitHub account and deploys the copy with its own Prisma Postgres database. The first visit fills the empty database with the demo data.

To deploy from your machine instead:

```bash
bunx prisma auth login # once; opens the browser
bun run deploy # next build, then prisma deploy
```

A deploy creates the Prisma project `revenue-metrics` (named after the module in `module.ts`) if it does not exist, provisions a Prisma Postgres database, applies the migration in `migrations/`, deploys the app and prints its URL.

- **Region:** the first deploy creates the project in `us-east-1`. To use another region, change `prismaCloud({ region })` in `prisma.config.ts` **before** the first deploy.
- **Windows:** use `bun run deploy`. `bunx prisma deploy` fails on Windows, because the deploy engine relaunches itself through `bunx.exe`.
- **Deploy on push:** connect the repository once with `bunx prisma git connect`. The included workflow (`.github/workflows/prisma-deploy.yml`) then deploys the default branch on every push.

## Use your real Stripe data

The four tables have the same columns, types and nulls as the Stripe tables that [Codeless Sync](https://codelesssync.com) creates, so you can sync your Stripe account into them and the dashboard shows your real numbers. Prisma's guide walks through it: [Codeless Sync with Prisma Postgres](https://www.prisma.io/docs/guides/integrations/codeless-sync). Sync the Subscriptions, Subscription Items, Prices and Invoices templates.

The demo rows all have ids containing `_seed_`, and synced rows never do, so the two never collide. To remove the demo data once your own data is in:

```bash
bun run db:seed --remove
```

## What this teaches

Read the files in this order:

1. **`src/prisma/contract.prisma`:** the four tables, written in PSL. `bun run contract:emit` writes `contract.json` and `contract.d.ts`, which type every query. [Author in PSL](https://www.prisma.io/docs/orm/contract-authoring/psl-syntax)
2. **`migrations/`:** the migration `bun run migration:plan` made from the contract, applied by `bun run db:migrate` and by every deploy. [How migrations work](https://www.prisma.io/docs/orm/migrations/how-migrations-work)
3. **`src/queries.ts`:** the four metrics as `db.raw.sql` statements with `.returnsRow()`. The comments explain codecs and why every value is cast in SQL. [Raw queries](https://www.prisma.io/docs/orm/reference/raw-queries)
4. **`src/prisma/seed.ts`:** the demo data, written with the ORM client (`createAll`, `deleteAll`) inside a transaction. [Transactions](https://www.prisma.io/docs/orm/fundamentals/transactions)
5. **`src/app/page.tsx`:** runs the queries at request time and caches the results for 60 seconds with [`unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache). `dashboard.tsx` is the only client component.
6. **`module.ts` and `src/service.ts`:** the app and its database, declared for Prisma Composer, which provisions and connects them on deploy. [Apps and modules](https://www.prisma.io/docs/composer/apps-and-modules)

### Try it: add a churn card

Add a fifth query to `src/queries.ts`: the subscriptions that were active 30 days ago, and how many of them have ended since.

```sql
SELECT
count(*) FILTER (WHERE created < now() - interval '30 days'
AND ended_at >= now() - interval '30 days')::int4 AS "churned",
count(*) FILTER (WHERE created < now() - interval '30 days'
AND (status = 'active'
OR ended_at >= now() - interval '30 days'))::int4 AS "activeBefore"
FROM stripe_subscriptions
```

Type it with `.returnsRow({ churned: 'pg/int4@1', activeBefore: 'pg/int4@1' })`, add it to `loadDashboard()`, and show `churned / activeBefore` as a percentage in a new card in `page.tsx`. TypeScript tells you everywhere the new metric needs to go.

## Scripts

| Command | What it does |
| --- | --- |
| `bun run dev` | Next.js dev server on [http://localhost:3000](http://localhost:3000). |
| `bun run build` | Emits the contract, then builds the app. Needs no database. |
| `bun run typecheck` | Type-checks the project. |
| `bun run contract:emit` | Writes `contract.json` and `contract.d.ts` from `contract.prisma`. |
| `bun run migration:plan --name <name>` | Plans a migration from contract changes. |
| `bun run db:migrate` | Applies the migrations to the database in `DATABASE_URL`. |
| `bun run db:seed` | Replaces the demo rows with a fresh set. `--remove` deletes them. |
| `bun run deploy` | Builds, then deploys to Prisma Compute. |

## Project layout

```text
src/
app/
page.tsx server component: loads, caches and formats the metrics
dashboard.tsx client component: cards, chart and SQL panel
layout.tsx fonts and page title
globals.css styles
prisma/
contract.prisma the four Stripe tables
db.ts the database client (Composer on Compute, DATABASE_URL locally)
seed.ts demo data and first-visit seeding
seed-cli.ts bun run db:seed
queries.ts the four metric queries
service.ts the Compute service
migrations/ the planned migration, applied by every deploy
module.ts the app for Prisma Composer: a database and the service
```
Loading