@aria-framework/notify 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/assets/bell.js +180 -0
- package/index.js +11 -1
- package/package.json +30 -28
- package/store.js +82 -45
- package/views/notify/bell.ejs +37 -0
package/README.md
CHANGED
|
@@ -65,6 +65,25 @@ were wrong, and the app's own view permission stays the single place access is d
|
|
|
65
65
|
consumer briefly included an `actorUserId` "so a viewer can ignore its own action"; no client
|
|
66
66
|
ever read it, so its only effect was disclosing a staffer's user id to every other viewer.
|
|
67
67
|
|
|
68
|
+
### A push reaches the page that CAUSED it — including mid-navigation
|
|
69
|
+
|
|
70
|
+
Since there is no `actorUserId`, a client that must not react to its own change has to know when
|
|
71
|
+
it made one. That is easy to get wrong in one specific way, and a consumer shipped the mistake:
|
|
72
|
+
|
|
73
|
+
A form POST is a navigation, but **the browser keeps the old page on screen — and its stream open —
|
|
74
|
+
until the response arrives.** So a push written while handling that POST is delivered to the very
|
|
75
|
+
page that caused it, which then re-fetches, sees its own change, and announces it. The redirect
|
|
76
|
+
lands a moment later and replaces everything. The consumer's code carried a comment asserting the
|
|
77
|
+
opposite: that a page which redirects "never sees an event for its own action".
|
|
78
|
+
|
|
79
|
+
The client-side fix is small — set a flag on `submit` and ignore events while it is set — but it
|
|
80
|
+
has to be deliberate, and `beforeunload` is too late (it fires once the response is already
|
|
81
|
+
arriving). This is not something the hub can do for you: it writes to open responses and has no
|
|
82
|
+
idea which one issued the request.
|
|
83
|
+
|
|
84
|
+
There is also **no replay**. `pushEntity` writes to whoever is connected at that instant, so an
|
|
85
|
+
event a page misses while navigating is simply gone — which is why suppressing it costs nothing.
|
|
86
|
+
|
|
68
87
|
## THE LIMIT: one process
|
|
69
88
|
|
|
70
89
|
The hub is in memory and per-process. Two app processes behind a load balancer each hold half
|
package/assets/bell.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @aria-framework/notify — the bell client. Both apps hand-rolled one against this package's
|
|
3
|
+
* server half; each had a fix the other lacked (one the SSE connection lifecycle, the other the
|
|
4
|
+
* same-origin href guard). This is the merge, and the stream's single owner.
|
|
5
|
+
*
|
|
6
|
+
* MARKUP CONTRACT (ships as views/notify/bell.ejs): a root with id="notif-menu" carrying
|
|
7
|
+
* [data-notif-badge], [data-notif-list], [data-notif-readall], and optionally:
|
|
8
|
+
* data-notif-base route prefix (default '/notifications')
|
|
9
|
+
* data-notif-fill 'load' (default) fills on page load; 'open' fills on the dropdown's
|
|
10
|
+
* show.bs.dropdown (server-rendered initial badge keeps working without JS)
|
|
11
|
+
*
|
|
12
|
+
* THE STREAM IS MULTIPLEXED AND THIS FILE OWNS IT. An SSE connection never completes, so it holds
|
|
13
|
+
* one of the browser's ~6 per-origin connections (HTTP/1.1); in a multi-page app every navigation
|
|
14
|
+
* opens a new one, so the old one MUST close on pagehide/hidden or leaked streams exhaust the pool
|
|
15
|
+
* and the whole site stalls. One connection per page — app features that want live frames do NOT
|
|
16
|
+
* open their own EventSource; they listen for the DOM events this file re-dispatches:
|
|
17
|
+
*
|
|
18
|
+
* 'aria:sse' detail = the parsed frame (every frame, whatever its type)
|
|
19
|
+
* 'aria:sse-open' detail = { firstOpen } — fired on connect and every reconnect; catch-up
|
|
20
|
+
* refreshes belong on reconnect only (firstOpen === false), because the first
|
|
21
|
+
* open lands right after the page rendered.
|
|
22
|
+
*
|
|
23
|
+
* Frame types listed in data-notif-quiet (comma-separated, e.g. "ticket,draft") do NOT re-sync
|
|
24
|
+
* the bell — a ticket reply cannot change the notification list, and draft frames fire while
|
|
25
|
+
* somebody is typing. Extra stream query params come from any page element carrying
|
|
26
|
+
* data-notif-stream-param="key=value" (a ticket page watching itself rides the same connection).
|
|
27
|
+
*
|
|
28
|
+
* XSS-safe by construction: rows are createElement/textContent, and only a same-origin PATH may
|
|
29
|
+
* become a row's href — a link that ever carried attacker-influenced text (javascript: or
|
|
30
|
+
* //host) would execute or leave the site on click.
|
|
31
|
+
*/
|
|
32
|
+
(function () {
|
|
33
|
+
'use strict';
|
|
34
|
+
|
|
35
|
+
var menu = document.getElementById('notif-menu');
|
|
36
|
+
if (!menu) return;
|
|
37
|
+
|
|
38
|
+
var badge = menu.querySelector('[data-notif-badge]');
|
|
39
|
+
var list = menu.querySelector('[data-notif-list]');
|
|
40
|
+
var readAllBtn = menu.querySelector('[data-notif-readall]');
|
|
41
|
+
if (!badge || !list) return;
|
|
42
|
+
|
|
43
|
+
var BASE = menu.getAttribute('data-notif-base') || '/notifications';
|
|
44
|
+
var FILL = menu.getAttribute('data-notif-fill') || 'load';
|
|
45
|
+
var QUIET = (menu.getAttribute('data-notif-quiet') || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
46
|
+
var tokenMeta = document.querySelector('meta[name="csrf-token"]');
|
|
47
|
+
var csrf = tokenMeta ? tokenMeta.getAttribute('content') : '';
|
|
48
|
+
|
|
49
|
+
function post(url) {
|
|
50
|
+
return fetch(url, { method: 'POST', headers: { 'x-csrf-token': csrf }, credentials: 'same-origin' });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function setBadge(n) {
|
|
54
|
+
if (n > 0) { badge.textContent = n > 99 ? '99+' : String(n); badge.hidden = false; }
|
|
55
|
+
else { badge.hidden = true; }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function safeHref(link) {
|
|
59
|
+
return (typeof link === 'string' && /^\/(?!\/)/.test(link)) ? link : BASE;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** "3m ago" over SQLite's UTC datetime('now') strings — the trailing Z is load-bearing. */
|
|
63
|
+
function relTime(iso) {
|
|
64
|
+
if (!iso) return '';
|
|
65
|
+
var t = Date.parse(String(iso).includes('T') ? iso : String(iso).replace(' ', 'T') + 'Z');
|
|
66
|
+
if (!Number.isFinite(t)) return '';
|
|
67
|
+
var s = Math.max(0, (Date.now() - t) / 1000);
|
|
68
|
+
if (s < 60) return 'just now';
|
|
69
|
+
if (s < 3600) return Math.floor(s / 60) + 'm ago';
|
|
70
|
+
if (s < 86400) return Math.floor(s / 3600) + 'h ago';
|
|
71
|
+
return Math.floor(s / 86400) + 'd ago';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function row(item) {
|
|
75
|
+
var a = document.createElement('a');
|
|
76
|
+
a.href = safeHref(item.link);
|
|
77
|
+
a.className = 'dropdown-item py-2 border-bottom' + (item.is_read ? '' : ' bg-light fw-semibold');
|
|
78
|
+
a.style.whiteSpace = 'normal';
|
|
79
|
+
|
|
80
|
+
var top = document.createElement('div');
|
|
81
|
+
top.className = 'small';
|
|
82
|
+
if (item.actor_name) {
|
|
83
|
+
var who = document.createElement('span');
|
|
84
|
+
who.textContent = item.actor_name + ' ';
|
|
85
|
+
top.appendChild(who);
|
|
86
|
+
}
|
|
87
|
+
var what = document.createElement('span');
|
|
88
|
+
what.className = 'text-muted';
|
|
89
|
+
what.textContent = item.title || '';
|
|
90
|
+
top.appendChild(what);
|
|
91
|
+
a.appendChild(top);
|
|
92
|
+
|
|
93
|
+
var meta = document.createElement('div');
|
|
94
|
+
meta.className = 'text-muted';
|
|
95
|
+
meta.style.fontSize = '0.72rem';
|
|
96
|
+
meta.textContent = relTime(item.created_at);
|
|
97
|
+
a.appendChild(meta);
|
|
98
|
+
|
|
99
|
+
a.addEventListener('click', function () {
|
|
100
|
+
if (!item.is_read) { post(BASE + '/' + item.id + '/read'); } // navigation continues
|
|
101
|
+
});
|
|
102
|
+
return a;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function render(data) {
|
|
106
|
+
setBadge(data.unread || 0);
|
|
107
|
+
list.textContent = '';
|
|
108
|
+
if (!data.items || !data.items.length) {
|
|
109
|
+
var empty = document.createElement('div');
|
|
110
|
+
empty.className = 'text-muted small px-3 py-3';
|
|
111
|
+
empty.textContent = 'No notifications yet.';
|
|
112
|
+
list.appendChild(empty);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
data.items.forEach(function (it) { list.appendChild(row(it)); });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function sync() {
|
|
119
|
+
fetch(BASE + '/recent', { credentials: 'same-origin' })
|
|
120
|
+
.then(function (r) { return r.ok ? r.json() : null; })
|
|
121
|
+
.then(function (d) { if (d) render(d); })
|
|
122
|
+
.catch(function () {});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (readAllBtn) {
|
|
126
|
+
readAllBtn.addEventListener('click', function () { post(BASE + '/read-all').then(sync).catch(function () {}); });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (FILL === 'open') {
|
|
130
|
+
// Server-rendered badge stands until the dropdown is opened; degrades to a plain link with JS off.
|
|
131
|
+
var filled = false;
|
|
132
|
+
menu.addEventListener('show.bs.dropdown', function () { if (!filled) { filled = true; sync(); } });
|
|
133
|
+
} else {
|
|
134
|
+
sync(); // initial paint
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ── The stream ──────────────────────────────────────────────────────────────────────────────
|
|
138
|
+
var es = null;
|
|
139
|
+
var firstOpen = true;
|
|
140
|
+
|
|
141
|
+
function streamUrl() {
|
|
142
|
+
var params = [];
|
|
143
|
+
document.querySelectorAll('[data-notif-stream-param]').forEach(function (el) {
|
|
144
|
+
var p = el.getAttribute('data-notif-stream-param');
|
|
145
|
+
if (p) params.push(p);
|
|
146
|
+
});
|
|
147
|
+
return BASE + '/stream' + (params.length ? '?' + params.join('&') : '');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function openStream() {
|
|
151
|
+
if (!window.EventSource || es) return;
|
|
152
|
+
try {
|
|
153
|
+
es = new EventSource(streamUrl());
|
|
154
|
+
es.onmessage = function (ev) {
|
|
155
|
+
var d = null;
|
|
156
|
+
try { d = JSON.parse(ev.data); } catch (_) { /* keep the notif behaviour */ }
|
|
157
|
+
// EVERY frame goes back out as a DOM event — the seam that lets app features (a live
|
|
158
|
+
// ticket page, a draft indicator, a version-skew banner) ride this connection without
|
|
159
|
+
// knowing it exists, and without burning a second one.
|
|
160
|
+
if (d) document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
|
|
161
|
+
if (!d || QUIET.indexOf(d.type) === -1) sync();
|
|
162
|
+
};
|
|
163
|
+
es.onopen = function () {
|
|
164
|
+
sync(); // self-heal the badge on every open, reconnects included
|
|
165
|
+
var wasFirst = firstOpen;
|
|
166
|
+
firstOpen = false;
|
|
167
|
+
document.dispatchEvent(new CustomEvent('aria:sse-open', { detail: { firstOpen: wasFirst } }));
|
|
168
|
+
};
|
|
169
|
+
} catch (e) { es = null; }
|
|
170
|
+
}
|
|
171
|
+
function closeStream() { if (es) { es.close(); es = null; } }
|
|
172
|
+
|
|
173
|
+
openStream();
|
|
174
|
+
// Release the connection when leaving or backgrounding; reopen on visible/bfcache restore.
|
|
175
|
+
window.addEventListener('pagehide', closeStream);
|
|
176
|
+
document.addEventListener('visibilitychange', function () {
|
|
177
|
+
if (document.visibilityState === 'hidden') { closeStream(); }
|
|
178
|
+
else { sync(); openStream(); }
|
|
179
|
+
});
|
|
180
|
+
})();
|
package/index.js
CHANGED
|
@@ -15,8 +15,18 @@
|
|
|
15
15
|
|
|
16
16
|
'use strict';
|
|
17
17
|
|
|
18
|
+
const path = require('path');
|
|
19
|
+
|
|
18
20
|
module.exports = {
|
|
19
21
|
...require('./store'),
|
|
20
22
|
...require('./hub'),
|
|
21
|
-
...require('./emit')
|
|
23
|
+
...require('./emit'),
|
|
24
|
+
// 0.2.0 — the bell CLIENT (2026-08-22 audit): both apps hand-rolled one against this package's
|
|
25
|
+
// server half, each with a fix the other lacked. assets/bell.js owns the page's ONE SSE
|
|
26
|
+
// connection and re-dispatches every frame as DOM events ('aria:sse', 'aria:sse-open');
|
|
27
|
+
// views/notify/bell.ejs is the markup half, shipped together so the hook names cannot drift.
|
|
28
|
+
// staticDirs.push({ mount: '/js/notify', dir: notify.assetsDir })
|
|
29
|
+
// viewDirs.push(notify.viewsDir)
|
|
30
|
+
assetsDir: path.join(__dirname, 'assets'),
|
|
31
|
+
viewsDir: path.join(__dirname, 'views')
|
|
22
32
|
};
|
package/package.json
CHANGED
|
@@ -1,28 +1,30 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aria-framework/notify",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
|
|
5
|
-
"license": "UNLICENSED",
|
|
6
|
-
"private": false,
|
|
7
|
-
"publishConfig": {
|
|
8
|
-
"access": "public"
|
|
9
|
-
},
|
|
10
|
-
"main": "index.js",
|
|
11
|
-
"files": [
|
|
12
|
-
"index.js",
|
|
13
|
-
"store.js",
|
|
14
|
-
"hub.js",
|
|
15
|
-
"emit.js"
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/notify",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"store.js",
|
|
14
|
+
"hub.js",
|
|
15
|
+
"emit.js",
|
|
16
|
+
"assets/",
|
|
17
|
+
"views/"
|
|
18
|
+
],
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"better-sqlite3": ">=11"
|
|
21
|
+
},
|
|
22
|
+
"peerDependenciesMeta": {
|
|
23
|
+
"better-sqlite3": {
|
|
24
|
+
"optional": true
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "node test/store.js && node test/hub.js && node test/emit.js && node test/bell.js"
|
|
29
|
+
}
|
|
30
|
+
}
|
package/store.js
CHANGED
|
@@ -18,8 +18,19 @@
|
|
|
18
18
|
'use strict';
|
|
19
19
|
|
|
20
20
|
/** The columns this module reads and writes. An app's migration must provide at least these. */
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Column list for the app's CREATE TABLE. A FUNCTION of the dialect since 0.3.0: the id column
|
|
23
|
+
* and the timestamp default are the two things engines genuinely differ on, and an app on
|
|
24
|
+
* Postgres cannot use `INTEGER PRIMARY KEY AUTOINCREMENT`.
|
|
25
|
+
*
|
|
26
|
+
* `is_read` stays INTEGER 0/1 rather than becoming BOOLEAN on Postgres — deliberately. A real
|
|
27
|
+
* boolean would make every `is_read = 0` in this file dialect-dependent for no gain, and
|
|
28
|
+
* INTEGER is valid on both.
|
|
29
|
+
*/
|
|
30
|
+
function schemaFor(dialect) {
|
|
31
|
+
const d = dialect || require('@aria-framework/db-worker').dialectFor('sqlite');
|
|
32
|
+
return `
|
|
33
|
+
id ${d.autoIncrementPk()},
|
|
23
34
|
user_id INTEGER NOT NULL, -- recipient; FK to the app's users table
|
|
24
35
|
type TEXT NOT NULL, -- app-defined, e.g. 'assigned' | 'invoice.overdue'
|
|
25
36
|
title TEXT NOT NULL, -- short line
|
|
@@ -30,27 +41,62 @@ const SCHEMA = `
|
|
|
30
41
|
entity_type TEXT, -- app's record type, e.g. 'ticket' | 'invoice'
|
|
31
42
|
entity_id INTEGER,
|
|
32
43
|
is_read INTEGER NOT NULL DEFAULT 0,
|
|
33
|
-
created_at TEXT NOT NULL DEFAULT (
|
|
44
|
+
created_at TEXT NOT NULL DEFAULT (${d.now()}),
|
|
34
45
|
read_at TEXT
|
|
35
46
|
`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The SQLite schema, unchanged, for consumers that predate schemaFor(). */
|
|
50
|
+
const SCHEMA = schemaFor(null);
|
|
36
51
|
|
|
37
52
|
/**
|
|
38
53
|
* @param {Function} getDb returns the better-sqlite3 handle. A function, not a handle, because
|
|
39
54
|
* the worker opens the database after modules are required.
|
|
40
55
|
* @param {string} table defaults to `notifications`
|
|
41
56
|
*/
|
|
42
|
-
|
|
43
|
-
|
|
57
|
+
/**
|
|
58
|
+
* @param {object} opts
|
|
59
|
+
* driver the @aria-framework/db-worker driver (preferred since 0.3.0) — engine-agnostic
|
|
60
|
+
* getDb LEGACY: a function returning a better-sqlite3 handle. Still accepted so a consumer
|
|
61
|
+
* can upgrade this package before it upgrades its wiring; wrapped in a driver here.
|
|
62
|
+
* table defaults to 'notifications'
|
|
63
|
+
*
|
|
64
|
+
* EVERY METHOD IS ASYNC as of 0.3.0. There is no synchronous Postgres driver, so a store that
|
|
65
|
+
* runs on both engines has no choice — and the DB worker already awaits whatever a model method
|
|
66
|
+
* returns, so the cost lands on the ~6 call sites inside a consumer's model, not on its routes.
|
|
67
|
+
*/
|
|
68
|
+
function createStore(opts = {}) {
|
|
69
|
+
const { table = 'notifications' } = opts;
|
|
70
|
+
let driver = opts.driver || null;
|
|
71
|
+
if (!driver) {
|
|
72
|
+
if (typeof opts.getDb !== 'function') {
|
|
73
|
+
throw new Error('notify: pass { driver } (preferred) or { getDb } (legacy)');
|
|
74
|
+
}
|
|
75
|
+
// Adopt the raw handle rather than opening anything: the app owns the connection.
|
|
76
|
+
const { createSqliteDriver } = require('@aria-framework/db-worker');
|
|
77
|
+
let adopted = null;
|
|
78
|
+
driver = new Proxy({}, {
|
|
79
|
+
get(_t, prop) {
|
|
80
|
+
if (!adopted) adopted = createSqliteDriver({ adopt: opts.getDb() });
|
|
81
|
+
return adopted[prop];
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
44
86
|
// Interpolated once, at construction, from a value the APP supplies — never from a request.
|
|
45
87
|
const T = String(table).replace(/[^A-Za-z0-9_]/g, '');
|
|
46
88
|
if (!T) throw new Error('notify: table name must be a plain identifier');
|
|
47
89
|
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
90
|
+
const d = () => driver.dialect;
|
|
91
|
+
|
|
92
|
+
async function unreadCount(userId) {
|
|
93
|
+
const r = await driver.get(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ? AND is_read = 0`, [userId]);
|
|
94
|
+
return Number(r.c);
|
|
95
|
+
}
|
|
51
96
|
|
|
52
97
|
return {
|
|
53
98
|
SCHEMA,
|
|
99
|
+
schemaFor,
|
|
54
100
|
table: T,
|
|
55
101
|
|
|
56
102
|
/**
|
|
@@ -59,76 +105,67 @@ function createStore({ getDb, table = 'notifications' } = {}) {
|
|
|
59
105
|
* Returns the ids actually written so the caller can hand them to the hub. De-duplicated,
|
|
60
106
|
* because "the assignee" and "a collaborator" are frequently the same person and two bells
|
|
61
107
|
* for one event reads as a bug.
|
|
62
|
-
*
|
|
63
|
-
* @param {number[]} userIds
|
|
64
|
-
* @param {{type, title, body?, link?, actor_name?, entity_type?, entity_id?}} p
|
|
65
|
-
* @returns {{userIds: number[]}}
|
|
66
108
|
*/
|
|
67
|
-
createMany(userIds, p = {}) {
|
|
109
|
+
async createMany(userIds, p = {}) {
|
|
68
110
|
const ids = [...new Set((userIds || []).filter((v) => v != null).map(Number))]
|
|
69
111
|
.filter((n) => Number.isInteger(n));
|
|
70
112
|
// A notification with no type or no title has nothing to show; refusing quietly is right
|
|
71
113
|
// because the caller is fire-and-forget and must not learn about this through a throw.
|
|
72
114
|
if (!ids.length || !p.type || !p.title) return { userIds: [] };
|
|
73
115
|
|
|
74
|
-
|
|
75
|
-
const ins = db.prepare(`
|
|
76
|
-
INSERT INTO ${T} (user_id, type, title, body, link, actor_name, entity_type, entity_id)
|
|
77
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
78
|
-
`);
|
|
79
|
-
db.transaction(() => {
|
|
116
|
+
await driver.transaction(async (tx) => {
|
|
80
117
|
for (const uid of ids) {
|
|
81
|
-
|
|
82
|
-
|
|
118
|
+
await tx.run(
|
|
119
|
+
`INSERT INTO ${T} (user_id, type, title, body, link, actor_name, entity_type, entity_id)
|
|
120
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
121
|
+
[uid, p.type, p.title, p.body || null, p.link || null,
|
|
122
|
+
p.actor_name || null, p.entity_type || null, p.entity_id || null]
|
|
123
|
+
);
|
|
83
124
|
}
|
|
84
|
-
})
|
|
125
|
+
});
|
|
85
126
|
return { userIds: ids };
|
|
86
127
|
},
|
|
87
128
|
|
|
88
129
|
unreadCount,
|
|
89
130
|
|
|
90
131
|
/** Latest N (read and unread) for the bell, plus the unread count. */
|
|
91
|
-
recent(userId, limit = 15) {
|
|
132
|
+
async recent(userId, limit = 15) {
|
|
92
133
|
const lim = Math.min(50, Math.max(1, parseInt(limit, 10) || 15));
|
|
93
|
-
const items =
|
|
94
|
-
`SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT
|
|
95
|
-
|
|
96
|
-
return { unread: unreadCount(userId), items };
|
|
134
|
+
const items = await driver.all(
|
|
135
|
+
`SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`, [userId, lim]);
|
|
136
|
+
return { unread: await unreadCount(userId), items };
|
|
97
137
|
},
|
|
98
138
|
|
|
99
139
|
/** Paginated history for a full notifications page. */
|
|
100
|
-
listPage(userId, page = 1, pageSize = 25) {
|
|
101
|
-
const db = getDb();
|
|
140
|
+
async listPage(userId, page = 1, pageSize = 25) {
|
|
102
141
|
const p = Math.max(1, parseInt(page, 10) || 1);
|
|
103
142
|
const size = Math.min(100, Math.max(5, parseInt(pageSize, 10) || 25));
|
|
104
|
-
const total =
|
|
105
|
-
const rows =
|
|
106
|
-
`SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET
|
|
107
|
-
|
|
143
|
+
const total = Number((await driver.get(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ?`, [userId])).c);
|
|
144
|
+
const rows = await driver.all(
|
|
145
|
+
`SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`,
|
|
146
|
+
[userId, size, (p - 1) * size]);
|
|
108
147
|
return {
|
|
109
148
|
rows, total, page: p, pageSize: size,
|
|
110
149
|
pages: Math.max(1, Math.ceil(total / size)),
|
|
111
|
-
unread: unreadCount(userId)
|
|
150
|
+
unread: await unreadCount(userId)
|
|
112
151
|
};
|
|
113
152
|
},
|
|
114
153
|
|
|
115
154
|
/** Mark one read — ONLY if it belongs to userId. The scope is the authorisation. */
|
|
116
|
-
markRead(id, userId) {
|
|
117
|
-
const r =
|
|
118
|
-
`UPDATE ${T} SET is_read = 1, read_at =
|
|
119
|
-
WHERE id = ? AND user_id = ? AND is_read = 0
|
|
120
|
-
).run(id, userId);
|
|
155
|
+
async markRead(id, userId) {
|
|
156
|
+
const r = await driver.run(
|
|
157
|
+
`UPDATE ${T} SET is_read = 1, read_at = ${d().now()}
|
|
158
|
+
WHERE id = ? AND user_id = ? AND is_read = 0`, [id, userId]);
|
|
121
159
|
return { changed: r.changes };
|
|
122
160
|
},
|
|
123
161
|
|
|
124
|
-
markAllRead(userId) {
|
|
125
|
-
const r =
|
|
126
|
-
`UPDATE ${T} SET is_read = 1, read_at =
|
|
127
|
-
WHERE user_id = ? AND is_read = 0
|
|
128
|
-
).run(userId);
|
|
162
|
+
async markAllRead(userId) {
|
|
163
|
+
const r = await driver.run(
|
|
164
|
+
`UPDATE ${T} SET is_read = 1, read_at = ${d().now()}
|
|
165
|
+
WHERE user_id = ? AND is_read = 0`, [userId]);
|
|
129
166
|
return { changed: r.changes };
|
|
130
167
|
}
|
|
131
168
|
};
|
|
132
169
|
}
|
|
133
170
|
|
|
134
|
-
module.exports = { createStore, SCHEMA };
|
|
171
|
+
module.exports = { createStore, SCHEMA, schemaFor };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
<%# The notification bell — markup half of assets/bell.js, shipped together so the hook names
|
|
2
|
+
(#notif-menu, data-notif-badge/-list/-readall) cannot drift from the script that binds them.
|
|
3
|
+
Both apps carried this dropdown skeleton with different hook spellings; this is the one shape.
|
|
4
|
+
|
|
5
|
+
Include locals (all optional):
|
|
6
|
+
notifBase route prefix (default '/notifications')
|
|
7
|
+
notifFill 'load' | 'open' (default 'load'; 'open' fills on first
|
|
8
|
+
dropdown open — pair it with notifUnread)
|
|
9
|
+
notifQuiet comma list of SSE frame types that must NOT re-sync the bell (e.g. 'ticket,draft')
|
|
10
|
+
notifUnread server-rendered initial unread count (keeps the badge honest before JS runs,
|
|
11
|
+
and with JS off the bell stays a working link to the notifications page)
|
|
12
|
+
notifWidth dropdown width (default '340px') %>
|
|
13
|
+
<%
|
|
14
|
+
var __base = (typeof notifBase === 'undefined') ? '/notifications' : notifBase;
|
|
15
|
+
var __fill = (typeof notifFill === 'undefined') ? 'load' : notifFill;
|
|
16
|
+
var __quiet = (typeof notifQuiet === 'undefined') ? '' : notifQuiet;
|
|
17
|
+
var __unread = (typeof notifUnread === 'undefined') ? 0 : Number(notifUnread) || 0;
|
|
18
|
+
var __width = (typeof notifWidth === 'undefined') ? '340px' : notifWidth;
|
|
19
|
+
%>
|
|
20
|
+
<div class="dropdown" id="notif-menu" data-notif-base="<%= __base %>" data-notif-fill="<%= __fill %>"<% if (__quiet) { %> data-notif-quiet="<%= __quiet %>"<% } %>>
|
|
21
|
+
<a href="<%= __base %>" class="bell-btn" role="button"
|
|
22
|
+
data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false" title="Notifications">
|
|
23
|
+
<i class="bi bi-bell"></i>
|
|
24
|
+
<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"
|
|
25
|
+
data-notif-badge <% if (!__unread) { %>hidden<% } %>><%= __unread > 99 ? '99+' : __unread %></span>
|
|
26
|
+
</a>
|
|
27
|
+
<div class="dropdown-menu dropdown-menu-end shadow border-0" style="width: <%= __width %>;">
|
|
28
|
+
<div class="d-flex justify-content-between align-items-center px-3 py-2 border-bottom">
|
|
29
|
+
<strong class="small">Notifications</strong>
|
|
30
|
+
<button type="button" class="btn btn-link btn-sm p-0 text-decoration-none" data-notif-readall>Mark all read</button>
|
|
31
|
+
</div>
|
|
32
|
+
<div data-notif-list style="max-height: 360px; overflow-y: auto;">
|
|
33
|
+
<div class="text-muted small px-3 py-3">Loading…</div>
|
|
34
|
+
</div>
|
|
35
|
+
<a class="dropdown-item text-center small border-top text-muted" href="<%= __base %>">See all</a>
|
|
36
|
+
</div>
|
|
37
|
+
</div>
|