mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-11 05:11:49 +01:00
feat: paginate company invite history
This commit is contained in:
1 parent
9604dc447e
commit
2a3910190f
10 files changed
+423
-150
No files matched your search
@@ -0,0 +1,164 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { companies, createDb, invites, joinRequests } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { accessRoutes } from "../routes/access.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
|
||||
vi.mock("../services/index.js", () => ({
|
||||
accessService: () => ({
|
||||
isInstanceAdmin: vi.fn(),
|
||||
canUser: vi.fn(),
|
||||
hasPermission: vi.fn(),
|
||||
}),
|
||||
agentService: () => ({
|
||||
getById: vi.fn(),
|
||||
}),
|
||||
boardAuthService: () => ({
|
||||
createChallenge: vi.fn(),
|
||||
resolveBoardAccess: vi.fn(),
|
||||
assertCurrentBoardKey: vi.fn(),
|
||||
revokeBoardApiKey: vi.fn(),
|
||||
}),
|
||||
deduplicateAgentName: vi.fn(),
|
||||
logActivity: vi.fn(),
|
||||
notifyHireApproved: vi.fn(),
|
||||
}));
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping embedded Postgres invite list route tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
||||
);
|
||||
}
|
||||
|
||||
describeEmbeddedPostgres("GET /companies/:companyId/invites", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
let companyId!: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-invite-list-route-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 20_000);
|
||||
|
||||
beforeEach(async () => {
|
||||
companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(joinRequests);
|
||||
await db.delete(invites);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
function createApp(currentCompanyId: string) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).actor = {
|
||||
type: "board",
|
||||
source: "local_implicit",
|
||||
userId: null,
|
||||
companyIds: [currentCompanyId],
|
||||
};
|
||||
next();
|
||||
});
|
||||
app.use(
|
||||
"/api",
|
||||
accessRoutes(db, {
|
||||
deploymentMode: "local_trusted",
|
||||
deploymentExposure: "private",
|
||||
bindHost: "127.0.0.1",
|
||||
allowedHostnames: [],
|
||||
}),
|
||||
);
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
it("returns invite history in descending pages with nextOffset", async () => {
|
||||
const inviteOneId = randomUUID();
|
||||
const inviteTwoId = randomUUID();
|
||||
const inviteThreeId = randomUUID();
|
||||
|
||||
await db.insert(invites).values([
|
||||
{
|
||||
id: inviteOneId,
|
||||
companyId,
|
||||
inviteType: "company_join",
|
||||
tokenHash: "invite-token-1",
|
||||
allowedJoinTypes: "human",
|
||||
defaultsPayload: { humanRole: "viewer" },
|
||||
expiresAt: new Date("2026-04-20T00:00:00.000Z"),
|
||||
createdAt: new Date("2026-04-10T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-04-10T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: inviteTwoId,
|
||||
companyId,
|
||||
inviteType: "company_join",
|
||||
tokenHash: "invite-token-2",
|
||||
allowedJoinTypes: "human",
|
||||
defaultsPayload: { humanRole: "operator" },
|
||||
expiresAt: new Date("2026-04-21T00:00:00.000Z"),
|
||||
createdAt: new Date("2026-04-11T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-04-11T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: inviteThreeId,
|
||||
companyId,
|
||||
inviteType: "company_join",
|
||||
tokenHash: "invite-token-3",
|
||||
allowedJoinTypes: "human",
|
||||
defaultsPayload: { humanRole: "admin" },
|
||||
expiresAt: new Date("2026-04-22T00:00:00.000Z"),
|
||||
createdAt: new Date("2026-04-12T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-04-12T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await db.insert(joinRequests).values({
|
||||
id: randomUUID(),
|
||||
inviteId: inviteThreeId,
|
||||
companyId,
|
||||
requestType: "human",
|
||||
status: "pending_approval",
|
||||
requestIp: "127.0.0.1",
|
||||
requestEmailSnapshot: "person@example.com",
|
||||
createdAt: new Date("2026-04-12T00:05:00.000Z"),
|
||||
updatedAt: new Date("2026-04-12T00:05:00.000Z"),
|
||||
});
|
||||
|
||||
const app = createApp(companyId);
|
||||
|
||||
const firstPage = await request(app).get(`/api/companies/${companyId}/invites?limit=2`);
|
||||
|
||||
expect(firstPage.status).toBe(200);
|
||||
expect(firstPage.body.invites).toHaveLength(2);
|
||||
expect(firstPage.body.invites.map((invite: { id: string }) => invite.id)).toEqual([inviteThreeId, inviteTwoId]);
|
||||
expect(firstPage.body.invites[0].relatedJoinRequestId).toBeTruthy();
|
||||
expect(firstPage.body.nextOffset).toBe(2);
|
||||
|
||||
const secondPage = await request(app).get(`/api/companies/${companyId}/invites?limit=2&offset=2`);
|
||||
|
||||
expect(secondPage.status).toBe(200);
|
||||
expect(secondPage.body.invites).toHaveLength(1);
|
||||
expect(secondPage.body.invites[0].id).toBe(inviteOneId);
|
||||
expect(secondPage.body.nextOffset).toBeNull();
|
||||
});
|
||||
});
|
||||
+74
-26
@@ -9,7 +9,7 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Router } from "express";
|
||||
import type { Request } from "express";
|
||||
import { and, desc, eq, inArray, isNull } from "drizzle-orm";
|
||||
import { and, desc, eq, gt, inArray, isNotNull, isNull, lte } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
assets,
|
||||
@@ -1033,25 +1033,74 @@ async function loadCompanyMemberRecords(db: Db, companyId: string) {
|
||||
}));
|
||||
}
|
||||
|
||||
async function loadCompanyInviteRecords(db: Db, companyId: string) {
|
||||
function inviteStateWhereClause(
|
||||
state: "active" | "accepted" | "expired" | "revoked" | undefined,
|
||||
) {
|
||||
const now = new Date();
|
||||
switch (state) {
|
||||
case "active":
|
||||
return and(
|
||||
isNull(invites.revokedAt),
|
||||
isNull(invites.acceptedAt),
|
||||
gt(invites.expiresAt, now),
|
||||
);
|
||||
case "accepted":
|
||||
return isNotNull(invites.acceptedAt);
|
||||
case "expired":
|
||||
return and(
|
||||
isNull(invites.revokedAt),
|
||||
isNull(invites.acceptedAt),
|
||||
lte(invites.expiresAt, now),
|
||||
);
|
||||
case "revoked":
|
||||
return isNotNull(invites.revokedAt);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCompanyInviteRecords(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
options: {
|
||||
state?: "active" | "accepted" | "expired" | "revoked";
|
||||
limit: number;
|
||||
offset: number;
|
||||
},
|
||||
) {
|
||||
const whereClause = inviteStateWhereClause(options.state);
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(invites)
|
||||
.where(eq(invites.companyId, companyId))
|
||||
.orderBy(desc(invites.createdAt));
|
||||
.where(whereClause ? and(eq(invites.companyId, companyId), whereClause) : eq(invites.companyId, companyId))
|
||||
.orderBy(desc(invites.createdAt))
|
||||
.limit(options.limit + 1)
|
||||
.offset(options.offset);
|
||||
const hasMore = rows.length > options.limit;
|
||||
const visibleRows = hasMore ? rows.slice(0, options.limit) : rows;
|
||||
const userIds = [
|
||||
...new Set(
|
||||
rows
|
||||
visibleRows
|
||||
.map((invite) => invite.invitedByUserId)
|
||||
.filter((value): value is string => Boolean(value)),
|
||||
),
|
||||
];
|
||||
const [userMap, joinRows, companyName] = await Promise.all([
|
||||
loadUsersById(db, userIds),
|
||||
db
|
||||
.select({ id: joinRequests.id, inviteId: joinRequests.inviteId })
|
||||
.from(joinRequests)
|
||||
.where(eq(joinRequests.companyId, companyId)),
|
||||
visibleRows.length
|
||||
? db
|
||||
.select({ id: joinRequests.id, inviteId: joinRequests.inviteId })
|
||||
.from(joinRequests)
|
||||
.where(
|
||||
and(
|
||||
eq(joinRequests.companyId, companyId),
|
||||
inArray(
|
||||
joinRequests.inviteId,
|
||||
visibleRows.map((invite) => invite.id),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Promise.resolve([]),
|
||||
db
|
||||
.select({ name: companies.name })
|
||||
.from(companies)
|
||||
@@ -1062,17 +1111,20 @@ async function loadCompanyInviteRecords(db: Db, companyId: string) {
|
||||
joinRows.map((row: { inviteId: string; id: string }) => [row.inviteId, row.id]),
|
||||
);
|
||||
|
||||
return rows.map((invite) => ({
|
||||
...invite,
|
||||
companyName,
|
||||
humanRole: extractInviteHumanRole(invite),
|
||||
inviteMessage: extractInviteMessage(invite),
|
||||
state: inviteState(invite),
|
||||
invitedByUser: invite.invitedByUserId
|
||||
? userMap.get(invite.invitedByUserId) ?? null
|
||||
: null,
|
||||
relatedJoinRequestId: joinRequestIdByInviteId.get(invite.id) ?? null,
|
||||
}));
|
||||
return {
|
||||
invites: visibleRows.map((invite) => ({
|
||||
...invite,
|
||||
companyName,
|
||||
humanRole: extractInviteHumanRole(invite),
|
||||
inviteMessage: extractInviteMessage(invite),
|
||||
state: inviteState(invite),
|
||||
invitedByUser: invite.invitedByUserId
|
||||
? userMap.get(invite.invitedByUserId) ?? null
|
||||
: null,
|
||||
relatedJoinRequestId: joinRequestIdByInviteId.get(invite.id) ?? null,
|
||||
})),
|
||||
nextOffset: hasMore ? options.offset + options.limit : null,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadJoinRequestRecords(db: Db, companyId: string) {
|
||||
@@ -3110,12 +3162,8 @@ export function accessRoutes(
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyPermission(req, companyId, "users:invite");
|
||||
const query = listCompanyInvitesQuerySchema.parse(req.query);
|
||||
const invitesForCompany = await loadCompanyInviteRecords(db, companyId);
|
||||
res.json(
|
||||
invitesForCompany.filter((invite) =>
|
||||
query.state ? invite.state === query.state : true,
|
||||
),
|
||||
);
|
||||
const invitesForCompany = await loadCompanyInviteRecords(db, companyId, query);
|
||||
res.json(invitesForCompany);
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/join-requests", async (req, res) => {
|
||||
|
||||
Reference in new issue
Block a user