mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
fix(dashboard): scope areas and responsibilities to each user (#22513)
This commit is contained in:
1 parent
558dbb0132
commit
856f14e507
68 files changed
+2708
-559
No files matched your search
@@ -212,6 +212,7 @@ describe("activity routes", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockAgentActionAuditService.list).toHaveBeenCalledWith({
|
||||
companyId: "company-1",
|
||||
dashboardUserId: "user-1",
|
||||
actorScope: "all",
|
||||
limit: 50,
|
||||
caseReadCondition,
|
||||
@@ -261,6 +262,7 @@ describe("activity routes", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockAgentActionAuditService.list).toHaveBeenCalledWith({
|
||||
companyId: "company-1",
|
||||
dashboardUserId: "user-1",
|
||||
actorScope: "all",
|
||||
actorType: "system",
|
||||
limit: 50,
|
||||
@@ -284,6 +286,7 @@ describe("activity routes", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockActivityService.list).toHaveBeenCalledWith({
|
||||
companyId: "company-1",
|
||||
dashboardUserId: "user-1",
|
||||
agentId: undefined,
|
||||
entityType: undefined,
|
||||
entityId: undefined,
|
||||
@@ -304,6 +307,7 @@ describe("activity routes", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockActivityService.list).toHaveBeenCalledWith({
|
||||
companyId: "company-1",
|
||||
dashboardUserId: "user-1",
|
||||
agentId: undefined,
|
||||
entityType: "issue",
|
||||
entityId: undefined,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import request from "supertest";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
@@ -214,6 +215,31 @@ describeEmbeddedPostgres("issue access grant and locked edge routes", { concurre
|
||||
};
|
||||
}
|
||||
|
||||
it("protects personal dashboard conversations from break-glass and title writes by teammates", async () => {
|
||||
const fixture = await seedFixture();
|
||||
const issueId = fixture.privateIssueId;
|
||||
await db.update(issues).set({
|
||||
originKind: "responsibility_dashboard",
|
||||
originId: fixture.ownerId,
|
||||
projectId: null,
|
||||
}).where(eq(issues.id, issueId));
|
||||
const owner = await createApp(db, boardActor(fixture.companyId, fixture.ownerId));
|
||||
const admin = await createApp(db, boardActor(fixture.companyId, fixture.adminId));
|
||||
const member = await createApp(db, boardActor(fixture.companyId, fixture.memberId));
|
||||
|
||||
await request(admin).get(`/api/issues/${issueId}?breakGlass=true&view=core`).expect(404);
|
||||
await request(member).put(`/api/issues/${issueId}/title`).send({ title: "Another title" }).expect(404);
|
||||
await request(member).put(`/api/issues/${issueId}/title`).send({
|
||||
title: "Another title", onlyIfProvisional: true,
|
||||
}).expect(404);
|
||||
await request(admin).post(`/api/issues/${issueId}/admin/force-release`).expect(404);
|
||||
const original = await request(owner).get(`/api/issues/${issueId}?view=core`).expect(200);
|
||||
expect(original.body.title).toBe("Confidential root");
|
||||
const renamed = await request(owner).put(`/api/issues/${issueId}/title`).send({ title: "My dashboard" }).expect(200);
|
||||
expect(renamed.body.title).toBe("My dashboard");
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "issue.break_glass_read"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("requires explicit owner/admin break-glass and records both audit evidence and an owner-visible notice", async () => {
|
||||
const fixture = await seedFixture();
|
||||
const adminApp = await createApp(db, boardActor(fixture.companyId, fixture.adminId));
|
||||
|
||||
@@ -240,12 +240,11 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect(created.status).toBe(201);
|
||||
expect(created.body).toMatchObject({ ownerUserId: OWNER, status: "active" });
|
||||
|
||||
// A named owner still wins, and a run that works for no person must name one.
|
||||
// A caller-supplied owner cannot change the verified dashboard.
|
||||
const other = await request(forOwner).get(`/api/companies/${company.id}/responsibilities?ownerUserId=other-user`);
|
||||
expect(other.body.ownerUserId).toBe("other-user");
|
||||
expect(other.status).toBe(404);
|
||||
const unbound = await request(createApp(db, agentActor(company.id, agent.id))).get(`/api/companies/${company.id}/responsibilities`);
|
||||
expect(unbound.status).toBe(422);
|
||||
expect(unbound.body.error).toContain("this run works for no person");
|
||||
expect(unbound.status).toBe(403);
|
||||
});
|
||||
|
||||
it("refuses a half-filled bar, and derives status from the metric", async () => {
|
||||
@@ -367,68 +366,22 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect(halfAgain.status).toBe(422);
|
||||
});
|
||||
|
||||
it("lets agents only propose, and confirming activates a proposed area in the same step", async () => {
|
||||
it("keeps proposals inside the directing person's dashboard and activates their area on confirmation", async () => {
|
||||
await enable();
|
||||
const company = await seedCompany();
|
||||
const guide = await seedAgent(company.id);
|
||||
const agentApp = createApp(db, agentActor(company.id, guide.id));
|
||||
const boardApp = createApp(db, localBoardActor());
|
||||
|
||||
const area = await request(agentApp).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Fundraising", status: "active" });
|
||||
expect(area.status).toBe(201);
|
||||
expect(area.body).toMatchObject({ status: "proposed", source: "onboarding", proposedByAgentId: guide.id });
|
||||
|
||||
expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Pipeline", ...METRIC })).status).toBe(422);
|
||||
expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "Pipeline", ...METRIC, ownerUserId: "stranger" })).status).toBe(404);
|
||||
// An agent always proposes the whole bar: a title alone, or the sentence alone, is refused.
|
||||
expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "Pipeline", ownerUserId: OWNER })).status).toBe(400);
|
||||
expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "Pipeline", ownerUserId: OWNER, standard: METRIC.standard })).status).toBe(400);
|
||||
expect((await request(agentApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "Pipeline", ownerUserId: OWNER, standard: METRIC.standard, metricName: METRIC.metricName })).status).toBe(400);
|
||||
|
||||
const proposed = await request(agentApp).post(`/api/companies/${company.id}/responsibilities`).send({
|
||||
title: "Pipeline",
|
||||
...METRIC,
|
||||
ownerUserId: OWNER,
|
||||
areaId: area.body.id,
|
||||
status: "active",
|
||||
evidence: "Three pipeline reviews on the calendar every week",
|
||||
});
|
||||
expect(proposed.status).toBe(201);
|
||||
expect(proposed.body).toMatchObject({ status: "proposed", source: "onboarding", proposedByAgentId: guide.id, confirmedAt: null, areaId: area.body.id });
|
||||
|
||||
const listed = await request(agentApp).get(`/api/companies/${company.id}/responsibilities?ownerUserId=${OWNER}`);
|
||||
expect(listed.body.proposed.map((row: { id: string }) => row.id)).toEqual([proposed.body.id]);
|
||||
// A proposed area a returned responsibility references is included.
|
||||
expect(listed.body.areas.map((row: { id: string; status: string }) => [row.id, row.status])).toEqual([[area.body.id, "proposed"]]);
|
||||
|
||||
expect((await request(agentApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ status: "active" })).status).toBe(403);
|
||||
const edited = await request(agentApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ title: "Deal pipeline" });
|
||||
expect(edited.status).toBe(200);
|
||||
|
||||
const confirmed = await request(boardApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ status: "active" });
|
||||
expect(confirmed.status).toBe(200);
|
||||
expect(confirmed.body.confirmedAt).not.toBeNull();
|
||||
const [areaRow] = await db.select().from(responsibilityAreas).where(eq(responsibilityAreas.id, area.body.id));
|
||||
expect(areaRow?.status).toBe("active");
|
||||
const logged = await actions(company.id);
|
||||
expect(logged).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ action: "responsibility_area.created", entityId: area.body.id }),
|
||||
expect.objectContaining({ action: "responsibility_area.activated", entityId: area.body.id }),
|
||||
]));
|
||||
|
||||
// Once confirmed, the agent can no longer edit it (beyond the metric) and cannot delete it.
|
||||
expect((await request(agentApp).patch(`/api/responsibilities/${proposed.body.id}`).send({ title: "x" })).status).toBe(403);
|
||||
expect((await request(agentApp).delete(`/api/responsibilities/${proposed.body.id}`)).status).toBe(403);
|
||||
|
||||
const dismissible = await request(agentApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "Portfolio", ...METRIC, ownerUserId: OWNER });
|
||||
const dismissed = await request(agentApp).patch(`/api/responsibilities/${dismissible.body.id}`).send({ status: "dismissed" });
|
||||
expect(dismissed.status).toBe(200);
|
||||
expect(dismissed.body.status).toBe("dismissed");
|
||||
const agent = await actingAgent(company.id, guide.id);
|
||||
const unbound = createApp(db, agentActor(company.id, guide.id));
|
||||
const board = createApp(db, localBoardActor());
|
||||
const path = `/api/companies/${company.id}/responsibilities`;
|
||||
const areas = `/api/companies/${company.id}/responsibility-areas`;
|
||||
await request(unbound).post(areas).send({ title: "Fundraising" }).expect(403);
|
||||
await request(unbound).post(path).send({ title: "Pipeline", ...METRIC, ownerUserId: OWNER }).expect(403);
|
||||
const area = (await request(agent).post(areas).send({ title: "Fundraising", status: "proposed" }).expect(201)).body;
|
||||
const item = (await request(agent).post(path).send({ title: "Pipeline", ...METRIC, areaId: area.id, status: "proposed" }).expect(201)).body;
|
||||
expect((await request(board).get(path)).body.proposed.map((r: Created) => r.id)).toEqual([item.id]);
|
||||
await request(board).patch(`/api/responsibilities/${item.id}`).send({ status: "active" }).expect(200);
|
||||
expect((await request(board).get(areas)).body[0]).toMatchObject({ id: area.id, status: "active" });
|
||||
});
|
||||
|
||||
it("lets only the running or assigned agent report the metric on an active responsibility", async () => {
|
||||
@@ -474,16 +427,16 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect((await actions(company.id)).some((entry) => entry.action === "responsibility.updated")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps board users to their own responsibilities unless they administer the company", async () => {
|
||||
it("keeps board users to their own responsibilities including company administrators", async () => {
|
||||
await enable();
|
||||
const company = await seedCompany();
|
||||
const ownerApp = createApp(db, localBoardActor());
|
||||
const area = await createResponsibility(ownerApp, company.id);
|
||||
const operatorApp = createApp(db, sessionBoardActor(company.id, "other-user"));
|
||||
expect((await request(operatorApp).get(`/api/responsibilities/${area.id}`)).status).toBe(200);
|
||||
expect((await request(operatorApp).patch(`/api/responsibilities/${area.id}`).send({ title: "Mine now" })).status).toBe(403);
|
||||
expect((await request(operatorApp).get(`/api/responsibilities/${area.id}`)).status).toBe(404);
|
||||
expect((await request(operatorApp).patch(`/api/responsibilities/${area.id}`).send({ title: "Mine now" })).status).toBe(404);
|
||||
expect((await request(operatorApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "For someone else", ...METRIC, ownerUserId: OWNER })).status).toBe(403);
|
||||
.send({ title: "For someone else", ...METRIC, ownerUserId: OWNER })).status).toBe(404);
|
||||
const own = await createResponsibility(operatorApp, company.id, { title: "Ops" });
|
||||
expect(own.ownerUserId).toBe("other-user");
|
||||
});
|
||||
@@ -519,7 +472,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect((await request(boardApp).patch(`/api/responsibilities/${area.id}`).send({ areaId: otherArea.body.id })).status).toBe(404);
|
||||
expect((await request(boardApp).post(`/api/companies/${company.id}/responsibilities`)
|
||||
.send({ title: "x", ...METRIC, runByAgentId: otherAgent.id })).status).toBe(404);
|
||||
expect((await request(boardApp).patch(`/api/responsibility-areas/${otherArea.body.id}`).send({ title: "Mine" })).status).toBe(200);
|
||||
expect((await request(boardApp).patch(`/api/responsibility-areas/${otherArea.body.id}`).send({ title: "Mine" })).status).toBe(404);
|
||||
expect((await request(createApp(db, sessionBoardActor(company.id, OWNER, "owner")))
|
||||
.patch(`/api/responsibility-areas/${otherArea.body.id}`).send({ title: "Mine" })).status).toBe(404);
|
||||
expect(await db.select().from(responsibilityLinks).where(eq(responsibilityLinks.companyId, company.id))).toHaveLength(0);
|
||||
@@ -622,8 +575,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
const guide = await seedAgent(company.id);
|
||||
const agentLookup = await request(createApp(db, agentActor(company.id, guide.id)))
|
||||
.get(`/api/companies/${company.id}/responsibility-links/lookup?issueId=${task.id}`);
|
||||
expect(agentLookup.status).toBe(200);
|
||||
expect(agentLookup.body.responsibilities).toHaveLength(2);
|
||||
expect(agentLookup.status).toBe(403);
|
||||
});
|
||||
|
||||
it("manages areas: idempotent create, board-only edits, delete keeps responsibilities", async () => {
|
||||
@@ -641,17 +593,17 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect(same.status).toBe(200);
|
||||
expect(same.body.id).toBe(created.body.id);
|
||||
const agentSame = await request(agentApp).post(areasPath).send({ title: "FUNDRAISING" });
|
||||
expect(agentSame.status).toBe(200);
|
||||
expect(agentSame.body).toMatchObject({ id: created.body.id, status: "active" });
|
||||
const customers = await request(agentApp).post(areasPath).send({ title: "Customers" });
|
||||
expect(agentSame.status).toBe(403);
|
||||
const customers = await request(boardApp).post(areasPath).send({ title: "Customers", status: "proposed" });
|
||||
expect(customers.body.status).toBe("proposed");
|
||||
|
||||
expect((await request(agentApp).patch(`/api/responsibility-areas/${created.body.id}`).send({ title: "x" })).status).toBe(403);
|
||||
expect((await request(agentApp).delete(`/api/responsibility-areas/${created.body.id}`)).status).toBe(403);
|
||||
expect((await request(createApp(db, sessionBoardActor(company.id, "viewer", "viewer"))).post(areasPath).send({ title: "Viewers" })).status).toBe(403);
|
||||
// Any board user with write access manages areas: they have no owner.
|
||||
// The owner alone can activate the area.
|
||||
const operatorApp = createApp(db, sessionBoardActor(company.id, "other-user"));
|
||||
expect((await request(operatorApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ status: "active", sortOrder: 2 })).status).toBe(200);
|
||||
expect((await request(operatorApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ status: "active", sortOrder: 2 })).status).toBe(404);
|
||||
await request(boardApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ status: "active", sortOrder: 2 }).expect(200);
|
||||
|
||||
const clash = await request(boardApp).patch(`/api/responsibility-areas/${customers.body.id}`).send({ title: "fundraising" });
|
||||
expect(clash.status).toBe(409);
|
||||
@@ -1049,7 +1001,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect(unfiled.body.unfiled).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("may not change what the person could not, and stays propose-only without a person", async () => {
|
||||
it("may not change what the person could not, and needs a directing person for proposals", async () => {
|
||||
await enable();
|
||||
const company = await seedCompany();
|
||||
const agent = await seedAgent(company.id);
|
||||
@@ -1058,21 +1010,15 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
|
||||
// An operator may not manage the owner's responsibilities, so neither may an agent acting for one.
|
||||
const forOperator = await actingAgent(company.id, agent.id, "other-user", "operator");
|
||||
expect((await request(forOperator).patch(`/api/responsibilities/${mine.id}`).send({ title: "x" })).status).toBe(403);
|
||||
expect((await request(forOperator).post(`/api/responsibilities/${mine.id}/file`).send({ items: [{ kind: "routine", id: randomUUID() }], moveFrom: "all" })).status).toBe(403);
|
||||
expect((await request(forOperator).patch(`/api/responsibilities/${mine.id}`).send({ title: "x" })).status).toBe(404);
|
||||
expect((await request(forOperator).post(`/api/responsibilities/${mine.id}/file`).send({ items: [{ kind: "routine", id: randomUUID() }], moveFrom: "all" })).status).toBe(404);
|
||||
|
||||
const alone = createApp(db, agentActor(company.id, agent.id));
|
||||
expect((await request(alone).patch(`/api/responsibility-areas/${randomUUID()}`).send({ title: "x" })).status).toBe(404);
|
||||
const area = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "People" });
|
||||
expect((await request(alone).patch(`/api/responsibility-areas/${area.body.id}`).send({ title: "x" })).status).toBe(403);
|
||||
const proposal = await request(alone).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Ops", ownerUserId: OWNER, ...METRIC });
|
||||
expect(proposal.body.status).toBe("proposed");
|
||||
// Filing under its proposal works as with /links (what create_responsibility's fileItems does); moving does not.
|
||||
const routine = await db.insert(routines).values({ companyId: company.id, title: "Weekly ops" }).returning().then((r) => r[0]!);
|
||||
const filed = await request(alone).post(`/api/responsibilities/${proposal.body.id}/file`).send({ items: [{ kind: "routine", id: routine.id }] });
|
||||
expect(filed.status).toBe(200);
|
||||
expect(filed.headers["x-paperclip-dashboard-version"]).toBeUndefined();
|
||||
expect((await request(alone).post(`/api/responsibilities/${proposal.body.id}/file`).send({ items: [{ kind: "routine", id: routine.id }], moveFrom: mine.id })).status).toBe(403);
|
||||
expect(proposal.status).toBe(403);
|
||||
});
|
||||
|
||||
it("does not borrow the authority of a person someone else named, or of the company default", async () => {
|
||||
@@ -1097,7 +1043,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect((await request(app).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Ops" })).status).toBe(400);
|
||||
}
|
||||
const proposal = await request(noTask).post(`/api/companies/${company.id}/responsibilities`).send({ title: "Ops", ...METRIC });
|
||||
expect(proposal.body).toMatchObject({ ownerUserId: OWNER, status: "proposed" });
|
||||
expect(proposal.status).toBe(403);
|
||||
const [row] = await db.select().from(responsibilities).where(eq(responsibilities.id, mine.id));
|
||||
expect(row?.status).toBe("active");
|
||||
});
|
||||
@@ -1248,30 +1194,12 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect(areaRow?.description).toBe("Who we hire");
|
||||
});
|
||||
|
||||
it("reports no Undo for a shared area's new description, and Undo of a delete brings the description back", async () => {
|
||||
it("restores the private area description after a confirmed deletion", async () => {
|
||||
await enable();
|
||||
const company = await seedCompany();
|
||||
const agent = await seedAgent(company.id);
|
||||
const app = await actingAgent(company.id, agent.id);
|
||||
const board = createApp(db, localBoardActor());
|
||||
const shared = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "People", description: "Who we hire" });
|
||||
await createResponsibility(board, company.id, { title: "Hiring", areaId: shared.body.id });
|
||||
// The other person's responsibility there is only proposed; the area is still shared.
|
||||
const other = await createResponsibility(board, company.id, { title: "Onboarding", areaId: shared.body.id, ownerUserId: "other-user" });
|
||||
await db.update(responsibilities).set({ status: "proposed" }).where(eq(responsibilities.id, other.id));
|
||||
const before = await latestVersion(company.id);
|
||||
const described = await request(app).patch(`/api/responsibility-areas/${shared.body.id}`).send({ description: "Hiring and onboarding" });
|
||||
expect(described.status).toBe(200);
|
||||
expect(described.headers["x-paperclip-dashboard-version"]).toBeUndefined();
|
||||
// No version is saved, so no Dashboard offers an Undo that would leave the description as it is.
|
||||
expect((await latestVersion(company.id))?.id).toBe(before?.id);
|
||||
// Nor for a shared area's status change Undo cannot reverse, such as confirming a proposed area.
|
||||
await db.update(responsibilityAreas).set({ status: "proposed" }).where(eq(responsibilityAreas.id, shared.body.id));
|
||||
const confirmed = await request(app).patch(`/api/responsibility-areas/${shared.body.id}`).send({ status: "active" });
|
||||
expect(confirmed.status).toBe(200);
|
||||
expect(confirmed.headers["x-paperclip-dashboard-version"]).toBeUndefined();
|
||||
expect((await latestVersion(company.id))?.id).toBe(before?.id);
|
||||
|
||||
const mine = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Money", description: "Cash and runway" });
|
||||
await createResponsibility(board, company.id, { title: "Runway", areaId: mine.body.id });
|
||||
const [card] = await db.insert(issueThreadInteractions).values({
|
||||
@@ -1352,7 +1280,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
// An agent acting for an operator may not change the owner's active responsibility: no area is left behind.
|
||||
const refused = await request(await actingAgent(company.id, agent.id, "other-user", "operator"))
|
||||
.patch(`/api/responsibilities/${created.body.id}`).send({ areaTitle: "Elsewhere" });
|
||||
expect(refused.status).toBe(403);
|
||||
expect(refused.status).toBe(404);
|
||||
expect(await db.select().from(responsibilityAreas).where(eq(responsibilityAreas.title, "Elsewhere"))).toHaveLength(0);
|
||||
expect((await request(await actingAgent(company.id, agent.id)).patch(`/api/responsibilities/${created.body.id}`)
|
||||
.send({ areaTitle: "People", areaId: people!.id })).status).toBe(422);
|
||||
@@ -1374,14 +1302,14 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
expect(deleted.status).toBe(200);
|
||||
});
|
||||
|
||||
it("saves a version for everyone whose responsibilities an area delete moves", async () => {
|
||||
it("saves the moved responsibilities in the owner’s history", async () => {
|
||||
await enable();
|
||||
const company = await seedCompany();
|
||||
const agent = await seedAgent(company.id);
|
||||
const board = createApp(db, localBoardActor());
|
||||
const from = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Money" });
|
||||
const to = await request(board).post(`/api/companies/${company.id}/responsibility-areas`).send({ title: "Finance" });
|
||||
await createResponsibility(board, company.id, { title: "Runway", areaId: from.body.id, ownerUserId: "other-user" });
|
||||
await createResponsibility(board, company.id, { title: "Runway", areaId: from.body.id });
|
||||
const chat = await db.insert(issues).values({ companyId: company.id, title: "Chat", status: "in_progress", priority: "medium" }).returning().then((r) => r[0]!);
|
||||
const [card] = await db.insert(issueThreadInteractions).values({
|
||||
companyId: company.id, issueId: chat.id, kind: "request_confirmation", status: "accepted", createdByAgentId: agent.id,
|
||||
@@ -1391,7 +1319,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
|
||||
const removed = await request(await actingAgent(company.id, agent.id))
|
||||
.delete(`/api/responsibility-areas/${from.body.id}?confirmationId=${card!.id}&moveResponsibilitiesTo=${to.body.id}`);
|
||||
expect(removed.status).toBe(200);
|
||||
expect(await latestVersion(company.id, "other-user")).toMatchObject({ cause: "change_set", actorAgentId: agent.id });
|
||||
expect(await latestVersion(company.id, "other-user")).toBeNull();
|
||||
// The response names the acting person's version, not the other owner's.
|
||||
expect(removed.headers["x-paperclip-dashboard-owner"]).toBe(OWNER);
|
||||
expect(removed.headers["x-paperclip-dashboard-version"]).toBe((await latestVersion(company.id))?.id);
|
||||
|
||||
@@ -274,14 +274,14 @@ describeEmbeddedPostgres("automation conversations and standing checks", () => {
|
||||
expect(started.body.details?.code ?? started.body.code).toBe("routine_from_task_private");
|
||||
expect(await db.select().from(issues).where(eq(issues.originId, privateId))).toHaveLength(0);
|
||||
const [open] = await db.select().from(issues).where(eq(issues.id, (await start(seeded, seeded.tasks.weekly.id, { agentId: seeded.agents.analyst.id })).body.conversation.issueId));
|
||||
expect(open).toMatchObject({ visibility: "open" });
|
||||
expect(open).toMatchObject({ visibility: "private", responsibleUserId: OWNER });
|
||||
});
|
||||
|
||||
it("lets only the conversation's agent propose, validates, keeps one pending, and creates nothing", async () => {
|
||||
const seeded = await seed();
|
||||
const started = await start(seeded, seeded.tasks.weekly.id, { agentId: seeded.agents.analyst.id });
|
||||
const issueId = started.body.conversation.issueId as string;
|
||||
expect((await propose(seeded, seeded.agents.watcher.id, issueId, SCHEDULE)).status).toBe(403);
|
||||
expect((await propose(seeded, seeded.agents.watcher.id, issueId, SCHEDULE)).status).toBe(404);
|
||||
expect((await request(seeded.app).post(`/api/issues/${issueId}/automation-proposals`).send(SCHEDULE)).status).toBe(403);
|
||||
expect((await propose(seeded, seeded.agents.analyst.id, seeded.tasks.weekly.id, SCHEDULE)).status).toBe(422);
|
||||
expect((await propose(seeded, seeded.agents.analyst.id, issueId, { ...SCHEDULE, trigger: { kind: "schedule", cadence: { frequency: "weekly", time: "16:00" } } })).status).toBe(400);
|
||||
@@ -318,9 +318,8 @@ describeEmbeddedPostgres("automation conversations and standing checks", () => {
|
||||
const before = row(await read(seeded), seeded.responsibilities.finance.id);
|
||||
expect(before).toMatchObject({ level: "manual", automationCount: 0, manualTaskCount: 3 });
|
||||
const { issueId, interactionId } = await proposed(seeded, seeded.tasks.weekly.id, seeded.agents.analyst.id, SCHEDULE);
|
||||
// A person without the assignment permission cannot accept.
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER)))
|
||||
.post(`/api/issues/${issueId}/automation-proposals/${interactionId}/accept`).send({ timezone: "UTC" })).status).toBe(403);
|
||||
.post(`/api/issues/${issueId}/automation-proposals/${interactionId}/accept`).send({ timezone: "UTC" })).status).toBe(404);
|
||||
|
||||
const accepts = await Promise.all([1, 2].map(() =>
|
||||
request(seeded.app).post(`/api/issues/${issueId}/automation-proposals/${interactionId}/accept`).send({ timezone: "America/New_York" })));
|
||||
|
||||
@@ -284,14 +284,14 @@ describeEmbeddedPostgres("responsibility automation read", () => {
|
||||
const seeded = await seed();
|
||||
// Agents name the person.
|
||||
const agent: Actor = { type: "agent", companyId: seeded.company.id, agentId: seeded.agent.id, source: "agent_jwt" };
|
||||
expect((await read(seeded.company.id, agent)).status).toBe(422);
|
||||
expect((await read(seeded.company.id, agent)).status).toBe(403);
|
||||
const asAgent = await read(seeded.company.id, agent, `?ownerUserId=${OWNER}`);
|
||||
expect(asAgent.status).toBe(200);
|
||||
expect(asAgent.body.responsibilities).toHaveLength(4);
|
||||
expect(asAgent.status).toBe(403);
|
||||
expect(asAgent.body.responsibilities).toBeUndefined();
|
||||
|
||||
// Another person's dashboard by ownerUserId.
|
||||
const theirs = await read(seeded.company.id, boardActor(), "?ownerUserId=someone-else");
|
||||
expect(theirs.body.responsibilities.map((item: ResponsibilityAutomation) => item.responsibilityId)).toEqual([seeded.responsibilities.someoneElse.id]);
|
||||
expect(theirs.status).toBe(404);
|
||||
|
||||
// A board user from outside the company cannot read it.
|
||||
const outsider: Actor = {
|
||||
|
||||
@@ -292,7 +292,7 @@ describeEmbeddedPostgres("responsibility bar templates and bar conversations", (
|
||||
it("lets only the agent in the conversation propose, validates the bar, and writes nothing to the responsibility", async () => {
|
||||
const seeded = await seed();
|
||||
const issueId = (await startConversation(seeded)).body.conversation.issueId as string;
|
||||
expect((await propose(seeded.company.id, seeded.analyst.id, issueId)).status).toBe(403);
|
||||
expect((await propose(seeded.company.id, seeded.analyst.id, issueId)).status).toBe(404);
|
||||
expect((await request(seeded.app).post(`/api/issues/${issueId}/bar-proposals`).send(RANGE_PROPOSAL)).status).toBe(403);
|
||||
// An agent from another company cannot reach it.
|
||||
const elsewhere = await seed();
|
||||
@@ -356,11 +356,11 @@ describeEmbeddedPostgres("responsibility bar templates and bar conversations", (
|
||||
const accept = (actor: Actor) => request(createApp(actor)).post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/accept`).send({});
|
||||
|
||||
expect((await accept(agentActor(seeded.company.id, seeded.ceo.id))).status).toBe(403);
|
||||
expect((await accept(sessionBoardActor(seeded.company.id, OTHER))).status).toBe(403);
|
||||
// An admin who does not own it may.
|
||||
const res = await accept(sessionBoardActor(seeded.company.id, OTHER, "admin"));
|
||||
expect((await accept(sessionBoardActor(seeded.company.id, OTHER))).status).toBe(404);
|
||||
await accept(sessionBoardActor(seeded.company.id, OTHER, "admin")).expect(404);
|
||||
const res = await accept(localBoardActor());
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.interaction).toMatchObject({ status: "accepted", resolvedByUserId: OTHER, result: { outcome: "accepted", responsibilityId: seeded.responsibility.id } });
|
||||
expect(res.body.interaction).toMatchObject({ status: "accepted", resolvedByUserId: OWNER, result: { outcome: "accepted", responsibilityId: seeded.responsibility.id } });
|
||||
expect(res.body.responsibility).toMatchObject({
|
||||
id: seeded.responsibility.id,
|
||||
standard: RANGE_PROPOSAL.standard,
|
||||
@@ -404,7 +404,7 @@ describeEmbeddedPostgres("responsibility bar templates and bar conversations", (
|
||||
const issueId = (await startConversation(seeded)).body.conversation.issueId as string;
|
||||
const offered = await propose(seeded.company.id, seeded.ceo.id, issueId);
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER)))
|
||||
.post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/decline`).send({})).status).toBe(403);
|
||||
.post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/decline`).send({})).status).toBe(404);
|
||||
const declined = await request(seeded.app).post(`/api/issues/${issueId}/bar-proposals/${offered.body.id}/decline`).send({});
|
||||
expect(declined.status).toBe(200);
|
||||
expect(declined.body).toMatchObject({ status: "rejected", result: { outcome: "declined" } });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
@@ -88,6 +89,54 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
await instanceSettingsService(db).updateExperimental({ enableResponsibilities: true });
|
||||
});
|
||||
|
||||
it("splits a previously shared area, preserves each owner's history and hides unattributed areas", async () => {
|
||||
const migration = readFileSync(new URL("../../../packages/db/src/migrations/0500_funny_malcolm_colcord.sql", import.meta.url), "utf8");
|
||||
await db.$client.begin(async (tx) => {
|
||||
await tx`set local search_path to pg_temp`;
|
||||
await tx.unsafe(`create temp table responsibility_areas (
|
||||
id uuid primary key, company_id uuid, title text, description text, status text default 'active',
|
||||
source text, proposed_by_agent_id uuid, sort_order integer, created_at timestamptz, updated_at timestamptz
|
||||
) on commit drop`);
|
||||
await tx`create unique index responsibility_areas_company_title_uq on responsibility_areas(company_id, lower(title))`;
|
||||
await tx`create temp table responsibilities (id uuid, company_id uuid, owner_user_id text, area_id uuid) on commit drop`;
|
||||
await tx`create temp table activity_log (company_id uuid, actor_type text, actor_id text, action text, entity_type text, entity_id text, details jsonb) on commit drop`;
|
||||
await tx`create temp table responsibility_dashboard_versions (company_id uuid, owner_user_id text, snapshot jsonb, snapshot_hash text) on commit drop`;
|
||||
await tx`create temp table issues (id uuid, company_id uuid, visibility text, privacy_root_issue_id uuid, responsible_user_id text, origin_id text, created_by_user_id text, origin_kind text) on commit drop`;
|
||||
await tx`create temp table issue_thread_interactions (company_id uuid, kind text, status text, payload jsonb) on commit drop`;
|
||||
const company = randomUUID();
|
||||
const shared = randomUUID();
|
||||
const empty = randomUUID();
|
||||
const unknown = randomUUID();
|
||||
await tx`insert into responsibility_areas (id, company_id, title) values
|
||||
(${shared}, ${company}, 'Operations'), (${empty}, ${company}, 'Future work'), (${unknown}, ${company}, 'Unattributed')`;
|
||||
await tx`insert into responsibilities values (gen_random_uuid(), ${company}, 'Alex', ${shared}), (gen_random_uuid(), ${company}, 'Blair', ${shared})`;
|
||||
await tx`insert into activity_log values (${company}, 'user', 'Alex', 'responsibility_area.created', 'responsibility_area', ${empty}, null)`;
|
||||
await tx`insert into responsibility_dashboard_versions values (${company}, 'Blair', ${JSON.stringify({
|
||||
areas: [{ id: shared, title: "Operations" }], responsibilities: [{ areaId: shared }], createdAreaIds: [shared],
|
||||
})}::jsonb, 'old')`;
|
||||
await tx`insert into issue_thread_interactions values (${company}, 'propose_dashboard_changes', 'pending', ${JSON.stringify({
|
||||
ownerUserId: "Blair", changes: [{ groupAreaId: shared, fromAreaId: shared }],
|
||||
})}::jsonb)`;
|
||||
// The old overview included every active area, even for a newcomer.
|
||||
expect(await tx`select id from responsibility_areas where company_id = ${company} and status = 'active'`).toHaveLength(3);
|
||||
for (const statement of migration.split("--> statement-breakpoint")) await tx.unsafe(statement);
|
||||
const rows = await tx`select r.owner_user_id as owner, a.id from responsibilities r
|
||||
join responsibility_areas a on a.id = r.area_id and r.owner_user_id = a.owner_user_id order by owner`;
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).toEqual({ owner: "Alex", id: shared });
|
||||
expect(rows[1].id).not.toBe(shared);
|
||||
const [proposal] = await tx`select payload from issue_thread_interactions`;
|
||||
expect(proposal.payload.changes).toEqual([{ groupAreaId: rows[1].id, fromAreaId: rows[1].id }]);
|
||||
const [version] = await tx`select snapshot from responsibility_dashboard_versions`;
|
||||
expect(version.snapshot).toMatchObject({
|
||||
areas: [{ id: rows[1].id, title: "Operations" }], responsibilities: [{ areaId: rows[1].id }], createdAreaIds: [rows[1].id],
|
||||
});
|
||||
expect(await tx`select id from responsibility_areas where owner_user_id = 'Alex' and id = ${empty}`).toHaveLength(1);
|
||||
expect(await tx`select id from responsibility_areas where owner_user_id is null`).toMatchObject([{ id: unknown }]);
|
||||
expect(await tx`select id from responsibility_areas where owner_user_id = 'New member'`).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
function createApp(actor: Actor) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
@@ -103,6 +152,23 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
return app;
|
||||
}
|
||||
|
||||
it("keeps two dashboards private when teammates create the same area", async () => {
|
||||
const { company, app } = await seed();
|
||||
const second = createApp(sessionBoardActor(company.id, OTHER, "owner"));
|
||||
const path = `/api/companies/${company.id}/responsibility-areas`;
|
||||
const overview = `/api/companies/${company.id}/responsibilities`;
|
||||
await db.insert(responsibilityAreas).values(Array.from({ length: 22 }, (_, i) => ({
|
||||
companyId: company.id, ownerUserId: OWNER, title: `Area ${i}`,
|
||||
})));
|
||||
expect((await request(second).get(overview).expect(200)).body.areas).toEqual([]);
|
||||
const mine = (await request(second).post(path).send({ title: "Area 0" }).expect(201)).body;
|
||||
const item = (await request(second).post(overview).send({ title: "Track operations", areaId: mine.id }).expect(201)).body;
|
||||
expect((await request(second).get(overview)).body.areas.map((area: { id: string }) => area.id)).toEqual([mine.id]);
|
||||
await request(app).get(`/api/responsibilities/${item.id}`).expect(404);
|
||||
await request(app).patch(`/api/responsibility-areas/${mine.id}`).send({ title: "Renamed" }).expect(404);
|
||||
expect((await request(app).get(overview)).body.areas).toHaveLength(22);
|
||||
});
|
||||
|
||||
async function seed(opts: { populated?: boolean } = {}) {
|
||||
const company = await db.insert(companies)
|
||||
.values({ name: "Dash Co", issuePrefix: `D${randomUUID().replace(/[^A-Z0-9]/gi, "").slice(0, 6).toUpperCase()}` })
|
||||
@@ -226,9 +292,9 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
const seeded = await seed({ populated: true });
|
||||
const url = `/api/companies/${seeded.company.id}/responsibility-dashboard`;
|
||||
const agentApp = createApp(agentActor(seeded.company.id, seeded.analyst.id));
|
||||
expect((await request(agentApp).get(url)).status).toBe(422);
|
||||
expect((await request(agentApp).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(200);
|
||||
expect((await request(agentApp).get(`${url}/versions?ownerUserId=${OWNER}`)).status).toBe(200);
|
||||
expect((await request(agentApp).get(url)).status).toBe(403);
|
||||
expect((await request(agentApp).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(403);
|
||||
expect((await request(agentApp).get(`${url}/versions?ownerUserId=${OWNER}`)).status).toBe(403);
|
||||
expect((await request(createApp(agentActor(randomUUID(), seeded.analyst.id))).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(403);
|
||||
// An agent's read never saves a version.
|
||||
expect(await versionsOf(seeded)).toHaveLength(0);
|
||||
@@ -313,14 +379,13 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
expect(second.body.conversation.issueId).not.toBe(issueId);
|
||||
});
|
||||
|
||||
it("lets only the person or an admin start it, and says so when no agent can hold it", async () => {
|
||||
it("lets only the dashboard owner start it, and says so when no agent can hold it", async () => {
|
||||
const seeded = await seed();
|
||||
expect((await start(seeded, { mode: "create", ownerUserId: OWNER }, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(403);
|
||||
expect((await start(seeded, { mode: "create", ownerUserId: OWNER }, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(404);
|
||||
expect((await start(seeded, { mode: "create" }, createApp(agentActor(seeded.company.id, seeded.ceo.id)))).status).toBe(403);
|
||||
// An admin may start one for someone else; their own dashboard is untouched.
|
||||
// Company administration grants no access to personal dashboards.
|
||||
const forOther = await start(seeded, { mode: "create", ownerUserId: OTHER });
|
||||
expect(forOther.status).toBe(201);
|
||||
expect(forOther.body.ownerUserId).toBe(OTHER);
|
||||
expect(forOther.status).toBe(404);
|
||||
expect((await start(seeded, { mode: "create", ownerUserId: "stranger" })).status).toBe(404);
|
||||
|
||||
const quiet = await seed();
|
||||
@@ -371,7 +436,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
it("lets only the conversation's agent propose, and writes nothing", async () => {
|
||||
const seeded = await seed();
|
||||
const issueId = (await start(seeded)).body.conversation.issueId as string;
|
||||
expect((await propose(seeded, issueId, FIRST_DASHBOARD, seeded.analyst.id)).status).toBe(403);
|
||||
expect((await propose(seeded, issueId, FIRST_DASHBOARD, seeded.analyst.id)).status).toBe(404);
|
||||
expect((await request(seeded.app).post(`/api/issues/${issueId}/dashboard-changes`).send(FIRST_DASHBOARD)).status).toBe(403);
|
||||
const elsewhere = await seed();
|
||||
expect((await request(createApp(agentActor(elsewhere.company.id, elsewhere.ceo.id))).post(`/api/issues/${issueId}/dashboard-changes`).send(FIRST_DASHBOARD)).status).toBe(404);
|
||||
@@ -402,8 +467,9 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
it("validates each kind of change against the dashboard", async () => {
|
||||
const seeded = await seed({ populated: true });
|
||||
const issueId = (await start(seeded, { mode: "edit" })).body.conversation.issueId as string;
|
||||
const [archived] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, title: "Old area", status: "archived" }).returning();
|
||||
const [theirs] = await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: seeded.areas.Hiring }).returning();
|
||||
const [archived] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, ownerUserId: OWNER, title: "Old area", status: "archived" }).returning();
|
||||
const [otherArea] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Hiring" }).returning();
|
||||
const [theirs] = await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: otherArea!.id }).returning();
|
||||
const fails = async (changes: object[], status: number, words?: string) => {
|
||||
const res = await propose(seeded, issueId, { changes });
|
||||
expect(res.status, JSON.stringify(changes)).toBe(status);
|
||||
@@ -427,7 +493,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
await fails([{ op: "add_area", ref: "f", name: "fundraising" }], 422, "already exists");
|
||||
await fails([{ op: "rename_area", areaId: fund, name: "Hiring" }], 422, "already called");
|
||||
await fails([{ op: "rename_area", areaId: fund, name: "Fundraising" }], 422, "already has that name");
|
||||
await fails([{ op: "remove_area", areaId: hiring, reason: "Not yours" }], 422, "another person");
|
||||
await fails([{ op: "remove_area", areaId: otherArea!.id, reason: "Not yours" }], 422, "No area");
|
||||
await fails([{ op: "reword_responsibility", responsibilityId: theirs!.id, sentence: "Mine now." }], 422, "not one of this person's");
|
||||
await fails([{ op: "reword_responsibility", responsibilityId: deck, sentence: "The deck is always current." }], 422, "same as the one it has");
|
||||
await fails([{ op: "move_responsibility", responsibilityId: deck, areaId: fund }], 422, "already in that area");
|
||||
@@ -435,7 +501,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
// A rename of a shared area says who else sees it.
|
||||
const shared = await propose(seeded, issueId, { changes: [{ op: "rename_area", areaId: hiring, name: "Recruiting" }] });
|
||||
expect(shared.status).toBe(201);
|
||||
expect(shared.body.payload.changes[0]).toMatchObject({ fromName: "Hiring", name: "Recruiting", sharedWith: 1 });
|
||||
expect(shared.body.payload.changes[0]).toMatchObject({ fromName: "Hiring", name: "Recruiting", sharedWith: 0 });
|
||||
// A removed area lists what goes with it, minus what is moved out.
|
||||
const removal = await propose(seeded, issueId, {
|
||||
changes: [
|
||||
@@ -477,7 +543,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
expect(logged).toEqual(expect.arrayContaining(["responsibility_dashboard.changes_applied", "issue.thread_interaction_accepted"]));
|
||||
// Only the person or an admin applies.
|
||||
const next = await propose(seeded, issueId, { changes: [{ op: "add_area", ref: "x", name: "Ops" }] });
|
||||
expect((await accept(seeded, issueId, next.body.id, {}, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(403);
|
||||
expect((await accept(seeded, issueId, next.body.id, {}, createApp(sessionBoardActor(seeded.company.id, OTHER)))).status).toBe(404);
|
||||
expect((await accept(seeded, issueId, next.body.id, {}, createApp(agentActor(seeded.company.id, seeded.ceo.id)))).status).toBe(403);
|
||||
});
|
||||
|
||||
@@ -538,12 +604,12 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
{ op: "remove_area", areaId: seeded.areas.Fundraising, reason: "The raise is done." },
|
||||
],
|
||||
});
|
||||
// Someone else files a responsibility in Fundraising meanwhile.
|
||||
await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: seeded.areas.Fundraising });
|
||||
// The destination is archived after the proposal was made.
|
||||
await db.update(responsibilityAreas).set({ status: "archived" }).where(eq(responsibilityAreas.id, seeded.areas.Hiring));
|
||||
const before = await dashboard(seeded);
|
||||
const refused = await accept(seeded, issueId, proposed.body.id);
|
||||
expect(refused.status).toBe(409);
|
||||
expect(refused.body.error).toContain("Someone else now has responsibilities in \"Fundraising\"");
|
||||
expect(refused.body.error).toContain("removed since");
|
||||
expect(await dashboard(seeded)).toEqual(before);
|
||||
expect(await versionsOf(seeded)).toHaveLength(0);
|
||||
const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, proposed.body.id));
|
||||
@@ -679,9 +745,10 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
expect(areas.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ title: "Talent", status: "archived" });
|
||||
});
|
||||
|
||||
it("leaves a shared area's name and order alone, and never archives what someone else still uses", async () => {
|
||||
it("restores private area names and ordering without touching a teammate’s copy", async () => {
|
||||
const seeded = await seed({ populated: true });
|
||||
await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: seeded.areas.Hiring });
|
||||
const [otherArea] = await db.insert(responsibilityAreas).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Hiring" }).returning();
|
||||
await db.insert(responsibilities).values({ companyId: seeded.company.id, ownerUserId: OTHER, title: "Theirs", status: "active", areaId: otherArea!.id });
|
||||
const svc = responsibilityDashboardVersionService(db);
|
||||
const first = await db.transaction((tx) => svc.checkpoint(tx, seeded.company.id, OWNER, OWNER));
|
||||
await request(seeded.app).patch(`/api/responsibility-areas/${seeded.areas.Hiring}`).send({ title: "Recruiting", sortOrder: 5 });
|
||||
@@ -690,7 +757,7 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
await request(seeded.app).patch(`/api/responsibilities/${seeded.items.pipeline}`).send({ areaId: seeded.areas.Fundraising });
|
||||
await request(seeded.app).post(`/api/responsibility-dashboard-versions/${first.row.id}/restore`).send({});
|
||||
const areas = await areaRows(seeded);
|
||||
expect(areas.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ title: "Recruiting", sortOrder: 5, status: "active" });
|
||||
expect(areas.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ title: "Hiring", sortOrder: 0, status: "active" });
|
||||
expect(areas.find((row) => row.id === seeded.areas.Fundraising)).toMatchObject({ title: "Fundraising" });
|
||||
expect((await ownRows(seeded)).find((row) => row.id === seeded.items.pipeline)).toMatchObject({ areaId: seeded.areas.Hiring });
|
||||
|
||||
@@ -700,17 +767,18 @@ describeEmbeddedPostgres("dashboard conversations, change sets and versions", ()
|
||||
}));
|
||||
await request(seeded.app).post(`/api/responsibility-dashboard-versions/${blank.row.id}/restore`).send({});
|
||||
const after = await areaRows(seeded);
|
||||
expect(after.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ status: "active" });
|
||||
expect(after.find((row) => row.id === seeded.areas.Hiring)).toMatchObject({ status: "archived" });
|
||||
expect(after.find((row) => row.id === otherArea!.id)).toMatchObject({ title: "Hiring", status: "active" });
|
||||
expect(after.find((row) => row.id === seeded.areas.Fundraising)).toMatchObject({ status: "archived" });
|
||||
expect((await ownRows(seeded)).every((row) => row.status === "let_go")).toBe(true);
|
||||
expect(await db.select().from(responsibilities).where(eq(responsibilities.ownerUserId, OTHER)).then((rows) => rows.filter((row) => row.companyId === seeded.company.id).map((row) => row.status))).toEqual(["active"]);
|
||||
});
|
||||
|
||||
it("lets only the person or an admin restore", async () => {
|
||||
it("lets only the dashboard owner restore", async () => {
|
||||
const seeded = await seed();
|
||||
const { applied } = await createFirstDashboard(seeded);
|
||||
const url = `/api/responsibility-dashboard-versions/${applied.version.id}/restore`;
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(url).send({})).status).toBe(403);
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(url).send({})).status).toBe(404);
|
||||
expect((await request(createApp(agentActor(seeded.company.id, seeded.ceo.id))).post(url).send({})).status).toBe(403);
|
||||
expect((await request(createApp(sessionBoardActor(randomUUID(), OWNER))).post(url).send({})).status).toBe(404);
|
||||
expect((await request(seeded.app).post(`/api/responsibility-dashboard-versions/${randomUUID()}/restore`).send({})).status).toBe(404);
|
||||
|
||||
@@ -154,8 +154,8 @@ describeEmbeddedPostgres("responsibility metric sets", () => {
|
||||
describe("the read", () => {
|
||||
it("is 404 with the flag off, and follows the detail route's access", async () => {
|
||||
const seeded = await seed();
|
||||
expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(200);
|
||||
expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(200);
|
||||
expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(404);
|
||||
expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(403);
|
||||
// Another company's board user gets what the detail route gives them.
|
||||
const outsider = createApp(sessionBoardActor(randomUUID(), OTHER));
|
||||
const detail = await request(outsider).get(`/api/responsibilities/${seeded.id}`);
|
||||
@@ -230,7 +230,7 @@ describeEmbeddedPostgres("responsibility metric sets", () => {
|
||||
expect(row!.metricCurrent).toBe(11);
|
||||
expect((await record(analyst, seeded.id, "primary", { value: true })).status).toBe(422);
|
||||
// A teammate who does not own it may not record either.
|
||||
expect((await record(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", { value: 3 })).status).toBe(403);
|
||||
expect((await record(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", { value: 3 })).status).toBe(404);
|
||||
const logged = await db.select({ action: activityLog.action }).from(activityLog).where(eq(activityLog.companyId, seeded.company.id));
|
||||
expect(logged.map((entry) => entry.action)).toEqual(expect.arrayContaining(["responsibility.metric_reading_recorded", "responsibility.metric_updated"]));
|
||||
});
|
||||
@@ -300,7 +300,7 @@ describeEmbeddedPostgres("responsibility metric sets", () => {
|
||||
describe("chosen sets", () => {
|
||||
it("lets the owner set and remove supporting metrics; others may not", async () => {
|
||||
const seeded = await seed();
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING })).status).toBe(403);
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING })).status).toBe(404);
|
||||
expect((await request(createApp(agentActor(seeded.company.id, seeded.analyst.id))).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING })).status).toBe(403);
|
||||
expect((await request(seeded.app).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: [...SUPPORTING, { ...SUPPORTING[1], title: "Third" }] })).status).toBe(400);
|
||||
const set = await request(seeded.app).put(`/api/responsibilities/${seeded.id}/metrics`).send({ metrics: SUPPORTING, primaryDisplay: "line" });
|
||||
@@ -348,7 +348,7 @@ describeEmbeddedPostgres("responsibility metric sets", () => {
|
||||
expect(primary.body).toMatchObject({ source: "chosen", chosenBy: { userId: OWNER } });
|
||||
expect((await showAs(seeded.app, seeded.id, "primary", "percent")).status).toBe(422);
|
||||
|
||||
expect((await showAs(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", "line")).status).toBe(403);
|
||||
expect((await showAs(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id, "primary", "line")).status).toBe(404);
|
||||
expect((await showAs(createApp(agentActor(seeded.company.id, seeded.analyst.id)), seeded.id, "primary", "line")).status).toBe(403);
|
||||
expect((await showAs(seeded.app, seeded.id, randomUUID(), "line")).status).toBe(404);
|
||||
const logged = await db.select({ details: activityLog.details }).from(activityLog)
|
||||
|
||||
@@ -185,8 +185,8 @@ describeEmbeddedPostgres("a responsibility's recent runs", () => {
|
||||
const seeded = await seed();
|
||||
await run(seeded, seeded.issues.direct.id, 5);
|
||||
// A teammate and an agent in the company read it, as they read the detail.
|
||||
expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(200);
|
||||
expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(200);
|
||||
expect((await read(createApp(sessionBoardActor(seeded.company.id, OTHER)), seeded.id)).status).toBe(404);
|
||||
expect((await read(createApp(agentActor(seeded.company.id, seeded.ceo.id)), seeded.id)).status).toBe(403);
|
||||
// Another company's board user gets what the detail route gives them.
|
||||
const outsider = createApp(sessionBoardActor(randomUUID(), OTHER));
|
||||
const detail = await request(outsider).get(`/api/responsibilities/${seeded.id}`);
|
||||
|
||||
@@ -192,8 +192,8 @@ describeEmbeddedPostgres("agent-written responsibility status", () => {
|
||||
expect(byOwner.status).toBe(201);
|
||||
expect(byOwner.body.current).toMatchObject({ status: "behind", agentId: null, userId: OWNER });
|
||||
|
||||
expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER))).status).toBe(403);
|
||||
expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER, "admin"))).status).toBe(201);
|
||||
expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER))).status).toBe(404);
|
||||
expect((await write(seeded, sessionBoardActor(seeded.company.id, OTHER, "admin"))).status).toBe(404);
|
||||
|
||||
// Nobody names the author: the body is strict, and the record follows the caller.
|
||||
const forged = await write(seeded, agentActor(seeded.company.id, seeded.builder.id), { ...REPORT, agentId: seeded.ceo.id });
|
||||
@@ -203,17 +203,17 @@ describeEmbeddedPostgres("agent-written responsibility status", () => {
|
||||
|
||||
const rows = await db.select().from(responsibilityStatusReports).where(eq(responsibilityStatusReports.responsibilityId, seeded.responsibility.id));
|
||||
expect(rows.map((row) => [row.agentId, row.userId]).sort()).toEqual([
|
||||
[null, OTHER], [null, OWNER], [seeded.analyst.id, null], [seeded.builder.id, null],
|
||||
[null, OWNER], [seeded.analyst.id, null], [seeded.builder.id, null],
|
||||
].sort());
|
||||
|
||||
const history = (await read(seeded)).body.history as Array<{ userId: string | null }>;
|
||||
expect(history).toHaveLength(4);
|
||||
expect(history[0]!.userId).toBe(OTHER);
|
||||
expect(history).toHaveLength(3);
|
||||
expect(history[0]!.userId).toBe(OWNER);
|
||||
|
||||
const logged = await db.select({ action: activityLog.action, details: activityLog.details }).from(activityLog)
|
||||
.where(and(eq(activityLog.companyId, seeded.company.id), eq(activityLog.action, "responsibility.status_reported")));
|
||||
expect(logged).toHaveLength(4);
|
||||
expect(logged.map((row) => (row.details as { writtenBy: string }).writtenBy).sort()).toEqual(["agent", "agent", "user", "user"]);
|
||||
expect(logged).toHaveLength(3);
|
||||
expect(logged.map((row) => (row.details as { writtenBy: string }).writtenBy).sort()).toEqual(["agent", "agent", "user"]);
|
||||
});
|
||||
|
||||
it("checks the message's shape", async () => {
|
||||
@@ -252,7 +252,7 @@ describeEmbeddedPostgres("agent-written responsibility status", () => {
|
||||
const ask = () => request(owner).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({});
|
||||
|
||||
// Someone who may not edit the responsibility cannot ask.
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({})).status).toBe(403);
|
||||
expect((await request(createApp(sessionBoardActor(seeded.company.id, OTHER))).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({})).status).toBe(404);
|
||||
expect((await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).post(`/api/responsibilities/${seeded.responsibility.id}/status-report/request`).send({})).status).toBe(403);
|
||||
|
||||
const first = await ask();
|
||||
@@ -404,8 +404,8 @@ describeEmbeddedPostgres("agent-written responsibility status", () => {
|
||||
const seeded = await seed();
|
||||
const url = `/api/companies/${seeded.company.id}/responsibilities/status-reports`;
|
||||
const agentRead = await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).get(url);
|
||||
expect(agentRead.status).toBe(422);
|
||||
expect((await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(200);
|
||||
expect(agentRead.status).toBe(403);
|
||||
expect((await request(createApp(agentActor(seeded.company.id, seeded.builder.id))).get(`${url}?ownerUserId=${OWNER}`)).status).toBe(403);
|
||||
expect((await request(createApp(agentActor(randomUUID(), seeded.builder.id))).get(url)).status).toBe(403);
|
||||
|
||||
await instanceSettingsService(db).updateExperimental({ enableResponsibilities: false });
|
||||
|
||||
@@ -200,9 +200,8 @@ describeEmbeddedPostgres("responsibility summary routes", () => {
|
||||
}).returning().then((rows) => rows[0]!);
|
||||
const agentApp = createApp(agentActor(company.id, agent.id)).app;
|
||||
const missingOwner = await request(agentApp).get(`/api/companies/${company.id}/responsibilities/summary`);
|
||||
expect(missingOwner.status).toBe(422);
|
||||
expect(missingOwner.body.error).toContain("ownerUserId is required");
|
||||
expect((await request(agentApp).get(`/api/companies/${company.id}/responsibilities/summary?ownerUserId=${OWNER}`)).status).toBe(200);
|
||||
expect((await request(agentApp).get(`/api/responsibilities/${created.body.id}/summary`)).status).toBe(200);
|
||||
expect(missingOwner.status).toBe(403);
|
||||
expect((await request(agentApp).get(`/api/companies/${company.id}/responsibilities/summary?ownerUserId=${OWNER}`)).status).toBe(403);
|
||||
expect((await request(agentApp).get(`/api/responsibilities/${created.body.id}/summary`)).status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -117,6 +117,7 @@ describeEmbeddedPostgres("routine suggestions", () => {
|
||||
priority: "medium",
|
||||
assigneeAgentId: agent.id,
|
||||
originKind: input.originKind ?? "manual",
|
||||
responsibleUserId: OWNER,
|
||||
parentId: input.parentId ?? null,
|
||||
createdByUserId: OWNER,
|
||||
}).returning().then((rows) => rows[0]!);
|
||||
|
||||
@@ -240,6 +240,7 @@ export function activityRoutes(db: Db) {
|
||||
entityId: req.query.entityId as string | undefined,
|
||||
limit: normalizeActivityLimit(Number(req.query.limit)),
|
||||
readCondition: await issueReadSqlCondition(db, req.actor),
|
||||
dashboardUserId: req.actor.type === "board" ? req.actor.userId : null,
|
||||
caseReadCondition: await caseActivityReadSqlCondition(db, req.actor),
|
||||
};
|
||||
const result = await svc.list(filters);
|
||||
@@ -267,6 +268,7 @@ export function activityRoutes(db: Db) {
|
||||
}
|
||||
if (parsedQuery.data.actorScope === "agents") {
|
||||
const result = await agentAudit.list({ companyId, ...parsedQuery.data,
|
||||
dashboardUserId: req.actor.type === "board" ? req.actor.userId : null,
|
||||
caseReadCondition: await caseActivityReadSqlCondition(db, req.actor) });
|
||||
res.json({ ...result, accessTier: "full" });
|
||||
return;
|
||||
@@ -277,6 +279,7 @@ export function activityRoutes(db: Db) {
|
||||
throw forbidden("Audit filters require permission: audit:view_agent_actions");
|
||||
}
|
||||
const result = await agentAudit.list({ companyId, ...parsedQuery.data,
|
||||
dashboardUserId: req.actor.type === "board" ? req.actor.userId : null,
|
||||
caseReadCondition: await caseActivityReadSqlCondition(db, req.actor) });
|
||||
res.json({
|
||||
...(canViewAttribution ? result : stripAuditAttribution(result)),
|
||||
@@ -298,7 +301,7 @@ export function activityRoutes(db: Db) {
|
||||
const rows: Awaited<ReturnType<typeof agentAudit.list>>["items"] = [];
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const page = await agentAudit.list({ companyId, ...filters, cursor, limit: AUDIT_CSV_PAGE_SIZE, caseReadCondition });
|
||||
const page = await agentAudit.list({ companyId, ...filters, cursor, limit: AUDIT_CSV_PAGE_SIZE, dashboardUserId: req.actor.userId, caseReadCondition });
|
||||
for (const item of page.items) {
|
||||
if (rows.length >= AUDIT_CSV_EXPORT_MAX_ROWS) break;
|
||||
rows.push(item);
|
||||
|
||||
@@ -81,15 +81,12 @@ export async function agentPersonInCompany(db: Db, req: Request, companyId: stri
|
||||
}
|
||||
|
||||
/**
|
||||
* The writer rule for an agent on a person's responsibilities: it acts for
|
||||
* the person who directed its run and may change what that person could, so
|
||||
* it manages that person's own responsibilities, and anyone's when that person
|
||||
* is a company owner or admin. Returns that person's user id, or null.
|
||||
* A directed agent run may manage the dashboard of the person who directed it.
|
||||
*/
|
||||
export async function agentActsForResponsibilityOwner(db: Db, req: Request, companyId: string, ownerUserId: string): Promise<string | null> {
|
||||
const person = await agentPersonInCompany(db, req, companyId);
|
||||
if (!person) return null;
|
||||
return person.userId === ownerUserId || person.role === "owner" || person.role === "admin" ? person.userId : null;
|
||||
return person.userId === ownerUserId && (!req.actor.authorizingUserId || req.actor.authorizingUserId === ownerUserId) ? person.userId : null;
|
||||
}
|
||||
|
||||
/** Why an agent may not act for a person here, for its error messages. */
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { SecretBindingTargetType } from "@paperclipai/shared";
|
||||
import { forbidden, HttpError, unauthorized } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { responsibleUserAuthzShadowMode } from "../services/authorization.js";
|
||||
import { dashboardConversationReadable, type DashboardConversationFields } from "../services/responsibility-privacy.js";
|
||||
import { getHiddenSettings } from "../services/settings-visibility.js";
|
||||
|
||||
function throwOrShadowResponsibleUserCompanyAccessDeny(
|
||||
@@ -315,7 +316,7 @@ export function hasCompanyAccess(req: Request, companyId: string): boolean {
|
||||
* Routes with bespoke not-found behavior (legacy `200 []` contracts,
|
||||
* audit-logged denials) should still compose `hasCompanyAccess` directly.
|
||||
*/
|
||||
export async function getAccessibleResource<T extends { companyId: string }>(
|
||||
export async function getAccessibleResource<T extends { companyId: string } & DashboardConversationFields>(
|
||||
req: Request,
|
||||
res: Response,
|
||||
resource: T | null | undefined | Promise<T | null | undefined>,
|
||||
@@ -323,7 +324,7 @@ export async function getAccessibleResource<T extends { companyId: string }>(
|
||||
notFoundBody: Record<string, unknown> = { error: notFoundMessage },
|
||||
): Promise<T | null> {
|
||||
const resolved = await resource;
|
||||
if (!resolved || !hasCompanyAccess(req, resolved.companyId)) {
|
||||
if (!resolved || !hasCompanyAccess(req, resolved.companyId) || !dashboardConversationReadable(req.actor, resolved)) {
|
||||
res.status(404).json(notFoundBody);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -72,27 +73,8 @@ function linkTarget(body: LinkResponsibility | ResponsibilityLinkLookupQuery): R
|
||||
return { kind: "routine", id: body.routineId! };
|
||||
}
|
||||
|
||||
/**
|
||||
* The writer rule: a board user manages their own responsibilities; company
|
||||
* owners/admins and instance admins manage anyone's.
|
||||
*/
|
||||
export function boardCanManageResponsibilityOwner(req: Request, companyId: string, ownerUserId: string) {
|
||||
if (req.actor.type !== "board") return false;
|
||||
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true;
|
||||
if (req.actor.userId && req.actor.userId === ownerUserId) return true;
|
||||
const membership = req.actor.memberships?.find((item) => item.companyId === companyId && item.status === "active");
|
||||
return membership?.membershipRole === "owner" || membership?.membershipRole === "admin";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whose responsibilities a request means when it names no owner: a board user
|
||||
* means their own, and an agent means the person its run works for (the
|
||||
* person chatting, or the task's responsible person).
|
||||
*/
|
||||
export function defaultResponsibilityOwnerUserId(req: Request): string | undefined {
|
||||
if (req.actor.type === "board") return req.actor.userId ?? undefined;
|
||||
if (req.actor.type === "agent") return req.actor.onBehalfOfUserId ?? undefined;
|
||||
return undefined;
|
||||
export function boardCanManageResponsibilityOwner(req: Request, _companyId: string, ownerUserId: string) {
|
||||
return req.actor.type === "board" && req.actor.userId === ownerUserId;
|
||||
}
|
||||
|
||||
export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWakeupDeps } = {}) {
|
||||
@@ -157,14 +139,15 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
|
||||
function assertBoardCanManage(req: Request, row: { companyId: string; ownerUserId: string }) {
|
||||
if (!boardCanManageOwner(req, row.companyId, row.ownerUserId)) {
|
||||
throw forbidden("Only the person who owns this responsibility, or a company admin, can change it");
|
||||
throw forbidden("Only the person who owns this responsibility can change it");
|
||||
}
|
||||
}
|
||||
|
||||
async function loadForRead(req: Request, res: Response) {
|
||||
async function loadForRead(req: Request, res: Response, reporting = false) {
|
||||
const row = await getAccessibleResource(req, res, svc.getById(req.params.id as string), NOT_FOUND);
|
||||
if (!row) return null;
|
||||
await assertCompanyRead(req, row.companyId);
|
||||
if (!(reporting && agentMayReportFor(req, row.ownerUserId) && row.status === "active")) await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -191,7 +174,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
}
|
||||
const personUserId = await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId);
|
||||
if (!personUserId) {
|
||||
throw forbidden(`Only the person who owns this responsibility, or a company admin, can change it, and this agent's run does not act for such a person. ${AGENT_PERSON_RULE}.`);
|
||||
throw forbidden(`Only the person who owns this responsibility can change it, and this agent's run does not act for such a person. ${AGENT_PERSON_RULE}.`);
|
||||
}
|
||||
return { personUserId, agentId: getActorInfo(req).actorId };
|
||||
}
|
||||
@@ -294,12 +277,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = listResponsibilitiesQuerySchema.parse(req.query);
|
||||
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
|
||||
if (!ownerUserId) {
|
||||
throw unprocessable(req.actor.type === "agent"
|
||||
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read"
|
||||
: "ownerUserId is required");
|
||||
}
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
|
||||
res.json(await svc.overview(companyId, ownerUserId, {
|
||||
includeLetGo: query.includeLetGo,
|
||||
scope: await readScope(req, companyId),
|
||||
@@ -311,28 +289,8 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const actor = getActorInfo(req);
|
||||
let ownerUserId: string;
|
||||
// An agent acting for someone who may manage the owner creates what that person could.
|
||||
let actsFor: string | null = null;
|
||||
if (req.actor.type === "agent") {
|
||||
const owner = req.body.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
|
||||
if (!owner) {
|
||||
throw unprocessable("ownerUserId is required: this run works for no person, so name the person in this company the responsibility is for");
|
||||
}
|
||||
ownerUserId = owner;
|
||||
if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company");
|
||||
actsFor = await agentActsForResponsibilityOwner(db, req, companyId, ownerUserId);
|
||||
} else {
|
||||
const self = req.actor.userId;
|
||||
ownerUserId = req.body.ownerUserId ?? self ?? "";
|
||||
if (!ownerUserId) throw unprocessable("ownerUserId is required");
|
||||
if (ownerUserId !== self) {
|
||||
if (!boardCanManageOwner(req, companyId, ownerUserId)) {
|
||||
throw forbidden("Only a company admin can create a responsibility for another person");
|
||||
}
|
||||
if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company");
|
||||
}
|
||||
}
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, req.body.ownerUserId);
|
||||
const actsFor = req.actor.type === "agent" ? ownerUserId : null;
|
||||
const { areaTitle, ...body } = req.body as typeof req.body & { areaTitle?: string };
|
||||
if (areaTitle && body.areaId) throw unprocessable("Send areaId or areaTitle, not both");
|
||||
const { responsibility: created, activatedArea, created: isNew, newArea } = await inChange(req, res, {
|
||||
@@ -341,7 +299,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
createdAreaIds: (result) => (result.newArea ? [result.newArea.id] : []),
|
||||
}, async ({ svc: scoped, areas }: ScopedServices) => {
|
||||
// The area by title is made in the same transaction, so a refused create leaves no area behind.
|
||||
const area = areaTitle ? await areas.create(companyId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
|
||||
const area = areaTitle ? await areas.create(companyId, ownerUserId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
|
||||
const result = await scoped.create(
|
||||
companyId,
|
||||
{ ...body, ...(area ? { areaId: area.area.id } : {}) },
|
||||
@@ -379,7 +337,8 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
|
||||
router.patch("/responsibilities/:id", validate(updateResponsibilitySchema), async (req, res) => {
|
||||
await assertResponsibilitiesEnabled();
|
||||
const row = await loadForWrite(req, res);
|
||||
const reporting = req.body.metricCurrent !== undefined && Object.keys(req.body).length === 1;
|
||||
const row = await loadForRead(req, res, reporting);
|
||||
if (!row) return;
|
||||
const scope = await readScope(req, row.companyId);
|
||||
const actsFor = req.actor.type === "agent" ? await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId) : null;
|
||||
@@ -391,7 +350,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
createdAreaIds: (result) => (result.newArea ? [result.newArea.id] : []),
|
||||
}, async ({ svc: scoped, areas }: ScopedServices) => {
|
||||
// The area by title is made in the same transaction, so a refused change leaves no area behind.
|
||||
const area = areaTitle ? await areas.create(row.companyId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
|
||||
const area = areaTitle ? await areas.create(row.companyId, row.ownerUserId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
|
||||
if (area) patch.areaId = area.area.id;
|
||||
const result = await scoped.update(
|
||||
row,
|
||||
@@ -523,7 +482,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
moveFromIds = await svc.liveIdsOfOwner(row.companyId, row.ownerUserId, row.id);
|
||||
} else if (req.body.moveFrom && req.body.moveFrom !== row.id) {
|
||||
const source = await svc.getById(req.body.moveFrom);
|
||||
if (!source || source.companyId !== row.companyId) throw notFound("Responsibility to move from not found");
|
||||
if (!source || source.companyId !== row.companyId || source.ownerUserId !== row.ownerUserId) throw notFound("Responsibility to move from not found");
|
||||
await assertWriter(req, source);
|
||||
moveFromIds = [source.id];
|
||||
owners.add(source.ownerUserId);
|
||||
@@ -612,7 +571,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
action: "issue.created",
|
||||
entityType: "issue",
|
||||
entityId: issue.id,
|
||||
details: { title: issue.title, identifier: issue.identifier, responsibilityId: row.id },
|
||||
details: { title: issue.title, identifier: issue.identifier },
|
||||
});
|
||||
await logMutation(req, row.companyId, "responsibility.delegated", row.id, {
|
||||
issueId: issue.id,
|
||||
@@ -639,7 +598,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = responsibilityLinkLookupQuerySchema.parse(req.query);
|
||||
const responsibilities = await svc.lookup(companyId, linkTarget(query), await readScope(req, companyId));
|
||||
const responsibilities = await svc.lookup(companyId, await dashboardOwner(db, req, companyId), linkTarget(query), await readScope(req, companyId));
|
||||
res.json({ responsibilities });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -19,11 +20,7 @@ import { assertBoardOrAgent, assertCompanyAccess, getAccessibleResource, getActo
|
||||
const NOT_FOUND = "Area not found";
|
||||
|
||||
/**
|
||||
* Responsibility areas (experimental, `enableResponsibilities`). Areas have no
|
||||
* owner: any board user with write access to the company manages them. An
|
||||
* agent acting for a member of the company may do the same, each change saved
|
||||
* as a version of that person's Dashboard they can undo (a delete only after
|
||||
* the person accepts a confirmation card); other agents can only propose one.
|
||||
* An owner or a run they directed can manage their areas. Agent changes are versioned.
|
||||
*/
|
||||
export function responsibilityAreaRoutes(db: Db) {
|
||||
const router = Router();
|
||||
@@ -55,6 +52,8 @@ export function responsibilityAreaRoutes(db: Db) {
|
||||
async function loadForBoardWrite(req: Request, res: Response) {
|
||||
const row = await getAccessibleResource(req, res, svc.getById(req.params.id as string), NOT_FOUND);
|
||||
if (!row) return null;
|
||||
await assertCompanyRead(req, row.companyId);
|
||||
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -90,7 +89,7 @@ export function responsibilityAreaRoutes(db: Db) {
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = listResponsibilityAreasQuerySchema.parse(req.query);
|
||||
res.json(await svc.list(companyId, { includeArchived: query.includeArchived }));
|
||||
res.json(await svc.list(companyId, await dashboardOwner(db, req, companyId), { includeArchived: query.includeArchived }));
|
||||
});
|
||||
|
||||
router.post("/companies/:companyId/responsibility-areas", validate(createResponsibilityAreaSchema), async (req, res) => {
|
||||
@@ -99,8 +98,9 @@ export function responsibilityAreaRoutes(db: Db) {
|
||||
await assertCompanyRead(req, companyId);
|
||||
const actor = getActorInfo(req);
|
||||
const person = await agentPersonInCompany(db, req, companyId);
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId);
|
||||
const create = (tx: Db) => responsibilityAreaService(tx).create(
|
||||
companyId,
|
||||
companyId, ownerUserId,
|
||||
req.body,
|
||||
req.actor.type !== "agent" ? { type: "board" }
|
||||
: person ? { type: "board", viaAgentId: actor.actorId }
|
||||
@@ -131,20 +131,9 @@ export function responsibilityAreaRoutes(db: Db) {
|
||||
const row = await loadForBoardWrite(req, res);
|
||||
if (!row) return;
|
||||
const writer = await assertAreaWriter(req, row.companyId);
|
||||
// On an area other people's proposed or active responsibilities share (the same test restore
|
||||
// uses), Undo never changes the name, description or order, and of status changes only brings
|
||||
// an archived area back. A change it cannot reverse saves no version, so no Dashboard offers an
|
||||
// Undo that would do nothing; it stays in the activity log.
|
||||
const sharedChange = Boolean(writer)
|
||||
&& (await svc.ownersInArea(row.companyId, row.id, ["proposed", "active"])).some((owner) => owner !== writer!.personUserId)
|
||||
&& ((req.body.title !== undefined && req.body.title !== row.title)
|
||||
|| (req.body.description !== undefined && req.body.description !== row.description)
|
||||
|| (req.body.sortOrder !== undefined && req.body.sortOrder !== row.sortOrder)
|
||||
|| (req.body.status !== undefined && req.body.status !== row.status && !(row.status === "active" && req.body.status === "archived")));
|
||||
// Otherwise everyone whose Dashboard shows the area gets a version.
|
||||
const updated = writer && !sharedChange
|
||||
const updated = writer
|
||||
? await agentChanges.record({
|
||||
companyId: row.companyId, ownerUserIds: [writer.personUserId, ...await svc.ownersInArea(row.companyId, row.id)],
|
||||
companyId: row.companyId, ownerUserIds: [writer.personUserId],
|
||||
agentId: writer.agentId, touchedAreaIds: [row.id],
|
||||
onVersion: reportVersionOf(res, writer.personUserId),
|
||||
}, (tx) => responsibilityAreaService(tx).update(row, req.body))
|
||||
@@ -172,6 +161,7 @@ export function responsibilityAreaRoutes(db: Db) {
|
||||
agentId: writer.agentId,
|
||||
interactionId: query.confirmationId,
|
||||
key: responsibilityDeletionKey("area", row.id),
|
||||
ownerUserId: writer.personUserId,
|
||||
});
|
||||
confirmationId = card.id;
|
||||
}
|
||||
@@ -179,7 +169,7 @@ export function responsibilityAreaRoutes(db: Db) {
|
||||
// Moving its responsibilities changes their owners' Dashboards too.
|
||||
const removed = writer
|
||||
? await agentChanges.record({
|
||||
companyId: row.companyId, ownerUserIds: [writer.personUserId, ...await svc.ownersInArea(row.companyId, row.id)],
|
||||
companyId: row.companyId, ownerUserIds: [writer.personUserId],
|
||||
agentId: writer.agentId,
|
||||
touchedAreaIds: [row.id, ...(query.moveResponsibilitiesTo ? [query.moveResponsibilitiesTo] : [])],
|
||||
onVersion: reportVersionOf(res, writer.personUserId),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -35,7 +36,6 @@ import { automationConversationService } from "../services/responsibility-automa
|
||||
import { standingCheckService } from "../services/routine-standing-checks.js";
|
||||
import { routineSuggestionService, type RoutineSuggestionResponsibilityFiling } from "../services/routine-suggestions.js";
|
||||
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
|
||||
import { defaultResponsibilityOwnerUserId } from "./responsibilities.js";
|
||||
import { getReadableIssue } from "./readable-issue.js";
|
||||
|
||||
const automationQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true });
|
||||
@@ -147,12 +147,7 @@ export function responsibilityAutomationRoutes(
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = automationQuerySchema.parse(req.query);
|
||||
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
|
||||
if (!ownerUserId) {
|
||||
throw unprocessable(req.actor.type === "agent"
|
||||
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read"
|
||||
: "ownerUserId is required");
|
||||
}
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
|
||||
res.json(await automation.overview(companyId, ownerUserId, { scope: await readScope(req) }));
|
||||
});
|
||||
|
||||
@@ -161,7 +156,7 @@ export function responsibilityAutomationRoutes(
|
||||
const issue = await getReadableIssue(access, req, res, issues.getById(req.params.id as string), ISSUE_NOT_FOUND);
|
||||
if (!issue) return;
|
||||
assertBoard(req);
|
||||
res.json(await conversations.conversationFor(issue));
|
||||
res.json(await conversations.conversationFor(issue, boardUserId(req)));
|
||||
});
|
||||
|
||||
router.post("/issues/:id/automation-conversation", validate(startAutomationConversationSchema), async (req, res) => {
|
||||
@@ -171,7 +166,7 @@ export function responsibilityAutomationRoutes(
|
||||
assertBoard(req);
|
||||
await assertBoardCanAssignTasks(req, source.companyId);
|
||||
const actor = getActorInfo(req);
|
||||
const agentId = req.body.agentId ?? await conversations.defaultAgentId(source, req.body.responsibilityId);
|
||||
const agentId = req.body.agentId ?? await conversations.defaultAgentId(source, boardUserId(req), req.body.responsibilityId);
|
||||
if (agentId) {
|
||||
// The same assignment permission the delegate route checks.
|
||||
const decision = await access.decide({
|
||||
@@ -224,7 +219,7 @@ export function responsibilityAutomationRoutes(
|
||||
requestedByActorId: actor.actorId,
|
||||
});
|
||||
}
|
||||
const body = await conversations.conversation(source);
|
||||
const body = await conversations.conversation(source, boardUserId(req));
|
||||
if (created) {
|
||||
res.status(201).json(body);
|
||||
return;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -71,10 +72,10 @@ export function responsibilityBarRoutes(db: Db, opts: { heartbeat?: IssueAssignm
|
||||
};
|
||||
}
|
||||
|
||||
/** The writer rule of the responsibilities routes: the owner, or a company admin. */
|
||||
/** The writer rule of the responsibilities routes: the owner. */
|
||||
function assertWriter(req: Request, row: { companyId: string; ownerUserId: string }) {
|
||||
if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) {
|
||||
throw forbidden("Only the person who owns this responsibility, or a company admin, can change its bar");
|
||||
throw forbidden("Only the person who owns this responsibility can change its bar");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +96,7 @@ export function responsibilityBarRoutes(db: Db, opts: { heartbeat?: IssueAssignm
|
||||
const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND);
|
||||
if (!row) return;
|
||||
assertBoard(req);
|
||||
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
res.json(await svc.conversation(row));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -22,10 +23,9 @@ import {
|
||||
toDashboardVersionSummary,
|
||||
type DashboardActivityEvent,
|
||||
} from "../services/responsibility-dashboard-versions.js";
|
||||
import { responsibilityService } from "../services/responsibilities.js";
|
||||
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
|
||||
import { getReadableIssue } from "./readable-issue.js";
|
||||
import { boardCanManageResponsibilityOwner, defaultResponsibilityOwnerUserId } from "./responsibilities.js";
|
||||
import { boardCanManageResponsibilityOwner } from "./responsibilities.js";
|
||||
|
||||
const ISSUE_NOT_FOUND = "Issue not found";
|
||||
const VERSION_NOT_FOUND = "Version not found";
|
||||
@@ -35,7 +35,7 @@ const VERSION_NOT_FOUND = "Version not found";
|
||||
* applied change saved as a version (experimental `enableResponsibilities`).
|
||||
* Reads follow the responsibilities overview: board users read their own by
|
||||
* default, agents name the person. A person who may edit that person's
|
||||
* responsibilities (themselves, or a company admin) starts the conversation,
|
||||
* responsibilities starts the conversation,
|
||||
* applies the agent's proposed changes and restores versions; only the agent
|
||||
* in the conversation proposes.
|
||||
*/
|
||||
@@ -44,7 +44,6 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
|
||||
const access = accessService(db);
|
||||
const svc = responsibilityDashboardService(db);
|
||||
const versions = responsibilityDashboardVersionService(db);
|
||||
const responsibilitiesSvc = responsibilityService(db);
|
||||
const issues = issueService(db);
|
||||
const references = issueReferenceService(db);
|
||||
const heartbeat = opts.heartbeat ?? heartbeatService(db);
|
||||
@@ -83,20 +82,9 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
|
||||
}
|
||||
}
|
||||
|
||||
/** The overview route's ownerUserId rule: board users default to themselves, agents to the person their run works for. */
|
||||
function ownerFrom(req: Request, ownerUserId: string | undefined) {
|
||||
const owner = ownerUserId ?? defaultResponsibilityOwnerUserId(req);
|
||||
if (!owner) {
|
||||
throw unprocessable(req.actor.type === "agent"
|
||||
? "ownerUserId is required: this run works for no person, so name the person whose dashboard to read"
|
||||
: "ownerUserId is required");
|
||||
}
|
||||
return owner;
|
||||
}
|
||||
|
||||
function assertWriter(req: Request, companyId: string, ownerUserId: string) {
|
||||
if (!boardCanManageResponsibilityOwner(req, companyId, ownerUserId)) {
|
||||
throw forbidden("Only the person whose dashboard this is, or a company admin, can change it");
|
||||
throw notFound("Dashboard item not found");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +109,7 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = responsibilityDashboardQuerySchema.parse(req.query);
|
||||
res.json(await svc.state(companyId, ownerFrom(req, query.ownerUserId)));
|
||||
res.json(await svc.state(companyId, await dashboardOwner(db, req, companyId, query.ownerUserId)));
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/responsibility-dashboard/versions", async (req, res) => {
|
||||
@@ -129,7 +117,7 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = responsibilityDashboardQuerySchema.parse(req.query);
|
||||
const ownerUserId = ownerFrom(req, query.ownerUserId);
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
|
||||
// Someone who may change this dashboard saves it as it is first, so the list starts with what they see.
|
||||
const writer = boardCanManageResponsibilityOwner(req, companyId, ownerUserId);
|
||||
const { list, saved } = await versions.list(companyId, ownerUserId, writer ? { checkpointBy: getActorInfo(req).actorId } : {});
|
||||
@@ -150,11 +138,8 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
|
||||
const companyId = req.params.companyId as string;
|
||||
assertBoard(req);
|
||||
assertCompanyAccess(req, companyId);
|
||||
const ownerUserId = ownerFrom(req, req.body.ownerUserId);
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, req.body.ownerUserId);
|
||||
assertWriter(req, companyId, ownerUserId);
|
||||
if (ownerUserId !== req.actor.userId && !(await responsibilitiesSvc.isCompanyMember(companyId, ownerUserId))) {
|
||||
throw notFound("Owner is not a member of this company");
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
const agentId = req.body.agentId ?? await svc.defaultAgentId(companyId);
|
||||
if (agentId) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -38,7 +39,7 @@ export function responsibilityMetricRoutes(db: Db) {
|
||||
}
|
||||
|
||||
/** The detail route's read rule: company access, board or agent, and agents inside the company-scope boundary. */
|
||||
async function loadForRead(req: Request, res: Response) {
|
||||
async function loadForRead(req: Request, res: Response, reporting = false) {
|
||||
const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND);
|
||||
if (!row) return null;
|
||||
if (req.actor.type !== "board" && req.actor.type !== "agent") throw forbidden("Board or agent access required");
|
||||
@@ -48,12 +49,13 @@ export function responsibilityMetricRoutes(db: Db) {
|
||||
throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision));
|
||||
}
|
||||
}
|
||||
if (!(reporting && agentMayReportFor(req, row.ownerUserId))) await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
return row;
|
||||
}
|
||||
|
||||
function assertOwnerOrAdmin(req: Request, row: { companyId: string; ownerUserId: string }) {
|
||||
if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) {
|
||||
throw forbidden("Only the person who owns this responsibility, or a company admin, can change its metrics");
|
||||
throw forbidden("Only the person who owns this responsibility can change its metrics");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +131,7 @@ export function responsibilityMetricRoutes(db: Db) {
|
||||
validate(recordResponsibilityMetricReadingSchema),
|
||||
async (req, res) => {
|
||||
await svc.assertEnabled();
|
||||
const row = await loadForRead(req, res);
|
||||
const row = await loadForRead(req, res, true);
|
||||
if (!row) return;
|
||||
const scope = await readScope(req);
|
||||
const actor = getActorInfo(req);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Request } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { forbidden, notFound } from "../errors.js";
|
||||
import { agentPersonInCompany } from "./agent-person-authz.js";
|
||||
|
||||
/** A dashboard belongs to the signed-in person or the person who directed this agent run. */
|
||||
export async function dashboardOwner(db: Db, req: Request, companyId: string, requested?: string | null): Promise<string> {
|
||||
const userId = req.actor.type === "board"
|
||||
? req.actor.userId
|
||||
: (await agentPersonInCompany(db, req, companyId))?.userId;
|
||||
if (!userId) throw forbidden("A personal dashboard requires a user or a run directed by that user");
|
||||
if (req.actor.authorizingUserId && req.actor.authorizingUserId !== userId) throw forbidden("Dashboard access requires the authorizing user");
|
||||
if (requested !== undefined && userId !== requested) throw notFound("Dashboard item not found");
|
||||
return userId;
|
||||
}
|
||||
|
||||
/** Reporting permissions apply only within the user scope of the agent's credentials or run. */
|
||||
export function agentMayReportFor(req: Request, ownerUserId: string) {
|
||||
return req.actor.type === "agent"
|
||||
&& (!req.actor.authorizingUserId || req.actor.authorizingUserId === ownerUserId)
|
||||
&& (!req.actor.onBehalfOfUserId || req.actor.onBehalfOfUserId === ownerUserId);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { forbidden } from "../errors.js";
|
||||
@@ -39,6 +40,7 @@ export function responsibilityRunRoutes(db: Db) {
|
||||
throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision));
|
||||
}
|
||||
}
|
||||
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
return row;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -51,10 +52,11 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
|
||||
}
|
||||
}
|
||||
|
||||
async function loadForRead(req: Request, res: Response) {
|
||||
async function loadForRead(req: Request, res: Response, reporting = false) {
|
||||
const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND);
|
||||
if (!row) return null;
|
||||
await assertCompanyRead(req, row.companyId);
|
||||
if (!(reporting && agentMayReportFor(req, row.ownerUserId))) await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -79,12 +81,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = ownerQuerySchema.parse(req.query);
|
||||
const ownerUserId = query.ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined);
|
||||
if (!ownerUserId) {
|
||||
throw unprocessable(req.actor.type === "agent"
|
||||
? "ownerUserId is required: name the person whose responsibilities to read"
|
||||
: "ownerUserId is required");
|
||||
}
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
|
||||
res.json(await svc.overview(companyId, ownerUserId));
|
||||
});
|
||||
|
||||
@@ -97,7 +94,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
|
||||
|
||||
router.post("/responsibilities/:id/status-report", validate(writeResponsibilityStatusReportSchema), async (req, res) => {
|
||||
await svc.assertEnabled();
|
||||
const row = await loadForRead(req, res);
|
||||
const row = await loadForRead(req, res, true);
|
||||
if (!row) return;
|
||||
let author: StatusReportAuthor;
|
||||
if (req.actor.type === "agent") {
|
||||
@@ -130,7 +127,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
|
||||
if (!row) return;
|
||||
assertBoard(req);
|
||||
if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) {
|
||||
throw forbidden("Only the person who owns this responsibility, or a company admin, can ask for an update");
|
||||
throw forbidden("Only the person who owns this responsibility can ask for an update");
|
||||
}
|
||||
const reporter = await svc.reporterOf(row);
|
||||
if (reporter) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { Router, type Request } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { listResponsibilitiesQuerySchema } from "@paperclipai/shared";
|
||||
@@ -15,7 +16,6 @@ import {
|
||||
type ResponsibilitySummaryServiceOptions,
|
||||
} from "../services/responsibility-summaries.js";
|
||||
import { assertCompanyAccess, getAccessibleResource } from "./authz.js";
|
||||
import { defaultResponsibilityOwnerUserId } from "./responsibilities.js";
|
||||
|
||||
const NOT_FOUND = "Responsibility not found";
|
||||
const summaryQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true });
|
||||
@@ -67,12 +67,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi
|
||||
const companyId = req.params.companyId as string;
|
||||
await assertCompanyRead(req, companyId);
|
||||
const query = summaryQuerySchema.parse(req.query);
|
||||
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
|
||||
if (!ownerUserId) {
|
||||
throw unprocessable(req.actor.type === "agent"
|
||||
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to summarize"
|
||||
: "ownerUserId is required");
|
||||
}
|
||||
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
|
||||
const overview = await responsibilities.overview(companyId, ownerUserId, {
|
||||
includeLetGo: false,
|
||||
scope: await readScope(req),
|
||||
@@ -85,6 +80,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi
|
||||
const row = await getAccessibleResource(req, res, responsibilities.getById(req.params.id as string), NOT_FOUND);
|
||||
if (!row) return;
|
||||
await assertCompanyRead(req, row.companyId);
|
||||
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
|
||||
const detail = await responsibilities.detail(row, await readScope(req), { actor: req.actor });
|
||||
res.json(await summaries.affectingTheNumber({ detail, actor: req.actor }));
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ import { trackRoutineCreated } from "@paperclipai/shared/telemetry";
|
||||
import { validate, validateIssueMutationBody } from "../middleware/validate.js";
|
||||
import { accessService, documentAnnotationService, instanceSettingsService, logActivity, routineService } from "../services/index.js";
|
||||
import { instanceSettingsService as experimentSettings } from "../services/instance-settings.js";
|
||||
import { dashboardOwner } from "./responsibility-owner.js";
|
||||
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
|
||||
import { agentPersonInCompany } from "./agent-person-authz.js";
|
||||
import { assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
|
||||
@@ -207,7 +208,8 @@ export function routineRoutes(
|
||||
&& (await experimentSettings(db).getExperimental()).enableResponsibilities !== true) {
|
||||
throw responsibilitiesDisabledError();
|
||||
}
|
||||
const result = await svc.list(companyId, { ...filters, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) });
|
||||
const ownerUserId = filters.responsibilityId || unfiled === "true" ? await dashboardOwner(db, req, companyId) : undefined;
|
||||
const result = await svc.list(companyId, { ...filters, ownerUserId, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) });
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isDashboardActivity } from "./responsibility-privacy.js";
|
||||
import { notifyActiveRunSilence } from "./live-run-recovery-notifications.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { beginRunPhase } from "./execution-preparation-timing.js";
|
||||
@@ -152,15 +153,21 @@ export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActi
|
||||
export function publishActivity(publication: ActivityPublication) {
|
||||
const finish = beginRunPhase("execution.realtime");
|
||||
try {
|
||||
publishLiveEvent({
|
||||
companyId: publication.companyId,
|
||||
type: "activity.logged",
|
||||
payload: publication.payload,
|
||||
});
|
||||
if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent);
|
||||
} catch (error) {
|
||||
finish(true);
|
||||
throw error;
|
||||
if (isDashboardActivity(publication.payload.entityType)) {
|
||||
// The company bus carries only an invalidation. Each viewer fetches their own data.
|
||||
publishLiveEvent({
|
||||
companyId: publication.companyId,
|
||||
type: "activity.logged",
|
||||
payload: { action: "responsibility.dashboard_changed", entityType: "responsibility" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
publishLiveEvent({
|
||||
companyId: publication.companyId,
|
||||
type: "activity.logged",
|
||||
payload: publication.payload,
|
||||
});
|
||||
if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent);
|
||||
} finally { finish(); }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardActivityCondition, dashboardAuditConversationCondition } from "./responsibility-privacy.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { skillAccessService } from "./skill-access.js";
|
||||
import { credentialAccessConnectionNameSql } from "./credential-access-visibility.js";
|
||||
@@ -37,6 +38,7 @@ export interface ActivityFilters {
|
||||
limit?: number;
|
||||
readCondition?: SQL<boolean>;
|
||||
caseReadCondition?: SQL<boolean>;
|
||||
dashboardUserId?: string | null;
|
||||
}
|
||||
|
||||
const DEFAULT_ACTIVITY_LIMIT = 100;
|
||||
@@ -418,6 +420,7 @@ export function activityService(db: Db) {
|
||||
return {
|
||||
list: async (filters: ActivityFilters) => {
|
||||
const conditions = [eq(activityLog.companyId, filters.companyId), await skillAccessService(db).activityCondition(filters.companyId),
|
||||
dashboardActivityCondition(filters.dashboardUserId), dashboardAuditConversationCondition(filters.dashboardUserId),
|
||||
filters.caseReadCondition ?? sql<boolean>`${activityLog.entityType} <> 'case'`];
|
||||
const limit = normalizeActivityLimit(filters.limit);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardActivityCondition, dashboardAuditConversationCondition } from "./responsibility-privacy.js";
|
||||
import { and, desc, eq, gte, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
@@ -22,6 +23,7 @@ export interface AgentActionAuditFilters {
|
||||
cursor?: string;
|
||||
limit: number;
|
||||
caseReadCondition?: SQL<boolean>;
|
||||
dashboardUserId?: string | null;
|
||||
}
|
||||
|
||||
type CursorValue = { createdAt: string; id: string };
|
||||
@@ -57,6 +59,7 @@ export function agentActionAuditService(db: Db) {
|
||||
if (filters.cursor && !cursor) throw badRequest("Invalid audit cursor");
|
||||
const effectiveResponsibleUserId = sql<string | null>`coalesce(${activityLog.responsibleUserId}, ${heartbeatRuns.responsibleUserId})`;
|
||||
const conditions = [eq(activityLog.companyId, filters.companyId),
|
||||
dashboardActivityCondition(filters.dashboardUserId), dashboardAuditConversationCondition(filters.dashboardUserId),
|
||||
filters.caseReadCondition ?? sql<boolean>`${activityLog.entityType} <> 'case'`];
|
||||
// Preserve the historical agent-audit query unless the caller opts into
|
||||
// the unified all-actors feed explicitly.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dashboardConversationCondition, dashboardConversationReadable } from "./responsibility-privacy.js";
|
||||
import { readOncePerRequest } from "./authorization-read-scope.js";
|
||||
import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
@@ -172,6 +173,7 @@ export type AuthorizationDecision = {
|
||||
| "deny_agent_interaction"
|
||||
| "deny_low_trust_boundary"
|
||||
| "deny_issue_private"
|
||||
| "deny_dashboard_conversation_private"
|
||||
| "deny_project_private"
|
||||
| "deny_scope"
|
||||
| "deny_unsupported_action";
|
||||
@@ -226,6 +228,7 @@ const PLAIN_DELEGATED_USER_DENIALS: Record<AuthorizationDenialReason, (subject:
|
||||
deny_low_trust_boundary: (subject, action) => `This company's limits for this agent do not let ${lowerFirst(subject)} ${action}.`,
|
||||
deny_agent_interaction: (_subject, action) => `Agents are not allowed to ${action} in this company; a person who manages permissions can change this.`,
|
||||
deny_issue_private: (subject) => `${subject} cannot see this private task.`,
|
||||
deny_dashboard_conversation_private: (subject) => `${subject} cannot see this personal dashboard conversation.`,
|
||||
deny_project_private: (subject) => `${subject} cannot see this private project.`,
|
||||
inbox_target_user_unresolved: () => "Paperclip could not tell whose inbox this is.",
|
||||
inbox_management_disabled: () => "This person has turned off agent management of their inbox.",
|
||||
@@ -741,12 +744,13 @@ export async function readInstanceAdmin(db: Db | DbTransaction, userId: string):
|
||||
}
|
||||
|
||||
export async function issueReadSqlCondition(db: Db | DbTransaction, actor: AuthorizationActor): Promise<SQL<boolean>> {
|
||||
if (actor.authorizingUserId) return issuePrivacyCondition(actor);
|
||||
if (issuePrivacyMode() !== "enforce") return sql<boolean>`true`;
|
||||
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return sql<boolean>`true`;
|
||||
const personal = dashboardConversationCondition(actor);
|
||||
if (actor.authorizingUserId) return sql<boolean>`(${personal} and ${issuePrivacyCondition(actor)})`;
|
||||
if (issuePrivacyMode() !== "enforce") return personal;
|
||||
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return personal;
|
||||
if (actor.type === "board" && !actor.ignoreInstanceAdmin && actor.source !== "cloud_tenant"
|
||||
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return sql<boolean>`true`;
|
||||
return issuePrivacyCondition(actor);
|
||||
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return personal;
|
||||
return sql<boolean>`(${personal} and ${issuePrivacyCondition(actor)})`;
|
||||
}
|
||||
|
||||
/** SQL equivalent used for project list/search pushdown. */
|
||||
@@ -3017,9 +3021,6 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
|| input.resource.type !== "issue"
|
||||
|| !input.resource.issueId
|
||||
|| !intersectedDecision.allowed
|
||||
|| intersectedDecision.reason === "allow_instance_admin"
|
||||
|| intersectedDecision.reason === "allow_local_board"
|
||||
|| (!input.actor.authorizingUserId && issuePrivacyMode() === "off")
|
||||
) return intersectedDecision;
|
||||
|
||||
const resource = input.resource;
|
||||
@@ -3029,6 +3030,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
.select({
|
||||
id: issues.id,
|
||||
companyId: issues.companyId,
|
||||
originKind: issues.originKind, originId: issues.originId,
|
||||
visibility: issues.visibility,
|
||||
privacyRootIssueId: issues.privacyRootIssueId,
|
||||
responsibleUserId: issues.responsibleUserId,
|
||||
@@ -3040,6 +3042,15 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, resource.issueId!), eq(issues.companyId, resource.companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (issue && !dashboardConversationReadable(input.actor, issue)) {
|
||||
return deny({
|
||||
action: input.action,
|
||||
reason: "deny_dashboard_conversation_private",
|
||||
explanation: "This personal dashboard conversation is private.",
|
||||
});
|
||||
}
|
||||
if (intersectedDecision.reason === "allow_instance_admin" || intersectedDecision.reason === "allow_local_board"
|
||||
|| (!input.actor.authorizingUserId && issuePrivacyMode() === "off")) return intersectedDecision;
|
||||
if (!issue || (retainedIssue?.companyId === resource.companyId
|
||||
? retainedIssue.readable : await canActorReadIssuePrivacy(db, input.actor, issue))) return intersectedDecision;
|
||||
|
||||
|
||||
@@ -885,11 +885,11 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
}
|
||||
|
||||
/** Company-wide unfinished projects, open tasks and active routines under no live responsibility. */
|
||||
async function looseWork(companyId: string, scope: ResponsibilityReadScope): Promise<ResponsibilityLooseWork> {
|
||||
async function looseWork(companyId: string, ownerUserId: string, scope: ResponsibilityReadScope): Promise<ResponsibilityLooseWork> {
|
||||
const liveLink = (column: SQL) => sql`exists (
|
||||
select 1 from ${responsibilityLinks} ll
|
||||
join ${responsibilities} lr on lr.id = ll.responsibility_id
|
||||
where ${column} and lr.status in ${LIVE_STATUS_SQL})`;
|
||||
where ${column} and lr.owner_user_id = ${ownerUserId} and lr.status in ${LIVE_STATUS_SQL})`;
|
||||
const projectLoose = sql`not ${liveLink(sql`ll.project_id = ${projects.id}`)}`;
|
||||
const issueLoose = sql`not ${liveLink(sql`ll.issue_id = ${issues.id}`)}
|
||||
and (${issues.projectId} is null or not ${liveLink(sql`ll.project_id = ${issues.projectId}`)})`;
|
||||
@@ -977,8 +977,8 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
return row;
|
||||
}
|
||||
|
||||
async function assertAreaUsable(companyId: string, areaId: string, database: Db | DbTransaction = db) {
|
||||
const area = await areasSvc.getInCompany(companyId, areaId, database);
|
||||
async function assertAreaUsable(companyId: string, ownerUserId: string, areaId: string, database: Db | DbTransaction = db) {
|
||||
const area = await areasSvc.getInCompany(companyId, ownerUserId, areaId, database);
|
||||
if (!area) throw notFound("Area not found");
|
||||
if (area.status === "archived") throw unprocessable("That area is archived; restore it or choose another area");
|
||||
return area;
|
||||
@@ -1017,7 +1017,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
/** Inside `tx`: when the row is active and its area is proposed, the area becomes active. */
|
||||
async function activateAreaFor(tx: DbTransaction, row: ResponsibilityRow): Promise<ResponsibilityArea | null> {
|
||||
if (row.status !== "active" || !row.areaId) return null;
|
||||
return areasSvc.activateIfProposed(tx, row.companyId, row.areaId);
|
||||
return areasSvc.activateIfProposed(tx, row.companyId, row.ownerUserId, row.areaId);
|
||||
}
|
||||
|
||||
/** Agent rule for an active responsibility: it runs it, or is assigned a member task or routine. */
|
||||
@@ -1208,8 +1208,8 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
withRollups(rows, opts.scope),
|
||||
distinctTaskTotals(activeIds, opts.scope),
|
||||
distinctProjectTotals(activeIds, opts.scope),
|
||||
looseWork(companyId, opts.scope),
|
||||
areasSvc.listActiveAnd(companyId, referencedAreaIds),
|
||||
looseWork(companyId, ownerUserId, opts.scope),
|
||||
areasSvc.listActiveAnd(companyId, ownerUserId, referencedAreaIds),
|
||||
]);
|
||||
const responsibilitiesList = all.filter((row) => row.status !== "proposed");
|
||||
const proposed = all.filter((row) => row.status === "proposed");
|
||||
@@ -1271,7 +1271,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
rollups, area, projectRows, directRoutineRows, projectRoutineRows, directTaskRows, projectTaskRows, skills, artifacts, projectTaskCounts,
|
||||
] = await Promise.all([
|
||||
computeRollups([row], scope),
|
||||
row.areaId ? areasSvc.getInCompany(row.companyId, row.areaId) : Promise.resolve(null),
|
||||
row.areaId ? areasSvc.getInCompany(row.companyId, row.ownerUserId, row.areaId) : Promise.resolve(null),
|
||||
db.select({
|
||||
linkId: responsibilityLinks.id,
|
||||
id: projects.id,
|
||||
@@ -1386,7 +1386,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
metricHigh: input.metricHigh ?? null,
|
||||
});
|
||||
}
|
||||
if (input.areaId) await assertAreaUsable(companyId, input.areaId);
|
||||
if (input.areaId) await assertAreaUsable(companyId, ownerUserId, input.areaId);
|
||||
if (input.runByAgentId) await assertAgentInCompany(companyId, input.runByAgentId);
|
||||
const now = new Date();
|
||||
// The schema guarantees a metric is either whole or absent; without one
|
||||
@@ -1518,7 +1518,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
throw forbidden("Agents can only propose or dismiss a responsibility; a board user confirms it");
|
||||
}
|
||||
}
|
||||
if (patch.areaId) await assertAreaUsable(existing.companyId, patch.areaId);
|
||||
if (patch.areaId) await assertAreaUsable(existing.companyId, existing.ownerUserId, patch.areaId);
|
||||
if (patch.runByAgentId) await assertAgentInCompany(existing.companyId, patch.runByAgentId);
|
||||
|
||||
const nextStatus = patch.status ?? existing.status;
|
||||
@@ -1736,6 +1736,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
*/
|
||||
async lookup(
|
||||
companyId: string,
|
||||
ownerUserId: string,
|
||||
target: ResponsibilityLinkTarget,
|
||||
scope: ResponsibilityReadScope,
|
||||
): Promise<ResponsibilityLinkLookupEntry[]> {
|
||||
@@ -1752,6 +1753,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
|
||||
.innerJoin(responsibilities, eq(responsibilities.id, responsibilityLinks.responsibilityId))
|
||||
.where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
eq(responsibilities.ownerUserId, ownerUserId),
|
||||
inArray(responsibilities.status, [...LIVE_STATUSES]),
|
||||
projectId
|
||||
? or(eq(column, target.id), eq(responsibilityLinks.projectId, projectId))
|
||||
|
||||
@@ -97,7 +97,7 @@ export function responsibilityAgentChangeService(db: Db) {
|
||||
agentId: string;
|
||||
interactionId: string | undefined;
|
||||
key: string;
|
||||
ownerUserId?: string;
|
||||
ownerUserId: string;
|
||||
}) {
|
||||
const refuse = () => forbidden(
|
||||
"A permanent delete needs the person's confirmation: post a confirmation card, then delete with its id after they accept it",
|
||||
@@ -129,8 +129,7 @@ export function responsibilityAgentChangeService(db: Db) {
|
||||
eq(companyMemberships.principalId, resolverUserId),
|
||||
eq(companyMemberships.status, "active"),
|
||||
));
|
||||
const allowed = membership && (!input.ownerUserId || resolverUserId === input.ownerUserId
|
||||
|| membership.role === "owner" || membership.role === "admin");
|
||||
const allowed = membership && resolverUserId === input.ownerUserId;
|
||||
if (!allowed) throw refuse();
|
||||
return card;
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ import { conflict, notFound } from "../errors.js";
|
||||
type AreaRow = typeof responsibilityAreas.$inferSelect;
|
||||
type DbOrTransaction = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
|
||||
const TITLE_UNIQUE_INDEX = "responsibility_areas_company_title_uq";
|
||||
const TITLE_UNIQUE_INDEX = "responsibility_areas_owner_title_uq";
|
||||
|
||||
/** `board` with `viaAgentId`: an agent acting for a member of the company, which creates what that person could. */
|
||||
export type ResponsibilityAreaCreateActor =
|
||||
@@ -20,7 +20,14 @@ export type ResponsibilityAreaCreateActor =
|
||||
|
||||
export function toResponsibilityArea(row: AreaRow): ResponsibilityArea {
|
||||
return {
|
||||
...row,
|
||||
id: row.id,
|
||||
companyId: row.companyId,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
proposedByAgentId: row.proposedByAgentId,
|
||||
sortOrder: row.sortOrder,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
status: row.status as ResponsibilityArea["status"],
|
||||
source: row.source as ResponsibilityArea["source"],
|
||||
};
|
||||
@@ -46,15 +53,13 @@ const AREA_ORDER = [
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Areas: broad nouns a company cares about. No owner. Board users, and agents
|
||||
* acting for a member of the company, manage them; other agents can only
|
||||
* propose one (idempotently, by case-insensitive title).
|
||||
* Area titles are unique within one person's dashboard in a company.
|
||||
*/
|
||||
export function responsibilityAreaService(db: Db) {
|
||||
async function findLiveByTitle(companyId: string, title: string, database: DbOrTransaction = db) {
|
||||
async function findLiveByTitle(companyId: string, ownerUserId: string, title: string, database: DbOrTransaction = db) {
|
||||
return database.select().from(responsibilityAreas)
|
||||
.where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
sql`lower(${responsibilityAreas.title}) = lower(${title})`,
|
||||
ne(responsibilityAreas.status, "archived"),
|
||||
))
|
||||
@@ -66,16 +71,16 @@ export function responsibilityAreaService(db: Db) {
|
||||
getById: (id: string) =>
|
||||
db.select().from(responsibilityAreas).where(eq(responsibilityAreas.id, id)).then((rows) => rows[0] ?? null),
|
||||
|
||||
async getInCompany(companyId: string, id: string, database: DbOrTransaction = db) {
|
||||
async getInCompany(companyId: string, ownerUserId: string, id: string, database: DbOrTransaction = db) {
|
||||
return database.select().from(responsibilityAreas)
|
||||
.where(and(eq(responsibilityAreas.id, id), eq(responsibilityAreas.companyId, companyId)))
|
||||
.where(and(eq(responsibilityAreas.id, id), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
},
|
||||
|
||||
async list(companyId: string, opts: { includeArchived?: boolean } = {}): Promise<ResponsibilityArea[]> {
|
||||
async list(companyId: string, ownerUserId: string, opts: { includeArchived?: boolean } = {}): Promise<ResponsibilityArea[]> {
|
||||
const rows = await db.select().from(responsibilityAreas)
|
||||
.where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
opts.includeArchived ? undefined : ne(responsibilityAreas.status, "archived"),
|
||||
))
|
||||
.orderBy(...AREA_ORDER);
|
||||
@@ -83,10 +88,10 @@ export function responsibilityAreaService(db: Db) {
|
||||
},
|
||||
|
||||
/** Active areas in the company plus the listed ids (whatever their status). */
|
||||
async listActiveAnd(companyId: string, ids: readonly string[]): Promise<ResponsibilityArea[]> {
|
||||
async listActiveAnd(companyId: string, ownerUserId: string, ids: readonly string[]): Promise<ResponsibilityArea[]> {
|
||||
const rows = await db.select().from(responsibilityAreas)
|
||||
.where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
ids.length > 0
|
||||
? or(eq(responsibilityAreas.status, "active"), inArray(responsibilityAreas.id, [...ids]))
|
||||
: eq(responsibilityAreas.status, "active"),
|
||||
@@ -102,13 +107,14 @@ export function responsibilityAreaService(db: Db) {
|
||||
*/
|
||||
async create(
|
||||
companyId: string,
|
||||
ownerUserId: string,
|
||||
input: CreateResponsibilityArea,
|
||||
actor: ResponsibilityAreaCreateActor,
|
||||
): Promise<{ area: ResponsibilityArea; created: boolean }> {
|
||||
const existing = await findLiveByTitle(companyId, input.title);
|
||||
const existing = await findLiveByTitle(companyId, ownerUserId, input.title);
|
||||
if (existing) return { area: toResponsibilityArea(existing), created: false };
|
||||
const values: typeof responsibilityAreas.$inferInsert = {
|
||||
companyId,
|
||||
companyId, ownerUserId,
|
||||
title: input.title,
|
||||
description: input.description ?? null,
|
||||
sortOrder: input.sortOrder ?? 0,
|
||||
@@ -123,13 +129,14 @@ export function responsibilityAreaService(db: Db) {
|
||||
} catch (error) {
|
||||
if (!isTitleConflict(error)) throw error;
|
||||
// A concurrent request created the same title first; return it.
|
||||
const winner = await findLiveByTitle(companyId, input.title);
|
||||
const winner = await findLiveByTitle(companyId, ownerUserId, input.title);
|
||||
if (!winner) throw error;
|
||||
return { area: toResponsibilityArea(winner), created: false };
|
||||
}
|
||||
},
|
||||
|
||||
async update(existing: AreaRow, patch: UpdateResponsibilityArea): Promise<ResponsibilityArea> {
|
||||
if (!existing.ownerUserId) throw notFound("Area not found");
|
||||
const set: Partial<typeof responsibilityAreas.$inferInsert> = { updatedAt: new Date() };
|
||||
for (const key of ["title", "description", "sortOrder", "status"] as const) {
|
||||
if (patch[key] !== undefined) (set as Record<string, unknown>)[key] = patch[key];
|
||||
@@ -137,7 +144,7 @@ export function responsibilityAreaService(db: Db) {
|
||||
const nextTitle = patch.title ?? existing.title;
|
||||
const nextStatus = patch.status ?? existing.status;
|
||||
if (nextStatus !== "archived" && (patch.title !== undefined || patch.status !== undefined)) {
|
||||
const clash = await findLiveByTitle(existing.companyId, nextTitle);
|
||||
const clash = await findLiveByTitle(existing.companyId, existing.ownerUserId, nextTitle);
|
||||
if (clash && clash.id !== existing.id) {
|
||||
throw conflict(`Another area is already called "${clash.title}"`, { areaId: clash.id });
|
||||
}
|
||||
@@ -160,12 +167,14 @@ export function responsibilityAreaService(db: Db) {
|
||||
* otherwise left with `areaId` null (FK on delete set null).
|
||||
*/
|
||||
async remove(existing: AreaRow, opts: { moveTo?: string | null } = {}): Promise<{ area: ResponsibilityArea; moved: number } | null> {
|
||||
const ownerUserId = existing.ownerUserId;
|
||||
if (!ownerUserId) throw notFound("Area not found");
|
||||
return db.transaction(async (tx) => {
|
||||
let moved = 0;
|
||||
if (opts.moveTo) {
|
||||
if (opts.moveTo === existing.id) throw conflict("Move its responsibilities to a different area");
|
||||
const target = await tx.select().from(responsibilityAreas)
|
||||
.where(and(eq(responsibilityAreas.id, opts.moveTo), eq(responsibilityAreas.companyId, existing.companyId)))
|
||||
.where(and(eq(responsibilityAreas.id, opts.moveTo), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, existing.companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!target) throw notFound("Area to move responsibilities to not found");
|
||||
if (target.status === "archived") throw conflict("That area is archived; restore it or choose another area");
|
||||
@@ -181,23 +190,13 @@ export function responsibilityAreaService(db: Db) {
|
||||
});
|
||||
},
|
||||
|
||||
/** The people with an active responsibility in the area, whose Dashboards show it. */
|
||||
async ownersInArea(companyId: string, areaId: string, statuses: readonly string[] = ["active"]): Promise<string[]> {
|
||||
const rows = await db.selectDistinct({ ownerUserId: responsibilities.ownerUserId }).from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
eq(responsibilities.areaId, areaId),
|
||||
inArray(responsibilities.status, [...statuses]),
|
||||
));
|
||||
return rows.map((row) => row.ownerUserId);
|
||||
},
|
||||
|
||||
/** Inside `tx`: make a proposed area active. Returns the area when it changed. */
|
||||
async activateIfProposed(tx: DbOrTransaction, companyId: string, areaId: string): Promise<ResponsibilityArea | null> {
|
||||
async activateIfProposed(tx: DbOrTransaction, companyId: string, ownerUserId: string, areaId: string): Promise<ResponsibilityArea | null> {
|
||||
const [row] = await tx.update(responsibilityAreas)
|
||||
.set({ status: "active", updatedAt: new Date() })
|
||||
.where(and(
|
||||
eq(responsibilityAreas.id, areaId),
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.status, "proposed"),
|
||||
))
|
||||
.returning();
|
||||
|
||||
@@ -96,15 +96,15 @@ export function automationConversationService(
|
||||
* responsibility the task is under (the one the person started from first);
|
||||
* otherwise the organization's first-created agent that can be assigned.
|
||||
*/
|
||||
async function defaultAgentId(source: Pick<IssueRow, "id" | "companyId" | "assigneeAgentId">, responsibilityId?: string): Promise<string | null> {
|
||||
async function defaultAgentId(source: Pick<IssueRow, "id" | "companyId" | "assigneeAgentId">, ownerUserId: string, responsibilityId?: string): Promise<string | null> {
|
||||
const [{ rows, usable }, under] = await Promise.all([
|
||||
companyAgents(source.companyId),
|
||||
responsibilitiesSvc.lookup(source.companyId, { kind: "issue", id: source.id }, unrestricted).catch(() => []),
|
||||
responsibilitiesSvc.lookup(source.companyId, ownerUserId, { kind: "issue", id: source.id }, unrestricted).catch(() => []),
|
||||
]);
|
||||
const ids = [...new Set([responsibilityId, ...under.map((entry) => entry.id)].filter((id): id is string => !!id))];
|
||||
const runners = ids.length === 0 ? [] : await db.select({ id: responsibilities.id, runByAgentId: responsibilities.runByAgentId })
|
||||
.from(responsibilities)
|
||||
.where(and(eq(responsibilities.companyId, source.companyId), inArray(responsibilities.id, ids)));
|
||||
.where(and(eq(responsibilities.companyId, source.companyId), eq(responsibilities.ownerUserId, ownerUserId), inArray(responsibilities.id, ids)));
|
||||
const runnerIds = ids.map((id) => runners.find((row) => row.id === id)?.runByAgentId).filter((id): id is string => !!id);
|
||||
return responsibleAutomationAgentId({
|
||||
taskAgentId: source.assigneeAgentId,
|
||||
@@ -114,11 +114,12 @@ export function automationConversationService(
|
||||
});
|
||||
}
|
||||
|
||||
async function latestConversation(source: Pick<IssueRow, "id" | "companyId">): Promise<IssueRow | null> {
|
||||
async function latestConversation(source: Pick<IssueRow, "id" | "companyId">, ownerUserId: string): Promise<IssueRow | null> {
|
||||
const [issue] = await db.select().from(issues).where(and(
|
||||
eq(issues.companyId, source.companyId),
|
||||
eq(issues.originKind, AUTOMATION_CONVERSATION_ORIGIN_KIND),
|
||||
eq(issues.originId, source.id),
|
||||
eq(issues.createdByUserId, ownerUserId),
|
||||
ne(issues.status, "cancelled"),
|
||||
)).orderBy(desc(issues.createdAt), desc(issues.id)).limit(1);
|
||||
return issue ?? null;
|
||||
@@ -168,8 +169,8 @@ export function automationConversationService(
|
||||
}
|
||||
|
||||
/** Where the automation conversation for a task stands. */
|
||||
async function conversation(source: IssueRow): Promise<AutomationConversation> {
|
||||
const [issue, agentId] = await Promise.all([latestConversation(source), defaultAgentId(source)]);
|
||||
async function conversation(source: IssueRow, ownerUserId: string): Promise<AutomationConversation> {
|
||||
const [issue, agentId] = await Promise.all([latestConversation(source, ownerUserId), defaultAgentId(source, ownerUserId)]);
|
||||
const proposal = issue ? await pendingProposal(issue) : null;
|
||||
const state: AutomationConversation["state"] = !issue ? "none"
|
||||
: proposal ? "proposal_waiting"
|
||||
@@ -201,7 +202,7 @@ export function automationConversationService(
|
||||
* not cancelled, while it is open or has a proposal waiting). Two queries
|
||||
* whatever the count.
|
||||
*/
|
||||
async conversationsForTasks(companyId: string, taskIds: readonly string[]): Promise<Map<string, AutomationConversationRef>> {
|
||||
async conversationsForTasks(companyId: string, taskIds: readonly string[], ownerUserId: string): Promise<Map<string, AutomationConversationRef>> {
|
||||
const found = new Map<string, AutomationConversationRef>();
|
||||
if (taskIds.length === 0) return found;
|
||||
const rows = await db.selectDistinctOn([issues.originId], {
|
||||
@@ -213,6 +214,7 @@ export function automationConversationService(
|
||||
}).from(issues).where(and(
|
||||
eq(issues.companyId, companyId),
|
||||
eq(issues.originKind, AUTOMATION_CONVERSATION_ORIGIN_KIND),
|
||||
eq(issues.createdByUserId, ownerUserId),
|
||||
inArray(issues.originId, [...new Set(taskIds)]),
|
||||
ne(issues.status, "cancelled"),
|
||||
)).orderBy(issues.originId, desc(issues.createdAt), desc(issues.id));
|
||||
@@ -238,9 +240,9 @@ export function automationConversationService(
|
||||
return found;
|
||||
},
|
||||
|
||||
async conversationFor(issueRef: { id: string; companyId: string }) {
|
||||
async conversationFor(issueRef: { id: string; companyId: string }, ownerUserId: string) {
|
||||
await assertEnabled();
|
||||
return conversation(await loadSource(issueRef.companyId, issueRef.id));
|
||||
return conversation(await loadSource(issueRef.companyId, issueRef.id), ownerUserId);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -259,11 +261,11 @@ export function automationConversationService(
|
||||
await suggestions.assertCanBeAutomated(issueRef);
|
||||
const source = await loadSource(issueRef.companyId, issueRef.id);
|
||||
await assertNotAutomatedYet(source);
|
||||
const existing = await latestConversation(source);
|
||||
const existing = await latestConversation(source, actor.userId);
|
||||
if (existing && (!isClosed(existing.status) || (await pendingProposal(existing)))) {
|
||||
return { source, issue: existing, created: false };
|
||||
}
|
||||
const agentId = input.agentId ?? await defaultAgentId(source, input.responsibilityId);
|
||||
const agentId = input.agentId ?? await defaultAgentId(source, actor.userId, input.responsibilityId);
|
||||
if (!agentId) {
|
||||
throw unprocessable("No agent in this organization can talk this through; set the automation up by hand", {
|
||||
code: "automation_conversation_no_agent",
|
||||
@@ -288,14 +290,9 @@ export function automationConversationService(
|
||||
...(hint ? ["", `Quick suggestion from its title (only a guess): ${hint.why}`] : []),
|
||||
...(backLink ? ["", backLink] : []),
|
||||
].join("\n");
|
||||
// The conversation copies the task's title and identifier, so a private
|
||||
// task's conversation is private too: only the person and the agent see it.
|
||||
const sourceIsPrivate = source.visibility === "private" || source.privacyRootIssueId !== null
|
||||
|| (source.projectId !== null && await db.select({ id: projects.id }).from(projects)
|
||||
.where(and(eq(projects.id, source.projectId), eq(projects.companyId, source.companyId), eq(projects.visibility, "private")))
|
||||
.limit(1).then((rows) => rows.length > 0));
|
||||
const issue = await issuesSvc.create(source.companyId, {
|
||||
...(sourceIsPrivate ? { visibility: "private" as const } : {}),
|
||||
visibility: "private",
|
||||
responsibleUserId: actor.userId,
|
||||
title: clip(`Automate “${source.title}”`, 200),
|
||||
description,
|
||||
status: "todo",
|
||||
@@ -344,7 +341,7 @@ export function automationConversationService(
|
||||
code: "automation_standing_check_no_heartbeat",
|
||||
});
|
||||
}
|
||||
const filedUnder = (await responsibilitiesSvc.lookup(issue.companyId, { kind: "issue", id: source.id }, unrestricted))
|
||||
const filedUnder = (await responsibilitiesSvc.lookup(issue.companyId, issue.createdByUserId!, { kind: "issue", id: source.id }, unrestricted))
|
||||
.map((entry) => ({ id: entry.id, title: entry.title }));
|
||||
const trigger: ProposeAutomationPayload["trigger"] = data.trigger.kind === "schedule"
|
||||
? (() => {
|
||||
|
||||
@@ -93,7 +93,7 @@ export function responsibilityAutomationService(
|
||||
suggestions.unrepeatableIssueIds(companyId, taskIds),
|
||||
routinesSvc.liveOriginIds(companyId, ROUTINE_FROM_TASK_ORIGIN_KIND, taskIds),
|
||||
interactions.routineSuggestionsForIssues(companyId, taskIds),
|
||||
conversations.conversationsForTasks(companyId, taskIds),
|
||||
conversations.conversationsForTasks(companyId, taskIds, ownerUserId),
|
||||
conversations.companyAgents(companyId),
|
||||
standingChecks.lastResults(companyId, routineIds, opts.scope.issueReadCondition),
|
||||
]);
|
||||
|
||||
@@ -273,6 +273,8 @@ export function responsibilityBarService(db: Db) {
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: agentId,
|
||||
visibility: "private",
|
||||
responsibleUserId: row.ownerUserId,
|
||||
originKind: RESPONSIBILITY_BAR_ORIGIN_KIND,
|
||||
originId: row.id,
|
||||
createdByUserId: actor.userId,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, desc, eq, inArray, ne, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { authUsers, issueThreadInteractions, issues, responsibilities, responsibilityAreas } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -24,8 +24,6 @@ const OTHER_AREA_LIMIT = 40;
|
||||
export interface DashboardGuidanceArea {
|
||||
id: string;
|
||||
title: string;
|
||||
/** How many other people have responsibilities in it. */
|
||||
others: number;
|
||||
/** This person's active responsibilities in it. */
|
||||
items: Array<{ id: string; sentence: string }>;
|
||||
}
|
||||
@@ -40,8 +38,8 @@ export interface DashboardGuidanceInput {
|
||||
areas: DashboardGuidanceArea[];
|
||||
/** The person's active responsibilities filed under no area. */
|
||||
unfiled: Array<{ id: string; sentence: string }>;
|
||||
/** Other live areas in the organization. */
|
||||
otherAreas: Array<{ id: string; title: string; others: number }>;
|
||||
/** Their other live areas. */
|
||||
otherAreas: Array<{ id: string; title: string }>;
|
||||
/** Responsibilities proposed earlier that wait for the person. */
|
||||
proposed: string[];
|
||||
/** Newest first. */
|
||||
@@ -61,7 +59,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
|
||||
return null;
|
||||
}
|
||||
const ownerUserId = issue.originId;
|
||||
const [issueRow, owner, items, areaRows, others, history] = await Promise.all([
|
||||
const [issueRow, owner, items, areaRows, history] = await Promise.all([
|
||||
db.select({ originFingerprint: issues.originFingerprint }).from(issues)
|
||||
.where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)))
|
||||
.then((rows) => rows[0] ?? null),
|
||||
@@ -80,14 +78,8 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
|
||||
)).orderBy(responsibilities.sortOrder, responsibilities.createdAt),
|
||||
db.select({ id: responsibilityAreas.id, title: responsibilityAreas.title, status: responsibilityAreas.status })
|
||||
.from(responsibilityAreas)
|
||||
.where(eq(responsibilityAreas.companyId, issue.companyId))
|
||||
.where(and(eq(responsibilityAreas.companyId, issue.companyId), eq(responsibilityAreas.ownerUserId, ownerUserId)))
|
||||
.orderBy(responsibilityAreas.sortOrder, sql`lower(${responsibilityAreas.title})`),
|
||||
db.select({ areaId: responsibilities.areaId, count: sql<number>`count(distinct ${responsibilities.ownerUserId})::int` })
|
||||
.from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, issue.companyId),
|
||||
ne(responsibilities.ownerUserId, ownerUserId),
|
||||
inArray(responsibilities.status, ["active", "proposed"]),
|
||||
)).groupBy(responsibilities.areaId),
|
||||
db.select({ status: issueThreadInteractions.status, payload: issueThreadInteractions.payload, result: issueThreadInteractions.result })
|
||||
.from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, issue.companyId),
|
||||
@@ -96,7 +88,6 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
|
||||
)).orderBy(desc(issueThreadInteractions.createdAt)).limit(PROPOSAL_HISTORY),
|
||||
]);
|
||||
if (!issueRow) return null;
|
||||
const othersByArea = new Map(others.filter((row) => row.areaId).map((row) => [row.areaId!, row.count]));
|
||||
const active = items.filter((item) => item.status === "active");
|
||||
const mine = new Set(active.map((item) => item.areaId).filter((id): id is string => id !== null));
|
||||
const areas: DashboardGuidanceArea[] = areaRows
|
||||
@@ -104,7 +95,6 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
|
||||
.map((area) => ({
|
||||
id: area.id,
|
||||
title: area.title,
|
||||
others: othersByArea.get(area.id) ?? 0,
|
||||
items: active.filter((item) => item.areaId === area.id).map((item) => ({ id: item.id, sentence: responsibilityDashboardSentence(item) })),
|
||||
}));
|
||||
return buildDashboardConversationGuidance({
|
||||
@@ -118,7 +108,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
|
||||
otherAreas: areaRows
|
||||
.filter((area) => area.status !== "archived" && !mine.has(area.id))
|
||||
.slice(0, OTHER_AREA_LIMIT)
|
||||
.map((area) => ({ id: area.id, title: area.title, others: othersByArea.get(area.id) ?? 0 })),
|
||||
.map((area) => ({ id: area.id, title: area.title })),
|
||||
proposed: items.filter((item) => item.status === "proposed").map((item) => responsibilityDashboardSentence(item)),
|
||||
proposals: history.map((entry) => {
|
||||
const payload = entry.payload as Partial<ProposeDashboardChangesPayload> | null;
|
||||
@@ -137,9 +127,7 @@ export async function loadDashboardConversationGuidance(db: Db, input: {
|
||||
});
|
||||
}
|
||||
|
||||
function shared(others: number) {
|
||||
return others === 0 ? "" : `; ${others === 1 ? "1 other person has" : `${others} other people have`} responsibilities in it`;
|
||||
}
|
||||
|
||||
|
||||
const CREATE_EXAMPLE = {
|
||||
message: "Here is a first dashboard from your answers and what I found in your calendar and mail.",
|
||||
@@ -169,7 +157,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
|
||||
: "They asked you to help change the dashboard they have."} End it with one proposed set of changes they can accept with one tap. You never change the dashboard yourself: only the person can, by accepting your proposal, and they can undo it afterwards.`,
|
||||
"",
|
||||
"What a dashboard is made of (reason from this, not only from the rules):",
|
||||
"- An area is a noun for something the person cares about: \"Fundraising\", \"Customers\", \"Hiring\". Nobody owns an area and it has no deadline; it groups what sits under it. Areas are shared across the organization, so other people may have responsibilities in the same area.",
|
||||
"- An area is a noun for something the person cares about: \"Fundraising\", \"Customers\", \"Hiring\". An area belongs to this person and groups their responsibilities.",
|
||||
"- A responsibility is something this person owns and answers for, on an ongoing basis. Write it as one sentence saying what must be true and stay true: \"Every prospective LP hears from us at least every two weeks.\" \"Customers get a reply within one working day.\" If it can be finished, it is a task or a project, not a responsibility: \"Send the deck to two LPs\" is a task, and \"Close Fund VI\" is a project that serves a responsibility.",
|
||||
"- Each responsibility passes three tests. Ongoing: it still makes sense after the current project ships. Theirs: they answer for it, not just take part in it (attending a meeting series is not owning it; running it is). In their words: the words their answers, mail subjects and calendar titles use, not job-description words.",
|
||||
`- Keep it small. A person can hold perhaps five to seven areas in their head, and one to three responsibilities under each is plenty. A few that are right beat a full list: every line is something they will look at every day, and a list that is mostly wrong teaches them to ignore it. Each sentence is at most ${RESPONSIBILITY_DASHBOARD_SENTENCE_MAX} characters.`,
|
||||
@@ -183,7 +171,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
|
||||
lines.push("- Empty: they own no responsibilities yet.");
|
||||
}
|
||||
for (const area of input.areas) {
|
||||
lines.push(`- Area "${area.title}" (areaId ${area.id}${shared(area.others)}):`);
|
||||
lines.push(`- Area "${area.title}" (areaId ${area.id}):`);
|
||||
for (const item of area.items) lines.push(` - "${item.sentence}" (responsibilityId ${item.id})`);
|
||||
}
|
||||
if (input.unfiled.length > 0) {
|
||||
@@ -191,8 +179,8 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
|
||||
for (const item of input.unfiled) lines.push(` - "${item.sentence}" (responsibilityId ${item.id})`);
|
||||
}
|
||||
if (input.otherAreas.length > 0) {
|
||||
lines.push("", "Other areas in the organization (file under one by its areaId rather than adding a near-duplicate):");
|
||||
for (const area of input.otherAreas) lines.push(`- "${area.title}" (areaId ${area.id}${shared(area.others)})`);
|
||||
lines.push("", "Their other areas (file under one by its areaId rather than adding a near-duplicate):");
|
||||
for (const area of input.otherAreas) lines.push(`- "${area.title}" (areaId ${area.id})`);
|
||||
}
|
||||
if (input.proposed.length > 0) {
|
||||
lines.push("", "Proposed to them earlier and still waiting for them (do not propose these again):");
|
||||
@@ -227,7 +215,7 @@ export function buildDashboardConversationGuidance(input: DashboardGuidanceInput
|
||||
"The changes, as an ordered list (each may carry a one-line reason; removals must):",
|
||||
"- { op: \"add_area\", ref, name }: ref is your own short key for the new area, used by later changes in the same list.",
|
||||
"- { op: \"rename_area\", areaId, name }: it is renamed for everyone with responsibilities in it.",
|
||||
"- { op: \"remove_area\", areaId, reason }: archives it and lets go of this person's responsibilities still in it (move any worth keeping). Refused when other people have responsibilities in it.",
|
||||
"- { op: \"remove_area\", areaId, reason }: archives it and lets go of this person's responsibilities still in it (move any worth keeping).",
|
||||
"- { op: \"add_responsibility\", areaId or areaRef, sentence }: one sentence of what must be true.",
|
||||
"- { op: \"reword_responsibility\", responsibilityId, sentence }",
|
||||
"- { op: \"move_responsibility\", responsibilityId, areaId or areaRef }",
|
||||
|
||||
@@ -34,7 +34,6 @@ type VersionRow = typeof responsibilityDashboardVersions.$inferSelect;
|
||||
type AreaRow = typeof responsibilityAreas.$inferSelect;
|
||||
type ResponsibilityRow = typeof responsibilities.$inferSelect;
|
||||
|
||||
const LIVE = ["proposed", "active"] as const;
|
||||
|
||||
/** One activity entry a restore or an applied change set writes after commit. */
|
||||
export interface DashboardActivityEvent {
|
||||
@@ -121,7 +120,7 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
createdNow: readonly string[] = [],
|
||||
touched: readonly string[] = [],
|
||||
): Promise<ResponsibilityDashboardSnapshot> {
|
||||
const [rows, linkRows, created] = await Promise.all([
|
||||
const [rows, linkRows] = await Promise.all([
|
||||
database.select({
|
||||
id: responsibilities.id,
|
||||
title: responsibilities.title,
|
||||
@@ -152,12 +151,6 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
eq(responsibilities.ownerUserId, ownerUserId),
|
||||
eq(responsibilities.status, "active"),
|
||||
)),
|
||||
database.selectDistinct({ id: sql<string>`jsonb_array_elements_text(${responsibilityDashboardVersions.snapshot} -> 'createdAreaIds')` })
|
||||
.from(responsibilityDashboardVersions)
|
||||
.where(and(
|
||||
eq(responsibilityDashboardVersions.companyId, companyId),
|
||||
eq(responsibilityDashboardVersions.ownerUserId, ownerUserId),
|
||||
)),
|
||||
]);
|
||||
const linksBy = new Map<string, ResponsibilityDashboardSnapshotLinks>();
|
||||
for (const link of linkRows) {
|
||||
@@ -179,20 +172,19 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
...item, links: sortedLinks(item.id), description, runByAgentId, evidence, healthOverride, healthNote,
|
||||
}));
|
||||
const referenced = [...new Set(items.map((item) => item.areaId).filter((value): value is string => value !== null))];
|
||||
const createdIds = [...new Set([...created.map((row) => row.id), ...createdNow])].filter((value) => !referenced.includes(value));
|
||||
// An area a change is about to touch is held whatever its status, so undoing a restore archives it again.
|
||||
const touchedIds = touched.filter((value) => !referenced.includes(value));
|
||||
const areas = referenced.length + createdIds.length + touchedIds.length === 0 ? [] : await database.select({
|
||||
const areas = await database.select({
|
||||
id: responsibilityAreas.id,
|
||||
title: responsibilityAreas.title,
|
||||
status: responsibilityAreas.status,
|
||||
sortOrder: responsibilityAreas.sortOrder,
|
||||
description: responsibilityAreas.description,
|
||||
}).from(responsibilityAreas).where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
or(
|
||||
referenced.length > 0 ? inArray(responsibilityAreas.id, referenced) : undefined,
|
||||
createdIds.length > 0 ? and(inArray(responsibilityAreas.id, createdIds), ne(responsibilityAreas.status, "archived")) : undefined,
|
||||
ne(responsibilityAreas.status, "archived"),
|
||||
touchedIds.length > 0 ? inArray(responsibilityAreas.id, touchedIds) : undefined,
|
||||
),
|
||||
));
|
||||
@@ -247,7 +239,9 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
// A version saved before snapshots held filed items is compared on what it holds.
|
||||
const legacy = previousSnapshot ? isLegacySnapshot(previousSnapshot) : false;
|
||||
const comparable = legacy ? dashboardSnapshotHash(input.snapshot, { legacy: true }) : hash;
|
||||
if (previous && previous.snapshotHash === comparable) {
|
||||
const previousHash = previous?.snapshotHash === "remapped" && previousSnapshot
|
||||
? dashboardSnapshotHash(previousSnapshot, { legacy }) : previous?.snapshotHash;
|
||||
if (previous && previousHash === comparable) {
|
||||
// One saved before skills could be filed hashes the same (no filed skills) but must hold the empty list too.
|
||||
if (!legacy && !lacksFiledSkills(previousSnapshot!)) return { row: previous, created: false };
|
||||
// The same dashboard as an older version that held no filed items,
|
||||
@@ -307,8 +301,7 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
* agent that runs it puts those back too (see restoreDetailsInTx); an older
|
||||
* version leaves them as they are.
|
||||
*
|
||||
* Areas other people have responsibilities in keep their name and order
|
||||
* (they see them too); a responsibility deleted since is created again with
|
||||
* A responsibility deleted since is created again with
|
||||
* its sentence; an area deleted since is created again (or the live area now
|
||||
* holding its name is used); when an area's old name is now another area's,
|
||||
* that area is used instead.
|
||||
@@ -326,20 +319,11 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
const now = new Date();
|
||||
const areaIds = [...new Set([...target.areas.map((area) => area.id), ...current.areas.map((area) => area.id)])];
|
||||
const targetItemIds = target.responsibilities.map((item) => item.id);
|
||||
const [areaRows, liveAreas, othersByArea, ownRows] = await Promise.all([
|
||||
const [areaRows, liveAreas, ownRows] = await Promise.all([
|
||||
areaIds.length === 0 ? Promise.resolve([] as AreaRow[]) : tx.select().from(responsibilityAreas)
|
||||
.where(and(eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, areaIds))),
|
||||
.where(and(eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), inArray(responsibilityAreas.id, areaIds))),
|
||||
tx.select({ id: responsibilityAreas.id, title: responsibilityAreas.title }).from(responsibilityAreas)
|
||||
.where(and(eq(responsibilityAreas.companyId, companyId), ne(responsibilityAreas.status, "archived"))),
|
||||
areaIds.length === 0 ? Promise.resolve([] as Array<{ areaId: string | null; count: number }>) : tx.select({
|
||||
areaId: responsibilities.areaId,
|
||||
count: sql<number>`count(*)::int`,
|
||||
}).from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
inArray(responsibilities.areaId, areaIds),
|
||||
ne(responsibilities.ownerUserId, ownerUserId),
|
||||
inArray(responsibilities.status, [...LIVE]),
|
||||
)).groupBy(responsibilities.areaId),
|
||||
.where(and(eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId), ne(responsibilityAreas.status, "archived"))),
|
||||
targetItemIds.length === 0 ? Promise.resolve([] as ResponsibilityRow[]) : tx.select().from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
eq(responsibilities.ownerUserId, ownerUserId),
|
||||
@@ -347,7 +331,6 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
)),
|
||||
]);
|
||||
const areasById = new Map(areaRows.map((row) => [row.id, row]));
|
||||
const shared = new Set(othersByArea.filter((row) => row.areaId && row.count > 0).map((row) => row.areaId!));
|
||||
// Live titles, kept current as this restore renames and archives, for the one-live-name-per-area rule.
|
||||
const liveTitle = new Map(liveAreas.map((row) => [lower(row.title), row.id]));
|
||||
const setLive = (row: { id: string; title: string; status: string }) => {
|
||||
@@ -368,7 +351,7 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
return true;
|
||||
}
|
||||
const [created] = await tx.insert(responsibilityAreas).values({
|
||||
companyId,
|
||||
companyId, ownerUserId,
|
||||
title: want.title,
|
||||
description: want.description ?? null,
|
||||
status: want.status === "archived" ? "archived" : "active",
|
||||
@@ -380,13 +363,8 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
events.push({ action: "responsibility_area.created", entityType: "responsibility_area", entityId: created!.id, details: { title: created!.title, status: created!.status, ...source } });
|
||||
return true;
|
||||
}
|
||||
const isShared = shared.has(row.id);
|
||||
// Other people see a shared area: only bring it back if it was archived, never rename or reorder it.
|
||||
const nextTitle = isShared ? row.title : want.title;
|
||||
const nextStatus = isShared ? (row.status === "archived" && want.status !== "archived" ? "active" : row.status) : want.status;
|
||||
const nextOrder = isShared ? row.sortOrder : want.sortOrder;
|
||||
// A version that holds the description puts it back, except on an area others share.
|
||||
const nextDescription = isShared || want.description === undefined ? row.description : want.description;
|
||||
const { title: nextTitle, status: nextStatus, sortOrder: nextOrder } = want;
|
||||
const nextDescription = want.description === undefined ? row.description : want.description;
|
||||
if (nextTitle === row.title && nextStatus === row.status && nextOrder === row.sortOrder && nextDescription === row.description) {
|
||||
areaFor.set(want.id, row.id);
|
||||
return true;
|
||||
@@ -402,7 +380,7 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
}
|
||||
const [updated] = await tx.update(responsibilityAreas)
|
||||
.set({ title: nextTitle, status: nextStatus, sortOrder: nextOrder, description: nextDescription, updatedAt: now })
|
||||
.where(and(eq(responsibilityAreas.id, row.id), eq(responsibilityAreas.companyId, companyId)))
|
||||
.where(and(eq(responsibilityAreas.id, row.id), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId)))
|
||||
.returning();
|
||||
areasById.set(row.id, updated!);
|
||||
setLive(updated!);
|
||||
@@ -505,7 +483,7 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
// Areas the snapshot does not hold that are now empty of anyone's live responsibilities: archived.
|
||||
const kept = new Set(areaFor.values());
|
||||
const candidates = [...new Set([...current.areas.map((area) => area.id), ...touchedAreas])].filter((areaId) => !kept.has(areaId));
|
||||
events.push(...await archiveIfEmpty(tx, companyId, candidates, source));
|
||||
events.push(...await archiveIfEmpty(tx, companyId, ownerUserId, candidates, source));
|
||||
return { events, createdAreaIds };
|
||||
}
|
||||
|
||||
@@ -611,10 +589,10 @@ export function responsibilityDashboardVersionService(db: Db) {
|
||||
}
|
||||
|
||||
/** Inside `tx`: archive each listed area that is not archived and holds no proposed or active responsibility of anyone. */
|
||||
async function archiveIfEmpty(tx: DashboardTransaction, companyId: string, areaIds: readonly string[], source: Record<string, unknown>) {
|
||||
async function archiveIfEmpty(tx: DashboardTransaction, companyId: string, ownerUserId: string, areaIds: readonly string[], source: Record<string, unknown>) {
|
||||
if (areaIds.length === 0) return [];
|
||||
const archived = await tx.update(responsibilityAreas).set({ status: "archived", updatedAt: new Date() }).where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
inArray(responsibilityAreas.id, [...areaIds]),
|
||||
ne(responsibilityAreas.status, "archived"),
|
||||
sql`not exists (select 1 from ${responsibilities} r where r.area_id = ${responsibilityAreas.id} and r.status in ('proposed', 'active'))`,
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
type IssueRow = typeof issues.$inferSelect;
|
||||
type AreaRow = typeof responsibilityAreas.$inferSelect;
|
||||
|
||||
const LIVE = ["proposed", "active"] as const;
|
||||
const NO_AREA = "No area";
|
||||
|
||||
function isClosed(status: string) {
|
||||
@@ -77,14 +76,15 @@ export function responsibilityDashboardService(db: Db) {
|
||||
if (experimental.enableResponsibilities !== true) throw responsibilitiesDisabledError();
|
||||
}
|
||||
|
||||
/** Empty: no active responsibility and none proposed. One query. */
|
||||
async function isEmpty(companyId: string, ownerUserId: string) {
|
||||
const [row] = await db.select({ id: responsibilities.id }).from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
eq(responsibilities.ownerUserId, ownerUserId),
|
||||
inArray(responsibilities.status, [...LIVE]),
|
||||
)).limit(1);
|
||||
return !row;
|
||||
const [state] = await db.execute<{ empty: boolean }>(sql`select not exists (
|
||||
select 1 from ${responsibilityAreas} where ${responsibilityAreas.companyId} = ${companyId}
|
||||
and ${responsibilityAreas.ownerUserId} = ${ownerUserId} and ${responsibilityAreas.status} <> 'archived'
|
||||
) and not exists (
|
||||
select 1 from ${responsibilities} where ${responsibilities.companyId} = ${companyId}
|
||||
and ${responsibilities.ownerUserId} = ${ownerUserId} and ${responsibilities.status} in ('active', 'proposed')
|
||||
) as empty`);
|
||||
return state.empty;
|
||||
}
|
||||
|
||||
async function latestConversation(companyId: string, ownerUserId: string): Promise<IssueRow | null> {
|
||||
@@ -123,7 +123,7 @@ export function responsibilityDashboardService(db: Db) {
|
||||
|
||||
/**
|
||||
* Check a change set against the person's dashboard as it is and resolve
|
||||
* the words the card shows. Three queries.
|
||||
* the words the card shows. Two queries.
|
||||
*/
|
||||
async function buildPayload(
|
||||
companyId: string,
|
||||
@@ -132,7 +132,7 @@ export function responsibilityDashboardService(db: Db) {
|
||||
data: CreateDashboardChangeSet,
|
||||
): Promise<ProposeDashboardChangesPayload> {
|
||||
const namedAreaIds = [...new Set(data.changes.flatMap((change) => ("areaId" in change && change.areaId ? [change.areaId] : [])))];
|
||||
const [own, areaRows, others] = await Promise.all([
|
||||
const [own, areaRows] = await Promise.all([
|
||||
db.select({
|
||||
id: responsibilities.id,
|
||||
title: responsibilities.title,
|
||||
@@ -144,23 +144,15 @@ export function responsibilityDashboardService(db: Db) {
|
||||
eq(responsibilities.status, "active"),
|
||||
)),
|
||||
db.select().from(responsibilityAreas).where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
namedAreaIds.length > 0
|
||||
? or(ne(responsibilityAreas.status, "archived"), inArray(responsibilityAreas.id, namedAreaIds))
|
||||
: ne(responsibilityAreas.status, "archived"),
|
||||
)),
|
||||
db.select({ areaId: responsibilities.areaId, count: sql<number>`count(distinct ${responsibilities.ownerUserId})::int` })
|
||||
.from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
ne(responsibilities.ownerUserId, ownerUserId),
|
||||
inArray(responsibilities.status, [...LIVE]),
|
||||
sql`${responsibilities.areaId} is not null`,
|
||||
)).groupBy(responsibilities.areaId),
|
||||
]);
|
||||
const ownById = new Map(own.map((row) => [row.id, row]));
|
||||
const areasById = new Map(areaRows.map((row) => [row.id, row]));
|
||||
const liveByTitle = new Map(areaRows.filter((row) => row.status !== "archived").map((row) => [lower(row.title), row]));
|
||||
const sharedWith = new Map(others.map((row) => [row.areaId!, row.count]));
|
||||
const refs = new Map<string, { index: number; name: string }>();
|
||||
const problems: string[] = [];
|
||||
const problem = (index: number, message: string) => problems.push(`changes[${index}]: ${message}`);
|
||||
@@ -239,16 +231,12 @@ export function responsibilityDashboardService(db: Db) {
|
||||
groupName: area.title,
|
||||
name: change.name.trim(),
|
||||
fromName: area.title,
|
||||
sharedWith: sharedWith.get(area.id) ?? 0,
|
||||
sharedWith: 0,
|
||||
};
|
||||
}
|
||||
case "remove_area": {
|
||||
const area = usableArea(index, change.areaId);
|
||||
if (!area) return base;
|
||||
const shared = sharedWith.get(area.id) ?? 0;
|
||||
if (shared > 0) {
|
||||
problem(index, `"${area.title}" holds responsibilities of ${shared === 1 ? "another person" : `${shared} other people`}, so it stays; move or remove this person's responsibilities in it instead`);
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
groupAreaId: area.id,
|
||||
@@ -338,12 +326,12 @@ export function responsibilityDashboardService(db: Db) {
|
||||
const stale = (message: string) => conflict(`${message}. Ask for the proposal again.`, { code: "responsibility_dashboard_changes_stale" });
|
||||
const loadArea = async (areaId: string) => {
|
||||
const [row] = await tx.select().from(responsibilityAreas)
|
||||
.where(and(eq(responsibilityAreas.id, areaId), eq(responsibilityAreas.companyId, companyId))).for("update");
|
||||
.where(and(eq(responsibilityAreas.id, areaId), eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId))).for("update");
|
||||
return row ?? null;
|
||||
};
|
||||
const liveAreaNamed = async (title: string, except?: string) => {
|
||||
const [row] = await tx.select().from(responsibilityAreas).where(and(
|
||||
eq(responsibilityAreas.companyId, companyId),
|
||||
eq(responsibilityAreas.ownerUserId, ownerUserId), eq(responsibilityAreas.companyId, companyId),
|
||||
sql`lower(${responsibilityAreas.title}) = lower(${title})`,
|
||||
ne(responsibilityAreas.status, "archived"),
|
||||
except ? ne(responsibilityAreas.id, except) : undefined,
|
||||
@@ -378,7 +366,7 @@ export function responsibilityDashboardService(db: Db) {
|
||||
refToArea.set(change.groupRef!, existing.id);
|
||||
continue;
|
||||
}
|
||||
const [created] = await tx.insert(responsibilityAreas).values({ companyId, title: change.name!, status: "active", source: "manual" }).returning();
|
||||
const [created] = await tx.insert(responsibilityAreas).values({ companyId, ownerUserId, title: change.name!, status: "active", source: "manual" }).returning();
|
||||
refToArea.set(change.groupRef!, created!.id);
|
||||
createdAreaIds.push(created!.id);
|
||||
events.push({ action: "responsibility_area.created", entityType: "responsibility_area", entityId: created!.id, details: { title: created!.title, status: "active", source: "manual", ...source } });
|
||||
@@ -435,13 +423,6 @@ export function responsibilityDashboardService(db: Db) {
|
||||
for (const change of byOp("remove_area")) {
|
||||
const area = await loadArea(change.groupAreaId!);
|
||||
if (!area || area.status === "archived") continue;
|
||||
const [others] = await tx.select({ id: responsibilities.id }).from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
eq(responsibilities.areaId, area.id),
|
||||
ne(responsibilities.ownerUserId, ownerUserId),
|
||||
inArray(responsibilities.status, [...LIVE]),
|
||||
)).limit(1);
|
||||
if (others) throw stale(`Someone else now has responsibilities in "${area.title}", so it stays`);
|
||||
const remaining = await tx.select({ id: responsibilities.id }).from(responsibilities).where(and(
|
||||
eq(responsibilities.companyId, companyId),
|
||||
eq(responsibilities.areaId, area.id),
|
||||
@@ -449,7 +430,7 @@ export function responsibilityDashboardService(db: Db) {
|
||||
eq(responsibilities.status, "active"),
|
||||
));
|
||||
for (const row of remaining) await letGo(row.id);
|
||||
events.push(...await versions.archiveIfEmpty(tx, companyId, [area.id], source));
|
||||
events.push(...await versions.archiveIfEmpty(tx, companyId, ownerUserId, [area.id], source));
|
||||
}
|
||||
return { events, createdAreaIds };
|
||||
}
|
||||
@@ -543,6 +524,8 @@ export function responsibilityDashboardService(db: Db) {
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: agentId,
|
||||
visibility: "private",
|
||||
responsibleUserId: ownerUserId,
|
||||
originKind: RESPONSIBILITY_DASHBOARD_ORIGIN_KIND,
|
||||
originId: ownerUserId,
|
||||
originFingerprint: input.mode,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { activityLog, issues } from "@paperclipai/db";
|
||||
import type { AuthorizationActor } from "./authorization.js";
|
||||
|
||||
const conversationKinds = ["responsibility_dashboard", "responsibility_bar", "responsibility_status_update", "automation_conversation"];
|
||||
export function isPersonalDashboardConversation(kind: string | null) {
|
||||
return kind !== null && conversationKinds.includes(kind);
|
||||
}
|
||||
|
||||
export type DashboardConversationFields = {
|
||||
originKind?: string | null;
|
||||
originId?: string | null;
|
||||
responsibleUserId?: string | null;
|
||||
assigneeAgentId?: string | null;
|
||||
};
|
||||
|
||||
export function dashboardConversationReadable(actor: AuthorizationActor, issue: DashboardConversationFields) {
|
||||
if (!isPersonalDashboardConversation(issue.originKind ?? null)) return true;
|
||||
const ownerId = issue.originKind === "responsibility_dashboard" ? issue.originId : issue.responsibleUserId;
|
||||
if (!ownerId) return false;
|
||||
if (actor.type === "board") return actor.userId === ownerId;
|
||||
return actor.type === "agent" && !!issue.assigneeAgentId && actor.agentId === issue.assigneeAgentId
|
||||
&& (!actor.onBehalfOfUserId || actor.onBehalfOfUserId === ownerId)
|
||||
&& (!actor.authorizingUserId || actor.authorizingUserId === ownerId);
|
||||
}
|
||||
|
||||
const personalConversationKinds = sql.join(conversationKinds.map(kind => sql`${kind}`), sql`, `);
|
||||
|
||||
export function dashboardConversationCondition(actor: AuthorizationActor) {
|
||||
const owner = sql`case when ${issues.originKind} = 'responsibility_dashboard' then ${issues.originId} else ${issues.responsibleUserId} end`;
|
||||
const allowed = actor.type === "board" ? sql`${owner} = ${actor.userId ?? null}`
|
||||
: actor.type === "agent" ? sql`${issues.assigneeAgentId} = ${actor.agentId ?? null}
|
||||
and ${actor.onBehalfOfUserId ? sql`${owner} = ${actor.onBehalfOfUserId}` : sql`true`}
|
||||
and ${actor.authorizingUserId ? sql`${owner} = ${actor.authorizingUserId}` : sql`true`}` : sql`false`;
|
||||
return sql<boolean>`(${issues.originKind} not in (${personalConversationKinds}) or (${owner} is not null and ${allowed}))`;
|
||||
}
|
||||
|
||||
const entities = ["responsibility", "responsibility_area", "responsibility_dashboard_version"];
|
||||
export function isDashboardActivity(entityType: unknown) {
|
||||
return typeof entityType === "string" && entities.includes(entityType);
|
||||
}
|
||||
|
||||
/** Activity without a current owner stays in the audit store and is invisible in company feeds. */
|
||||
export function dashboardActivityCondition(userId?: string | null) {
|
||||
const ordinary = sql`${activityLog.entityType} not in ('responsibility', 'responsibility_area', 'responsibility_dashboard_version')`;
|
||||
if (!userId) return sql<boolean>`${ordinary}`;
|
||||
return sql<boolean>`(${ordinary} or case ${activityLog.entityType}
|
||||
when 'responsibility' then exists (select 1 from responsibilities r where r.id::text = ${activityLog.entityId} and r.company_id = ${activityLog.companyId} and r.owner_user_id = ${userId})
|
||||
when 'responsibility_area' then exists (select 1 from responsibility_areas a where a.id::text = ${activityLog.entityId} and a.company_id = ${activityLog.companyId} and a.owner_user_id = ${userId})
|
||||
when 'responsibility_dashboard_version' then exists (select 1 from responsibility_dashboard_versions v where v.id::text = ${activityLog.entityId} and v.company_id = ${activityLog.companyId} and v.owner_user_id = ${userId})
|
||||
else false end)`;
|
||||
}
|
||||
|
||||
/** Audit entries can refer to a conversation directly, through a comment or through a document. */
|
||||
export function dashboardAuditConversationCondition(userId?: string | null) {
|
||||
const entity = activityLog.entityId;
|
||||
const privateIssue = sql`select 1 from issues i where i.company_id = ${activityLog.companyId}
|
||||
and i.origin_kind in (${personalConversationKinds})
|
||||
and (${userId ?? null}::text is null or (case when i.origin_kind = 'responsibility_dashboard' then i.origin_id else i.responsible_user_id end)
|
||||
is distinct from ${userId ?? null})`;
|
||||
return sql<boolean>`case ${activityLog.entityType}
|
||||
when 'issue' then not exists (${privateIssue} and i.id::text = ${entity})
|
||||
when 'issue_comment' then not exists (${privateIssue} and i.id in
|
||||
(select c.issue_id from issue_comments c where c.id::text = ${entity}))
|
||||
when 'issue_document' then not exists (${privateIssue} and i.id in
|
||||
(select d.issue_id from issue_documents d where d.id::text = ${entity} or d.document_id::text = ${entity}))
|
||||
else true end`;
|
||||
}
|
||||
@@ -197,6 +197,8 @@ export function responsibilityStatusReportService(db: Db) {
|
||||
status: "todo",
|
||||
priority: "low",
|
||||
assigneeAgentId: reporter.agentId,
|
||||
visibility: "private",
|
||||
responsibleUserId: row.ownerUserId,
|
||||
originKind: RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND,
|
||||
originId: row.id,
|
||||
createdByUserId: actor.userId,
|
||||
|
||||
@@ -44,7 +44,7 @@ const ROUTINE_EXECUTION_ORIGIN_KIND = "routine_execution";
|
||||
*/
|
||||
export interface RoutineSuggestionResponsibilityFiling {
|
||||
/** Every responsibility the task is under (directly or through its project); empty when loose. */
|
||||
responsibilitiesForIssue(companyId: string, issueId: string): Promise<Array<{ id: string }>>;
|
||||
responsibilitiesForIssue(companyId: string, issueId: string, ownerUserId: string): Promise<Array<{ id: string }>>;
|
||||
/** File the routine under one responsibility. Linking is additive and idempotent. */
|
||||
fileRoutine(responsibilityId: string, routineId: string): Promise<{ linkId: string; created: boolean } | null>;
|
||||
}
|
||||
@@ -60,8 +60,8 @@ export function responsibilityFilingForRoutineSuggestions(db: Db): RoutineSugges
|
||||
// linking a routine reads no task or project rows, so no further read scope applies.
|
||||
const unrestricted = { issueReadCondition: sql<boolean>`true`, projectReadCondition: sql<boolean>`true` };
|
||||
return {
|
||||
async responsibilitiesForIssue(companyId, issueId) {
|
||||
return svc.lookup(companyId, { kind: "issue", id: issueId }, unrestricted);
|
||||
async responsibilitiesForIssue(companyId, issueId, ownerUserId) {
|
||||
return svc.lookup(companyId, ownerUserId, { kind: "issue", id: issueId }, unrestricted);
|
||||
},
|
||||
async fileRoutine(responsibilityId, routineId) {
|
||||
const row = await svc.getById(responsibilityId);
|
||||
@@ -346,7 +346,7 @@ export function routineSuggestionService(
|
||||
|
||||
const filed: FiledUnder = [];
|
||||
try {
|
||||
for (const responsibility of await filing.responsibilitiesForIssue(issue.companyId, issue.id)) {
|
||||
for (const responsibility of await filing.responsibilitiesForIssue(issue.companyId, issue.id, actor.userId)) {
|
||||
try {
|
||||
const link = await filing.fileRoutine(responsibility.id, routine.id);
|
||||
if (link) filed.push({ responsibilityId: responsibility.id, ...link });
|
||||
|
||||
@@ -2180,6 +2180,7 @@ export function routineService(
|
||||
responsibleUserId?: string;
|
||||
/** Filed under this responsibility, directly or through its project. */
|
||||
responsibilityId?: string;
|
||||
ownerUserId?: string;
|
||||
/** Filed under no proposed or active responsibility, directly or through its project. */
|
||||
unfiled?: boolean;
|
||||
},
|
||||
@@ -2197,7 +2198,7 @@ export function routineService(
|
||||
const filedUnder = (responsibility: SQL) => sql`exists (
|
||||
select 1 from ${responsibilityLinks} fl
|
||||
join ${responsibilities} fr on fr.id = fl.responsibility_id
|
||||
where ${responsibility} and fr.company_id = ${companyId}
|
||||
where ${responsibility} and fr.company_id = ${companyId} and fr.owner_user_id = ${filters?.ownerUserId ?? null}
|
||||
and (fl.routine_id = ${routines.id} or (${routines.projectId} is not null and fl.project_id = ${routines.projectId})))`;
|
||||
if (filters?.responsibilityId) conditions.push(filedUnder(sql`fr.id = ${filters.responsibilityId}`));
|
||||
if (filters?.unfiled) conditions.push(sql`not ${filedUnder(sql`fr.status in ('proposed', 'active')`)}`);
|
||||
|
||||
Reference in new issue
Block a user