Metadata-Version: 2.4
Name: fastpluggy-notification-center
Version: 0.3.3
Summary: Persistent notification center with topbar bell, event bus integration, and optional Web Push
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: FastPluggy<1,>=0.4.95
Provides-Extra: push
Requires-Dist: pywebpush>=2.0.0; extra == "push"
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Requires-Dist: fastpluggy-db-purge; extra == "tests"
Provides-Extra: e2e
Requires-Dist: fastpluggy-cli; extra == "e2e"

# fastpluggy-notification-center

![Notification Center](https://img.shields.io/badge/FastPluggy-Notification%20Center-blue)
[![Release](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/badges/release.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/releases)
[![Pipeline Status](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/badges/main/pipeline.svg?key_text=CI)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/pipelines?ignore_skipped=true)
[![Coverage](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/badges/main/coverage.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/pipelines)

Persistent notification center for FastPluggy with topbar bell icon, event bus integration, pluggable delivery channels, and optional Web Push support.

## Installation

```bash
pip install fastpluggy-notification-center
```

For Web Push support:

```bash
pip install fastpluggy-notification-center[push]
```

## Features

- **Topbar bell icon** — unread badge count, slide-out notification panel
- **Event bus integration** — listens to all `notification.*` events automatically
- **Pluggable channels** — any plugin can register as a delivery channel via the `NotificationChannel` protocol
- **Channel relay** — forward notifications to external channels (ntfy, email, etc.) based on category
- **Web Push** — browser push notifications via VAPID (auto-generates keys on first load)
- **Notification categories** — `info`, `success`, `warning`, `error` with colored badges
- **Global or per-user notifications** — a notification goes to everyone, or to one user only (`user_id`)
- **Read/unread tracking per user** — each user has their own read state and badge
- **Auto-cleanup** — retention rule declared to the `db_purge` plugin when it is installed

## Configuration

Settings are managed via `NotificationCenterSettings` (database-backed). Configure through the FastPluggy settings UI.

| Setting | Default | Description |
|---------|---------|-------------|
| `notification_retention_days` | `30` | Retention of the `db_purge` rule for notifications (see [Cleanup](#cleanup)) |
| `max_notifications_per_page` | `50` | Pagination size for notification list |
| `relay_enabled` | `false` | Enable forwarding to delivery channels |
| `relay_channels` | `[]` | Channel names to relay to (empty = all discovered) |
| `relay_categories` | `["error"]` | Only relay notifications with these categories |
| `web_push_enabled` | `true` | Enable browser Web Push support |
| `vapid_private_key` | `""` | VAPID private key (auto-generated if empty) |
| `vapid_public_key` | `""` | VAPID public key (auto-generated if empty) |
| `vapid_contact_email` | `""` | Contact email for VAPID identification |
| `push_max_failures` | `5` | Consecutive push failures after which a subscription is deleted |

## Usage

### Sending notifications via event bus

Any plugin can emit a notification event. The payload is passed as keyword arguments:

```python
fast_pluggy.events.emit(
    "notification.info", source="my_plugin",
    title="Task completed",
    message="Backup finished successfully",
    category="success",
    data={"task_id": 42},
)
```

### Global or per-user

Without `user_id` the notification is **global**: every user sees it. With `user_id` it is visible **only to that user**:

```python
fast_pluggy.events.emit(
    "notification.info", source="my_plugin",
    title="Your export is ready", message="report.csv", user_id=user.id,
)
```

`user_id` is the user's `id` (or its `username` when the auth backend's users have no `id`); it is stored as a string.

| | Global (`user_id` absent) | Targeted (`user_id` set) |
|---|---|---|
| Visible to | everyone | that user only (not even admins) |
| Read state | per user | per user |
| Delete | admins only (it disappears for everyone) | the recipient |
| Channel relay (ntfy, ...) | yes, per `relay_*` settings | **never**: channels are shared |
| Web Push (`notification.push`) | every subscribed browser | that user's browsers only |

In an app **without** an auth manager there is a single anonymous user: it sees every notification, targeted ones included, and may delete any.

Over HTTP, `POST /api/notifications` accepts `user_id` too; targeting another user than yourself takes an admin.

### Sending browser push notifications

```python
fast_pluggy.events.emit(
    "notification.push", source="my_plugin",
    title="Deployment ready",
    message="v1.2.0 is live",
    url="/plugin/ecosystem_status/",
    # user_id=user.id  -> only this user's browsers
)
```

A browser subscription belongs to the user who subscribed it.

### Explicit relay to all channels

Bypasses the category filter (refused for a targeted notification):

```python
fast_pluggy.events.emit(
    "notification.relay", source="my_plugin",
    title="Critical alert",
    message="Database connection lost",
    category="error",
)
```

### Reading from another plugin

Use the repository functions, never the models: they apply the audience and read-state rules.

```python
from fastpluggy_plugin.notification_center.audience import NO_AUTH_VIEWER
from fastpluggy_plugin.notification_center.repository import list_notifications, mark_read_for_everyone

# e.g. the event a notification announced is resolved: mark it read for every user
mine = list_notifications(NO_AUTH_VIEWER, source="my_plugin", limit=None)
mark_read_for_everyone([n.id for n in mine if n.data and n.data.get("job") == job_id])
```

### Registering a delivery channel

Any plugin can act as a delivery channel by implementing the `NotificationChannel` protocol:

```python
from fastpluggy_plugin.notification_center.channels import NotificationChannel

class MyChannel:
    channel_name = "my_channel"

    def send(self, title, message, category, data=None):
        # deliver the notification; raise on failure
        ...

class MyPlugin(FastPluggyBaseModule):
    notification_channel = MyChannel()
```

The notification center discovers channels automatically at startup.

`send()` can be a plain function or an `async def`. The relay runs every delivery in a background thread (pool of 4), never on the caller's event loop, so a slow channel never blocks the app:

- a plain `send()` may do blocking I/O (`requests`, SMTP, ...);
- an `async def send()` is awaited to completion in its own event loop in that thread. Don't schedule work on the caller's loop (`asyncio.get_running_loop()` has no loop there) and don't share loop-bound clients across calls.

An exception raised by `send()` counts as a failed delivery and is logged; other channels are not affected.

## Dashboard

The notification panel is accessible via the topbar bell icon on every page. A full notification history page is available at `/plugin/notification_center/` (CI) or `/plugin-pkg/notification_center/` (local dev).

## Operations

### Cleanup

Cleanup is delegated to the `db_purge` plugin. When it is installed, this plugin declares three rules on every load:

| Table | Rule |
|-------|------|
| `notification_center_notifications` | Purge on `created_at`, retention = `notification_retention_days` |
| `notification_center_reads` | Purge on `read_at`, same retention (per-user read state; sweeps the rows of purged notifications) |
| `notification_center_push_subscriptions` | Excluded: live browser subscriptions, removed by the plugin itself after `push_max_failures` failed pushes |

db_purge creates the purge rules **disabled**: enable them once in the db_purge UI. Changing `notification_retention_days` updates the rule at the next restart and disables it again until an admin re-validates it.

Without `db_purge`, notifications accumulate indefinitely.

### Metrics

This plugin does not currently expose Prometheus metrics.

### Upgrade Notes

**0.3.1**: on PostgreSQL the schema setup runs under an advisory lock, so an app booting several processes (web + task workers) migrates once; in 0.3.0 the processes raced and all but one failed to load the plugin with `DuplicateColumn`.

**0.3.0** (global + per-user notifications, [#5](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/issues/5)). The schema is upgraded automatically at the first load:

- `user_id` is added to notifications and push subscriptions (existing rows stay global / unowned);
- the shared `read` / `read_at` columns move to the new `notification_center_reads` table. A notification that was read stays **read for everyone**, so no old notification comes back unread; then the columns and their indexes are dropped.

**Breaking changes in 0.3.0** (for code that imports this plugin):

- the repository functions take a `Viewer` first argument (`audience.get_viewer(request)`, or `NO_AUTH_VIEWER` outside a request) and return `NotificationView` objects, not ORM rows;
- `Notification.read` / `read_at` no longer exist: use `mark_read`, `mark_all_read` or `mark_read_for_everyone`;
- `push_service.send_push_to_all()` is now `send_push(..., user_id=None)`.

Earlier versions need no migration: the plugin creates its tables on first load.

**Security notes:** VAPID private keys are auto-generated on first load and stored in the database. If you regenerate keys manually via `/api/push/generate-vapid-keys`, all existing browser push subscriptions will be invalidated. See [#3](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/issues/3) for key logging concerns.
