P1 flow fix: register makes a solo user by default, collective creation is an opt-in flag, post-login menu for collective-less accounts

This commit is contained in:
glass beadian 2026-10-12 16:19:08 +00:00
parent 2665f43cc4
commit 2a3a1d79a1
15 changed files with 614 additions and 24 deletions

View file

@ -53,6 +53,18 @@ export class CollectivesController {
);
}
/**
* Count of collectives in MY workspace (roots only) — the post-login router:
* zero => the app shows the "no collectives yet" home menu (create / join /
* solo tools) instead of the streams wall. Cheaper and more stable than the
* full tree for a boolean decision; same permission as the tree read.
*/
@Get("mine/count")
@RequirePermission("workspace.view")
async myCount(@Req() request: AuthedRequest): Promise<{ collectives: number; workspaceKind: "shared" | "personal" }> {
return this.collectives.myCollectiveCount(requireSession(request).workspaceId);
}
/** The workspace's collective tree: collectives as roots, subcollectives nested. */
@Get("tree")
@RequirePermission("workspace.view")

View file

@ -265,6 +265,24 @@ export class CollectivesService {
return node;
}
/**
* Root-collective count + the workspace's tenancy kind, for the post-login
* home decision (operator flow reorder #3). A personal workspace reports zero
* by construction — it never contains collective rows — but the kind is
* returned anyway so the client can label the menu honestly ("solo account")
* without a second round-trip.
*/
async myCollectiveCount(workspaceId: string): Promise<{ collectives: number; workspaceKind: "shared" | "personal" }> {
return withTenant(workspaceId, async (client) => {
const rows = await client.query<{ n: string }>(
"SELECT count(*)::text AS n FROM groups WHERE workspace_id = $1 AND kind = 'collective'",
[workspaceId],
);
const kind = await client.query<{ kind: "shared" | "personal" }>("SELECT kind FROM workspaces WHERE id = $1", [workspaceId]);
return { collectives: Number(rows.rows[0]?.n ?? 0), workspaceKind: kind.rows[0]?.kind ?? "shared" };
});
}
/**
* The collective tree for the workspace: collectives as roots, subcollectives
* nested, every node carrying its room set. 'plain' groups are sharing

View file

@ -0,0 +1,166 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { join } from "node:path";
import { Pool, type PoolClient } from "pg";
/**
* Solo registration + the personal-workspace flag (operator flow reorder #1/#2)
* against a live PostgreSQL. Own database (the shared tenancy suite wipes every
* workspace and vitest runs files in parallel): COLLECTIVES_IT_DATABASE_URL +
* COLLECTIVES_IT_SUPER_DATABASE_URL, the same convention as the collectives
* integration suite. Skipped when unset.
*
* What these tests pin:
* - register() with NO workspaceName creates a kind='personal' workspace,
* one Owner membership, and /me reports the kind;
* - the personal workspace is invisible to the collective surface (zero rows
* in groups; myCollectiveCount => 0);
* - the classic named registration still produces kind='shared';
* - migration 031's CHECK rejects any third kind at the DB level.
*/
const appUrl = process.env.COLLECTIVES_IT_DATABASE_URL;
const ownerUrl = process.env.COLLECTIVES_IT_SUPER_DATABASE_URL;
type Modules = {
auth: typeof import("../auth/auth.service.js");
collectives: typeof import("./collectives.service.js");
db: typeof import("../db/client.js");
};
describe.skipIf(appUrl === undefined || ownerUrl === undefined)("solo registration (live DB)", () => {
let m: Modules;
let ownerPool: Pool;
const suffix = `${Date.now()}${Math.floor(Math.random() * 1e6)}`;
const solo = `solo${suffix}`;
const named = `named${suffix}`;
let soloAccount: Awaited<ReturnType<Modules["auth"]["AuthService"]["prototype"]["register"]>>;
let namedAccount: typeof soloAccount;
/** The swap-fake provisioner: none of these tests talk to Matrix. */
const fakeProvisioner = {
botUserId: "@unused:example.com",
// Room ids must satisfy 030's format CHECK (!localpart:domain) — the fake
// honours the same contract as the real provisioner.
provisionCollective: async () => ({
open: { roomId: `!open-${suffix}:chat.example.com` },
closed: { roomId: `!closed-${suffix}:chat.example.com` },
onboarding: { roomId: `!onboarding-${suffix}:chat.example.com` },
}),
};
function service(): InstanceType<typeof m.collectives.CollectivesService> {
return new m.collectives.CollectivesService(fakeProvisioner);
}
async function asOwner<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await ownerPool.connect();
try {
return await fn(client);
} finally {
await client.query("ROLLBACK").catch(() => undefined);
client.release();
}
}
beforeAll(async () => {
process.env.DATABASE_URL = appUrl;
process.env.SUPER_DATABASE_URL = ownerUrl;
const { runMigrations } = await import("../db/migrate.js");
await runMigrations(join(process.cwd(), "migrations"));
m = {
auth: await import("../auth/auth.service.js"),
collectives: await import("./collectives.service.js"),
db: await import("../db/client.js"),
};
ownerPool = new Pool({ connectionString: ownerUrl });
// Register both account shapes ONCE: usernames are globally unique, and
// re-registering would 409 (which is itself covered by the auth suite).
const auth = new m.auth.AuthService();
soloAccount = await auth.register({ username: solo, password: "correct-horse-1", displayName: "Solita Pérez" });
namedAccount = await auth.register({ workspaceName: "Colectivo Nombrado", username: named, password: "correct-horse-1", displayName: "Nombrada" });
});
afterAll(async () => {
if (ownerPool !== undefined) {
// Solo accounts are their own workspace: cascading the workspace removes
// the membership + user in one sweep.
await asOwner(async (c) => {
const ws = await c.query("SELECT id FROM workspaces WHERE slug LIKE $1", [`%${suffix}%`]);
const ids = ws.rows.map((row) => row.id as string);
if (ids.length > 0) {
await c.query("DELETE FROM users WHERE external_id = ANY($1)", [[`local:${solo}`, `local:${named}`]]);
await c.query("DELETE FROM workspaces WHERE id = ANY($1::uuid[])", [ids]);
}
});
await ownerPool.end();
}
await m?.db.pool.end();
});
it("register with NO workspaceName creates a personal workspace with one Owner and kind in /me", async () => {
const reg = soloAccount;
expect(reg.me.role).toBe("Owner");
expect(reg.me.workspace.kind).toBe("personal");
expect(reg.me.workspace.name).toBe("Solita Pérez"); // display name when given
expect(reg.me.workspace.slug).toContain(solo);
const rows = await asOwner(async (c) =>
c.query<{ kind: string; n: string }>(
`SELECT w.kind, (SELECT count(*)::text FROM memberships m WHERE m.workspace_id = w.id AND m.status = 'active') AS n
FROM workspaces w WHERE w.id = $1`,
[reg.me.workspace.id],
),
);
expect(rows.rows[0]).toMatchObject({ kind: "personal", n: "1" });
});
it("a personal workspace holds no collective rows and reports zero in myCollectiveCount", async () => {
const count = await service().myCollectiveCount(soloAccount.me.workspace.id);
expect(count).toEqual({ collectives: 0, workspaceKind: "personal" });
const tree = await service().collectiveTree(soloAccount.me.workspace.id);
expect(tree).toHaveLength(0);
});
it("register WITH a workspaceName still creates a shared workspace (classic flow unchanged)", async () => {
expect(namedAccount.me.workspace.kind).toBe("shared");
expect(namedAccount.me.workspace.name).toBe("Colectivo Nombrado");
expect(await service().myCollectiveCount(namedAccount.me.workspace.id)).toEqual({ collectives: 0, workspaceKind: "shared" });
});
it("login surfaces the kind for both account shapes", async () => {
const auth = new m.auth.AuthService();
const soloLogin = await auth.login({ username: solo, password: "correct-horse-1" });
expect(soloLogin.me.workspace.kind).toBe("personal");
const namedLogin = await auth.login({ username: named, password: "correct-horse-1" });
expect(namedLogin.me.workspace.kind).toBe("shared");
});
it("a personal workspace can later hold a collective: the kinds are orthogonal", async () => {
// The workspace KIND is orthogonal: a personal workspace that later gains a
// real collective (via the in-app door) is a member of the collective
// surface like any other. What never happens is the workspace ITSELF
// appearing as a collective — it has no groups row.
const created = await service().createCollective(
soloAccount.me.workspace.id,
{ name: "Su Colectivo", language: "es" },
{ userId: soloAccount.me.user.id, role: soloAccount.me.role },
);
expect(created.kind).toBe("collective");
expect(await service().myCollectiveCount(soloAccount.me.workspace.id)).toEqual({ collectives: 1, workspaceKind: "personal" });
});
it("migration 031 CHECK: only 'shared' and 'personal' are storable kinds", async () => {
await expect(
asOwner(async (c) => c.query("INSERT INTO workspaces (name, slug, kind) VALUES ('Bad', 'bad-kind', 'cooperative')")),
).rejects.toThrow(/kind/);
});
it("existing workspaces were backfilled to 'shared'", async () => {
// Any workspace created before 031 keeps working: the column is NOT NULL
// with a default, so old rows read as shared.
const rows = await asOwner(async (c) =>
c.query<{ kind: string }>("SELECT kind FROM workspaces WHERE slug NOT LIKE $1 LIMIT 5", [`%${suffix}%`]),
);
for (const row of rows.rows) expect(["shared", "personal"]).toContain(row.kind);
});
});