Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

wip: notifications

Nikolai Giman0e1455b9476f
diff --git a/api/.env.example b/api/.env.example
index d31f924..55c33bc 100644
--- a/api/.env.example
+++ b/api/.env.example
@@ -46,4 +46,11 @@ GITLAB_INTEGRATION_CLIENT_SECRET=
GITLAB_INTEGRATION_CALLBACK_URL=http://localhost:1401/module/integrations/oauth/gitlab/callback
# For self-hosted GitLab, override these:
# GITLAB_BASE_URL=https://gitlab.yourcompany.com
-# GITLAB_API_URL=https://gitlab.yourcompany.com/api/v4
\ No newline at end of file
+# GITLAB_API_URL=https://gitlab.yourcompany.com/api/v4
+
+# Centrifugo (real-time notifications, optional)
+# CENTRIFUGO_API_URL=http://localhost:8000
+# CENTRIFUGO_API_KEY=your_centrifugo_api_key_here
+# CENTRIFUGO_TOKEN_SECRET=your_centrifugo_token_secret_here
+# Public port that clients use to connect to Centrifugo (exposed port, not internal docker port)
+# CENTRIFUGO_PUBLIC_PORT=8000
\ No newline at end of file
diff --git a/api/dev-containers-test/.env.centrifugo b/api/dev-containers-test/.env.centrifugo
new file mode 100644
index 0000000..5d3d024
--- /dev/null
+++ b/api/dev-containers-test/.env.centrifugo
@@ -0,0 +1,6 @@
+CENTRIFUGO_TOKEN_HMAC_SECRET_KEY=taskview-centrifugo-secret-change-me
+CENTRIFUGO_API_KEY=taskview-centrifugo-api-key-change-me
+CENTRIFUGO_ALLOWED_ORIGINS=*
+CENTRIFUGO_ADMIN=true
+CENTRIFUGO_ADMIN_PASSWORD=admin
+CENTRIFUGO_ADMIN_SECRET=admin-secret-change-me
diff --git a/api/dev-containers-test/centrifugo/config.json b/api/dev-containers-test/centrifugo/config.json
new file mode 100644
index 0000000..1bc3180
--- /dev/null
+++ b/api/dev-containers-test/centrifugo/config.json
@@ -0,0 +1,15 @@
+{
+ "allow_subscribe_for_client": true,
+ "user_personal_channel_namespace": "personal",
+ "namespaces": [
+ {
+ "name": "personal",
+ "presence": false,
+ "join_leave": false,
+ "history_size": 10,
+ "history_ttl": "300s",
+ "force_recovery": true,
+ "allow_subscribe_for_client": true
+ }
+ ]
+}
diff --git a/api/dev-containers-test/docker-compose.centrifugo.yml b/api/dev-containers-test/docker-compose.centrifugo.yml
new file mode 100644
index 0000000..c06625e
--- /dev/null
+++ b/api/dev-containers-test/docker-compose.centrifugo.yml
@@ -0,0 +1,15 @@
+services:
+ centrifugo:
+ image: centrifugo/centrifugo:v5
+ restart: unless-stopped
+ command: centrifugo -c config.json
+ env_file:
+ - ./.env.centrifugo
+ ports:
+ - "8000:8000"
+ volumes:
+ - ./centrifugo/config.json:/centrifugo/config.json
+ ulimits:
+ nofile:
+ soft: 65535
+ hard: 65535
diff --git a/api/package.json b/api/package.json
index af2e5e2..118e3a0 100644
--- a/api/package.json
+++ b/api/package.json
@@ -62,6 +62,7 @@
"passport-github2": "^0.1.12",
"passport-google-oauth20": "^2.0.0",
"pg": "^8.16.3",
+ "pg-boss": "^12.14.0",
"pino": "^9.4.0",
"rotating-file-stream": "^3.2.5",
"semver": "^7.6.3",
diff --git a/api/src/App.ts b/api/src/App.ts
index 53e1e1c..cdc2c2c 100644
--- a/api/src/App.ts
+++ b/api/src/App.ts
@@ -6,6 +6,7 @@ import errorHandler from './middlewares/error-handler';
import routes from './routes';
import passport, { initPassportLogin } from './tv-modules/auth/strategies/passport-login';
import cookieParser from 'cookie-parser';
+import { registerAllEventHandlers, startAllWorkers } from './core/all-events';
const allow = new Set([
...(process.env.CORS_REMOVE_DEFAULT_ALLOWED_ORIGINS === 'true' ? [] : [
@@ -30,6 +31,7 @@ export default class App {
this.extendApp();
this.initializeMiddlewares();
+ registerAllEventHandlers();
this.initializeRoutes();
this.app.use(errorHandler);
this.app.use(passport.initialize());
@@ -81,8 +83,9 @@ export default class App {
}
public listen() {
- return this.app.listen(this.port, '0.0.0.0', () => {
+ return this.app.listen(this.port, '0.0.0.0', async () => {
console.log(`Server is running on port ${this.port}`);
+ await startAllWorkers();
});
}
}
diff --git a/api/src/core/AppUser.ts b/api/src/core/AppUser.ts
index cb54f76..b3c7176 100644
--- a/api/src/core/AppUser.ts
+++ b/api/src/core/AppUser.ts
@@ -8,6 +8,7 @@ import { GoalListManager } from '../tv-modules/lists/GoalListManager';
import { StartManager } from '../tv-modules/start/StartManager';
import { TagsManager } from '../tv-modules/tags/TagsManager';
import { IntegrationsManager } from '../tv-modules/integrations/IntegrationsManager';
+import { NotificationsManager } from '../tv-modules/notifications/NotificationsManager';
import { TasksManager } from '../tv-modules/tasks/TasksManager';
import type { UserDbRecord, UserJwtPayload } from '../types/auth.types';
import { GoalPermissionsFetcher } from './GoalPermissionsFetcher';
@@ -28,6 +29,7 @@ export class AppUser {
public readonly kanbanManager: KanbanManager;
public readonly graphManager: GraphManager;
public readonly integrationsManager: IntegrationsManager;
+ public readonly notificationsManager: NotificationsManager;
constructor(userData?: UserJwtPayload) {
this.userData = userData;
@@ -43,6 +45,7 @@ export class AppUser {
this.kanbanManager = new KanbanManager(this);
this.graphManager = new GraphManager(this);
this.integrationsManager = new IntegrationsManager(this);
+ this.notificationsManager = new NotificationsManager(this);
}
getTokenId(): number | undefined {
diff --git a/api/src/core/CentrifugoClient.ts b/api/src/core/CentrifugoClient.ts
new file mode 100644
index 0000000..a9bc955
--- /dev/null
+++ b/api/src/core/CentrifugoClient.ts
@@ -0,0 +1,77 @@
+import { $logger } from '../modules/logget';
+
+interface CentrifugoPublishPayload {
+ channel: string;
+ data: Record<string, unknown>;
+}
+
+export class CentrifugoClient {
+ private readonly apiUrl: string;
+ private readonly apiKey: string;
+ private readonly enabled: boolean;
+
+ constructor() {
+ const url = process.env.CENTRIFUGO_API_URL;
+ const key = process.env.CENTRIFUGO_API_KEY;
+ this.enabled = !!(url && key);
+ this.apiUrl = url || '';
+ this.apiKey = key || '';
+
+ if (!this.enabled) {
+ $logger.warn('[Centrifugo] Not configured — real-time notifications disabled');
+ }
+ }
+
+ async publish(channel: string, data: Record<string, unknown>): Promise<boolean> {
+ if (!this.enabled) return false;
+
+ try {
+ const payload: CentrifugoPublishPayload = { channel, data };
+ const response = await fetch(`${this.apiUrl}/api/publish`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `apikey ${this.apiKey}`,
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!response.ok) {
+ $logger.error({ status: response.status }, '[Centrifugo] Publish failed');
+ return false;
+ }
+
+ return true;
+ } catch (err) {
+ $logger.error({ err }, '[Centrifugo] Publish error');
+ return false;
+ }
+ }
+
+ async publishToUser(userId: number, event: string, data: Record<string, unknown>): Promise<boolean> {
+ return this.publish(`personal:#${userId}`, { event, ...data });
+ }
+
+ isEnabled(): boolean {
+ return this.enabled;
+ }
+
+ static generateConnectionToken(userId: number): string {
+ const jwt = require('jsonwebtoken');
+ const secret = process.env.CENTRIFUGO_TOKEN_SECRET || process.env.JWT_SIGN;
+ return jwt.sign(
+ { sub: String(userId) },
+ secret,
+ { expiresIn: '24h' }
+ );
+ }
+}
+
+let _instance: CentrifugoClient | null = null;
+
+export function getCentrifugoClient(): CentrifugoClient {
+ if (!_instance) {
+ _instance = new CentrifugoClient();
+ }
+ return _instance;
+}
diff --git a/api/src/core/EventBus.ts b/api/src/core/EventBus.ts
new file mode 100644
index 0000000..1509a66
--- /dev/null
+++ b/api/src/core/EventBus.ts
@@ -0,0 +1,37 @@
+import { EventEmitter } from 'node:events';
+import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';
+import { $logger } from '../modules/logget';
+
+export interface AppEvents {
+ 'task.created': { task: TasksSchemaTypeForSelect; userId: number };
+ 'task.updated': { task: TasksSchemaTypeForSelect; changes: Record<string, unknown>; userId: number };
+ 'task.deleted': { taskId: number; goalId: number };
+}
+
+type EventName = keyof AppEvents;
+type EventHandler<T extends EventName> = (data: AppEvents[T]) => void | Promise<void>;
+
+class AppEventBus {
+ private emitter = new EventEmitter();
+
+ on<T extends EventName>(event: T, handler: EventHandler<T>) {
+ this.emitter.on(event, (data: AppEvents[T]) => {
+ try {
+ const result = handler(data);
+ if (result instanceof Promise) {
+ result.catch((err) => {
+ $logger.error(err, `EventBus handler error [${event}]`);
+ });
+ }
+ } catch (err) {
+ $logger.error(err, `EventBus handler error [${event}]`);
+ }
+ });
+ }
+
+ emit<T extends EventName>(event: T, data: AppEvents[T]) {
+ this.emitter.emit(event, data);
+ }
+}
+
+export const eventBus = new AppEventBus();
diff --git a/api/src/core/JobQueue.ts b/api/src/core/JobQueue.ts
new file mode 100644
index 0000000..637d976
--- /dev/null
+++ b/api/src/core/JobQueue.ts
@@ -0,0 +1,31 @@
+import { PgBoss } from 'pg-boss';
+import { $logger } from '../modules/logget';
+
+let boss: PgBoss | null = null;
+
+export async function startJobQueue(): Promise<PgBoss> {
+ boss = new PgBoss({
+ host: process.env.DB_HOST,
+ user: process.env.DB_USER,
+ password: process.env.DB_PASSWORD,
+ database: process.env.DB_NAME,
+ port: +process.env.DB_PORT!,
+ schema: 'pgboss',
+ });
+
+ boss.on('error', (err) => {
+ $logger.error(err, '[JobQueue] Error');
+ });
+
+ await boss.start();
+ $logger.info('[JobQueue] Started');
+
+ return boss;
+}
+
+export function getJobQueue(): PgBoss {
+ if (!boss) {
+ throw new Error('JobQueue not started. Call startJobQueue() first.');
+ }
+ return boss;
+}
diff --git a/api/src/core/all-events.ts b/api/src/core/all-events.ts
new file mode 100644
index 0000000..a073791
--- /dev/null
+++ b/api/src/core/all-events.ts
@@ -0,0 +1,17 @@
+import { startJobQueue } from './JobQueue';
+import { registerNotificationEventHandlers, registerNotificationWorkers } from '../tv-modules/notifications/notifications.events';
+
+/**
+ * Register all event handlers (called on app init, before JobQueue starts)
+ */
+export function registerAllEventHandlers() {
+ registerNotificationEventHandlers();
+}
+
+/**
+ * Start JobQueue and register all job workers
+ */
+export async function startAllWorkers() {
+ await startJobQueue();
+ await registerNotificationWorkers();
+}
diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.json
index f42e2a5..339dd48 100644
--- a/api/src/migrations/taskview/migrate.json
+++ b/api/src/migrations/taskview/migrate.json
@@ -339,5 +339,16 @@
"description": [
"Added source_url column to tasks for external issue links"
]
+ },
+ "27": {
+ "version": "1.24.0",
+ "name": "Release 1.24.0",
+ "releaseDate": "20260315",
+ "scripts": [
+ "/1.24.0/0.1.24.0.sql"
+ ],
+ "description": [
+ "Added reminders, notifications, and push_subscriptions tables"
+ ]
}
}
\ No newline at end of file
diff --git a/api/src/migrations/taskview/sql/1.24.0/0.1.24.0.sql b/api/src/migrations/taskview/sql/1.24.0/0.1.24.0.sql
new file mode 100644
index 0000000..8347d6f
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.24.0/0.1.24.0.sql
@@ -0,0 +1,13 @@
+-- Notifications
+CREATE TABLE IF NOT EXISTS tasks.notifications (
+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,
+ task_id INTEGER REFERENCES tasks.tasks(id) ON DELETE SET NULL,
+ title VARCHAR(255) NOT NULL,
+ body VARCHAR(1000),
+ read BOOLEAN NOT NULL DEFAULT false,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX IF NOT EXISTS idx_notifications_user_unread
+ ON tasks.notifications (user_id, created_at DESC) WHERE NOT read;
diff --git a/api/src/routes/index.ts b/api/src/routes/index.ts
index ff09b13..3faf6f0 100644
--- a/api/src/routes/index.ts
+++ b/api/src/routes/index.ts
@@ -4,6 +4,7 @@ import CollaborationRolesRoutes from '../tv-modules/collaboration-roles/Collabor
import GoalsRoutes from '../tv-modules/goals/GoalsRoutes';
import GraphRoutes from '../tv-modules/graph/GraphRoutes';
import IntegrationsRoutes from '../tv-modules/integrations/IntegrationsRoutes';
+import NotificationsRoutes from '../tv-modules/notifications/NotificationsRoutes';
import KanbanRoutes from '../tv-modules/kanban/KanbanRoutes';
import GoalListRoutes from '../tv-modules/lists/GoalListRoutes';
import StartRoutes from '../tv-modules/start/StartRoutes';
@@ -25,6 +26,7 @@ const routes: Record<string, RoutableConstructor> = {
'/module/kanban': KanbanRoutes,
'/module/graph': GraphRoutes,
'/module/integrations': IntegrationsRoutes,
+ '/module/notifications': NotificationsRoutes,
};
export default routes;
diff --git a/api/src/tv-modules/notifications/NotificationsController.ts b/api/src/tv-modules/notifications/NotificationsController.ts
new file mode 100644
index 0000000..8839943
--- /dev/null
+++ b/api/src/tv-modules/notifications/NotificationsController.ts
@@ -0,0 +1,46 @@
+import { type } from 'arktype';
+import type { Request, Response } from 'express';
+import { CentrifugoClient } from '../../core/CentrifugoClient';
+
+const NotificationArkTypeMarkRead = type({
+ notificationId: 'number',
+});
+
+export class NotificationsController {
+ fetch = async (req: Request, res: Response) => {
+ const cursor = req.query.cursor ? Number(req.query.cursor) : undefined;
+ return res.tvJson(await req.appUser.notificationsManager.fetchByUser(cursor));
+ };
+
+ markRead = async (req: Request, res: Response) => {
+ const out = NotificationArkTypeMarkRead(req.body);
+ if (out instanceof type.errors) {
+ return res.status(400).send(out.summary);
+ }
+ return res.tvJson(await req.appUser.notificationsManager.markRead(out.notificationId));
+ };
+
+ markAllRead = async (_req: Request, res: Response) => {
+ return res.tvJson(await _req.appUser.notificationsManager.markAllRead());
+ };
+
+ connectionToken = async (req: Request, res: Response) => {
+ const userId = req.appUser.getUserData()?.id;
+ if (!userId) {
+ return res.status(401).send('Unauthorized');
+ }
+
+ const publicPort = process.env.CENTRIFUGO_PUBLIC_PORT;
+ if (!publicPort) {
+ return res.tvJson({ token: null, url: null });
+ }
+
+ const appUrl = process.env.APP_URL || 'http://localhost:3000';
+ const parsed = new URL(appUrl);
+ const protocol = parsed.protocol === 'http:' ? 'ws' : 'wss';
+ const url = `${protocol}://${parsed.hostname}:${publicPort}/connection/websocket`;
+
+ const token = CentrifugoClient.generateConnectionToken(userId);
+ return res.tvJson({ token, url });
+ };
+}
diff --git a/api/src/tv-modules/notifications/NotificationsManager.ts b/api/src/tv-modules/notifications/NotificationsManager.ts
new file mode 100644
index 0000000..2c4fb7c
--- /dev/null
+++ b/api/src/tv-modules/notifications/NotificationsManager.ts
@@ -0,0 +1,31 @@
+import type { AppUser } from '../../core/AppUser';
+import { NotificationsRepository } from './NotificationsRepository';
+
+export class NotificationsManager {
+ private readonly user: AppUser;
+ public readonly repository: NotificationsRepository;
+
+ constructor(user: AppUser) {
+ this.user = user;
+ this.repository = new NotificationsRepository();
+ }
+
+ async fetchByUser(cursor?: number) {
+ const userId = this.user.getUserData()?.id;
+ if (!userId) return { notifications: [] };
+ const notifications = await this.repository.fetchByUser(userId, cursor);
+ return { notifications };
+ }
+
+ async markRead(notificationId: number) {
+ const userId = this.user.getUserData()?.id;
+ if (!userId) return false;
+ return this.repository.markRead(notificationId, userId);
+ }
+
+ async markAllRead() {
+ const userId = this.user.getUserData()?.id;
+ if (!userId) return false;
+ return this.repository.markAllRead(userId);
+ }
+}
diff --git a/api/src/tv-modules/notifications/NotificationsRepository.ts b/api/src/tv-modules/notifications/NotificationsRepository.ts
new file mode 100644
index 0000000..5994e07
--- /dev/null
+++ b/api/src/tv-modules/notifications/NotificationsRepository.ts
@@ -0,0 +1,95 @@
+import { and, eq, desc, lt, like, sql } from 'drizzle-orm';
+import { NotificationsSchema, TasksSchema, type NotificationsSchemaTypeForSelect } from 'taskview-db-schemas';
+import { Database } from '../../modules/db';
+import { callWithCatch } from '../../utils/helpers';
+
+export class NotificationsRepository {
+ private readonly db: Database;
+
+ constructor() {
+ this.db = Database.getInstance();
+ }
+
+ async create(data: { userId: number; taskId: number | null; title: string; body: string | null }): Promise<NotificationsSchemaTypeForSelect | false> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.insert(NotificationsSchema).values({
+ userId: data.userId,
+ taskId: data.taskId,
+ title: data.title,
+ body: data.body,
+ }).returning()
+ );
+ if (!result) return false;
+ return result[0];
+ }
+
+ async fetchByUser(userId: number, cursor?: number) {
+ const limit = 30;
+ const conditions = [eq(NotificationsSchema.userId, userId)];
+ if (cursor) {
+ conditions.push(lt(NotificationsSchema.id, cursor));
+ }
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.select({
+ id: NotificationsSchema.id,
+ userId: NotificationsSchema.userId,
+ taskId: NotificationsSchema.taskId,
+ title: NotificationsSchema.title,
+ body: NotificationsSchema.body,
+ read: NotificationsSchema.read,
+ createdAt: NotificationsSchema.createdAt,
+ goalId: TasksSchema.goalId,
+ goalListId: TasksSchema.goalListId,
+ })
+ .from(NotificationsSchema)
+ .leftJoin(TasksSchema, eq(NotificationsSchema.taskId, TasksSchema.id))
+ .where(and(...conditions))
+ .orderBy(desc(NotificationsSchema.id))
+ .limit(limit)
+ );
+ return result || [];
+ }
+
+ async markRead(notificationId: number, userId: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.update(NotificationsSchema)
+ .set({ read: true })
+ .where(and(
+ eq(NotificationsSchema.id, notificationId),
+ eq(NotificationsSchema.userId, userId),
+ ))
+ );
+ return !!result;
+ }
+
+ async deleteDeadlineNotifications(taskId: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.delete(NotificationsSchema)
+ .where(and(
+ eq(NotificationsSchema.taskId, taskId),
+ like(NotificationsSchema.title, 'Deadline:%'),
+ ))
+ );
+ return !!result;
+ }
+
+ async deleteOlderThanDays(days: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.delete(NotificationsSchema)
+ .where(lt(NotificationsSchema.createdAt, sql`NOW() - INTERVAL '${sql.raw(String(days))} days'`))
+ );
+ return !!result;
+ }
+
+ async markAllRead(userId: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.update(NotificationsSchema)
+ .set({ read: true })
+ .where(and(
+ eq(NotificationsSchema.userId, userId),
+ eq(NotificationsSchema.read, false),
+ ))
+ );
+ return !!result;
+ }
+}
diff --git a/api/src/tv-modules/notifications/NotificationsRoutes.ts b/api/src/tv-modules/notifications/NotificationsRoutes.ts
new file mode 100644
index 0000000..0c52409
--- /dev/null
+++ b/api/src/tv-modules/notifications/NotificationsRoutes.ts
@@ -0,0 +1,26 @@
+import { Router } from 'express';
+import type { Routable } from '../../types/routable.type';
+import { IsLoggedIn } from '../auth/middlewares/is-logged-in';
+import { NotificationsController } from './NotificationsController';
+
+export default class NotificationsRoutes implements Routable {
+ private readonly router: ReturnType<typeof Router>;
+ private readonly controller: NotificationsController;
+
+ constructor() {
+ this.router = Router();
+ this.controller = new NotificationsController();
+ this.initRoutes();
+ }
+
+ getRouter() {
+ return this.router;
+ }
+
+ initRoutes() {
+ this.router.get('/', [IsLoggedIn], this.controller.fetch);
+ this.router.patch('/read', [IsLoggedIn], this.controller.markRead);
+ this.router.patch('/read-all', [IsLoggedIn], this.controller.markAllRead);
+ this.router.get('/connection-token', [IsLoggedIn], this.controller.connectionToken);
+ }
+}
diff --git a/api/src/tv-modules/notifications/notifications.events.ts b/api/src/tv-modules/notifications/notifications.events.ts
new file mode 100644
index 0000000..964074c
--- /dev/null
+++ b/api/src/tv-modules/notifications/notifications.events.ts
@@ -0,0 +1,123 @@
+import { eventBus } from '../../core/EventBus';
+import { getJobQueue } from '../../core/JobQueue';
+import { NotificationsRepository } from './NotificationsRepository';
+import { getCentrifugoClient } from '../../core/CentrifugoClient';
+import { $logger } from '../../modules/logget';
+import { Database } from '../../modules/db';
+import { sql } from 'drizzle-orm';
+
+const DEADLINE_JOB = 'deadline-notification';
+const CLEANUP_JOB = 'notifications-cleanup';
+const NOTIFICATIONS_RETENTION_DAYS = 1;
+
+interface DeadlineJobData {
+ taskId: number;
+ description: string;
+ goalId: number;
+ goalListId: number | null;
+ owner: number;
+ endDate: string;
+ endTime: string | null;
+}
+
+async function scheduleDeadlineJob(task: { id: number; description: string | null; goalId: number; goalListId: number | null; owner: number | null; endDate: string | null; endTime: string | null }) {
+ if (!task.endDate) return;
+
+ const boss = getJobQueue();
+ const jobKey = `deadline-${task.id}`;
+ const startAfter = new Date(task.endDate);
+
+ if (task.endTime) {
+ const [h, m] = task.endTime.split(':');
+ startAfter.setHours(Number(h), Number(m), 0, 0);
+ }
+
+ const now = new Date();
+ await boss.send(DEADLINE_JOB, {
+ taskId: task.id,
+ description: task.description,
+ goalId: task.goalId,
+ goalListId: task.goalListId,
+ owner: task.owner,
+ endDate: task.endDate,
+ endTime: task.endTime,
+ }, {
+ startAfter: startAfter >= now ? startAfter : undefined,
+ singletonKey: jobKey,
+ });
+ $logger.info({ taskId: task.id, startAfter }, '[Notifications] Deadline job scheduled');
+}
+
+export function registerNotificationEventHandlers() {
+ const repo = new NotificationsRepository();
+
+ // New task created with deadline
+ eventBus.on('task.created', async (data) => {
+ if (data.task.endDate) {
+ await scheduleDeadlineJob(data.task);
+ }
+ });
+
+ // Deadline changed on existing task
+ eventBus.on('task.updated', async (data) => {
+ const hasDeadlineChange =
+ data.changes.endDate !== undefined ||
+ data.changes.startDate !== undefined ||
+ data.changes.endTime !== undefined ||
+ data.changes.startTime !== undefined;
+
+ if (!hasDeadlineChange) return;
+
+ repo.deleteDeadlineNotifications(data.task.id);
+ await scheduleDeadlineJob(data.task);
+ });
+}
+
+export async function registerNotificationWorkers() {
+ const boss = getJobQueue();
+ const repo = new NotificationsRepository();
+ const db = Database.getInstance();
+
+ await boss.createQueue(DEADLINE_JOB);
+ await boss.createQueue(CLEANUP_JOB);
+
+ // Worker: process deadline notifications
+ await boss.work<DeadlineJobData>(DEADLINE_JOB, async ([job]) => {
+ const { taskId, description, goalId, goalListId, owner, endDate, endTime } = job.data;
+
+ // Check if task is still active (not completed or deleted)
+ const check = await db.dbDrizzle.execute<{ complete: boolean;[key: string]: unknown }>(
+ sql`SELECT complete FROM tasks.tasks WHERE id = ${taskId} AND complete = false`
+ );
+ if (check.rows.length === 0) return;
+
+ const title = `Deadline: ${description || 'Task'}`;
+ const timeStr = endTime ? `${endDate} ${endTime}` : endDate;
+ const body = `Deadline approaching: ${timeStr}`;
+
+ const notification = await repo.create({
+ userId: owner,
+ taskId,
+ title,
+ body,
+ });
+
+ if (notification) {
+ await getCentrifugoClient().publishToUser(owner, 'notification', {
+ notification,
+ goalId,
+ goalListId,
+ });
+ }
+
+ $logger.info({ taskId, userId: owner }, '[Notifications] Deadline notification sent');
+ });
+
+ // Schedule periodic cleanup of old notifications
+ await boss.schedule(CLEANUP_JOB, '0 3 * * *'); // daily at 3:00 AM
+
+ await boss.work(CLEANUP_JOB, async (_jobs) => {
+ await repo.deleteOlderThanDays(NOTIFICATIONS_RETENTION_DAYS);
+ $logger.info('[Notifications] Old notifications cleaned up');
+ });
+}
diff --git a/api/src/tv-modules/tasks/TasksManager.ts b/api/src/tv-modules/tasks/TasksManager.ts
index 59ced37..44303d2 100644
--- a/api/src/tv-modules/tasks/TasksManager.ts
+++ b/api/src/tv-modules/tasks/TasksManager.ts
@@ -1,6 +1,7 @@
import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';
import type { AppUser } from '../../core/AppUser';
import { $logger } from '../../modules/logget';
+import { eventBus } from '../../core/EventBus';
import { GoalPermissions } from '../../types/auth.types';
import type {
AddTaskArg,
@@ -80,7 +81,7 @@ export class TasksManager {
const tagsMap: Record<number, number[]> = {};
const ids = tasks.map((t) => t.id);
-
+
const tags = await this.repository.fetchTagsForTasks(ids);
if (tags) {
@@ -115,7 +116,7 @@ export class TasksManager {
const tagsMap: Record<number, number[]> = {};
const ids = tasks.map((t) => t.id);
-
+
const tags = await this.repository.fetchTagsForTasks(ids);
if (tags) {
@@ -157,7 +158,7 @@ export class TasksManager {
if (!task) return false;
// Sync task completion state to linked GitHub/GitLab issue
- this.user.integrationsManager.onTaskCompleteChanged(arg.taskId, arg.complete).catch(() => {});
+ this.user.integrationsManager.onTaskCompleteChanged(arg.taskId, arg.complete).catch(() => { });
return new TaskItemForClient(task);
}
@@ -274,6 +275,13 @@ export class TasksManager {
if (!synced) syncFailed = true;
}
+ const { id, ...changes } = data;
+ eventBus.emit('task.updated', {
+ task,
+ changes,
+ userId: this.user.getUserData()?.id as number,
+ });
+
const tasks = await this.extendTasksWithTagsAndAssignees([task]);
const result = tasks[0] ?? null;
if (!result) return null;
@@ -388,7 +396,16 @@ export class TasksManager {
}
const task = await this.repository.addTaskNew(newData);
- return await this.extendTasksWithTagsAndAssignees(task, true);
+ const result = await this.extendTasksWithTagsAndAssignees(task, true);
+
+ if (task[0]) {
+ eventBus.emit('task.created', {
+ task: task[0],
+ userId: this.user.getUserData()?.id as number,
+ });
+ }
+
+ return result;
}
async deleteTaskNew(data: TaskArgDelete) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f292a4c..448d952 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -22,7 +22,7 @@ importers:
version: 2.1.20
drizzle-arktype:
specifier: 0.1.3
passport:
specifier: ^0.7.0
version: 0.7.0
@@ -59,7 +59,7 @@ importers:
'@vitejs/plugin-vue':
specifier: ^5.1.4
arktype:
specifier: 2.1.20
version: 2.1.20
@@ -86,7 +86,7 @@ importers:
version: 0.44.7(@types/[email protected])([email protected])
emailjs:
specifier: ^4.0.3
- version: 4.0.3([email protected])
+ version: 4.0.3([email protected])
express:
specifier: 4.21.0
version: 4.21.0
@@ -111,6 +111,9 @@ importers:
pg:
specifier: ^8.16.3
version: 8.17.1
+ pg-boss:
+ specifier: ^12.14.0
+ version: 12.14.0
pino:
specifier: ^9.4.0
version: 9.14.0
@@ -128,7 +131,7 @@ importers:
version: 5.46.0
typescript:
specifier: ^5.0.0
- version: 5.8.3
+ version: 5.9.3
zod:
specifier: ^3.23.8
version: 3.25.76
@@ -229,10 +232,10 @@ importers:
version: 2.1.20
drizzle-arktype:
specifier: ^0.1.3
drizzle-orm:
specifier: ^0.44.4
- version: 0.44.7(@types/[email protected])([email protected])
+ version: 0.44.7(@types/[email protected])([email protected])
vite-plugin-dts:
specifier: ^4.5.4
@@ -354,6 +357,9 @@ importers:
axios:
specifier: ^1.13.4
version: 1.13.5
+ centrifuge:
+ specifier: ^5.5.3
+ version: 5.5.3
date-fns:
specifier: ^4.1.0
version: 4.1.0
@@ -3673,6 +3679,9 @@ packages:
resolution: {integrity: sha512-LWcNtSyZrakjECqmpP4qdg0MMGdN368D7X8XvvAqOcqMv0RxnlqVKZl2V6/mBR68oYMxOZPLw/gO7DuisMHUvQ==}
+ resolution: {integrity: sha512-LPkWnsAxu7JaE5S738XiREzJIko3Pf/qnWb3kd0q/OR0OJONUbSdnZ5pKsEI2yFi/odQ89SYsHPhLuEeZFhp/g==}
+
resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
engines: {node: '>=18'}
@@ -3937,6 +3946,10 @@ packages:
resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}
+ resolution: {integrity: sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
@@ -5535,6 +5548,10 @@ packages:
resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-Uly1Bu4lO1hwHUW0CQeSWuRtzCMNO00CmXtS8N6fyvB3B979GOEEeAkiTUDsmbYLAbvpUS/Kt5c4ibosAzVyVg==}
@@ -5800,6 +5817,10 @@ packages:
resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==}
+ resolution: {integrity: sha512-TMB1uHiGsHRGv1uYclfhivcnf0/PdFp2pNqRxXjncaAsjYMoisaQJI+SSZCqRq+VliwRTC8tsMQfmrWjDMhkPQ==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==}
@@ -6027,12 +6048,20 @@ packages:
resolution: {integrity: sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==}
+ resolution: {integrity: sha512-sxF+Y5w6uRRkFCen3LM6BOcSG5gdMM3/hs+WiycAHHX8EuP5Zod5eTo79IlmegXFzIgtYWs7Bcjjhid4TRLlvg==}
+ engines: {node: '>=22.12.0'}
+ hasBin: true
+
resolution: {integrity: sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==}
resolution: {integrity: sha512-ur/eoPKzDx2IjPaYyXS6Y8NSblxM7X64deV2ObV57vhjsWiwLvUD6meukAzogiOsu60GO8m/3Cb6FdJsWNjwXg==}
+ resolution: {integrity: sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==}
+
resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==}
engines: {node: '>=4.0.0'}
@@ -6042,9 +6071,17 @@ packages:
peerDependencies:
pg: '>=8.0'
+ resolution: {integrity: sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==}
+ peerDependencies:
+ pg: '>=8.0'
+
resolution: {integrity: sha512-pfsxk2M9M3BuGgDOfuy37VNRRX3jmKgMjcvAcWqNDpZSf4cUmv8HSOl5ViRQFsfARFn0KuUQTgLxVMbNq5NW3g==}
+ resolution: {integrity: sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==}
+
resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==}
engines: {node: '>=4'}
@@ -6058,6 +6095,15 @@ packages:
pg-native:
optional: true
+ resolution: {integrity: sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==}
+ engines: {node: '>= 16.0.0'}
+ peerDependencies:
+ pg-native: '>=3.0.1'
+ peerDependenciesMeta:
+ pg-native:
+ optional: true
+
resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==}
@@ -6562,6 +6608,10 @@ packages:
resolution: {integrity: sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-bBZaRwLH9PN5HbLCjPId4dP5bNGEtumcErgOX952IsvOhVPrm3/AeK1y0UHA/QaPG701eg0yEnOKsCOC6X/kaA==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==}
engines: {node: '>= 0.8.0'}
@@ -6794,6 +6844,10 @@ packages:
resolution: {integrity: sha512-Nk8c4lXvMB98MtbmjX7JwJRgJOL8fluecYCfCeYBznwmpOs8Bf15hLM6z4z71EDAhQVrQrI+wt1aLWSXZq+hXA==}
+ resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==}
@@ -7009,6 +7063,10 @@ packages:
resolution: {integrity: sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-JnTrzGu+zPV3aXIUhnyWJj4z/wigMsdYajGLIYakqyOW1nPllzXEJee0QQbHj+CTIQtXGlAjuK0UY+2xTyjVAw==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}
engines: {node: '>= 0.6'}
@@ -10724,10 +10782,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
- vue: 3.5.27([email protected])
+ vue: 3.5.27([email protected])
dependencies:
@@ -10957,12 +11015,6 @@ snapshots:
'@vue/shared': 3.5.27
csstype: 3.2.3
- dependencies:
- '@vue/compiler-ssr': 3.5.27
- '@vue/shared': 3.5.27
- vue: 3.5.27([email protected])
-
dependencies:
'@vue/compiler-ssr': 3.5.27
@@ -11494,6 +11546,11 @@ snapshots:
+ dependencies:
+ events: 3.3.0
+ protobufjs: 7.5.4
+
dependencies:
assertion-error: 2.0.1
@@ -11785,6 +11842,10 @@ snapshots:
+ dependencies:
+ luxon: 3.7.2
+
dependencies:
path-key: 3.1.1
@@ -12168,11 +12229,21 @@ snapshots:
arktype: 2.1.20
drizzle-orm: 0.44.7(@types/[email protected])([email protected])
+ dependencies:
+ arktype: 2.1.20
+ drizzle-orm: 0.44.7(@types/[email protected])([email protected])
+
optionalDependencies:
'@types/pg': 8.16.0
pg: 8.17.1
+ optionalDependencies:
+ '@types/pg': 8.16.0
+ pg: 8.20.0
+
dependencies:
call-bind-apply-helpers: 1.0.2
@@ -12197,9 +12268,9 @@ snapshots:
optionalDependencies:
- typescript: 5.8.3
+ typescript: 5.9.3
dependencies:
@@ -13401,6 +13472,8 @@ snapshots:
dependencies:
yallist: 4.0.0
+
dependencies:
estree-walker: 3.0.3
@@ -13681,6 +13754,8 @@ snapshots:
+
dependencies:
hosted-git-info: 2.8.9
@@ -13900,19 +13975,35 @@ snapshots:
+ dependencies:
+ cron-parser: 5.5.0
+ pg: 8.20.0
+ serialize-error: 13.0.1
+ transitivePeerDependencies:
+ - pg-native
+
optional: true
+
dependencies:
pg: 8.17.1
+ dependencies:
+ pg: 8.20.0
+
+
dependencies:
pg-int8: 1.0.1
@@ -13931,6 +14022,16 @@ snapshots:
optionalDependencies:
pg-cloudflare: 1.3.0
+ dependencies:
+ pg-connection-string: 2.12.0
+ pg-pool: 3.13.0([email protected])
+ pg-protocol: 1.13.0
+ pg-types: 2.2.0
+ pgpass: 1.0.5
+ optionalDependencies:
+ pg-cloudflare: 1.3.0
+
dependencies:
split2: 4.2.0
@@ -14183,7 +14284,7 @@ snapshots:
'@protobufjs/path': 1.1.2
'@protobufjs/pool': 1.1.0
'@protobufjs/utf8': 1.1.0
- '@types/node': 25.3.0
+ '@types/node': 22.19.7
long: 5.3.2
@@ -14527,6 +14628,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ non-error: 0.1.0
+ type-fest: 5.4.4
+
dependencies:
encodeurl: 2.0.0
@@ -14786,6 +14892,8 @@ snapshots:
+
@@ -15020,6 +15128,10 @@ snapshots:
+ dependencies:
+ tagged-tag: 1.0.0
+
dependencies:
media-typer: 0.3.0
@@ -15489,16 +15601,6 @@ snapshots:
'@vue/language-core': 3.2.5
typescript: 5.9.3
- dependencies:
- '@vue/compiler-dom': 3.5.27
- '@vue/compiler-sfc': 3.5.27
- '@vue/runtime-dom': 3.5.27
- '@vue/server-renderer': 3.5.27([email protected]([email protected]))
- '@vue/shared': 3.5.27
- optionalDependencies:
- typescript: 5.8.3
-
dependencies:
'@vue/compiler-dom': 3.5.27
diff --git a/taskview-packages/taskview-api/src/api/notifications.api.types.ts b/taskview-packages/taskview-api/src/api/notifications.api.types.ts
new file mode 100644
index 0000000..e93cd29
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/notifications.api.types.ts
@@ -0,0 +1,22 @@
+export interface Notification {
+ id: number;
+ userId: number;
+ taskId: number | null;
+ title: string;
+ body: string | null;
+ read: boolean;
+ createdAt: string;
+ goalId: number | null;
+ goalListId: number | null;
+}
+
+export type NotificationResponseFetch = {
+ notifications: Notification[];
+};
+
+export type NotificationResponseMarkRead = boolean;
+
+export type NotificationResponseConnectionToken = {
+ token: string | null;
+ url: string | null;
+};
diff --git a/taskview-packages/taskview-api/src/api/notifications.ts b/taskview-packages/taskview-api/src/api/notifications.ts
new file mode 100644
index 0000000..f17aca0
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/notifications.ts
@@ -0,0 +1,39 @@
+import TvApiBase from "./base";
+import type { AppResponse } from "./base.types";
+import type { NotificationResponseFetch, NotificationResponseMarkRead, NotificationResponseConnectionToken } from "./notifications.api.types";
+
+export default class TvNotificationsApi extends TvApiBase {
+ protected moduleUrl = '/module/notifications';
+
+ public async fetch(cursor?: number) {
+ return this.request(
+ this.$axios.get<AppResponse<NotificationResponseFetch>>(
+ this.moduleUrl, { params: cursor ? { cursor } : {} }
+ )
+ );
+ }
+
+ public async markRead(notificationId: number) {
+ return this.request(
+ this.$axios.patch<AppResponse<NotificationResponseMarkRead>>(
+ `${this.moduleUrl}/read`, { notificationId }
+ )
+ );
+ }
+
+ public async markAllRead() {
+ return this.request(
+ this.$axios.patch<AppResponse<NotificationResponseMarkRead>>(
+ `${this.moduleUrl}/read-all`
+ )
+ );
+ }
+
+ public async getConnectionToken() {
+ return this.request(
+ this.$axios.get<AppResponse<NotificationResponseConnectionToken>>(
+ `${this.moduleUrl}/connection-token`
+ )
+ );
+ }
+}
diff --git a/taskview-packages/taskview-api/src/index.ts b/taskview-packages/taskview-api/src/index.ts
index 53fce78..963e54c 100644
--- a/taskview-packages/taskview-api/src/index.ts
+++ b/taskview-packages/taskview-api/src/index.ts
@@ -9,4 +9,5 @@ export * from '@/api/collaboration.types';
export * from '@/api/tags.api.types';
export * from '@/api/goals-list.types';
export * from '@/api/kanban.types';
-export * from '@/api/integrations.types';
\ No newline at end of file
+export * from '@/api/integrations.types';
+export * from '@/api/notifications.api.types';
\ No newline at end of file
diff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.ts
index 7fc2984..e6a68d9 100644
--- a/taskview-packages/taskview-api/src/tv.ts
+++ b/taskview-packages/taskview-api/src/tv.ts
@@ -7,6 +7,7 @@ import TvGoalListApi from "./api/goals-list";
import TvTagsApi from "./api/tags";
import TvIntegrationsApi from "./api/integrations";
import TvKanban from "./api/kanban";
+import TvNotificationsApi from "./api/notifications";
export class TvApi {
@@ -28,6 +29,8 @@ export class TvApi {
public integrations: TvIntegrationsApi;
+ public notifications: TvNotificationsApi;
+
constructor($axios: AxiosInstance) {
this.$axios = $axios;
@@ -46,6 +49,8 @@ export class TvApi {
this.kanban = new TvKanban(this.$axios);
this.integrations = new TvIntegrationsApi(this.$axios);
+
+ this.notifications = new TvNotificationsApi(this.$axios);
}
public setBaseUrl(baseUrl: string) {
diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.ts
index 2aa9b6b..4249b8b 100644
--- a/taskview-packages/taskview-db-schemas/src/index.ts
+++ b/taskview-packages/taskview-db-schemas/src/index.ts
@@ -9,3 +9,4 @@ export * from './schemas/goals.schema';
export * from './schemas/goals-list.schema';
export * from './schemas/tasks-statuses.schema';
export * from './schemas/integrations.schema';
+export * from './schemas/notifications.schema';
diff --git a/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.ts
new file mode 100644
index 0000000..245258a
--- /dev/null
+++ b/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.ts
@@ -0,0 +1,16 @@
+import { integer, pgSchema, varchar, boolean, timestamp } from "drizzle-orm/pg-core";
+import { TasksSchema } from "./tasks.schema";
+import { UsersSchema } from "./users.schema";
+
+export const NotificationsSchema = pgSchema('tasks').table('notifications', {
+ id: integer().primaryKey().generatedAlwaysAsIdentity(),
+ userId: integer('user_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),
+ taskId: integer('task_id').references(() => TasksSchema.id, { onDelete: 'set null' }),
+ title: varchar({ length: 255 }).notNull(),
+ body: varchar({ length: 1000 }),
+ read: boolean().notNull().default(false),
+ createdAt: timestamp('created_at').notNull().defaultNow(),
+});
+
+export type NotificationsSchemaTypeForSelect = typeof NotificationsSchema.$inferSelect;
+export type NotificationsSchemaTypeForInsert = typeof NotificationsSchema.$inferInsert;
diff --git a/web/package.json b/web/package.json
index 9f50d62..5e578c3 100644
--- a/web/package.json
+++ b/web/package.json
@@ -56,6 +56,7 @@
"@vueuse/core": "^14.1.0",
"arktype": "2.1.20",
"axios": "^1.13.4",
+ "centrifuge": "^5.5.3",
"date-fns": "^4.1.0",
"pinia": "^2.3.1",
"qs": "^6.14.1",
diff --git a/web/src/components/NotificationBell.vue b/web/src/components/NotificationBell.vue
new file mode 100644
index 0000000..1433815
--- /dev/null
+++ b/web/src/components/NotificationBell.vue
@@ -0,0 +1,148 @@
+<template>
+ <UPopover
+ v-model:open="isOpen"
+ :content="{ align: 'end', side: 'right', sideOffset: 8 }"
+ >
+ <UButton
+ icon="i-lucide-bell"
+ color="neutral"
+ variant="ghost"
+ size="xl"
+ class="relative"
+ :aria-label="t('notifications.title')"
+ >
+ <template v-if="notificationsStore.unreadCount > 0" #trailing>
+ <UBadge
+ :label="notificationsStore.unreadCount > 99 ? '99+' : String(notificationsStore.unreadCount)"
+ color="error"
+ size="xs"
+ class="absolute -top-1 -right-1 min-w-5 justify-center"
+ />
+ </template>
+ </UButton>
+
+ <template #content>
+ <div class="w-80 max-h-96 flex flex-col">
+ <div class="flex items-center justify-between p-3 border-b border-default">
+ <span class="text-sm font-medium">{{ t('notifications.title') }}</span>
+ <UButton
+ v-if="notificationsStore.unreadCount > 0"
+ :label="t('notifications.markAllRead')"
+ variant="link"
+ size="xs"
+ @click="handleMarkAllRead"
+ />
+ </div>
+
+ <div class="overflow-y-auto flex-1">
+ <div
+ v-if="notificationsStore.notifications.length === 0"
+ class="p-6 text-center text-sm text-dimmed"
+ >
+ {{ t('notifications.empty') }}
+ </div>
+
+ <div
+ v-for="notification in notificationsStore.notifications"
+ :key="notification.id"
+ class="p-3 border-b border-default last:border-b-0 cursor-pointer hover:bg-elevated/50 transition-colors"
+ :class="{ 'bg-elevated/25': !notification.read }"
+ @click="handleNotificationClick(notification)"
+ >
+ <div class="flex items-start gap-2">
+ <span
+ v-if="!notification.read"
+ class="mt-1.5 size-2 rounded-full bg-primary shrink-0"
+ />
+ <div class="flex-1 min-w-0">
+ <p class="text-sm font-medium truncate">{{ notification.title }}</p>
+ <p
+ v-if="notification.body"
+ class="text-xs text-dimmed mt-0.5 line-clamp-2"
+ >
+ {{ notification.body }}
+ </p>
+ <p class="text-xs text-dimmed mt-1">
+ {{ formatDate(notification.createdAt) }}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div
+ v-if="notificationsStore.hasMore && notificationsStore.notifications.length > 0"
+ class="p-2 border-t border-default"
+ >
+ <UButton
+ :label="t('notifications.loadMore')"
+ variant="ghost"
+ color="neutral"
+ size="xs"
+ block
+ :loading="notificationsStore.loading"
+ @click="notificationsStore.fetchNotifications()"
+ />
+ </div>
+ </div>
+ </template>
+ </UPopover>
+</template>
+
+<script setup lang="ts">
+import { ref, onMounted, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useRouter } from 'vue-router'
+import type { Notification } from 'taskview-api'
+import { useNotificationsStore } from '@/stores/notifications.store'
+import { useUserStore } from '@/stores/user.store'
+import { ALL_TASKS_LIST_ID } from 'taskview-api'
+import { formatDistanceToNow } from 'date-fns'
+
+const { t } = useI18n()
+const router = useRouter()
+const notificationsStore = useNotificationsStore()
+const userStore = useUserStore()
+const isOpen = ref(false)
+
+function formatDate(dateStr: string) {
+ try {
+ return formatDistanceToNow(new Date(dateStr), { addSuffix: true })
+ } catch {
+ return dateStr
+ }
+}
+
+async function handleNotificationClick(notification: Notification) {
+ if (!notification.read) {
+ await notificationsStore.markRead(notification.id)
+ }
+ if (notification.taskId && notification.goalId) {
+ isOpen.value = false
+ router.push({
+ name: 'user',
+ params: {
+ projectId: notification.goalId,
+ listId: notification.goalListId ?? ALL_TASKS_LIST_ID,
+ taskId: notification.taskId,
+ },
+ })
+ }
+}
+
+async function handleMarkAllRead() {
+ await notificationsStore.markAllRead()
+}
+
+watch(isOpen, (open) => {
+ if (open && notificationsStore.notifications.length === 0) {
+ notificationsStore.fetchNotifications(true)
+ }
+})
+
+onMounted(() => {
+ if (userStore.isLoggedIn) {
+ notificationsStore.fetchNotifications(true)
+ }
+})
+</script>
diff --git a/web/src/composables/useCentrifugo.ts b/web/src/composables/useCentrifugo.ts
new file mode 100644
index 0000000..b0cfbe4
--- /dev/null
+++ b/web/src/composables/useCentrifugo.ts
@@ -0,0 +1,80 @@
+import { ref } from 'vue'
+import { Centrifuge } from 'centrifuge'
+import type { Subscription } from 'centrifuge'
+import { $tvApi } from '@/plugins/axios'
+import { useNotificationsStore } from '@/stores/notifications.store'
+import { useUserStore } from '@/stores/user.store'
+import { parseJwt } from '@/helpers/Helper'
+
+let centrifuge: Centrifuge | null = null
+let subscription: Subscription | null = null
+let initialized = false
+
+export function useCentrifugo() {
+ const connected = ref(false)
+
+ async function connect() {
+ if (initialized) return
+
+ const userStore = useUserStore()
+ if (!userStore.isLoggedIn) return
+
+ try {
+ const tokenResult = await $tvApi.notifications.getConnectionToken()
+ if (!tokenResult?.token || !tokenResult?.url) return
+
+ const parsed = parseJwt<{ sub: string }>(tokenResult.token)
+ const userId = parsed?.sub
+ if (!userId) return
+
+ centrifuge = new Centrifuge(tokenResult.url, {
+ token: tokenResult.token,
+ getToken: async () => {
+ const result = await $tvApi.notifications.getConnectionToken()
+ return result?.token || ''
+ },
+ })
+
+ centrifuge.on('connected', () => {
+ connected.value = true
+ })
+
+ centrifuge.on('disconnected', () => {
+ connected.value = false
+ })
+
+ subscription = centrifuge.newSubscription(`personal:#${userId}`)
+ subscription.on('publication', (ctx) => {
+ const notificationsStore = useNotificationsStore()
+ if (ctx.data?.event === 'notification' && ctx.data?.notification) {
+ notificationsStore.addRealtimeNotification({
+ ...ctx.data.notification,
+ goalId: ctx.data.goalId ?? null,
+ goalListId: ctx.data.goalListId ?? null,
+ })
+ }
+ })
+
+ subscription.subscribe()
+ centrifuge.connect()
+ initialized = true
+ } catch (err) {
+ console.error('[Centrifugo] Connection failed:', err)
+ }
+ }
+
+ function disconnect() {
+ if (subscription) {
+ subscription.unsubscribe()
+ subscription = null
+ }
+ if (centrifuge) {
+ centrifuge.disconnect()
+ centrifuge = null
+ }
+ initialized = false
+ connected.value = false
+ }
+
+ return { connected, connect, disconnect }
+}
diff --git a/web/src/layouts/UserLayout.vue b/web/src/layouts/UserLayout.vue
index a652e1b..1ff9708 100644
--- a/web/src/layouts/UserLayout.vue
+++ b/web/src/layouts/UserLayout.vue
@@ -12,12 +12,16 @@
:class="isSidebarCollapsed ? 'overflow-hidden min-w-0 w-0 transition-[width] duration-200 linear' : 'transition-[width] duration-200 linear'"
:ui="{ footer: 'lg:border-t lg:border-default' }"
>
- <TvGoalLikeItem
- to="/user"
- variant="taskview"
- >
- {{ t('main') }}
- </TvGoalLikeItem>
+ <div class="flex items-center justify-between px-1 gap-2">
+ <TvGoalLikeItem
+ to="/user"
+ variant="taskview"
+ class="flex-1"
+ >
+ {{ t('main') }}
+ </TvGoalLikeItem>
+ <NotificationBell />
+ </div>
<ProjectsSidebar />
@@ -41,8 +45,11 @@ import { useUpdater } from '@/composables/useUpdater'
import { useAppStore } from '@/stores/app.store'
import { useI18n } from 'vue-i18n'
import ProjectsSidebar from '@/components/features/projects/ProjectsSidebar.vue'
+import NotificationBell from '@/components/NotificationBell.vue'
+import { useCentrifugo } from '@/composables/useCentrifugo'
const { isSidebarOpen, isSidebarCollapsed } = useDashboard()
+const { connect: connectCentrifugo } = useCentrifugo()
const { t } = useI18n()
const appStore = useAppStore()
@@ -69,6 +76,7 @@ App.addListener('appStateChange', async ({ isActive }) => {
onMounted(async () => {
appStore.initTaskDetailDisplayMode()
+ connectCentrifugo()
await CapacitorUpdater.notifyAppReady()
console.log('notifyAppReady', APP_VERSION)
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index c6e3413..12c90fa 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -417,6 +417,12 @@ export default {
deleted: 'Account deleted',
codeSendError: 'Unable to send the code. Please contact support to delete your account.',
},
+ notifications: {
+ title: 'Notifications',
+ empty: 'No notifications',
+ markAllRead: 'Mark all read',
+ loadMore: 'Load more',
+ },
server: {
selectServer: 'Server',
addServer: 'Add server',
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index fc189f3..13cf526 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -417,6 +417,12 @@ export default {
deleted: 'Аккаунт удалён',
codeSendError: 'Не удалось отправить код. Обратитесь в поддержку для удаления аккаунта.',
},
+ notifications: {
+ title: 'Уведомления',
+ empty: 'Нет уведомлений',
+ markAllRead: 'Прочитать все',
+ loadMore: 'Загрузить ещё',
+ },
server: {
selectServer: 'Сервер',
addServer: 'Добавить сервер',
diff --git a/web/src/stores/notifications.store.ts b/web/src/stores/notifications.store.ts
new file mode 100644
index 0000000..9c6a8fe
--- /dev/null
+++ b/web/src/stores/notifications.store.ts
@@ -0,0 +1,65 @@
+import { defineStore } from 'pinia'
+import type { Notification } from 'taskview-api'
+import { $tvApi } from '@/plugins/axios'
+
+interface NotificationsState {
+ notifications: Notification[]
+ loading: boolean
+ hasMore: boolean
+}
+
+export const useNotificationsStore = defineStore('notifications', {
+ state: (): NotificationsState => ({
+ notifications: [],
+ loading: false,
+ hasMore: true,
+ }),
+ getters: {
+ unreadCount: (state) => state.notifications.filter(n => !n.read).length,
+ },
+ actions: {
+ async fetchNotifications(reset = false) {
+ if (this.loading) return
+ if (reset) {
+ this.hasMore = true
+ }
+
+ this.loading = true
+ try {
+ const cursor = reset ? undefined : this.notifications.at(-1)?.id
+ const result = await $tvApi.notifications.fetch(cursor)
+ if (result) {
+ if (reset) {
+ this.notifications = result.notifications
+ } else {
+ this.notifications.push(...result.notifications)
+ }
+ this.hasMore = result.notifications.length > 0
+ }
+ } finally {
+ this.loading = false
+ }
+ },
+
+ async markRead(notificationId: number) {
+ const result = await $tvApi.notifications.markRead(notificationId)
+ if (result) {
+ const notification = this.notifications.find(n => n.id === notificationId)
+ if (notification) {
+ notification.read = true
+ }
+ }
+ },
+
+ async markAllRead() {
+ const result = await $tvApi.notifications.markAllRead()
+ if (result) {
+ this.notifications.forEach(n => { n.read = true })
+ }
+ },
+
+ addRealtimeNotification(notification: Notification) {
+ this.notifications.unshift(notification)
+ },
+ },
+})