Metadata-Version: 2.4
Name: fastpluggy-notification-center
Version: 0.4.4
Summary: Persistent notification center with topbar bell, event bus integration, and optional Web Push
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: FastPluggy<1,>=0.10.0
Provides-Extra: push
Requires-Dist: pywebpush>=2.0.0; extra == "push"
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: httpx>=0.27; 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"
Dynamic: license-file

# 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** — every `notification.*` event goes to the bell
- **Notification rules** — when an event happens (a task fails, a plugin fails to load, a purge is suspended…), send to the bell, push, ntfy or email, with an anti-spam delay and a "recovered" message (Admin › Notifications › Rules)
- **Pluggable channels** — any plugin can add a delivery channel via the `NotificationChannel` protocol
- **Web Push** — browser push notifications via VAPID (auto-generates keys on first load); state, keys and subscription counts on Admin › Notifications › Web Push
- **Pages** — each user's inbox at the plugin's root (the bell's *View all*), outside Admin; the admin pages Rules and Web Push read Admin › Notifications › <page> and are listed on the admin home's *Plugin tools* card
- **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 |
| `public_base_url` | `""` | Public address of the app (`https://app.example.org`): makes the links of rule messages absolute, so ntfy and email get them. Empty: only the bell and push keep a link |
| `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},
)
```

A path in `data["url"]` (or an `http(s)` address) makes the notification a link: a click in the bell or on the full page opens it and marks it read. Any other value (`javascript:`, `//host`) is ignored. Title and message are always printed as text.

```python
fast_pluggy.events.emit(
    "notification.warning", source="my_plugin",
    title="Approval needed", message="Run 12 waits for an answer",
    category="warning", data={"url": "/plugin-pkg/my_plugin/runs/12"},
)
```

### 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 |
| Web Push | through a rule (`push` channel, to `all` or a user) | through a rule (`push` channel, to that user) |

Rules on `notification.*` decide what else is sent: a rule can require `user_id` empty, so a notification for one user never reaches a shared channel (the rules converted from the old relay settings do).

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, every route needs a signed-in user when the app has an auth manager (anonymous callers get `401`, or the login redirect for the page). `POST /api/notifications` accepts `user_id` too: a user may notify themselves; a global notification or one for another user takes an admin.

### Notification rules

A plugin emits an event and never picks a channel; a rule, written by an admin on **Admin › Notifications › Rules**, says who is told:

- **When**: an event the core or a loaded plugin declares (`emits`), by its exact name or `<prefix>.*`, or `notification.*`.
- **Only if**: equalities on the event's fields (`function = backup_db`), all required; an empty value means the field is absent.
- **Then send to**: one or more destinations: `inbox` (the bell; `all` or a user's key), `push` (`all` or a user's key), `ntfy` (a topic; empty = ntfy_tools' default topic), `email` (an address; mail_plugin).
- **Not too often**: at most one message per delay (15 min by default) for each occurrence, told apart by the event's `EventSpec.key` (one delay per task function, per plugin, per table). With *recovered*, the first success after a failure (`x_failed` / `x_succeeded` events) sends a "Recovered" message and resets the delay.

The message is the event's: its `title` and `message` fields, else the event's description and its fields. A path `url` is made absolute with `public_base_url`; without it, only the bell and push keep the link.

Each rule has a **Test** button (one message to every destination, marked `[test]`, with the result of each) and shows its state (failing since, last sent) and its latest matching events (sent, held by the anti-spam, recovered).

How it runs:

- The listener only queues the event. One background thread reads the rules (re-read at most every 10 s, so a rule saved in another process applies), claims the anti-spam state and sends: a slow database or channel never slows the end of a task or a request.
- The rule is checked in the process where the event happens, task workers included. The anti-spam state is in the database, claimed with a conditional `UPDATE`: several processes seeing the same failure send one message.
- A plugin that failed to load before this one listened is replayed at load, so a rule on `fp.plugin.load_failed` sees it.

Other plugins show and link the rules about their own things through the `notification_rules` capability, without importing this plugin:

```python
rules = GlobalRegistry.get_capability("notification_rules")
if rules:
    watched = rules.watching(request, "tasks_worker.task_failed", "function", ["backup_db"])
    # {"backup_db": [{"id", "name", "enabled", "targets", "failing_since", "url"}]}
    link = rules.new_rule_url(request, "tasks_worker.task_failed", function="backup_db")
```

### 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, to=None):
        # deliver to `to` (a topic, an address, a user...); empty = the channel's default
        # if it has one; raise on failure
        ...

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

The notification center discovers channels automatically at startup, next to its own `inbox` and `push`.

`send()` can be a plain function or an `async def`. It runs in the rules' background thread, 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: it is logged, shown in the rule's history and in its test result; other destinations 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.4.0** (notification rules, [#17](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/issues/17)). Needs FastPluggy 0.10.0 (`EventSpec.key`).

- New tables `notification_center_rules`, `notification_center_rule_state`, `notification_center_rule_sends` (the last one purged by `db_purge` after 30 days).
- At the first load, the saved routing settings become rules, then are deleted: `relay_enabled` on gives one rule per relayed category on `notification.*` (to everyone only, every time, as before); each `ntfy_tools` `ntfy_topics` entry gives a rule to its topic (`<prefix>.*` and exact names only: other globs never matched). Settings given as environment variables are not converted: write the rules by hand.
- **Removed**: the `notification.push` and `notification.relay` events (send through a rule's `push` or channel destinations), the `relay_enabled` / `relay_channels` / `relay_categories` settings, and `channels.relay_to_channels`. A channel's `send()` gets a `to` recipient.

**0.3.5** ([#14](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/issues/14)): in an app with an auth manager, every HTTP route needs a signed-in user (anonymous: `401`), and creating a global notification or regenerating the VAPID keys over HTTP takes an admin. Event-bus notifications and the `repository` functions are unchanged. The Web Push card of the page is shown to admins only.

**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. Regenerating them via `POST /api/push/generate-vapid-keys` (admin only) invalidates every existing browser push subscription. See [#3](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/notification_center/-/issues/3) for key logging concerns.
