Skip to content
Merged
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
18 changes: 11 additions & 7 deletions components/reports/publish-flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -770,21 +770,25 @@ export function PublishFlow() {
* Reports ready in the person's other workspaces, said where they are looking: each workspace's Publish lists only
* its own. Every workspace that holds some has its line, so the lines add up to the count on Publish in the rail.
*/
function WaitingElsewhere({ waiting, className }: { waiting: Array<{ name: string; slug: string | null; ready: number }>; className?: string }) {
function WaitingElsewhere({ waiting, className }: { waiting: Array<{ name: string; slug: string | null; ready: number; unfinished: number }>; className?: string }) {
const t = useTranslations("publishReports.flow");
if (!waiting.length) return null;
return (
<div className={cn("space-y-2", className)}>
{waiting.map(({ name, slug, ready }) => (
<p key={slug ?? ""} role="status" className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-2xl bg-inset px-4 py-3 text-sm">
{/* A line for each workspace's ready reports, which wait on the person, and one for their own that aren't live yet,
which they may have lost: each opens that workspace's reports, the ready ones for the first. */}
{waiting.flatMap(({ name, slug, ready, unfinished }) => [
...(ready ? [{ id: `${slug ?? ""}-ready`, words: slug ? t("waitingIn", { count: ready, name }) : t("waitingOwn", { count: ready }), href: `${slug ? `/o/${slug}` : ""}/publish?view=reports&show=ready`, count: ready }] : []),
...(unfinished ? [{ id: `${slug ?? ""}-unfinished`, words: slug ? t("unfinishedIn", { count: unfinished, name }) : t("unfinishedOwn", { count: unfinished }), href: `${slug ? `/o/${slug}` : ""}/publish?view=reports`, count: unfinished }] : []),
]).map(({ id, words, href, count }) => (
<p key={id} role="status" className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-2xl bg-inset px-4 py-3 text-sm">
<span className="flex min-w-0 items-start gap-2.5">
<PublishIcon className="mt-0.5 size-4 shrink-0 text-primary" />
{slug ? t("waitingIn", { count: ready, name }) : t("waitingOwn", { count: ready })}
{words}
</span>
<Button size="sm" variant="outline" asChild>
{/* A plain address: the other workspace's own reports, the ready ones. */}
<a href={`${slug ? `/o/${slug}` : ""}/publish?view=reports&show=ready`}>
{t("waitingOpen", { count: ready })} <ArrowRight />
<a href={href}>
{t("waitingOpen", { count })} <ArrowRight />
</a>
</Button>
</p>
Expand Down
3 changes: 2 additions & 1 deletion components/workspaces/item-home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ export function LastWorkspace() {
const named = addressWorkspace(pathname);
const query = useSearchParams().toString();
const { userId } = useAuth();
// The browser's cookies are the outside system: the proxy and the server read them on the next page load.
// The browser's cookies are the outside system: the proxy and the server read them on the next page load, and the
// proxy tells the person's account of a change (proxy.ts `keepOnAccount`).
useEffect(() => {
if (!userId || named === undefined) return;
const raw = lookCookieIn(document.cookie);
Expand Down
2 changes: 2 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,7 @@ import type * as webhooks_projections from "../webhooks/projections.js";
import type * as workpool from "../workpool.js";
import type * as workspaces_actor from "../workspaces/actor.js";
import type * as workspaces_create from "../workspaces/create.js";
import type * as workspaces_lastUsed from "../workspaces/lastUsed.js";
import type * as workspaces_makers from "../workspaces/makers.js";
import type * as workspaces_move from "../workspaces/move.js";
import type * as workspaces_personal from "../workspaces/personal.js";
Expand Down Expand Up @@ -1130,6 +1131,7 @@ declare const fullApi: ApiFromModules<{
workpool: typeof workpool;
"workspaces/actor": typeof workspaces_actor;
"workspaces/create": typeof workspaces_create;
"workspaces/lastUsed": typeof workspaces_lastUsed;
"workspaces/makers": typeof workspaces_makers;
"workspaces/move": typeof workspaces_move;
"workspaces/personal": typeof workspaces_personal;
Expand Down
2 changes: 2 additions & 0 deletions convex/lib/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ export const userFields = {
locale: v.optional(v.string()),
/** When they finished or skipped the profile setup. Until either, a new account gets it in front of every page. */
onboarding: v.optional(v.object({ finishedAt: v.optional(v.number()), skippedAt: v.optional(v.number()) })),
/** The organization, by its address's slug, the person last worked in; none for their own workspace. A browser that has never been used remembers nothing, so it opens there (convex/workspaces/lastUsed.ts, proxy.ts). */
lastWorkspace: v.optional(v.string()),
createdAt: v.number(),
updatedAt: v.number(),
};
Expand Down
9 changes: 5 additions & 4 deletions convex/reports/flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,17 +183,18 @@ describe("a report's details sent under another licence", () => {
});

describe("reports that wait in a person's other workspaces", () => {
it("tells an admin of the lab, from their own workspace, and tells a member nothing", async () => {
it("tells an admin of the lab, from their own workspace, and the member who made it that it isn't live yet", async () => {
const world = await setup();
await checked(world, [passed("byline"), passed("harm")], world.member, world.lab);
const ownOf = (clerkId: string) => world.t.run(async (ctx) => ensureWorkspace(ctx, { kind: "personal", userId: (await ctx.db.query("users").withIndex("by_clerk_id", (q) => q.eq("clerkId", clerkId)).unique())!._id }));
expect(await world.orgAdmin.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("orgadmin") })).toEqual({ ready: 1, workspaces: [{ name: "Learning Lab", slug: "lab", ready: 1 }] });
expect(await world.orgAdmin.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("orgadmin") })).toEqual({ ready: 1, workspaces: [{ name: "Learning Lab", slug: "lab", ready: 1, unfinished: 0 }] });
// In the lab itself its own Publish says so, and a member activates nothing.
expect(await world.orgAdmin.query(api.reports.flow.waitingElsewhere, { workspaceId: world.lab })).toEqual({ ready: 0, workspaces: [] });
expect(await world.member.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("member") })).toEqual({ ready: 0, workspaces: [] });
// A member activates nothing, but finds their own report from their own workspace, where they may have landed.
expect(await world.member.query(api.reports.flow.waitingElsewhere, { workspaceId: await ownOf("member") })).toEqual({ ready: 0, workspaces: [{ name: "Learning Lab", slug: "lab", ready: 0, unfinished: 1 }] });
// A person's own ready report is said in the lab, where they are only a member.
await checked(world, [passed("byline"), passed("harm")]);
expect(await world.author.query(api.reports.flow.waitingElsewhere, { workspaceId: world.lab })).toEqual({ ready: 1, workspaces: [{ name: "", slug: null, ready: 1 }] });
expect(await world.author.query(api.reports.flow.waitingElsewhere, { workspaceId: world.lab })).toEqual({ ready: 1, workspaces: [{ name: "", slug: null, ready: 1, unfinished: 0 }] });
});
});

Expand Down
34 changes: 21 additions & 13 deletions convex/reports/flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -914,16 +914,17 @@ export const countsForAssistant = assistantQuery(countsAction);
const ELSEWHERE_REPORTS = 200;

/**
* The reports that wait on the person in the workspaces they aren't looking at: their own, and each organization
* they are an admin of. Someone in their own workspace is told there that their lab's report is ready, and the other
* way round, since each workspace's Publish page lists only its own.
* The reports that wait on the person in the workspaces they aren't looking at: their own, and each organization they
* are in. Someone in their own workspace is told there that their lab's report is ready, or that their own report
* there isn't finished, and the other way round, since each workspace's Publish page lists only its own: a person who
* lands in the wrong workspace finds their report from here.
*/
export const waitingElsewhereAction = defineUserQuery({
path: "reports/flow:waitingElsewhere",
description:
"The person's other workspaces that hold reports ready for them to activate on Openscholar: their own workspace and each organization they are an admin of, " +
"leaving out the workspace asked from. It says how many are ready in all (`ready`) and names each workspace that holds some (`workspaces`): its name, " +
"its address (`slug`, none for their own) and how many are ready there. `workspaces` is empty when nothing waits.",
"The person's other workspaces that hold reports waiting on them on Openscholar: their own workspace and each organization they are in, " +
"leaving out the workspace asked from. It says how many are ready for them to activate in all (`ready`, only in their own workspace and organizations they are an admin of) and names each workspace that holds some, or holds reports of theirs that aren't live yet (`workspaces`): its name, " +
"its address (`slug`, none for their own), how many are ready there and how many of their own aren't finished (`unfinished`: being worked on, checked, reviewed or declined). `workspaces` is empty when nothing waits.",
args: {},
returns: v.object({ ready: v.number(), /** Every one of them, so what the page names adds up to `ready`: the person's own first. */ workspaces: waitingWorkspacesValidator }),
run: async (ctx, { userId, workspaceId }) => {
Expand All @@ -932,22 +933,29 @@ export const waitingElsewhereAction = defineUserQuery({
const reviewed = await reviewedIn(ctx);
// Only reports that never went live can be ready, and a workspace holds few of those: its newest are looked at,
// since a ready report was worked on lately and old drafts weren't.
const readyIn = async (id: Id<"workspaces">) =>
(await ctx.db.query("reports").withIndex("by_workspaceId_and_activatedAt", (q) => q.eq("workspaceId", id).eq("activatedAt", undefined)).order("desc").take(ELSEWHERE_REPORTS)).filter((report) => stageOf(report, reviewed(id)) === "ready").length;
// The person's own reports that never went live, wherever they are, read once: a workspace's newest reports by others never hide them.
const mineUnlive = await ctx.db.query("reports").withIndex("by_ownerId_and_activatedAt", (q) => q.eq("ownerId", userId).eq("activatedAt", undefined)).order("desc").take(ELSEWHERE_REPORTS);
// Ready ones are the person's to activate only where they can: their own workspace, or an organization they run.
const waitingIn = async (id: Id<"workspaces">, activates: boolean) => {
const ready = (report: Doc<"reports">) => activates && stageOf(report, reviewed(id)) === "ready";
const others = activates ? await ctx.db.query("reports").withIndex("by_workspaceId_and_activatedAt", (q) => q.eq("workspaceId", id).eq("activatedAt", undefined)).order("desc").take(ELSEWHERE_REPORTS) : [];
return { ready: others.filter(ready).length, unfinished: mineUnlive.filter((report) => report.workspaceId === id && !ready(report)).length };
};
const own = await ctx.db.query("workspaces").withIndex("by_userId", (q) => q.eq("userId", userId)).unique();
// ponytail: the first organizations a person is an admin of are asked about; an admin of more than these opens the rest to see.
// ponytail: the first organizations a person is in are asked about, those they run first, whose ready reports the
// sidebar counts; someone in more than these opens the rest to see.
const memberships = (await ctx.db.query("organizationMemberships").withIndex("by_clerkUserId_and_state", (q) => q.eq("clerkUserId", user.clerkId).eq("state", "active")).take(MAX_ORGANIZATIONS_PER_PERSON))
.filter((membership) => membership.role === "org:admin")
.sort((a, b) => Number(b.role === "org:admin") - Number(a.role === "org:admin"))
.slice(0, ELSEWHERE_WORKSPACES);
const organizations = await Promise.all(
memberships.map(async (membership) => {
const organization = await ctx.db.get("organizations", membership.organizationId);
const workspace = organization?.state === "active" ? await ctx.db.query("workspaces").withIndex("by_organizationId", (q) => q.eq("organizationId", organization._id)).unique() : null;
return organization && workspace && workspace._id !== workspaceId ? [{ name: organization.name, slug: organization.slug as string | null, ready: await readyIn(workspace._id) }] : [];
return organization && workspace && workspace._id !== workspaceId ? [{ name: organization.name, slug: organization.slug as string | null, ...(await waitingIn(workspace._id, membership.role === "org:admin")) }] : [];
}),
);
const mine = own && own._id !== workspaceId ? [{ name: "", slug: null, ready: await readyIn(own._id) }] : [];
const waiting = [...mine, ...organizations.flat()].filter((workspace) => workspace.ready > 0);
const mine = own && own._id !== workspaceId ? [{ name: "", slug: null, ...(await waitingIn(own._id, true)) }] : [];
const waiting = [...mine, ...organizations.flat()].filter((workspace) => workspace.ready > 0 || workspace.unfinished > 0);
return { ready: waiting.reduce((sum, workspace) => sum + workspace.ready, 0), workspaces: waiting };
},
});
Expand Down
2 changes: 1 addition & 1 deletion convex/reports/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,7 @@ export const reportRowsValidator = capped(v.array(authorRowValidator), REPORTS_P
/** How many of the organizations a person is an admin of are asked about for reports that wait on them. */
export const ELSEWHERE_WORKSPACES = 20;
/** The person's other workspaces that hold reports ready for them to activate: their own, and those organizations. */
export const waitingWorkspacesValidator = capped(v.array(v.object({ name: v.string(), slug: v.union(v.string(), v.null()), ready: v.number() })), ELSEWHERE_WORKSPACES + 1);
export const waitingWorkspacesValidator = capped(v.array(v.object({ name: v.string(), slug: v.union(v.string(), v.null()), ready: v.number(), /** The person's own reports there that aren't live yet and aren't theirs to activate now: being worked on, checked, reviewed or declined. */ unfinished: v.number() })), ELSEWHERE_WORKSPACES + 1);
/** A report's authors by name, as its signed agreement lists them. */
export const signerNamesValidator = capped(v.array(v.string()), DETAIL_CAPS.authors);

Expand Down
2 changes: 2 additions & 0 deletions convex/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,8 @@ export default defineSchema({
.index("by_updatedAt_and_key", ["updatedAt", "key"])
// A workspace's reports that never went live, which go with it when it is deleted (workspaces/purge.ts).
.index("by_workspaceId_and_activatedAt", ["workspaceId", "activatedAt"])
// A person's own reports that never went live, wherever they are: Publish points to them from other workspaces (reports/flow.ts `waitingElsewhere`).
.index("by_ownerId_and_activatedAt", ["ownerId", "activatedAt"])
// Live reports by their titles, which Already published searches before anywhere else (reports/ownReports.ts): the
// very same title, in any script, and titles that share its words.
.index("by_status_and_title", ["status", "title"])
Expand Down
25 changes: 25 additions & 0 deletions convex/workspaces/lastUsed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// The organization a person last worked in, kept on their account for a browser that remembers nothing (proxy.ts).
import { describe, expect, it } from "vitest";
import { api } from "../_generated/api";
import { setup } from "../reports/reports.test-support";

describe("the workspace a person last worked in", () => {
it("is kept on their account, back to their own workspace too, and is forgotten once they leave the organization", async () => {
const { t, author, stranger } = await setup();
expect(await author.query(api.workspaces.lastUsed.get, {})).toBeNull();
await author.mutation(api.workspaces.lastUsed.remember, { slug: "lab" });
expect(await author.query(api.workspaces.lastUsed.get, {})).toBe("lab");
await author.mutation(api.workspaces.lastUsed.remember, { slug: null });
expect(await author.query(api.workspaces.lastUsed.get, {})).toBeNull();
// Someone who isn't a member is never sent there, whatever their account says.
await stranger.mutation(api.workspaces.lastUsed.remember, { slug: "lab" });
expect(await stranger.query(api.workspaces.lastUsed.get, {})).toBeNull();
// Nor is someone who left it.
await author.mutation(api.workspaces.lastUsed.remember, { slug: "lab" });
await t.run(async (ctx) => {
const membership = await ctx.db.query("organizationMemberships").filter((q) => q.eq(q.field("clerkUserId"), "author")).first();
await ctx.db.patch("organizationMemberships", membership!._id, { state: "revoked" });
});
expect(await author.query(api.workspaces.lastUsed.get, {})).toBeNull();
});
});
39 changes: 39 additions & 0 deletions convex/workspaces/lastUsed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// The organization a person last worked in, kept on their account (users.lastWorkspace) as well as in each browser's
// cookie (lib/workspaces/look-cache.ts): a browser that has never been used, or has been cleared, asks here, so the
// person starts where they left off on another device rather than in their own workspace (proxy.ts).
import { v } from "convex/values";
import { mutation, query } from "../lib/functions";
import { getCurrentUser } from "../lib/auth";
import { createError } from "../lib/errors";
import { actorIn } from "./actor";
import { organizationAt } from "../organizations/read";

/** Slugs are short; a longer one isn't an organization's address. */
const SLUG_MAX = 200;

/** The slug of the organization the person last worked in, while they are still its member; null for their own workspace. */
export const get = query({
args: {},
returns: v.union(v.string(), v.null()),
handler: async (ctx) => {
const user = await getCurrentUser(ctx);
const slug = user?.lastWorkspace;
if (!user || !slug) return null;
const organization = await organizationAt(ctx, slug);
const workspace = organization && (await ctx.db.query("workspaces").withIndex("by_organizationId", (q) => q.eq("organizationId", organization._id)).unique());
return workspace && (await actorIn(ctx, user, workspace._id)) ? slug : null;
},
});

/** Keeps the workspace a page was opened in as the one the person last worked in: an organization by its slug, or null for their own. */
export const remember = mutation({
args: { slug: v.union(v.string(), v.null()) },
returns: v.null(),
handler: async (ctx, { slug }) => {
const user = await getCurrentUser(ctx);
if (!user) return null;
if (slug !== null && (!slug || slug.length > SLUG_MAX)) throw createError("VALIDATION_ERROR", "That isn't an organization's address.");
if ((user.lastWorkspace ?? null) !== slug) await ctx.db.patch("users", user._id, { lastWorkspace: slug ?? undefined });
return null;
},
});
Loading
Loading