Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat: rebuild tasks page (#257)

grim711c909cf016
diff --git a/apps/api/src/activities/activities-config.ts b/apps/api/src/activities/activities-config.ts
new file mode 100644
index 00000000..c395305f
--- /dev/null
+++ b/apps/api/src/activities/activities-config.ts
@@ -0,0 +1,6 @@
+export const TASKS = {
+ day: {
+ timeZone: "UTC",
+ weekStartsOn: 1,
+ },
+} as const;
diff --git a/apps/api/src/activities/activities.contracts.ts b/apps/api/src/activities/activities.contracts.ts
index ad984fde..2b633c38 100644
--- a/apps/api/src/activities/activities.contracts.ts
+++ b/apps/api/src/activities/activities.contracts.ts
@@ -1,6 +1,8 @@
import { ActivityType } from "@crm/db";
import { activityMeta } from "@crm/validation/activity-meta";
import { z } from "zod";
+import { listInput } from "../trpc/list-input";
+import { TASK_WINDOWS, taskDueDayInput } from "./task-due-date";
const COMPOSABLE_TYPES = [
ActivityType.NOTE,
@@ -59,7 +61,7 @@ export const activityCreateInput = z
subject: z.string().trim().optional(),
body: z.string().trim().optional(),
occurredAt: z.string().optional(),
- dueAt: z.string().nullable().optional(),
+ dueAt: taskDueDayInput.nullable().optional(),
companyId: z.string().optional(),
contactId: z.string().optional(),
dealId: z.string().optional(),
@@ -77,6 +79,16 @@ export const activityCreateInput = z
export type ActivityCreateInput = z.infer<typeof activityCreateInput>;
+export const activityUpdateInput = z.object({
+ id: z.string(),
+ subject: z.string().trim().min(1, {
+ message: "A task needs a subject — it is the thing to do.",
+ }),
+ dueAt: taskDueDayInput.nullable(),
+});
+
+export type ActivityUpdateInput = z.infer<typeof activityUpdateInput>;
+
export const completeInput = z.object({
id: z.string(),
completed: z.boolean().default(true),
@@ -89,6 +101,14 @@ export const myTasksInput = z.object({
export type MyTasksInput = z.infer<typeof myTasksInput>;
+export const taskListInput = listInput.extend({
+ status: z.enum(["all", "open", "done"]).default("all"),
+ due: z.array(z.enum(TASK_WINDOWS)).default([]),
+ createdBy: z.array(z.string()).default([]),
+});
+
+export type TaskListInput = z.infer<typeof taskListInput>;
+
const activityAuthorOutput = z.object({
id: z.string(),
name: z.string(),
@@ -178,6 +198,44 @@ export type TimelineCounts = z.infer<typeof timelineCountsOutput>;
export const myTasksOutput = z.array(activityEntryOutput);
+const taskCompanyRefOutput = z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ domain: z.string().nullable(),
+ iconUrl: z.string().nullable(),
+ iconDarkUrl: z.string().nullable(),
+ iconTone: z.string().nullable(),
+ logoUrl: z.string().nullable(),
+ })
+ .nullable();
+
+const taskRowOutput = z.object({
+ id: z.string(),
+ subject: z.string().nullable(),
+ dueAt: z.string().nullable(),
+ completedAt: z.string().nullable(),
+ createdAt: z.string(),
+ createdBy: activityAuthorOutput,
+ company: taskCompanyRefOutput,
+ contact: activityContactRefOutput,
+ deal: activityDealRefOutput,
+});
+
+export const taskListOutput = z.object({
+ rows: z.array(taskRowOutput),
+ total: z.number(),
+ day: z.object({
+ today: taskDueDayInput,
+ timeZone: z.string(),
+ }),
+ facetCounts: z.record(z.string(), z.record(z.string(), z.number())),
+});
+
+export type TaskListResult = z.infer<typeof taskListOutput>;
+
export const activityCreateOutput = activityEntryOutput;
+export const activityUpdateOutput = activityEntryOutput;
+
export const completeOutput = activityEntryOutput;
diff --git a/apps/api/src/activities/activities.router.ts b/apps/api/src/activities/activities.router.ts
index 6b1fd81b..870be857 100644
--- a/apps/api/src/activities/activities.router.ts
+++ b/apps/api/src/activities/activities.router.ts
@@ -14,10 +14,14 @@ import { restMeta } from "../trpc/openapi";
import {
activityCreateInput,
activityCreateOutput,
+ activityUpdateInput,
+ activityUpdateOutput,
completeInput,
completeOutput,
myTasksInput,
myTasksOutput,
+ taskListInput,
+ taskListOutput,
timelineCountsInput,
timelineCountsOutput,
timelineInput,
@@ -62,6 +66,15 @@ export class ActivitiesRouter {
return this.activities.myTasks(input, ctx.user.id);
}
+ @Query({
+ input: taskListInput,
+ output: taskListOutput,
+ meta: restMeta("GET", "/activities/tasks", ["Activities"]),
+ })
+ async tasks(@Input() input: z.infer<typeof taskListInput>) {
+ return this.activities.tasks(input);
+ }
+
@Mutation({
input: activityCreateInput,
output: activityCreateOutput,
@@ -74,6 +87,15 @@ export class ActivitiesRouter {
return this.activities.create(input, ctx.user.id);
}
+ @Mutation({
+ input: activityUpdateInput,
+ output: activityUpdateOutput,
+ meta: restMeta("PATCH", "/activities/{id}", ["Activities"]),
+ })
+ async update(@Input() input: z.infer<typeof activityUpdateInput>) {
+ return this.activities.update(input);
+ }
+
@Mutation({
input: completeInput,
output: completeOutput,
diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts
index 50439fcb..3b9a67a6 100644
--- a/apps/api/src/activities/activities.service.ts
+++ b/apps/api/src/activities/activities.service.ts
@@ -1,4 +1,4 @@
-import { ActivityType, type Db, type Prisma } from "@crm/db";
+import { ActivityType, type Db, Prisma } from "@crm/db";
import { activityMeta } from "@crm/validation/activity-meta";
import {
BadRequestException,
@@ -6,18 +6,35 @@ import {
Logger,
NotFoundException,
} from "@nestjs/common";
+import { z } from "zod";
import { ActivityStampService } from "../crm/activity-stamp.service";
import { blankToNull } from "../crm/values";
import { InjectDatabase } from "../database/database.constants";
+import {
+ countsByKey,
+ type OrderByColumns,
+ paginate,
+ resolveOrderBy,
+} from "../trpc/list-input";
import type {
ActivityCreateInput,
ActivityEntry,
+ ActivityUpdateInput,
MyTasksInput,
+ TaskListInput,
+ TaskListResult,
TimelineCounts,
TimelineFilter,
TimelineInput,
TimelineResult,
} from "./activities.contracts";
+import { TASKS } from "./activities-config";
+import {
+ parseTaskDueDay,
+ serializeTaskDueDay,
+ taskDayBoundaries,
+ taskWindowFilter,
+} from "./task-due-date";
const AUTHOR_SELECT = {
id: true,
@@ -68,6 +85,65 @@ const NOTE_TYPES = [
ActivityType.MEETING,
];
+const TASK_SELECT = {
+ id: true,
+ subject: true,
+ dueAt: true,
+ completedAt: true,
+ createdAt: true,
+ createdBy: { select: AUTHOR_SELECT },
+ company: {
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
+ logoUrl: true,
+ },
+ },
+ contact: { select: { id: true, firstName: true, lastName: true } },
+ deal: { select: { id: true, name: true } },
+} as const;
+
+const TASK_SORTABLE: OrderByColumns<Prisma.ActivityOrderByWithRelationInput[]> =
+ {
+ subject: (dir) => [{ subject: { sort: dir, nulls: "last" } }],
+ dueAt: (dir) => [
+ { dueAt: { sort: dir, nulls: "last" } },
+ { createdAt: "desc" },
+ ],
+ status: (dir) => [
+ {
+ completedAt: {
+ sort: dir,
+ nulls: dir === "asc" ? "first" : "last",
+ },
+ },
+ { dueAt: { sort: "asc", nulls: "last" } },
+ ],
+ company: (dir) => [
+ { company: { name: dir } },
+ { dueAt: { sort: "asc", nulls: "last" } },
+ ],
+ createdBy: (dir) => [
+ { createdBy: { name: dir } },
+ { dueAt: { sort: "asc", nulls: "last" } },
+ ],
+ createdAt: (dir) => [{ createdAt: dir }],
+ };
+
+const taskAggregateRow = z.object({
+ open: z.coerce.number().int().nonnegative(),
+ done: z.coerce.number().int().nonnegative(),
+ overdue: z.coerce.number().int().nonnegative(),
+ today: z.coerce.number().int().nonnegative(),
+ week: z.coerce.number().int().nonnegative(),
+ later: z.coerce.number().int().nonnegative(),
+ none: z.coerce.number().int().nonnegative(),
+});
+
@Injectable()
export class ActivitiesService {
private readonly logger = new Logger(ActivitiesService.name);
@@ -141,7 +217,7 @@ export class ActivitiesService {
subject: blankToNull(input.subject ?? ""),
body: blankToNull(input.body ?? ""),
occurredAt: parseDate(input.occurredAt) ?? new Date(),
- dueAt: isTask ? parseDate(input.dueAt) : null,
+ dueAt: isTask ? parseTaskDueDay(input.dueAt) : null,
companyId,
contactId: input.contactId ?? null,
dealId: input.dealId ?? null,
@@ -164,19 +240,20 @@ export class ActivitiesService {
return serializeEntry(activity);
}
- async complete(id: string, completed: boolean): Promise<ActivityEntry> {
- const activity = await this.db.activity.findUnique({
- where: { id },
- select: { type: true },
+ async update(input: ActivityUpdateInput): Promise<ActivityEntry> {
+ await this.requireTask(input.id, "Only tasks can be edited.");
+
+ const updated = await this.db.activity.update({
+ where: { id: input.id },
+ data: { subject: input.subject, dueAt: parseTaskDueDay(input.dueAt) },
+ select: ENTRY_SELECT,
});
- if (!activity) {
- throw new NotFoundException(`No activity with id ${id}.`);
- }
+ return serializeEntry(updated);
+ }
- if (activity.type !== ActivityType.TASK) {
- throw new BadRequestException("Only tasks can be completed.");
- }
+ async complete(id: string, completed: boolean): Promise<ActivityEntry> {
+ await this.requireTask(id, "Only tasks can be completed.");
const updated = await this.db.activity.update({
where: { id },
@@ -214,6 +291,146 @@ export class ActivitiesService {
return tasks.map(serializeEntry);
}
+ async tasks(input: TaskListInput): Promise<TaskListResult> {
+ const now = new Date();
+ const where = this.taskWhere(input, now);
+ const { skip, take } = paginate(input);
+
+ const [rows, total, facetCounts] = await Promise.all([
+ this.db.activity.findMany({
+ where,
+ skip,
+ take,
+ orderBy: resolveOrderBy(input, TASK_SORTABLE, [
+ { dueAt: { sort: "asc", nulls: "last" } },
+ { createdAt: "desc" },
+ ]),
+ select: TASK_SELECT,
+ }),
+ this.db.activity.count({ where }),
+ this.taskFacetCounts(input.q, now),
+ ]);
+
+ return {
+ rows: rows.map(serializeTask),
+ total,
+ day: {
+ today: serializeTaskDueDay(taskDayBoundaries(now).startOfToday) ?? "",
+ timeZone: TASKS.day.timeZone,
+ },
+ facetCounts,
+ };
+ }
+
+ private taskWhere(
+ input: TaskListInput,
+ now: Date,
+ ): Prisma.ActivityWhereInput {
+ const where = this.taskBaseWhere(input.q);
+
+ if (input.status === "open") where.completedAt = null;
+ if (input.status === "done") where.completedAt = { not: null };
+ if (input.createdBy.length > 0) {
+ where.createdById = { in: input.createdBy };
+ }
+ if (input.due.length > 0) {
+ where.AND = [
+ { OR: input.due.map((window) => taskWindowFilter(window, now)) },
+ ];
+ }
+
+ return where;
+ }
+
+ private taskBaseWhere(q: string): Prisma.ActivityWhereInput {
+ const term = q.trim();
+ const where: Prisma.ActivityWhereInput = { type: ActivityType.TASK };
+ if (!term) return where;
+
+ where.OR = [
+ { subject: { contains: term, mode: "insensitive" } },
+ { body: { contains: term, mode: "insensitive" } },
+ { company: { name: { contains: term, mode: "insensitive" } } },
+ { deal: { name: { contains: term, mode: "insensitive" } } },
+ { contact: { firstName: { contains: term, mode: "insensitive" } } },
+ { contact: { lastName: { contains: term, mode: "insensitive" } } },
+ ];
+
+ return where;
+ }
+
+ private async taskFacetCounts(q: string, now: Date) {
+ const where = this.taskBaseWhere(q);
+ const term = q.trim();
+ const search = term
+ ? Prisma.sql`AND (
+ strpos(lower(COALESCE(activity."subject", '')), lower(${term})) > 0
+ OR strpos(lower(COALESCE(activity."body", '')), lower(${term})) > 0
+ OR strpos(lower(COALESCE(company."name", '')), lower(${term})) > 0
+ OR strpos(lower(COALESCE(deal."name", '')), lower(${term})) > 0
+ OR strpos(lower(COALESCE(contact."firstName", '')), lower(${term})) > 0
+ OR strpos(lower(COALESCE(contact."lastName", '')), lower(${term})) > 0
+ )`
+ : Prisma.empty;
+ const { startOfToday, startOfTomorrow, startOfNextWeek } =
+ taskDayBoundaries(now);
+
+ const [authors, aggregateRows] = await Promise.all([
+ this.db.activity.groupBy({
+ by: ["createdById"],
+ where,
+ _count: { _all: true },
+ }),
+ this.db.$queryRaw`
+ SELECT
+ COUNT(*) FILTER (WHERE activity."completedAt" IS NULL) AS "open",
+ COUNT(*) FILTER (WHERE activity."completedAt" IS NOT NULL) AS "done",
+ COUNT(*) FILTER (WHERE activity."dueAt" < ${startOfToday}) AS "overdue",
+ COUNT(*) FILTER (WHERE activity."dueAt" >= ${startOfToday} AND activity."dueAt" < ${startOfTomorrow}) AS "today",
+ COUNT(*) FILTER (WHERE activity."dueAt" >= ${startOfTomorrow} AND activity."dueAt" < ${startOfNextWeek}) AS "week",
+ COUNT(*) FILTER (WHERE activity."dueAt" >= ${startOfNextWeek}) AS "later",
+ COUNT(*) FILTER (WHERE activity."dueAt" IS NULL) AS "none"
+ FROM "activity" activity
+ LEFT JOIN "company" company ON company."id" = activity."companyId"
+ LEFT JOIN "contact" contact ON contact."id" = activity."contactId"
+ LEFT JOIN "deal" deal ON deal."id" = activity."dealId"
+ WHERE activity."type" = ${ActivityType.TASK}::"ActivityType"
+ ${search}
+ `,
+ ]);
+
+ const aggregate = taskAggregateRow.parse(
+ z.array(z.unknown()).length(1).parse(aggregateRows)[0],
+ );
+
+ return {
+ status: { open: aggregate.open, done: aggregate.done },
+ createdBy: countsByKey(authors, "createdById"),
+ due: {
+ overdue: aggregate.overdue,
+ today: aggregate.today,
+ week: aggregate.week,
+ later: aggregate.later,
+ none: aggregate.none,
+ },
+ };
+ }
+
+ private async requireTask(id: string, wrongType: string) {
+ const activity = await this.db.activity.findUnique({
+ where: { id },
+ select: { type: true },
+ });
+
+ if (!activity) {
+ throw new NotFoundException(`No activity with id ${id}.`);
+ }
+
+ if (activity.type !== ActivityType.TASK) {
+ throw new BadRequestException(wrongType);
+ }
+ }
+
private anchor(
input: Pick<TimelineInput, "companyId" | "contactId" | "dealId">,
): Prisma.ActivityWhereInput {
@@ -277,6 +494,17 @@ function filterClause(filter: TimelineFilter): Prisma.ActivityWhereInput {
type Entry = Prisma.ActivityGetPayload<{ select: typeof ENTRY_SELECT }>;
+type Task = Prisma.ActivityGetPayload<{ select: typeof TASK_SELECT }>;
+
+function serializeTask(task: Task) {
+ return {
+ ...task,
+ dueAt: serializeTaskDueDay(task.dueAt),
+ completedAt: task.completedAt?.toISOString() ?? null,
+ createdAt: task.createdAt.toISOString(),
+ };
+}
+
function serializeEntry(entry: Entry) {
return {
...entry,
diff --git a/apps/api/src/activities/task-due-date.ts b/apps/api/src/activities/task-due-date.ts
new file mode 100644
index 00000000..84aaa198
--- /dev/null
+++ b/apps/api/src/activities/task-due-date.ts
@@ -0,0 +1,84 @@
+import type { Prisma } from "@crm/db";
+import { BadRequestException } from "@nestjs/common";
+import { z } from "zod";
+import { TASKS } from "./activities-config";
+
+const DAY_MS = 86_400_000;
+
+export const TASK_WINDOWS = [
+ "overdue",
+ "today",
+ "week",
+ "later",
+ "none",
+] as const;
+
+export type TaskWindow = (typeof TASK_WINDOWS)[number];
+
+export const taskDueDayInput = z.iso.date();
+
+export type TaskDayBoundaries = {
+ startOfToday: Date;
+ startOfTomorrow: Date;
+ startOfNextWeek: Date;
+};
+
+export function taskDayBoundaries(reference: Date): TaskDayBoundaries {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: TASKS.day.timeZone,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ }).formatToParts(reference);
+ const part = (type: Intl.DateTimeFormatPartTypes) =>
+ parts.find((item) => item.type === type)?.value ?? "";
+ const day = `${part("year")}-${part("month")}-${part("day")}`;
+ const startOfToday = new Date(`${day}T00:00:00.000Z`);
+ const startOfTomorrow = new Date(startOfToday.getTime() + DAY_MS);
+ const weekday = startOfToday.getUTCDay();
+ const daysUntilNextWeek = (TASKS.day.weekStartsOn - weekday + 7) % 7 || 7;
+ const startOfNextWeek = new Date(
+ startOfToday.getTime() + daysUntilNextWeek * DAY_MS,
+ );
+
+ return { startOfToday, startOfTomorrow, startOfNextWeek };
+}
+
+export function taskDueDay(value: string): Date {
+ const parsed = taskDueDayInput.safeParse(value);
+ if (!parsed.success) {
+ throw new BadRequestException(`"${value}" is not a calendar day.`);
+ }
+
+ return new Date(`${parsed.data}T00:00:00.000Z`);
+}
+
+export function parseTaskDueDay(value: string | null | undefined): Date | null {
+ if (value === null || value === undefined) return null;
+ return taskDueDay(value);
+}
+
+export function serializeTaskDueDay(value: Date | null): string | null {
+ return value?.toISOString().slice(0, 10) ?? null;
+}
+
+export function taskWindowFilter(
+ window: TaskWindow,
+ reference: Date,
+): Prisma.ActivityWhereInput {
+ const { startOfToday, startOfTomorrow, startOfNextWeek } =
+ taskDayBoundaries(reference);
+
+ switch (window) {
+ case "overdue":
+ return { dueAt: { lt: startOfToday } };
+ case "today":
+ return { dueAt: { gte: startOfToday, lt: startOfTomorrow } };
+ case "week":
+ return { dueAt: { gte: startOfTomorrow, lt: startOfNextWeek } };
+ case "later":
+ return { dueAt: { gte: startOfNextWeek } };
+ case "none":
+ return { dueAt: null };
+ }
+}
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
index 75065fc2..30756818 100644
--- a/apps/api/src/dashboard/dashboard.service.ts
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -2,6 +2,7 @@ import { ActivityType, type Db, DealStage } from "@crm/db";
import { OPEN_DEAL_STAGES } from "@crm/db/deal-stage";
import { activityMeta } from "@crm/validation/activity-meta";
import { Injectable } from "@nestjs/common";
+import { taskDayBoundaries } from "../activities/task-due-date";
import { toCents } from "../crm/values";
import { ConversionService } from "../currency/conversion.service";
import { InjectDatabase } from "../database/database.constants";
@@ -42,6 +43,7 @@ export class DashboardService {
const owned = mine ? { ownerId: actingUserId } : {};
const now = new Date();
+ const { startOfToday } = taskDayBoundaries(now);
const startOfMonth = monthStart(now, 0);
const startOfNextMonth = monthStart(now, 1);
const startOfPrevMonth = monthStart(now, -1);
@@ -136,7 +138,7 @@ export class DashboardService {
where: {
type: ActivityType.TASK,
completedAt: null,
- dueAt: { lt: now },
+ dueAt: { lt: startOfToday },
createdById: actingUserId,
},
orderBy: [{ dueAt: "asc" }],
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
index 459d19ec..47cf9652 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -13,7 +13,7 @@ import { z } from "zod";
const t = initTRPC.create();
const publicProcedure = t.procedure;
-import { timelineInput, timelineOutput, timelineCountsInput, timelineCountsOutput, myTasksInput, myTasksOutput, activityCreateInput, activityCreateOutput, completeInput, completeOutput } from "../activities/activities.contracts";
+import { timelineInput, timelineOutput, timelineCountsInput, timelineCountsOutput, myTasksInput, myTasksOutput, taskListInput, taskListOutput, activityCreateInput, activityCreateOutput, activityUpdateInput, activityUpdateOutput, completeInput, completeOutput } from "../activities/activities.contracts";
import { agentListOutput, agentReviseInput, agentReviseOutput, agentIdInput, agentFilesOutput, agentSaveFileInput, agentSaveFileOutput, agentByIdOutput, agentHistoryInput, agentHistoryOutput, agentActivityOutput, agentUpdateInput, agentUpdateOutput, agentDeployInput, agentDeployOutput, agentPauseOutput, agentResumeOutput, agentArchiveOutput, agentRestoreOutput, agentRemoveOutput, agentRunNowInput, agentRunNowOutput, agentRetryRunInput, agentRetryRunOutput, agentCancelRunInput, agentCancelRunOutput } from "../agent/agents.contracts";
import { apiKeyListInput, apiKeyListOutput, createApiKeyInput, createApiKeyOutput, revokeApiKeyInput, revokeApiKeyOutput } from "../api-keys/api-keys.contracts";
import { companyListInput, companyListOutput, companyIdInput, companyDetailOutput, companyOptionsInput, companyOptionOutput, companyCreateInput, companySummaryOutput, companyImportInput, companyImportOutput, companyUpdateArgs, companyArchiveResultOutput, companyBulkOwnerInput, companyBulkResultOutput, companyBulkInput, companyEnrichOutput, companyResearchOutput, setPrimaryContactInput, companySetPrimaryContactOutput } from "../companies/companies.contracts";
@@ -49,10 +49,18 @@ const appRouter = t.router({
.input(myTasksInput)
.output(myTasksOutput)
.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as any),
+ tasks: publicProcedure
+ .input(taskListInput)
+ .output(taskListOutput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as any),
create: publicProcedure
.input(activityCreateInput)
.output(activityCreateOutput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as any),
+ update: publicProcedure
+ .input(activityUpdateInput)
+ .output(activityUpdateOutput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as any),
complete: publicProcedure
.input(completeInput)
.output(completeOutput)
diff --git a/apps/api/test/task-due-date.spec.ts b/apps/api/test/task-due-date.spec.ts
new file mode 100644
index 00000000..c65cdba2
--- /dev/null
+++ b/apps/api/test/task-due-date.spec.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "bun:test";
+import {
+ parseTaskDueDay,
+ serializeTaskDueDay,
+ taskDayBoundaries,
+ taskWindowFilter,
+} from "../src/activities/task-due-date";
+
+describe("task calendar days", () => {
+ it("stores and returns a selected day without a timezone shift", () => {
+ const stored = parseTaskDueDay("2026-10-22");
+
+ expect(stored?.toISOString()).toBe("2026-10-22T00:00:00.000Z");
+ expect(serializeTaskDueDay(stored)).toBe("2026-10-22");
+ });
+
+ it("rejects an instant where a calendar day is required", () => {
+ expect(() => parseTaskDueDay("2026-10-22T14:00:00.000Z")).toThrow(
+ "is not a calendar day",
+ );
+ });
+
+ it("uses one UTC workspace day on both sides of midnight", () => {
+ expect(taskDayBoundaries(new Date("2026-10-22T23:59:59.999Z"))).toEqual(
+ taskDayBoundaries(new Date("2026-10-22T00:00:00.000Z")),
+ );
+ });
+
+ it("ends this week at the next Monday", () => {
+ const reference = new Date("2026-10-22T12:00:00.000Z");
+
+ expect(taskWindowFilter("week", reference)).toEqual({
+ dueAt: {
+ gte: new Date("2026-10-23T00:00:00.000Z"),
+ lt: new Date("2026-10-26T00:00:00.000Z"),
+ },
+ });
+ });
+
+ it("keeps today separate from overdue work", () => {
+ const reference = new Date("2026-10-22T12:00:00.000Z");
+
+ expect(taskWindowFilter("overdue", reference)).toEqual({
+ dueAt: { lt: new Date("2026-10-22T00:00:00.000Z") },
+ });
+ expect(taskWindowFilter("today", reference)).toEqual({
+ dueAt: {
+ gte: new Date("2026-10-22T00:00:00.000Z"),
+ lt: new Date("2026-10-23T00:00:00.000Z"),
+ },
+ });
+ });
+});
diff --git a/apps/api/test/tasks.spec.ts b/apps/api/test/tasks.spec.ts
new file mode 100644
index 00000000..36ea6211
--- /dev/null
+++ b/apps/api/test/tasks.spec.ts
@@ -0,0 +1,155 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { ActivityType, db } from "@crm/db";
+import { ActivitiesService } from "../src/activities/activities.service";
+import {
+ serializeTaskDueDay,
+ taskDayBoundaries,
+} from "../src/activities/task-due-date";
+import { ActivityStampService } from "../src/crm/activity-stamp.service";
+
+const suffix = process.env.TEST_RUN_ID ?? "tasks-spec";
+const userId = `tasks-user-${suffix}`;
+const domain = `tasks-${suffix}.test`;
+const stamp = new ActivityStampService(db);
+const activities = new ActivitiesService(db, stamp);
+let companyId: string;
+
+async function clean() {
+ await db.activity.deleteMany({ where: { createdById: userId } });
+ await db.company.deleteMany({ where: { domain } });
+ await db.user.deleteMany({ where: { id: userId } });
+}
+
+beforeAll(async () => {
+ await clean();
+ await db.user.create({
+ data: { id: userId, name: "Task Owner", email: `owner@${domain}` },
+ });
+ const company = await db.company.create({
+ data: { name: "Task Company", domain },
+ select: { id: true },
+ });
+ companyId = company.id;
+
+ const { startOfToday } = taskDayBoundaries(new Date());
+ const yesterday = new Date(startOfToday.getTime() - 86_400_000);
+ await db.activity.createMany({
+ data: [
+ {
+ type: ActivityType.TASK,
+ subject: "Ship 100% complete",
+ dueAt: startOfToday,
+ companyId,
+ createdById: userId,
+ },
+ {
+ type: ActivityType.TASK,
+ subject: "Past task",
+ dueAt: yesterday,
+ companyId,
+ createdById: userId,
+ },
+ {
+ type: ActivityType.TASK,
+ subject: "No date task",
+ companyId,
+ createdById: userId,
+ },
+ {
+ type: ActivityType.TASK,
+ subject: "Done task",
+ completedAt: new Date(),
+ companyId,
+ createdById: userId,
+ },
+ ],
+ });
+});
+
+afterAll(clean);
+
+const baseInput = {
+ q: "",
+ sort: "dueAt",
+ dir: "asc" as const,
+ page: 1,
+ pageSize: 25,
+ status: "all" as const,
+ due: [],
+ createdBy: [],
+};
+
+describe("task list", () => {
+ it("returns related records and complete facet totals", async () => {
+ const result = await activities.tasks(baseInput);
+
+ expect(result.total).toBe(4);
+ expect(result.rows[0]?.company?.name).toBe("Task Company");
+ expect(result.facetCounts.status).toEqual({ open: 3, done: 1 });
+ expect(result.facetCounts.due).toMatchObject({
+ overdue: 1,
+ today: 1,
+ none: 2,
+ });
+ expect(result.day.today).toBe(
+ serializeTaskDueDay(taskDayBoundaries(new Date()).startOfToday) ?? "",
+ );
+ });
+
+ it("searches task subjects", async () => {
+ const result = await activities.tasks({ ...baseInput, q: "100" });
+
+ expect(result.total).toBe(1);
+ expect(result.rows[0]?.subject).toBe("Ship 100% complete");
+ });
+
+ it("combines status, due, and creator filters", async () => {
+ const result = await activities.tasks({
+ ...baseInput,
+ status: "open",
+ due: ["overdue"],
+ createdBy: [userId],
+ });
+
+ expect(result.total).toBe(1);
+ expect(result.rows[0]?.subject).toBe("Past task");
+ });
+
+ it("sorts open tasks before completed tasks in ascending order", async () => {
+ const result = await activities.tasks({
+ ...baseInput,
+ sort: "status",
+ dir: "asc",
+ });
+
+ expect(result.rows.at(-1)?.subject).toBe("Done task");
+ });
+
+ it("sorts completed tasks before open tasks in descending order", async () => {
+ const result = await activities.tasks({
+ ...baseInput,
+ sort: "status",
+ dir: "desc",
+ });
+
+ expect(result.rows[0]?.subject).toBe("Done task");
+ });
+});
+
+describe("task editing", () => {
+ it("updates a task with a calendar day", async () => {
+ const task = await db.activity.findFirstOrThrow({
+ where: { createdById: userId, subject: "No date task" },
+ select: { id: true },
+ });
+
+ const updated = await activities.update({
+ id: task.id,
+ subject: "Dated task",
+ dueAt: "2026-12-03",
+ });
+
+ expect(updated.subject).toBe("Dated task");
+ expect(updated.dueAt).toBe("2026-12-03T00:00:00.000Z");
+ });
+});
diff --git a/apps/app/app/(app)/[slug]/dashboard-summary.tsx b/apps/app/app/(app)/[slug]/dashboard-summary.tsx
index a14e0428..08ae17d6 100644
--- a/apps/app/app/(app)/[slug]/dashboard-summary.tsx
+++ b/apps/app/app/(app)/[slug]/dashboard-summary.tsx
@@ -204,6 +204,11 @@ export function DashboardSummary() {
? "Every task you have logged is either done or still to come"
: `${formatCount(overdueTasks.length, "task")} past due`}
</CardDescription>
+ <CardAction>
+ <Button asChild variant="contrast" size="sm">
+ <Link href={workspaceUrl("/tasks")}>Open tasks</Link>
+ </Button>
+ </CardAction>
</CardHeader>
<CardPanel>
{overdueTasks.length === 0 ? (
diff --git a/apps/app/app/(app)/[slug]/layout.tsx b/apps/app/app/(app)/[slug]/layout.tsx
index 863d0da8..d562cd03 100644
--- a/apps/app/app/(app)/[slug]/layout.tsx
+++ b/apps/app/app/(app)/[slug]/layout.tsx
@@ -5,6 +5,7 @@ import { AppHeader, AppHeaderFallback } from "@/components/app-header";
import { AppIconRail, AppIconRailFallback } from "@/components/app-icon-rail";
import { QuickSwitcher } from "@/components/crm/quick-switcher";
import { RecordSheetHost } from "@/components/crm/record-sheet/record-sheet-host";
+import { RecordStackBoundary } from "@/components/crm/record-sheet/record-stack";
import { MobileNavProvider } from "@/components/mobile-nav";
import { requireMailboxAccess } from "@/lib/session";
import { HydrateClient } from "@/lib/trpc/hydrate";
@@ -16,26 +17,28 @@ export default function AppLayout({
}: LayoutProps<"/[slug]">) {
return (
<MobileNavProvider>
- <div className="isolate flex h-svh flex-col">
- <Suspense fallback={<AppHeaderFallback />}>
- <WorkspaceHeader params={params} />
- </Suspense>
-
- <div className="flex min-h-0 flex-1">
- <Suspense fallback={<AppIconRailFallback />}>
- <AppIconRail />
+ <RecordStackBoundary>
+ <div className="isolate flex h-svh flex-col">
+ <Suspense fallback={<AppHeaderFallback />}>
+ <WorkspaceHeader params={params} />
</Suspense>
- {children}
- </div>
- <Suspense fallback={null}>
- <RecordSheetHost />
- </Suspense>
+ <div className="flex min-h-0 flex-1">
+ <Suspense fallback={<AppIconRailFallback />}>
+ <AppIconRail />
+ </Suspense>
+ {children}
+ </div>
+
+ <Suspense fallback={null}>
+ <RecordSheetHost />
+ </Suspense>
- <Suspense fallback={null}>
- <QuickSwitcher />
- </Suspense>
- </div>
+ <Suspense fallback={null}>
+ <QuickSwitcher />
+ </Suspense>
+ </div>
+ </RecordStackBoundary>
</MobileNavProvider>
);
}
diff --git a/apps/app/app/(app)/[slug]/tasks/page.tsx b/apps/app/app/(app)/[slug]/tasks/page.tsx
new file mode 100644
index 00000000..f08cadcc
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/tasks/page.tsx
@@ -0,0 +1,66 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellLoading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { normalizeTasksInput, tasksSearchParams } from "./tasks-search-params";
+import { TasksTable } from "./tasks-table";
+
+export const metadata: Metadata = { title: "Tasks" };
+
+export default function TasksPage({
+ searchParams,
+}: PageProps<"/[slug]/tasks">) {
+ return (
+ <PageShell className="min-h-0">
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Tasks</PageShellTitle>
+ <PageShellDescription>
+ Work that needs a next step.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+ <PageShellContent className="min-h-0">
+ <Suspense fallback={<PageShellLoading />}>
+ <Tasks searchParams={searchParams} />
+ </Suspense>
+ </PageShellContent>
+ </PageShell>
+ );
+}
+
+async function Tasks({
+ searchParams,
+}: Pick<PageProps<"/[slug]/tasks">, "searchParams">) {
+ const [, values] = await Promise.all([
+ requireSession(),
+ tasksSearchParams.load(searchParams),
+ ]);
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+
+ await Promise.all([
+ queryClient.prefetchQuery(
+ trpc.activities.tasks.queryOptions(
+ normalizeTasksInput(tasksSearchParams.toInput(values)),
+ ),
+ ),
+ queryClient.prefetchQuery(trpc.users.list.queryOptions()),
+ ]);
+
+ return (
+ <HydrateClient>
+ <TasksTable />
+ </HydrateClient>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/tasks/task-focus.ts b/apps/app/app/(app)/[slug]/tasks/task-focus.ts
new file mode 100644
index 00000000..8b0b4c03
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/tasks/task-focus.ts
@@ -0,0 +1,12 @@
+export function nextTaskFocusId(
+ ids: string[],
+ currentId: string,
+ currentRemains: boolean,
+): string | null {
+ if (currentRemains) return currentId;
+
+ const index = ids.indexOf(currentId);
+ if (index < 0) return ids[0] ?? null;
+
+ return ids[index + 1] ?? ids[index - 1] ?? null;
+}
diff --git a/apps/app/app/(app)/[slug]/tasks/tasks-search-params.ts b/apps/app/app/(app)/[slug]/tasks/tasks-search-params.ts
new file mode 100644
index 00000000..f03b0280
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/tasks/tasks-search-params.ts
@@ -0,0 +1,38 @@
+import { createListSearchParams } from "@/components/data-table/list-search-params";
+
+export const tasksSearchParams = createListSearchParams({
+ defaultSort: "dueAt",
+ defaultDir: "asc",
+ tabId: "status",
+ tabDefault: "open",
+ facetIds: ["due", "createdBy"] as const,
+});
+
+const TASK_STATUSES = ["all", "open", "done"] as const;
+const TASK_DUE_WINDOWS = ["overdue", "today", "week", "later", "none"] as const;
+
+type TaskStatus = (typeof TASK_STATUSES)[number];
+type TaskDueWindow = (typeof TASK_DUE_WINDOWS)[number];
+
+function isTaskStatus(value: string): value is TaskStatus {
+ return TASK_STATUSES.some((status) => status === value);
+}
+
+function isTaskDueWindow(value: string): value is TaskDueWindow {
+ return TASK_DUE_WINDOWS.some((window) => window === value);
+}
+
+export function normalizeTasksInput(
+ input: ReturnType<typeof tasksSearchParams.toInput>,
+) {
+ return {
+ q: input.q,
+ sort: input.sort,
+ dir: input.dir,
+ page: input.page,
+ pageSize: input.pageSize,
+ status: isTaskStatus(input.status) ? input.status : "all",
+ due: input.due.filter(isTaskDueWindow),
+ createdBy: input.createdBy,
+ };
+}
diff --git a/apps/app/app/(app)/[slug]/tasks/tasks-table.tsx b/apps/app/app/(app)/[slug]/tasks/tasks-table.tsx
new file mode 100644
index 00000000..704616b5
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/tasks/tasks-table.tsx
@@ -0,0 +1,252 @@
+"use client";
+
+import { Checkbox } from "@crm/ui/components/checkbox";
+import {
+ DataTable,
+ type DataTableColumn,
+ type DataTableFacet,
+} from "@crm/ui/components/data-table";
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import { PersonAvatar } from "@crm/ui/components/person-avatar";
+import { cn } from "@crm/ui/lib/utils";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { useRef, useState } from "react";
+import { toast } from "sonner";
+import { contactName } from "@/components/crm/contact-name";
+import { RecordLink } from "@/components/crm/record-sheet/record-link";
+import { ListSearch } from "@/components/data-table/list-search";
+import { useTableQuery } from "@/components/data-table/use-table-query";
+import { LocalDay, LocalRelativeTime } from "@/components/local-date-time";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { nextTaskFocusId } from "./task-focus";
+import { normalizeTasksInput, tasksSearchParams } from "./tasks-search-params";
+
+type TaskRow = RouterOutputs["activities"]["tasks"]["rows"][number];
+
+const DUE_OPTIONS = [
+ { value: "overdue", label: "Overdue" },
+ { value: "today", label: "Today" },
+ { value: "week", label: "This week" },
+ { value: "later", label: "Later" },
+ { value: "none", label: "No due date" },
+];
+
+export function TasksTable() {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+ const table = useTableQuery(tasksSearchParams);
+ const { query } = table;
+ const input = normalizeTasksInput(table.input);
+ const searchRef = useRef<HTMLInputElement>(null);
+ const completionRefs = useRef(new Map<string, HTMLButtonElement>());
+ const [announcement, setAnnouncement] = useState("");
+ const tasks = useQuery({
+ ...trpc.activities.tasks.queryOptions(input),
+ placeholderData: (previous) => previous,
+ });
+ const users = useQuery(trpc.users.list.queryOptions());
+ const rows = tasks.data?.rows ?? [];
+
+ const complete = useMutation(
+ trpc.activities.complete.mutationOptions({
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const setCompleted = (row: TaskRow, completed: boolean) => {
+ const rowIds = rows.map((item) => item.id);
+ const remains =
+ input.status === "all" ||
+ (input.status === "open" ? !completed : completed);
+ const focusId = nextTaskFocusId(rowIds, row.id, remains);
+
+ complete.mutate(
+ { id: row.id, completed },
+ {
+ onSuccess: async () => {
+ setAnnouncement(completed ? "Task completed." : "Task reopened.");
+ await cache.activity();
+ requestAnimationFrame(() => {
+ const target = focusId ? completionRefs.current.get(focusId) : null;
+ (target ?? searchRef.current)?.focus();
+ });
+ },
+ },
+ );
+ };
+
+ const today = tasks.data?.day.today ?? "";
+ const columns: DataTableColumn<TaskRow>[] = [
+ {
+ id: "status",
+ header: <span className="sr-only">Status</span>,
+ label: "Status",
+ sortable: true,
+ hideable: false,
+ width: "w-12",
+ cell: (row) => (
+ <Checkbox
+ ref={(element) => {
+ if (element) completionRefs.current.set(row.id, element);
+ else completionRefs.current.delete(row.id);
+ }}
+ checked={row.completedAt !== null}
+ disabled={complete.isPending && complete.variables?.id === row.id}
+ onCheckedChange={(checked) => setCompleted(row, checked === true)}
+ aria-label={`${row.completedAt ? "Reopen" : "Complete"} ${row.subject ?? "task"}`}
+ />
+ ),
+ },
+ {
+ id: "subject",
+ header: "Task",
+ sortable: true,
+ hideable: false,
+ width: "w-[34%]",
+ cell: (row) =>
+ row.subject ? (
+ <span
+ className={cn(
+ "truncate font-medium",
+ row.completedAt && "text-muted-foreground line-through",
+ )}
+ >
+ {row.subject}
+ </span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "company",
+ header: "Related to",
+ sortable: true,
+ width: "w-[24%]",
+ cell: (row) => {
+ if (row.deal) {
+ return (
+ <RecordLink kind="deal" id={row.deal.id}>
+ {row.deal.name}
+ </RecordLink>
+ );
+ }
+ if (row.contact) {
+ return (
+ <RecordLink kind="contact" id={row.contact.id}>
+ {contactName(row.contact)}
+ </RecordLink>
+ );
+ }
+ if (row.company) {
+ return (
+ <RecordLink kind="company" id={row.company.id}>
+ {row.company.name}
+ </RecordLink>
+ );
+ }
+ return <EmptyCellValue />;
+ },
+ },
+ {
+ id: "dueAt",
+ header: "Due",
+ sortable: true,
+ align: "right",
+ width: "w-32",
+ cell: (row) =>
+ row.dueAt ? (
+ <span
+ className={cn(
+ "text-muted-foreground",
+ !row.completedAt && row.dueAt < today && "text-destructive",
+ )}
+ >
+ <LocalDay date={row.dueAt} />
+ </span>
+ ) : (
+ <EmptyCellValue />
+ ),
+ },
+ {
+ id: "createdBy",
+ header: "Created by",
+ sortable: true,
+ width: "w-44",
+ hideBelow: "md",
+ cell: (row) => (
+ <span className="flex min-w-0 items-center gap-2">
+ <PersonAvatar
+ src={row.createdBy.image}
+ name={row.createdBy.name}
+ email={row.createdBy.email}
+ size="sm"
+ />
+ <span className="truncate text-muted-foreground">
+ {row.createdBy.name}
+ </span>
+ </span>
+ ),
+ },
+ {
+ id: "createdAt",
+ header: "Created",
+ sortable: true,
+ align: "right",
+ width: "w-24",
+ defaultHidden: true,
+ cell: (row) => (
+ <span className="text-muted-foreground">
+ <LocalRelativeTime date={row.createdAt} />
+ </span>
+ ),
+ },
+ ];
+
+ const facetCounts = tasks.data?.facetCounts;
+ const facets: DataTableFacet[] = [
+ {
+ id: "due",
+ label: "Due",
+ options: DUE_OPTIONS.filter(
+ (option) => (facetCounts?.due?.[option.value] ?? 0) > 0,
+ ),
+ },
+ {
+ id: "createdBy",
+ label: "Created by",
+ options: (users.data ?? [])
+ .map((user) => ({ value: user.id, label: user.name }))
+ .filter((option) => (facetCounts?.createdBy?.[option.value] ?? 0) > 0),
+ },
+ ];
+
+ return (
+ <>
+ <span className="sr-only" role="status" aria-live="polite">
+ {announcement}
+ </span>
+ <DataTable
+ query={query}
+ search={<ListSearch inputRef={searchRef} placeholder="Search tasks…" />}
+ columns={columns}
+ rows={rows}
+ total={tasks.data?.total ?? 0}
+ facetCounts={facetCounts}
+ facets={facets}
+ tabs={{
+ id: "status",
+ allLabel: "All tasks",
+ options: [
+ { value: "open", label: "Open" },
+ { value: "done", label: "Done" },
+ ],
+ }}
+ getRowId={(row) => row.id}
+ loading={tasks.isFetching}
+ empty="No tasks match this view."
+ />
+ </>
+ );
+}
diff --git a/apps/app/components/app-icon-rail.tsx b/apps/app/components/app-icon-rail.tsx
index ad3440e0..62e42503 100644
--- a/apps/app/components/app-icon-rail.tsx
+++ b/apps/app/components/app-icon-rail.tsx
@@ -5,6 +5,7 @@ import Close from "@carbon/icons-react/es/Close";
import Dashboard from "@carbon/icons-react/es/Dashboard";
import Partnership from "@carbon/icons-react/es/Partnership";
import Settings from "@carbon/icons-react/es/Settings";
+import Task from "@carbon/icons-react/es/Task";
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
import { Button } from "@crm/ui/components/button";
import type { CarbonIcon } from "@crm/ui/components/icon";
@@ -57,6 +58,7 @@ const ITEMS: RailItem[] = [
match: "prefix",
},
{ title: "Deals", href: "/deals", icon: Partnership, match: "prefix" },
+ { title: "Tasks", href: "/tasks", icon: Task, match: "prefix" },
{ title: "Settings", href: "/settings", icon: Settings, match: "prefix" },
];
diff --git a/apps/app/components/crm/record-sheet/record-stack.ts b/apps/app/components/crm/record-sheet/record-stack.ts
index d3324443..d4cddea0 100644
--- a/apps/app/components/crm/record-sheet/record-stack.ts
+++ b/apps/app/components/crm/record-sheet/record-stack.ts
@@ -6,7 +6,16 @@ import {
parseAsStringLiteral,
useQueryStates,
} from "nuqs";
-import { useCallback, useMemo } from "react";
+import {
+ createContext,
+ createElement,
+ type ReactNode,
+ Suspense,
+ useCallback,
+ useContext,
+ useMemo,
+ useRef,
+} from "react";
import { timelineTabParser } from "@/components/crm/timeline/timeline-search-params";
import { SEARCH_PARAM } from "@/lib/search-param-keys";
@@ -50,9 +59,10 @@ function parseRef(raw: string): RecordRef | null {
: null;
}
-export function useRecordStack() {
+function useRecordStackState() {
const [values, setParams] = useQueryStates(params);
const record = values[SEARCH_PARAM.record.stack];
+ const returnFocus = useRef<HTMLElement | null>(null);
const stack = useMemo(
() => record.map(parseRef).filter((ref): ref is RecordRef => ref !== null),
@@ -61,7 +71,7 @@ export function useRecordStack() {
const write = useCallback(
(next: RecordRef[], history: "push" | "replace") => {
- void setParams(
+ return setParams(
{
[SEARCH_PARAM.record.stack]:
next.length === 0 ? null : next.map(recordKey),
@@ -73,15 +83,18 @@ export function useRecordStack() {
[SEARCH_PARAM.record.timeline]: null,
},
{ history },
- );
+ ).then(() => undefined);
},
[setParams],
);
const open = useCallback(
(ref: RecordRef) => {
+ if (stack.length === 0 && document.activeElement instanceof HTMLElement) {
+ returnFocus.current = document.activeElement;
+ }
const key = recordKey(ref);
- write(
+ void write(
[...stack.filter((entry) => recordKey(entry) !== key), ref],
stack.length === 0 ? "push" : "replace",
);
@@ -89,12 +102,19 @@ export function useRecordStack() {
[stack, write],
);
- const close = useCallback(
- () => write(stack.slice(0, -1), "replace"),
- [stack, write],
- );
+ const close = useCallback(() => {
+ const next = stack.slice(0, -1);
+ void write(next, "replace").then(() => {
+ if (next.length > 0) return;
+ requestAnimationFrame(() => returnFocus.current?.focus());
+ });
+ }, [stack, write]);
- const closeAll = useCallback(() => write([], "replace"), [write]);
+ const closeAll = useCallback(() => {
+ void write([], "replace").then(() => {
+ requestAnimationFrame(() => returnFocus.current?.focus());
+ });
+ }, [write]);
return {
stack,
@@ -105,6 +125,47 @@ export function useRecordStack() {
};
}
+type RecordStackState = ReturnType<typeof useRecordStackState>;
+
+const RecordStackContext = createContext<RecordStackState | null>(null);
+
+const EMPTY_RECORD_STACK: RecordStackState = {
+ stack: [],
+ top: null,
+ open: () => undefined,
+ close: () => undefined,
+ closeAll: () => undefined,
+};
+
+function RecordStackFallbackProvider({ children }: { children: ReactNode }) {
+ return createElement(
+ RecordStackContext.Provider,
+ { value: EMPTY_RECORD_STACK },
+ children,
+ );
+}
+
+export function RecordStackProvider({ children }: { children: ReactNode }) {
+ const state = useRecordStackState();
+ return createElement(RecordStackContext.Provider, { value: state }, children);
+}
+
+export function RecordStackBoundary({ children }: { children: ReactNode }) {
+ return createElement(
+ Suspense,
+ {
+ fallback: createElement(RecordStackFallbackProvider, null, children),
+ },
+ createElement(RecordStackProvider, null, children),
+ );
+}
+
+export function useRecordStack(): RecordStackState {
+ const state = useContext(RecordStackContext);
+ if (!state) throw new Error("RecordStackProvider is missing.");
+ return state;
+}
+
export function useOpenRecord() {
return useRecordStack().open;
}
diff --git a/apps/app/components/crm/section-prefetch.ts b/apps/app/components/crm/section-prefetch.ts
index 5e9d7eb5..fd7c8b57 100644
--- a/apps/app/components/crm/section-prefetch.ts
+++ b/apps/app/components/crm/section-prefetch.ts
@@ -5,6 +5,10 @@ import { useCallback } from "react";
import { companiesSearchParams } from "@/app/(app)/[slug]/companies/companies-search-params";
import { contactsSearchParams } from "@/app/(app)/[slug]/contacts/contacts-search-params";
import { dealsSearchParams } from "@/app/(app)/[slug]/deals/deals-search-params";
+import {
+ normalizeTasksInput,
+ tasksSearchParams,
+} from "@/app/(app)/[slug]/tasks/tasks-search-params";
import { useTRPC } from "@/lib/trpc/client";
export function usePrefetchSection(): (section: string) => void {
@@ -38,6 +42,13 @@ export function usePrefetchSection(): (section: string) => void {
trpc.deals.list.queryOptions(dealsSearchParams.defaultInput()),
);
return;
+ case "/tasks":
+ void queryClient.prefetchQuery(
+ trpc.activities.tasks.queryOptions(
+ normalizeTasksInput(tasksSearchParams.defaultInput()),
+ ),
+ );
+ return;
default:
return;
}
diff --git a/apps/app/components/crm/timeline/activity-composer.tsx b/apps/app/components/crm/timeline/activity-composer.tsx
index 6cebb991..a17ce9d0 100644
--- a/apps/app/components/crm/timeline/activity-composer.tsx
+++ b/apps/app/components/crm/timeline/activity-composer.tsx
@@ -16,6 +16,7 @@ import {
} from "@crm/ui/components/popover";
import { Spinner } from "@crm/ui/components/spinner";
import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";
+import { toDay } from "@crm/ui/lib/format";
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
@@ -75,7 +76,7 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {
type,
subject: isTask ? text : undefined,
body: isTask ? undefined : text,
- dueAt: isTask ? (dueAt?.toISOString() ?? null) : undefined,
+ dueAt: isTask ? (dueAt ? toDay(dueAt) : null) : undefined,
});
};
diff --git a/apps/app/components/crm/timeline/activity-form.tsx b/apps/app/components/crm/timeline/activity-form.tsx
new file mode 100644
index 00000000..38d5f371
--- /dev/null
+++ b/apps/app/components/crm/timeline/activity-form.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupTextarea,
+} from "@crm/ui/components/input-group";
+import type { ReactNode } from "react";
+
+export function ActivityForm({
+ value,
+ onValueChange,
+ ariaLabel,
+ onSubmit,
+ onEscape,
+ children,
+}: {
+ value: string;
+ onValueChange: (next: string) => void;
+ ariaLabel: string;
+ onSubmit: () => void;
+ onEscape: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ onSubmit();
+ }}
+ >
+ <InputGroup>
+ <InputGroupTextarea
+ value={value}
+ onChange={(event) => onValueChange(event.target.value)}
+ aria-label={ariaLabel}
+ autoFocus
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ onSubmit();
+ }
+ if (event.key === "Escape") onEscape();
+ }}
+ />
+ <InputGroupAddon align="block-end" className="gap-2 border-t">
+ {children}
+ </InputGroupAddon>
+ </InputGroup>
+ </form>
+ );
+}
diff --git a/apps/app/components/crm/timeline/due-date-button.tsx b/apps/app/components/crm/timeline/due-date-button.tsx
new file mode 100644
index 00000000..8d4582ee
--- /dev/null
+++ b/apps/app/components/crm/timeline/due-date-button.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import CalendarGlyph from "@carbon/icons-react/es/Calendar";
+import { Button } from "@crm/ui/components/button";
+import { Calendar } from "@crm/ui/components/calendar";
+import { Icon } from "@crm/ui/components/icon";
+import { InputGroupButton } from "@crm/ui/components/input-group";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@crm/ui/components/popover";
+import { formatDay, fromDay, toDay } from "@crm/ui/lib/format";
+import { useState } from "react";
+
+export function DueDateButton({
+ value,
+ onChange,
+ disabled,
+}: {
+ value: string | null;
+ onChange: (next: string) => void;
+ disabled: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const selected = fromDay(value);
+ const choose = (next: string) => {
+ onChange(next);
+ setOpen(false);
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <InputGroupButton variant="ghost" size="xs" disabled={disabled}>
+ <Icon icon={CalendarGlyph} data-icon="inline-start" />
+ {selected ? formatDay(value) : "Due date"}
+ </InputGroupButton>
+ </PopoverTrigger>
+ <PopoverContent size="fit" align="start">
+ <Calendar
+ mode="single"
+ selected={selected}
+ defaultMonth={selected}
+ onSelect={(next) => choose(next ? toDay(next) : "")}
+ autoFocus
+ />
+ {selected ? (
+ <div className="border-t p-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start"
+ onClick={() => choose("")}
+ >
+ Clear due date
+ </Button>
+ </div>
+ ) : null}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/app/components/crm/timeline/task-editor.tsx b/apps/app/components/crm/timeline/task-editor.tsx
new file mode 100644
index 00000000..15d2743e
--- /dev/null
+++ b/apps/app/components/crm/timeline/task-editor.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { InputGroupButton } from "@crm/ui/components/input-group";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useMutation } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+import { ActivityForm } from "./activity-form";
+import { DueDateButton } from "./due-date-button";
+import type { TimelineEntryData } from "./timeline-entry";
+
+export function TaskEditor({
+ task,
+ onClose,
+}: {
+ task: Pick<TimelineEntryData, "id" | "subject" | "dueAt">;
+ onClose: () => void;
+}) {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+ const [draft, setDraft] = useState(task.subject ?? "");
+ const [dueAt, setDueAt] = useState(task.dueAt?.slice(0, 10) ?? "");
+ const text = draft.trim();
+ const update = useMutation(
+ trpc.activities.update.mutationOptions({
+ onSuccess: async () => {
+ await cache.activity({ settle: "record" });
+ onClose();
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const submit = () => {
+ if (!text || update.isPending) return;
+ update.mutate({ id: task.id, subject: text, dueAt: dueAt || null });
+ };
+
+ return (
+ <ActivityForm
+ value={draft}
+ onValueChange={setDraft}
+ ariaLabel="Task"
+ onSubmit={submit}
+ onEscape={onClose}
+ >
+ <DueDateButton
+ value={dueAt}
+ onChange={setDueAt}
+ disabled={update.isPending}
+ />
+ <InputGroupButton
+ type="button"
+ variant="ghost"
+ size="xs"
+ className="ml-auto"
+ disabled={update.isPending}
+ onClick={onClose}
+ >
+ Cancel
+ </InputGroupButton>
+ <InputGroupButton
+ type="submit"
+ variant="default"
+ size="xs"
+ disabled={!text || update.isPending}
+ >
+ {update.isPending ? <Spinner /> : null}
+ Save
+ </InputGroupButton>
+ </ActivityForm>
+ );
+}
diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsx
index 0a9d730a..615b5da5 100644
--- a/apps/app/components/crm/timeline/timeline-entry.tsx
+++ b/apps/app/components/crm/timeline/timeline-entry.tsx
@@ -1,14 +1,18 @@
"use client";
+import Edit from "@carbon/icons-react/es/Edit";
import { DealStage } from "@crm/db/enums";
+import { Button } from "@crm/ui/components/button";
import { Checkbox } from "@crm/ui/components/checkbox";
+import { Icon } from "@crm/ui/components/icon";
import { StatusIndicator } from "@crm/ui/components/status-indicator";
import { cn } from "@crm/ui/lib/utils";
import { useMutation } from "@tanstack/react-query";
+import { useRef, useState } from "react";
import { toast } from "sonner";
import { z } from "zod";
import { RecordLink } from "@/components/crm/record-sheet/record-link";
-import { LocalDateTime, LocalRelativeTime } from "@/components/local-date-time";
+import { LocalDateTime, LocalDay } from "@/components/local-date-time";
import { activityLabel } from "@/lib/activity-presentation";
import { dealStageLabel } from "@/lib/deal-stage";
import { useCrmCache } from "@/lib/trpc/cache";
@@ -17,6 +21,7 @@ import type { RouterOutputs } from "@/lib/trpc/types";
import { ActivityIcon } from "./activity-icon";
import { EmailThreadEntry } from "./email-thread-entry";
import { MeetingEntry } from "./meeting-entry";
+import { TaskEditor } from "./task-editor";
import type { TimelineAnchor } from "./timeline";
export type TimelineEntryData =
@@ -47,6 +52,8 @@ export function TimelineEntry({
}) {
const trpc = useTRPC();
const cache = useCrmCache();
+ const [editing, setEditing] = useState(false);
+ const editButton = useRef<HTMLButtonElement>(null);
const complete = useMutation(
trpc.activities.complete.mutationOptions({
@@ -61,7 +68,24 @@ export function TimelineEntry({
isTask &&
!done &&
entry.dueAt !== null &&
- new Date(entry.dueAt) < new Date();
+ entry.dueAt.slice(0, 10) < new Date().toISOString().slice(0, 10);
+ const closeEditor = () => {
+ setEditing(false);
+ requestAnimationFrame(() => editButton.current?.focus());
+ };
+
+ if (editing) {
+ return (
+ <li className="flex gap-2.5 py-2">
+ <span className="mt-0.5 shrink-0 text-muted-foreground">
+ <Checkbox checked={done} disabled aria-label="Task status" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <TaskEditor task={entry} onClose={closeEditor} />
+ </div>
+ </li>
+ );
+ }
const change =
entry.type === "STAGE_CHANGE" ? stageChange.parse(entry.meta) : null;
@@ -144,6 +168,20 @@ export function TimelineEntry({
<LocalDateTime date={when} options={TIME_OPTIONS} />
</span>
</span>
+
+ {isTask ? (
+ <Button
+ ref={editButton}
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ disabled={complete.isPending}
+ onClick={() => setEditing(true)}
+ >
+ <Icon icon={Edit} />
+ <span className="sr-only">Edit task</span>
+ </Button>
+ ) : null}
</div>
{entry.calendarEvent ? (
@@ -172,7 +210,7 @@ export function TimelineEntry({
label={
<>
{overdue ? "Overdue" : "Due"}{" "}
- <LocalRelativeTime date={entry.dueAt} />
+ <LocalDay date={entry.dueAt} />
</>
}
/>
diff --git a/apps/app/components/data-table/list-search-params.ts b/apps/app/components/data-table/list-search-params.ts
index d5a899f1..1a58a777 100644
--- a/apps/app/components/data-table/list-search-params.ts
+++ b/apps/app/components/data-table/list-search-params.ts
@@ -70,6 +70,7 @@ export type ListTableConfig<TTab extends string, TFacet extends string> = {
defaultDir?: SortDirection;
pageSize?: number;
tabId?: TTab;
+ tabDefault?: string;
facetIds?: readonly TFacet[];
facetDefaults?: Partial<Record<TFacet, string[]>>;
};
@@ -95,6 +96,7 @@ export function createListSearchParams<
defaultDir = "asc",
pageSize = 25,
tabId,
+ tabDefault = "all",
facetIds = [],
facetDefaults,
} = config;
@@ -105,7 +107,7 @@ export function createListSearchParams<
);
const tabExtras: Record<string, StringParser> = {};
- if (tabId) tabExtras[tabId] = parseAsString.withDefault("all");
+ if (tabId) tabExtras[tabId] = parseAsString.withDefault(tabDefault);
const facetExtras: Record<string, ArrayParser> = {};
for (const id of facetIds) {
@@ -129,7 +131,7 @@ export function createListSearchParams<
const toInput = (values: ListSearchValues<TTab, TFacet>) => {
const selectedTab: Record<string, string> = {};
- if (tabId) selectedTab[tabId] = values[tabId] ?? "all";
+ if (tabId) selectedTab[tabId] = values[tabId] ?? tabDefault;
const selectedFacets: Record<string, string[]> = {};
for (const id of facetIds) {
diff --git a/apps/app/components/data-table/list-search.tsx b/apps/app/components/data-table/list-search.tsx
index c2c7cda7..f82b7c90 100644
--- a/apps/app/components/data-table/list-search.tsx
+++ b/apps/app/components/data-table/list-search.tsx
@@ -8,9 +8,16 @@ import {
} from "@crm/ui/components/input-group";
import { useSearchInput } from "@crm/ui/hooks/use-search-input";
import { useQueryStates } from "nuqs";
+import type { Ref } from "react";
import { searchParsers } from "./list-search-params";
-export function ListSearch({ placeholder }: { placeholder: string }) {
+export function ListSearch({
+ placeholder,
+ inputRef,
+}: {
+ placeholder: string;
+ inputRef?: Ref<HTMLInputElement>;
+}) {
const [{ q }, setState] = useQueryStates(searchParsers);
return (
@@ -18,6 +25,7 @@ export function ListSearch({ placeholder }: { placeholder: string }) {
committed={q}
commit={(next) => setState({ q: next, page: 1 })}
placeholder={placeholder}
+ inputRef={inputRef}
/>
);
}
@@ -26,10 +34,12 @@ function ListSearchInput({
committed,
commit,
placeholder,
+ inputRef,
}: {
committed: string;
commit: (value: string) => void;
placeholder: string;
+ inputRef?: Ref<HTMLInputElement>;
}) {
const [value, setValue] = useSearchInput(committed, commit);
@@ -39,6 +49,7 @@ function ListSearchInput({
<Search />
</InputGroupAddon>
<InputGroupInput
+ ref={inputRef}
placeholder={placeholder}
value={value}
onChange={(event) => setValue(event.target.value)}
diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.ts
index 790e3721..c41cb08d 100644
--- a/apps/app/lib/trpc/cache.ts
+++ b/apps/app/lib/trpc/cache.ts
@@ -69,6 +69,7 @@ export function useCrmCache(): CrmCache {
trpc.activities.timeline.pathKey(),
trpc.activities.timelineCounts.queryKey(),
trpc.activities.myTasks.queryKey(),
+ trpc.activities.tasks.queryKey(),
];
const listKeys = () => [
diff --git a/apps/app/proxy.ts b/apps/app/proxy.ts
index 6040b706..374128c4 100644
--- a/apps/app/proxy.ts
+++ b/apps/app/proxy.ts
@@ -18,7 +18,7 @@ const UNGATED = ["/grant-access", "/eve"];
const ANONYMOUS = ["/t"];
-const SECTIONS = ["/companies", "/contacts", "/deals", "/settings"];
+const SECTIONS = ["/companies", "/contacts", "/deals", "/tasks", "/settings"];
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
diff --git a/apps/app/test/task-focus.spec.ts b/apps/app/test/task-focus.spec.ts
new file mode 100644
index 00000000..3a3b2ff0
--- /dev/null
+++ b/apps/app/test/task-focus.spec.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "bun:test";
+import { nextTaskFocusId } from "@/app/(app)/[slug]/tasks/task-focus";
+
+describe("task completion focus", () => {
+ it("keeps focus on a task that remains visible", () => {
+ expect(nextTaskFocusId(["first", "second"], "first", true)).toBe("first");
+ });
+
+ it("moves focus to the next task when the current task leaves", () => {
+ expect(nextTaskFocusId(["first", "second", "third"], "second", false)).toBe(
+ "third",
+ );
+ });
+
+ it("moves focus to the previous task after the final task leaves", () => {
+ expect(nextTaskFocusId(["first", "second"], "second", false)).toBe("first");
+ });
+
+ it("returns no task when the list becomes empty", () => {
+ expect(nextTaskFocusId(["only"], "only", false)).toBeNull();
+ });
+});