# Member area — tiers, a members' discussion, and members-only tools

> A member area with TIERS on top of a payment recipe — gold and platinum, supporter levels, a top tier that gets the owner's own tools — for a creator's audience from YouTube, a newsletter or a community: load it beside stripe-subscriptions (renewing, the default), square (when the person names Square) or stripe (dues or a season pass), never on its own, and only when the person asks for tiers, a members' discussion or members-only tools. Each tier is an owner-written plan record with a rank, copied onto the membership by backend.js; a member of rank N holds channels tier-1 through tier-N while entitled; every post, room and message names its lowest tier in minRank; members post in rooms their tier reads, checked with ctx.requireAccess in access.js; members-only tools run in backend.js and answer 403 below the tool's rank before ctx.callAI; on Square or a one-time Stripe charge a tier is a pass whose paidThrough each paid order moves forward. One database for memberships, plans, posts, rooms and messages. A single members-only feed with one price and no tiers, discussion or tools is stripe-subscriptions alone

Source: https://good.vibes.diy/docs/reference/member-area

When someone asks for a **member area with tiers** — gold and platinum for a
YouTube audience, supporter levels for a newsletter, a community where the top
tier gets the owner's own tools — build the layer this page teaches on top of
a payment recipe. The payment recipe decides *who paid and until when*; this
page decides *what each tier opens*: a ladder of tiers, a discussion members
post in, and tools that only a tier's members can run.

**This page sits on a payment recipe, and it works the same on each one.**

- **Stripe, renewing** (the default, and what "a month", "subscribe" or "a
  membership" means): the `stripe-subscriptions` recipe. Stripe renews and
  retries, and its status plus the grace period is the entitlement.
- **Square** ("I sell on Square", "with my Square account"): the `square`
  recipe, which takes one payment at a time. A tier is a **pass**: the member
  buys a month (or a year) and buys the next one when it runs out (§ 6).
- **Stripe, once** (annual dues, a season pass with no renewal): the `stripe`
  recipe, with the same pass shape as Square.

Whichever it is, the payment recipe keeps its own rules word for word — its
setup items, its read-back, its sweep, its mode. This page adds a field to its
plan record, a field to its membership record, and the records the member
area holds. Nothing here talks to a payment provider.

**One database.** Grants are reduced per database, so the membership records,
the plans, the posts, the rooms and the messages all live in the payment
recipe's one database (`club` in `stripe-subscriptions`), and one access
function handles every type. A discussion kept in a second database would
grant a paying member a channel no message is on.

**The owner names the tiers.** The app's code writes no tier names and no
prices: "Gold" and "Platinum" are plan records the owner creates on the
**Plans** screen, and the page shows each plan's own title. Asking the builder
for "a gold tier at $5 and a platinum tier at $15" writes those two records,
the same ones the screen does.

## 1. A tier is a plan with a rank

Each tier is a plan with a rank the owner sets — 1 for the first tier, 2 for the one above it — and the membership carries the rank of the plan it was settled for, copied by backend.js from the plan record, never sent by the browser.

- The plan record gains `rank`, a whole number from 1 to `MAX_RANK` (5). The
  **Plans** screen shows it as "Tier 1, 2, 3" beside the title, and `access.js`
  checks it with the plan's price and interval. Two plans may share a rank —
  a monthly and a yearly Gold are both rank 1.
- The route that opens checkout (`/subscribe` in `stripe-subscriptions`, the
  pass checkout in § 6) copies `rank` from the plan record onto the pending
  membership beside the price, exactly as it copies the amount. The browser
  names a plan; the rank, like the price, is the server's reading of it.
- `access.js` checks a new membership's `rank` is a whole number from 1 to
  `MAX_RANK`, and every later change of it goes through `ctx.requireBackend()`
  with the rest of the membership.

## 2. A higher tier opens everything below it

A member of rank N holds every tier channel from tier-1 to tier-N, so a higher tier opens everything below it: the access function grants them from the membership record's rank while it is entitled.

```js
const MAX_RANK = 5;
// tier-1 … tier-<rank>: Platinum (rank 2) reads Gold's posts and its own.
const tiersUpTo = (rank) => Array.from({ length: Math.min(rank, MAX_RANK) }, (_, i) => `tier-${i + 1}`);
```

The membership case of the access function grants `tiersUpTo(doc.rank)` in
place of the single `members` channel the payment recipe grants, and only
while `doc.entitled === true`; the rewrite that says otherwise takes every
tier away on the next sync. The owner holds every tier through the role grant
(`roles: { owner: tiersUpTo(MAX_RANK) }`), so the owner reads every room.

The page reads the same facts for display: `access.hasChannel("tier-2")`
shows the Platinum room's door open, and a Gold member sees it with
"Platinum members" and the Join button for that plan. Display never decides
access; the grant does.

## 3. Every members-only thing names its lowest tier

Every members-only document — a post, a room, a message, a file — names the lowest tier that reads it in minRank, and the access function routes it to that tier's channel.

- A **post** the owner writes carries `minRank` (0 for public): the access
  function checks `ctx.requireRole("owner")` and routes it to
  `minRank > 0 ? \`tier-${minRank}\` : "public"`. The owner's post form picks
  the tier from the plans that exist, by title.
- A **room** is the owner's: `_id` is `room-<minRank>-<slug>`, written only by
  the owner, with a title and a line about what it is for. A Gold room and a
  Platinum room are two rooms.
- A file a member downloads (a pattern, a recording) is a post with the file
  on it, so it follows the same rule.

## 4. The discussion: members post where their tier reads

A member posts to the discussion only into a room their tier reads: the access function checks the author is the signed-in member and calls ctx.requireAccess on the room's tier channel.

A `message` carries `roomId`, `minRank`, `authorHandle`, `text` and
`createdAt`. The access function can read only the document in front of it,
so the room's tier is written into the room's id and the message proves it
carries the same one:

```js
if (doc.type === "message") {
  if (!Number.isInteger(doc.minRank) || doc.minRank < 1 || !doc.roomId?.startsWith(`room-${doc.minRank}-`)) {
    throw { forbidden: "a message carries its room's tier" };
  }
  if (oldDoc && (oldDoc.authorHandle !== doc.authorHandle || oldDoc.roomId !== doc.roomId)) throw { forbidden: "a message keeps its author and its room" };
  if (oldDoc && doc.authorHandle !== user.userHandle) {
    // The owner's moderation: hiding someone else's message, never rewriting it.
    ctx.requireRole("owner");
    if (doc.text !== oldDoc.text) throw { forbidden: "the owner hides a message, never rewrites it" };
  } else {
    if (doc.authorHandle !== user.userHandle) throw { forbidden: "a message is its author's" };
    // The writer holds the room's tier right now: a lapsed member reads nothing and posts nothing.
    ctx.requireAccess(`tier-${doc.minRank}`);
  }
  return { channels: [`tier-${doc.minRank}`] };
}
```

The owner hides any message with a `hidden: true` rewrite the page filters
out; a member edits only their own. The page lists a room's
messages with a live query on `roomId`, newest last, with the composer gated
on `can.create(...)` for that room — so a lapsed member sees the room's door,
"Rejoin to post", and no composer.

## 5. Members-only tools run in backend.js

A members-only tool runs in backend.js: the route reads the caller's own membership record and answers 403 unless it is entitled at the tool's rank, before it calls ctx.callAI or anything else that costs the owner.

The tool is often the reason the top tier exists — a sewing-pattern advisor
that knows the owner's own fitting rules, a critique of a member's draft in
the owner's voice, a calculator built on the owner's method. Its prompt and
its know-how are the owner's work, so they live in `backend.js`, where no
browser reads them, and the page sends only the member's question.

```js
// The owner's tools, each with the lowest tier that runs it.
const TOOLS = { "pattern-advisor": { minRank: 2 } };

async function memberRank(ctx, mode) {
  const me = ctx.userInfo?.userHandle;
  if (!me) return 0;
  if (me === ctx.appInfo.ownerHandle) return MAX_RANK; // the owner runs every tool, as the page shows them
  const m = await ctx.db.get(`membership-${mode}-${me}`, { db: DB });
  return m?.entitled === true && Number.isInteger(m.rank) ? m.rank : 0;
}

// inside fetch(request, ctx):
if (url.pathname === "/tool/pattern-advisor" && request.method === "POST") {
  const { mode } = await checkoutMode(ctx);
  if ((await memberRank(ctx, mode)) < TOOLS["pattern-advisor"].minRank) {
    return json({ ok: false, reason: "tier", minRank: TOOLS["pattern-advisor"].minRank }, 403);
  }
  const { question } = await request.json();
  const answer = await ctx.callAI(`${ADVISOR_PROMPT}\n\nThe member asks: ${String(question).slice(0, 4000)}`, { max_tokens: 900 });
  return json({ ok: true, answer });
}
```

- The route reads **one** record, the caller's own membership in the app's
  current mode, so it sits under the `unfilteredReads` declaration the payment
  recipe already makes; add the tool routes to its `why`.
- The page calls it with `apiFetch`, shows the tool to a member whose tier
  runs it, and shows a member below it the tool's name, what it does and the
  plan that opens it. A 403 with `reason: "tier"` reads the same way.
- `ctx.callAI` in a `fetch` route runs on the signed-in caller's credits; a
  tool that saves its answers writes them to the member's own channel
  (`user:<handle>`), so each member's history is theirs.

## 6. Passes: a tier on Square, or on Stripe once

On Square, which takes one payment at a time, a tier is a pass: each paid order moves the membership's paidThrough forward by the plan's period, and backend.js writes entitled from paidThrough and the clock.

- The plan is the payment recipe's product record with `rank` and an
  `interval` of `month` or `year`; a pass order is one line, that plan, priced
  from the record like every other line.
- A pass membership is named for the payment's mode as well as the member,
  `membership-<mode>-<handle>` (Stripe's `test` or `live`, Square's `sandbox`
  or `production`), exactly as the payment recipe keeps its orders apart: a
  test pass grants nothing once the app takes real money, and the tool check
  and the page read the record for the app's current mode only.
- When the recipe's settle marks a pass order paid, the same settle rewrites
  the buyer's membership record in the order's own mode: `paidThrough` becomes
  `max(now, paidThrough) + one interval`, `rank` becomes the plan's, and
  `entitled` is `paidThrough > now`. A member who buys early keeps every day
  they already paid for.
- The recipe's scheduled sweep also reads every entitled membership and
  rewrites `entitled: false` once `paidThrough` has passed, so a lapsed pass
  closes the tiers on its own. Three days before, the sweep tells the member
  with `ctx.notify` (dedupeKey `renew-<handle>-<paidThrough>`) that their pass
  runs to that date, with the app's link to buy the next one.
- A pass order needs the buyer signed in, because the membership is theirs:
  the Join button asks for sign-in first, and the order records
  `buyerHandle`.
- Moving up a tier on a pass is buying the higher pass: the new rank applies
  at once, and the days left carry over.

## 7. The front door is a link the owner shares

The owner finds their people somewhere else — a video's description, a
newsletter, a pinned post — so the public page is the one they link. It reads
well to someone arriving cold: the owner's name and what the community is
for, each tier's title, price and what it opens (the rooms and tools at that
rank, read from the records), a Join per tier, and one public post or a
sample of the tool's output that shows what members get. The owner's **Share**
button copies that link with `?from=` set to where they will post it
(`youtube`, `newsletter`), and the membership records that `from` once, so the
**Members** page can say where each member came from.

**Changing tier on a renewing plan.** On `stripe-subscriptions` the app does
not change a live subscription's price, so a member holds one tier per
subscription. The page says which tier they hold and when it renews, and a
member who wants another tier cancels in the Customer Portal — which keeps
their tier to the end of the period they paid for — and joins the other tier
from the app once that period ends.
