Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -20,11 +20,16 @@
// global User lookup (resolveUserLabels): User is not tenant-scoped (a user can
// belong to several tenants), so it stays on the db singleton.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
import { tasksIndex } from "@hivegrid/search";
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { publishSearchProjectionDelete, publishTaskSearchUpsert } from "~/services/search/searchIndexProjection.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { assertFileLinkTargetVisibleWithTx } from "./fileVisibility.server";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import type { ProjectVisibilityContext } from "./projects/projectService.server";
/**
* Domain error carrying an i18n message key (M002 Klartext). Routes map
@@ -47,20 +52,80 @@ export type TaskEntityType = "contact" | "company" | "lead" | "deal" | "project"
const TERMINAL_STATUSES: ReadonlySet<TaskStatus> = new Set(["done", "cancelled"]);
const MAX_TITLE_LENGTH = 255;
export type TaskVisibilityContext = {
userId: string;
/** The user's permission names for this tenant (from getPermissionsByUser). */
permissions: readonly string[];
};
export type TaskVisibilityContext = ProjectVisibilityContext;
function hasPermission(ctx: TaskVisibilityContext, permission: string): boolean {
return ctx.permissions.includes(permission);
}
function requireTaskPermission(ctx: TaskVisibilityContext, permission: "tasks.write" | "tasks.delete"): void {
if (!hasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound);
}
}
async function requireTenantUserWithTx(tx: DbTransactionClient, tenantId: string, userId: string): Promise<void> {
const member = await tx.tenantUser.findFirst({
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: { id: true },
});
if (!member) {
throw new CatalogError(foundationErrors.notFound, { userId });
}
}
async function requireTenantGroupWithTx(tx: DbTransactionClient, tenantId: string, groupId: string): Promise<void> {
const group = await tx.group.findFirst({
where: { id: groupId, tenantId },
select: { id: true },
});
if (!group) {
throw new CatalogError(foundationErrors.notFound, { groupId });
}
}
async function requireTenantAssignmentWithTx(
tx: DbTransactionClient,
tenantId: string,
assignment: { assignedToUserId: string | null; assignedToGroupId: string | null },
): Promise<void> {
if (assignment.assignedToUserId) {
await requireTenantUserWithTx(tx, tenantId, assignment.assignedToUserId);
}
if (assignment.assignedToGroupId) {
await requireTenantGroupWithTx(tx, tenantId, assignment.assignedToGroupId);
}
}
async function requireVisibleEntityLinkWithTx(
tx: DbTransactionClient,
tenantId: string,
linkedEntityType: TaskEntityType | null,
linkedEntityId: string | null,
ctx: TaskVisibilityContext,
): Promise<void> {
if (!linkedEntityType || !linkedEntityId) return;
await assertFileLinkTargetVisibleWithTx(tx as unknown as TenantRlsClient, tenantId, linkedEntityType, linkedEntityId, ctx);
const expectedPipelineType = linkedEntityType === "deal" ? "sales" : linkedEntityType === "order" ? "auftrag" : null;
if (!expectedPipelineType) return;
const project = await tx.projekt.findFirst({
where: {
id: linkedEntityId,
tenantId,
archivedAt: null,
pipeline: { tenantId, archivedAt: null, typHint: expectedPipelineType },
},
select: { id: true },
});
if (!project) throw new CatalogError(foundationErrors.notFound, { entityType: linkedEntityType, entityId: linkedEntityId });
}
/** The group ids the user belongs to in this tenant (for group-assignment
* visibility), on the active RLS transaction client. GroupUser has no tenantId of
* its own; scope via the group's tenant. */
async function userGroupIdsWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise<string[]> {
async function userGroupIdsWithTx(tx: DbTransactionClient, tenantId: string, userId: string): Promise<string[]> {
const memberships = await tx.groupUser.findMany({
where: { userId, group: { tenantId } },
select: { groupId: true },
@@ -119,7 +184,7 @@ export function resolveAssignment(input: { creatorUserId: string; assignedToUser
export type CreateTaskInput = {
tenantId: string;
userId: string;
ctx: TaskVisibilityContext;
title: string;
description?: string | null;
priority?: TaskPriority;
@@ -131,15 +196,82 @@ export type CreateTaskInput = {
source?: TaskSource;
sourceRef?: string | null;
isDemoData?: boolean;
/** Tenant slug for the in-app assignment notification deeplink; without it the notification carries no link. */
tenantSlug?: string;
};
export async function createTask(input: CreateTaskInput): Promise<TaskRow> {
/**
* In-app notification for the assignee (M011). Self-assignments are silent;
* a notification failure never breaks the task write.
*/
const TASK_PRIORITY_NOTIFICATION_TONES: Record<TaskPriority, string> = {
urgent: "subtle-negative",
high: "subtle-warning",
normal: "subtle-information",
low: "subtle-neutral",
};
async function notifyTaskAssignedWithTx(
tx: DbTransactionClient,
input: {
tenantId: string;
actorUserId: string;
assignedToUserId: string | null;
taskId: string;
taskTitle: string;
taskPriority: TaskPriority;
tenantSlug?: string;
}
): Promise<void> {
if (!input.assignedToUserId || input.assignedToUserId === input.actorUserId) return;
try {
await notify(
{
tenantId: input.tenantId,
userId: input.assignedToUserId,
channel: "IN_APP",
category: "tasks",
messageKey: "tasks.notification.assigned",
sourceKey: `task-assigned:${input.taskId}:${input.assignedToUserId}`,
payloadMetadata: {
taskId: input.taskId,
taskTitle: input.taskTitle,
subjectLabel: input.taskTitle,
tagKey: `tasks.priority.${input.taskPriority}`,
tagTone: TASK_PRIORITY_NOTIFICATION_TONES[input.taskPriority] ?? "subtle-neutral",
...(input.tenantSlug ? { deeplink: appPath({ tenantSlug: input.tenantSlug, path: `tasks/${input.taskId}`, mode: "host-aware" }) } : {}),
},
},
tx as unknown as Parameters<typeof notify>[1]
);
} catch {
// Notification delivery is best-effort; the task mutation must not fail on it.
}
}
async function createTaskWithPermissionResult(
input: CreateTaskInput,
permission: "tasks.write" | "acceptance.write",
options: { readonly idempotentSourceRef?: boolean } = {}
): Promise<{ task: TaskRow; replayed: boolean }> {
return withTenantRLS(input.tenantId, (tx) => createTaskWithPermissionResultWithTx(tx, input, permission, options));
}
async function createTaskWithPermissionResultWithTx(
tx: DbTransactionClient,
input: CreateTaskInput,
permission: "tasks.write" | "acceptance.write",
options: { readonly idempotentSourceRef?: boolean } = {}
): Promise<{ task: TaskRow; replayed: boolean }> {
if (!hasPermission(input.ctx, permission)) {
throw new CatalogError(foundationErrors.notFound);
}
const title = input.title.trim();
if (!title) {
throw new TaskServiceError("tasks.error.titleRequired");
}
const assignment = resolveAssignment({
creatorUserId: input.userId,
creatorUserId: input.ctx.userId,
assignedToUserId: input.assignedToUserId,
assignedToGroupId: input.assignedToGroupId,
});
@@ -148,33 +280,84 @@ export async function createTask(input: CreateTaskInput): Promise<TaskRow> {
if ((linkedEntityType && !linkedEntityId) || (!linkedEntityType && linkedEntityId)) {
throw new TaskServiceError("tasks.error.invalidEntityLink");
}
const task = await withTenantRLS(input.tenantId, async (tx) => {
const created = await tx.task.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
title: title.slice(0, MAX_TITLE_LENGTH),
description: input.description ?? null,
priority: input.priority ?? "normal",
deadline: input.deadline ?? null,
assignedToUserId: assignment.assignedToUserId,
assignedToGroupId: assignment.assignedToGroupId,
linkedEntityType,
linkedEntityId,
source: input.source ?? "manual",
sourceRef: input.sourceRef ?? null,
isDemoData: input.isDemoData ?? false,
},
const source = input.source ?? "manual";
const sourceRef = input.sourceRef?.trim() || null;
if (options.idempotentSourceRef && !sourceRef) {
throw new TaskServiceError("tasks.error.sourceRefRequired");
}
await requireTenantUserWithTx(tx, input.tenantId, input.ctx.userId);
if (options.idempotentSourceRef && sourceRef) {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`task-source:${input.tenantId}:${source}:${sourceRef}`}, 0))`;
const existing = await tx.task.findFirst({
where: { tenantId: input.tenantId, source, sourceRef, archivedAt: null },
});
await publishTaskSearchUpsert(tx, created);
return created;
if (existing) return { task: existing as TaskRow, replayed: true };
}
await requireTenantAssignmentWithTx(tx, input.tenantId, assignment);
await requireVisibleEntityLinkWithTx(tx, input.tenantId, linkedEntityType, linkedEntityId, input.ctx);
const created = await tx.task.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.ctx.userId,
title: title.slice(0, MAX_TITLE_LENGTH),
description: input.description ?? null,
priority: input.priority ?? "normal",
deadline: input.deadline ?? null,
assignedToUserId: assignment.assignedToUserId,
assignedToGroupId: assignment.assignedToGroupId,
linkedEntityType,
linkedEntityId,
source,
sourceRef,
isDemoData: input.isDemoData ?? false,
},
});
return task as TaskRow;
await publishTaskSearchUpsert(tx as unknown as TenantRlsClient, created);
await notifyTaskAssignedWithTx(tx, {
tenantId: input.tenantId,
actorUserId: input.ctx.userId,
assignedToUserId: assignment.assignedToUserId,
taskId: created.id,
taskTitle: created.title,
taskPriority: (created.priority as TaskPriority) ?? "normal",
tenantSlug: input.tenantSlug,
});
return { task: created as TaskRow, replayed: false };
}
export async function createTask(input: CreateTaskInput): Promise<TaskRow> {
return (await createTaskWithPermissionResult(input, "tasks.write")).task;
}
export async function createIdempotentTaskFromSource(
input: CreateTaskInput & { readonly source: Exclude<TaskSource, "manual">; readonly sourceRef: string }
): Promise<{ readonly task: TaskRow; readonly replayed: boolean }> {
return createTaskWithPermissionResult(input, "tasks.write", { idempotentSourceRef: true });
}
/** Compose a source-backed task into an existing RLS transaction. This keeps
* cross-module source links and effects atomic with the task row. */
export function createIdempotentTaskFromSourceWithTx(
tx: DbTransactionClient,
input: CreateTaskInput & { readonly source: Exclude<TaskSource, "manual">; readonly sourceRef: string }
): Promise<{ readonly task: TaskRow; readonly replayed: boolean }> {
return createTaskWithPermissionResultWithTx(tx, input, "tasks.write", { idempotentSourceRef: true });
}
export type CreateAcceptanceFollowUpTaskInput = Omit<CreateTaskInput, "source" | "linkedEntityType"> & {
linkedEntityType: "project";
sourceRef: string;
};
/** Create the follow-up task that is part of submitting an acceptance protocol. */
export async function createAcceptanceFollowUpTask(input: CreateAcceptanceFollowUpTaskInput): Promise<TaskRow> {
return (await createTaskWithPermissionResult({ ...input, source: "automation" }, "acceptance.write")).task;
}
export type UpdateTaskInput = {
tenantId: string;
taskId: string;
ctx: TaskVisibilityContext;
title?: string;
description?: string | null;
status?: TaskStatus;
@@ -185,6 +368,7 @@ export type UpdateTaskInput = {
};
export async function updateTask(input: UpdateTaskInput): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
if (input.title !== undefined && !input.title.trim()) {
throw new TaskServiceError("tasks.error.titleRequired");
}
@@ -194,15 +378,15 @@ export async function updateTask(input: UpdateTaskInput): Promise<void> {
completedAt = TERMINAL_STATUSES.has(input.status) ? new Date() : null;
}
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({
where: { id: input.taskId, tenantId: input.tenantId },
select: { id: true, status: true },
});
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
const existing = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
const linkedEntityType = input.linkedEntityType !== undefined ? input.linkedEntityType : existing.linkedEntityType;
const linkedEntityId = input.linkedEntityId !== undefined ? input.linkedEntityId : existing.linkedEntityId;
if ((linkedEntityType && !linkedEntityId) || (!linkedEntityType && linkedEntityId)) {
throw new TaskServiceError("tasks.error.invalidEntityLink");
}
await requireVisibleEntityLinkWithTx(tx, input.tenantId, linkedEntityType, linkedEntityId, input.ctx);
const updated = await tx.task.update({
where: { id: existing.id },
where: { id: existing.id, tenantId: input.tenantId },
data: {
...(input.title !== undefined ? { title: input.title.trim().slice(0, MAX_TITLE_LENGTH) } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
@@ -222,93 +406,102 @@ export async function updateTask(input: UpdateTaskInput): Promise<void> {
export async function reassignTask(input: {
tenantId: string;
taskId: string;
ctx: TaskVisibilityContext;
assignedToUserId?: string | null;
assignedToGroupId?: string | null;
/** Tenant slug for the in-app assignment notification deeplink. */
tenantSlug?: string;
}): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({
where: { id: input.taskId, tenantId: input.tenantId },
select: { id: true, createdByUserId: true },
});
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const existing = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
const assignment = resolveAssignment({
creatorUserId: existing.createdByUserId,
assignedToUserId: input.assignedToUserId,
assignedToGroupId: input.assignedToGroupId,
});
await requireTenantAssignmentWithTx(tx, input.tenantId, assignment);
const updated = await tx.task.update({
where: { id: existing.id },
where: { id: existing.id, tenantId: input.tenantId },
data: { assignedToUserId: assignment.assignedToUserId, assignedToGroupId: assignment.assignedToGroupId },
});
await publishTaskSearchUpsert(tx, updated);
if (assignment.assignedToUserId && assignment.assignedToUserId !== existing.assignedToUserId) {
await notifyTaskAssignedWithTx(tx, {
tenantId: input.tenantId,
actorUserId: input.ctx.userId,
assignedToUserId: assignment.assignedToUserId,
taskId: existing.id,
taskTitle: existing.title,
taskPriority: (existing.priority as TaskPriority) ?? "normal",
tenantSlug: input.tenantSlug,
});
}
});
}
export async function completeTask(input: { tenantId: string; taskId: string; ctx: TaskVisibilityContext }): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
const updated = await tx.task.update({
where: { id: existing.id, tenantId: input.tenantId },
data: { status: "done", completedAt: new Date() },
});
await publishTaskSearchUpsert(tx, updated);
});
}
export async function completeTask(input: { tenantId: string; taskId: string }): Promise<void> {
export async function archiveTask(input: { tenantId: string; taskId: string; ctx: TaskVisibilityContext }): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const updated = await tx.task.update({ where: { id: existing.id }, data: { status: "done", completedAt: new Date() } });
await publishTaskSearchUpsert(tx, updated);
});
}
export async function archiveTask(input: { tenantId: string; taskId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
await tx.task.update({ where: { id: existing.id }, data: { archivedAt: new Date() } });
const existing = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
await tx.task.update({ where: { id: existing.id, tenantId: input.tenantId }, data: { archivedAt: new Date() } });
await publishSearchProjectionDelete(tx, { schema: tasksIndex, tenantId: input.tenantId, entityType: "task", entityId: existing.id });
});
}
export async function reactivateTask(input: { tenantId: string; taskId: string }): Promise<void> {
export async function reactivateTask(input: { tenantId: string; taskId: string; ctx: TaskVisibilityContext }): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const updated = await tx.task.update({ where: { id: existing.id }, data: { archivedAt: null } });
const existing = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
const updated = await tx.task.update({ where: { id: existing.id, tenantId: input.tenantId }, data: { archivedAt: null } });
await publishTaskSearchUpsert(tx, updated);
});
}
export async function hardDeleteTask(input: { tenantId: string; taskId: string }): Promise<void> {
export async function hardDeleteTask(input: { tenantId: string; taskId: string; ctx: TaskVisibilityContext }): Promise<void> {
requireTaskPermission(input.ctx, "tasks.delete");
await withTenantRLS(input.tenantId, async (tx) => {
const task = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!task) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const task = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
// TaskWatcher rows cascade on Task delete (schema onDelete: Cascade).
await tx.task.delete({ where: { id: task.id } });
await tx.task.delete({ where: { id: task.id, tenantId: input.tenantId } });
await publishSearchProjectionDelete(tx, { schema: tasksIndex, tenantId: input.tenantId, entityType: "task", entityId: task.id });
});
}
// --- Watchers -------------------------------------------------------------
export async function addWatcher(input: { tenantId: string; taskId: string; userId: string }): Promise<void> {
export async function addWatcher(input: { tenantId: string; taskId: string; userId: string; ctx: TaskVisibilityContext }): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
await withTenantRLS(input.tenantId, async (tx) => {
const task = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!task) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const task = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
await requireTenantUserWithTx(tx, input.tenantId, input.userId);
await tx.taskWatcher.upsert({
where: { taskId_userId: { taskId: input.taskId, userId: input.userId } },
where: { taskId_userId: { taskId: task.id, userId: input.userId } },
update: {},
create: { tenantId: input.tenantId, taskId: input.taskId, userId: input.userId },
create: { tenantId: input.tenantId, taskId: task.id, userId: input.userId },
});
});
}
export async function removeWatcher(input: { tenantId: string; taskId: string; userId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.taskWatcher.deleteMany({ where: { tenantId: input.tenantId, taskId: input.taskId, userId: input.userId } }));
export async function removeWatcher(input: { tenantId: string; taskId: string; userId: string; ctx: TaskVisibilityContext }): Promise<void> {
requireTaskPermission(input.ctx, "tasks.write");
await withTenantRLS(input.tenantId, async (tx) => {
const task = await getVisibleTaskOrThrowWithTx(tx, input.tenantId, input.taskId, input.ctx);
await requireTenantUserWithTx(tx, input.tenantId, input.userId);
await tx.taskWatcher.deleteMany({ where: { tenantId: input.tenantId, taskId: task.id, userId: input.userId } });
});
}
// --- Visibility / read ----------------------------------------------------
@@ -321,13 +514,16 @@ export async function removeWatcher(input: { tenantId: string; taskId: string; u
// Internal: visibility check on an already-loaded task, using the active RLS
// transaction client (no own transaction → safe to call inside withTenantRLS).
async function isTaskVisibleWithTx(
tx: TenantRlsClient,
tx: DbTransactionClient,
task: Pick<TaskRow, "id" | "tenantId" | "createdByUserId" | "assignedToUserId" | "assignedToGroupId">,
ctx: TaskVisibilityContext
): Promise<boolean> {
if (hasPermission(ctx, "tasks.read_all")) {
return true;
}
if (!hasPermission(ctx, "tasks.read_own")) {
return false;
}
if (task.createdByUserId === ctx.userId || task.assignedToUserId === ctx.userId) {
return true;
}
@@ -340,7 +536,7 @@ async function isTaskVisibleWithTx(
}
if (task.assignedToGroupId) {
const membership = await tx.groupUser.findFirst({
where: { groupId: task.assignedToGroupId, userId: ctx.userId },
where: { groupId: task.assignedToGroupId, userId: ctx.userId, group: { tenantId: task.tenantId } },
select: { id: true },
});
if (membership) {
@@ -356,7 +552,13 @@ export async function isTaskVisible(
): Promise<boolean> {
// Fast paths need no DB; only the watcher/group lookups open a tenant-scoped
// transaction.
if (hasPermission(ctx, "tasks.read_all") || task.createdByUserId === ctx.userId || task.assignedToUserId === ctx.userId) {
if (hasPermission(ctx, "tasks.read_all")) {
return true;
}
if (!hasPermission(ctx, "tasks.read_own")) {
return false;
}
if (task.createdByUserId === ctx.userId || task.assignedToUserId === ctx.userId) {
return true;
}
return withTenantRLS(task.tenantId, (tx) => isTaskVisibleWithTx(tx, task, ctx));
@@ -365,7 +567,7 @@ export async function isTaskVisible(
export type TaskWatcherRow = { userId: string };
// Internal: load + visibility on the active transaction client (no own tx).
async function getVisibleTaskOrThrowWithTx(tx: TenantRlsClient, tenantId: string, taskId: string, ctx: TaskVisibilityContext): Promise<TaskRow> {
async function getVisibleTaskOrThrowWithTx(tx: DbTransactionClient, tenantId: string, taskId: string, ctx: TaskVisibilityContext): Promise<TaskRow> {
const task = await tx.task.findFirst({ where: { id: taskId, tenantId } });
if (!task) {
throw new CatalogError(foundationErrors.notFound, { taskId });
@@ -398,10 +600,9 @@ export async function getVisibleTaskWithWatchers(
});
}
export type TaskListPreset = "mine" | "created" | "all";
export type ListTasksFilter = {
preset?: TaskListPreset;
/** Free-text needle matched case-insensitively against title and description. */
search?: string | null;
status?: TaskStatus | null;
priority?: TaskPriority | null;
assignedToUserId?: string | null;
@@ -414,10 +615,8 @@ export type ListTasksFilter = {
/**
* List tasks for the browser (tenant-scoped + read_own visibility), newest
* first, cursor-paginated. Presets: `mine` (assigned to me / my groups),
* `created` (created by me), `all` (everything visible). Non-read_all users only
* ever see tasks they own, are assigned, watch, or whose assigned group they are
* a member of.
* first, cursor-paginated. Non-read_all users only ever see tasks they own, are
* assigned, watch, or whose assigned group they are a member of.
*/
export async function listTasksForBrowser(input: {
tenantId: string;
@@ -426,9 +625,12 @@ export async function listTasksForBrowser(input: {
cursor?: string | null;
limit?: number;
}): Promise<{ rows: TaskRow[]; nextCursor: string | null }> {
if (!hasPermission(input.ctx, "tasks.read_all") && !hasPermission(input.ctx, "tasks.read_own")) {
return { rows: [], nextCursor: null };
}
const limit = Math.min(Math.max(input.limit ?? 50, 1), 100);
const filter = input.filter ?? {};
const preset = filter.preset ?? "all";
const search = filter.search?.trim() ?? "";
return withTenantRLS(input.tenantId, async (tx) => {
const groupIds = await userGroupIdsWithTx(tx, input.tenantId, input.ctx.userId);
@@ -442,15 +644,16 @@ export async function listTasksForBrowser(input: {
// Base visibility scope: read_all sees all in-tenant; otherwise restricted.
const visibilityScope = hasPermission(input.ctx, "tasks.read_all") ? {} : { OR: visibleToUser };
// Preset narrows further within the visible scope.
let presetScope: Record<string, unknown> = {};
if (preset === "created") {
presetScope = { createdByUserId: input.ctx.userId };
} else if (preset === "mine") {
presetScope = {
OR: [{ assignedToUserId: input.ctx.userId }, ...(groupIds.length > 0 ? [{ assignedToGroupId: { in: groupIds } }] : [])],
};
}
// Free-text search narrows further within the visible scope. Kept as a
// separate AND branch so it can never widen what the user may see.
const searchScope: Record<string, unknown> = search
? {
OR: [
{ title: { contains: search, mode: "insensitive" as const } },
{ description: { contains: search, mode: "insensitive" as const } },
],
}
: {};
const where = {
tenantId: input.tenantId,
@@ -461,7 +664,7 @@ export async function listTasksForBrowser(input: {
...(filter.assignedToUserId ? { assignedToUserId: filter.assignedToUserId } : {}),
...(filter.linkedEntityType && filter.linkedEntityId ? { linkedEntityType: filter.linkedEntityType, linkedEntityId: filter.linkedEntityId } : {}),
...(filter.source ? { source: filter.source } : {}),
AND: [visibilityScope, presetScope],
AND: [visibilityScope, searchScope],
};
const rows = await tx.task.findMany({
@@ -516,7 +719,7 @@ export async function resolveGroupLabels(tenantId: string, groupIds: readonly st
export async function listAssignableUsers(tenantId: string): Promise<LabeledOption[]> {
const members = await withTenantRLS(tenantId, (tx) =>
tx.tenantUser.findMany({
where: { tenantId },
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
}),
);