@7365admin1/layer-common 4.17.1-staging.335 → 4.17.1-staging.336

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.
@@ -104,14 +104,13 @@ const props = defineProps({
104
104
  /**
105
105
  * Whether to show the notification bell.
106
106
  *
107
- * Off by default, and opt-in per application rather than always on: this
108
- * header is mounted by every app in the estate, and only the ones whose
109
- * modules actually raise notifications should grow a bell that would
110
- * otherwise sit there permanently empty.
107
+ * ON by default (owner requirement 2026-09-19: every type of account on the
108
+ * web is told about its notifications). An app can still pass `false` for a
109
+ * screen that should not have one.
111
110
  */
112
111
  showNotifications: {
113
112
  type: Boolean,
114
- default: false,
113
+ default: true,
115
114
  },
116
115
  });
117
116
 
@@ -1,146 +1,205 @@
1
1
  <template>
2
- <v-menu
3
- v-model="open"
4
- offset="10px"
5
- :close-on-content-click="false"
6
- location="bottom end"
7
- >
8
- <template #activator="{ props: activator }">
9
- <v-btn
10
- v-bind="activator"
11
- variant="text"
12
- size="36"
13
- class="app-topbar-shell__icon-btn ms-2"
14
- :aria-label="
15
- unread > 0 ? `Notifications, ${unread} unread` : 'Notifications'
16
- "
17
- >
18
- <v-badge
19
- :model-value="unread > 0"
20
- :content="badgeLabel"
21
- color="error"
22
- offset-x="-2"
23
- offset-y="-2"
2
+ <div class="notif-bell">
3
+ <v-menu
4
+ v-model="open"
5
+ offset="10px"
6
+ :close-on-content-click="false"
7
+ location="bottom end"
8
+ >
9
+ <template #activator="{ props: activator }">
10
+ <v-btn
11
+ v-bind="activator"
12
+ variant="text"
13
+ size="36"
14
+ class="app-topbar-shell__icon-btn ms-2"
15
+ :aria-label="
16
+ unread > 0 ? `Notifications, ${unread} unread` : 'Notifications'
17
+ "
24
18
  >
25
- <v-icon icon="mdi-bell-outline" size="20" />
26
- </v-badge>
27
- </v-btn>
28
- </template>
19
+ <v-badge
20
+ :model-value="unread > 0"
21
+ :content="badgeLabel"
22
+ color="error"
23
+ offset-x="-2"
24
+ offset-y="-2"
25
+ >
26
+ <v-icon icon="mdi-bell-outline" size="20" />
27
+ </v-badge>
28
+ </v-btn>
29
+ </template>
30
+
31
+ <v-card :width="440" elevation="0" class="notif-panel">
32
+ <div class="notif-panel__head">
33
+ <span>Notification</span>
34
+ <v-btn
35
+ v-if="unread > 0"
36
+ variant="text"
37
+ size="small"
38
+ class="text-none"
39
+ :loading="markingAll"
40
+ @click="readAll"
41
+ >
42
+ Mark all as read
43
+ </v-btn>
44
+ </div>
29
45
 
30
- <v-card :width="440" elevation="0" class="notif-panel">
31
- <div class="notif-panel__head">Notification</div>
46
+ <div v-if="canAskDesktop" class="notif-panel__desktop">
47
+ <v-icon icon="mdi-monitor" size="18" />
48
+ <span>Get a pop-up on this computer when something new arrives.</span>
49
+ <v-btn variant="tonal" size="small" class="text-none" @click="askDesktop">
50
+ Turn on
51
+ </v-btn>
52
+ </div>
32
53
 
33
- <div class="notif-panel__body">
34
- <div v-if="loading" class="notif-panel__state">
35
- <v-progress-circular indeterminate size="22" />
54
+ <div class="notif-panel__body">
55
+ <div v-if="loading" class="notif-panel__state">
56
+ <v-progress-circular indeterminate size="22" />
57
+ </div>
58
+
59
+ <p v-else-if="error" class="notif-panel__state text-error">
60
+ Notifications could not be loaded.
61
+ </p>
62
+
63
+ <p v-else-if="!items.length" class="notif-panel__state">
64
+ You have no notifications.
65
+ </p>
66
+
67
+ <template v-else>
68
+ <button
69
+ v-for="item in items"
70
+ :key="item._id"
71
+ type="button"
72
+ class="notif-card"
73
+ :class="{ 'notif-card--unread': !item.hasRead }"
74
+ @click="openNotification(item)"
75
+ >
76
+ <div class="notif-card__top">
77
+ <span class="notif-card__title" :class="titleClass(item)">
78
+ {{ item.title }}
79
+ </span>
80
+ <span class="notif-card__age">{{ timeAgo(item.createdAt) }}</span>
81
+ </div>
82
+
83
+ <div class="notif-card__bottom">
84
+ <v-icon size="18" class="notif-card__icon">
85
+ {{ iconFor(item) }}
86
+ </v-icon>
87
+ <span class="notif-card__body">{{ item.body }}</span>
88
+ <span
89
+ class="notif-card__dot"
90
+ :class="{ 'notif-card__dot--read': item.hasRead }"
91
+ />
92
+ </div>
93
+ </button>
94
+ </template>
36
95
  </div>
37
96
 
38
- <p v-else-if="error" class="notif-panel__state text-error">
39
- Notifications could not be loaded.
40
- </p>
41
-
42
- <p v-else-if="!items.length" class="notif-panel__state">
43
- You have no notifications.
44
- </p>
45
-
46
- <template v-else>
47
- <button
48
- v-for="item in items"
49
- :key="item._id"
50
- type="button"
51
- class="notif-card"
52
- :class="{ 'notif-card--unread': !item.hasRead }"
53
- @click="openNotification(item)"
97
+ <div class="notif-panel__foot">
98
+ <NuxtLink
99
+ :to="{ path: '/notification-settings' }"
100
+ class="notif-panel__settings"
101
+ @click="open = false"
54
102
  >
55
- <div class="notif-card__top">
56
- <span class="notif-card__title" :class="titleClass(item)">
57
- {{ item.title }}
58
- </span>
59
- <span class="notif-card__age">{{ relativeAge(item.createdAt) }}</span>
60
- </div>
61
-
62
- <div class="notif-card__bottom">
63
- <v-icon size="18" class="notif-card__icon">
64
- mdi-file-document-outline
65
- </v-icon>
66
- <span class="notif-card__body">{{ item.body }}</span>
67
- <span
68
- class="notif-card__dot"
69
- :class="{ 'notif-card__dot--read': item.hasRead }"
70
- />
71
- </div>
72
- </button>
73
- </template>
103
+ <v-icon icon="mdi-cog-outline" size="16" /> Notification settings
104
+ </NuxtLink>
105
+ </div>
106
+ </v-card>
107
+ </v-menu>
108
+
109
+ <v-snackbar
110
+ v-model="toast.show"
111
+ location="top right"
112
+ :timeout="6000"
113
+ color="surface"
114
+ class="notif-toast"
115
+ >
116
+ <div class="d-flex align-center ga-3">
117
+ <v-icon icon="mdi-bell-ring-outline" color="primary" />
118
+ <div>
119
+ <div class="font-weight-bold">{{ toast.title }}</div>
120
+ <div v-if="toast.body" class="text-body-2">{{ toast.body }}</div>
121
+ </div>
74
122
  </div>
75
- </v-card>
76
- </v-menu>
123
+ <template #actions>
124
+ <v-btn variant="text" class="text-none" @click="viewFromToast">View</v-btn>
125
+ </template>
126
+ </v-snackbar>
127
+ </div>
77
128
  </template>
78
129
 
79
130
  <script setup lang="ts">
131
+ import {
132
+ badgeText,
133
+ newArrivals,
134
+ timeAgo,
135
+ type TInboxItem,
136
+ } from "../utils/notification-inbox";
137
+
80
138
  /**
81
- * The top-bar notification feed for the web.
139
+ * The top-bar notification feed for the web, in every signed-in app.
140
+ *
141
+ * Owner requirement (2026-09-19): every type of account on the web gets the
142
+ * bell AND is told when something new arrives. So it is on by default in
143
+ * `Layout/Header.vue`, and it checks the unread count every 30 seconds and
144
+ * whenever the tab comes back into view — one small count query, not the list.
145
+ * When the count rises, the newest unread items are read and anything not seen
146
+ * before pops up in the page; if the person turned it on, as a desktop
147
+ * notification too (a browser only allows asking after a click, hence the
148
+ * "Turn on" button, never a prompt on load).
82
149
  *
83
- * Opt-in from `Layout/Header.vue` rather than always on: the header is shared by
84
- * every app in the estate, and only the ones whose modules actually raise a
85
- * notification should grow a bell that is permanently empty.
150
+ * The list shows everything addressed to the person, not only the current
151
+ * site: the unread count is never site-scoped, and most rows carry no site, so
152
+ * a site-scoped list disagreed with its own badge and was empty on site pages.
153
+ * `siteId` is still accepted so existing callers keep working.
86
154
  */
87
155
  const PAGE_SIZE = 10;
156
+ const POLL_MS = 30_000;
88
157
 
89
- const props = defineProps({
90
- /** Scopes the feed to one site. Empty shows everything addressed to the user. */
158
+ defineProps({
159
+ /** Accepted for existing callers; the feed is not narrowed by it (see above). */
91
160
  siteId: {
92
161
  type: String,
93
162
  default: "",
94
163
  },
95
164
  });
96
165
 
97
- const { getAll, getUnreadCount, markAsRead } = useNotification();
166
+ const { getAll, getUnreadCount, markAsRead, markAllAsRead } = useNotification();
98
167
  const { currentUser } = useLocalAuth();
99
168
 
100
169
  const open = ref(false);
101
170
  const loading = ref(false);
102
171
  const error = ref(false);
172
+ const markingAll = ref(false);
103
173
  const items = ref<Array<Record<string, any>>>([]);
104
174
  const unread = ref(0);
175
+ const toast = reactive({ show: false, title: "", body: "" });
105
176
 
106
177
  const userId = computed(() => String(currentUser.value?._id ?? ""));
178
+ const badgeLabel = computed(() => badgeText(unread.value));
107
179
 
108
- /** Three digits of badge is a smudge; past 99 the exact number changes nothing. */
109
- const badgeLabel = computed(() => (unread.value > 99 ? "99+" : String(unread.value)));
180
+ const seen = new Set<string>();
181
+ let firstLook = true;
182
+ let timer: ReturnType<typeof setInterval> | null = null;
183
+
184
+ const desktopState = ref<NotificationPermission | "unsupported">("unsupported");
185
+ const canAskDesktop = computed(() => desktopState.value === "default");
110
186
 
111
187
  /**
112
- * Red for a document that has already lapsed, amber for one approaching it.
113
- *
114
- * Matched on the title because the stored feed row carries no structured stage:
115
- * `send()` persists title, body, module, screen and params, and drops the rest
116
- * of its `data`. The two titles come from one tested function in
117
- * `document-expiry-reminder.util.ts`, and "expiring" does not contain
118
- * "expired", so the test is narrower than it looks.
188
+ * Red for a document that has already lapsed, amber for one approaching it;
189
+ * everything else is plain. Matched on the title because the stored feed row
190
+ * carries no structured stage (see `document-expiry-reminder.util.ts`).
119
191
  */
120
192
  function titleClass(item: Record<string, any>) {
121
- return /expired/i.test(String(item?.title ?? ""))
122
- ? "notif-card__title--urgent"
123
- : "notif-card__title--warn";
193
+ const title = String(item?.title ?? "");
194
+ if (/expired/i.test(title)) return "notif-card__title--urgent";
195
+ if (/expir/i.test(title)) return "notif-card__title--warn";
196
+ return "";
124
197
  }
125
198
 
126
- /** "24 mins ago", the form the design prints. */
127
- function relativeAge(value?: string | Date | null) {
128
- if (!value) return "";
129
-
130
- const then = new Date(value).getTime();
131
- if (Number.isNaN(then)) return "";
132
-
133
- const seconds = Math.max(0, Math.floor((Date.now() - then) / 1000));
134
- if (seconds < 60) return "just now";
135
-
136
- const minutes = Math.floor(seconds / 60);
137
- if (minutes < 60) return `${minutes} min${minutes === 1 ? "" : "s"} ago`;
138
-
139
- const hours = Math.floor(minutes / 60);
140
- if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
141
-
142
- const days = Math.floor(hours / 24);
143
- return `${days} day${days === 1 ? "" : "s"} ago`;
199
+ function iconFor(item: Record<string, any>) {
200
+ return /expir|document/i.test(`${item?.title ?? ""} ${item?.module ?? ""}`)
201
+ ? "mdi-file-document-outline"
202
+ : "mdi-bell-outline";
144
203
  }
145
204
 
146
205
  /** Tolerates the reply being paginated, wrapped once, or a bare array. */
@@ -156,33 +215,12 @@ function readCount(response: any): number {
156
215
  return Number.isFinite(Number(value)) ? Number(value) : 0;
157
216
  }
158
217
 
159
- async function refreshUnread() {
160
- if (!userId.value) return;
161
-
162
- try {
163
- unread.value = readCount(await getUnreadCount(userId.value));
164
- } catch {
165
- // A badge that cannot be counted is not worth an error in the top bar of
166
- // every screen; the panel itself reports a failure when it is opened.
167
- unread.value = 0;
168
- }
169
- }
170
-
171
218
  async function refreshList() {
172
219
  if (!userId.value) return;
173
-
174
220
  loading.value = true;
175
221
  error.value = false;
176
-
177
222
  try {
178
- items.value = readRows(
179
- await getAll({
180
- page: 1,
181
- limit: PAGE_SIZE,
182
- siteId: props.siteId,
183
- user: userId.value,
184
- }),
185
- );
223
+ items.value = readRows(await getAll({ page: 1, limit: PAGE_SIZE, user: userId.value }));
186
224
  } catch {
187
225
  error.value = true;
188
226
  items.value = [];
@@ -191,35 +229,124 @@ async function refreshList() {
191
229
  }
192
230
  }
193
231
 
232
+ /** One check: the count, and — only if it rose — the newest unread, to announce what is new. */
233
+ async function check() {
234
+ if (!userId.value) return;
235
+ try {
236
+ const count = readCount(await getUnreadCount(userId.value));
237
+ const rose = count > unread.value;
238
+ unread.value = count;
239
+ if (!firstLook && !rose) return;
240
+ const latest = readRows(
241
+ await getAll({ page: 1, limit: PAGE_SIZE, hasRead: false, user: userId.value }),
242
+ ) as TInboxItem[];
243
+ const fresh = newArrivals(latest, seen, firstLook);
244
+ latest.forEach((i) => i?._id && seen.add(i._id));
245
+ firstLook = false;
246
+ if (fresh.length) announce(fresh);
247
+ if (open.value) await refreshList();
248
+ } catch {
249
+ // A failed check is retried on the next tick; the top bar never shows an error for it.
250
+ }
251
+ }
252
+
253
+ function announce(fresh: TInboxItem[]) {
254
+ const first = fresh[0];
255
+ toast.title = fresh.length > 1 ? `${fresh.length} new notifications` : first.title || "New notification";
256
+ toast.body = fresh.length > 1 ? first.title || "" : first.body || "";
257
+ toast.show = true;
258
+ if (desktopState.value === "granted" && document.visibilityState !== "visible") {
259
+ try {
260
+ const note = new Notification(toast.title, { body: toast.body, tag: `iservice365-${first._id}` });
261
+ note.onclick = () => {
262
+ window.focus();
263
+ open.value = true;
264
+ note.close();
265
+ };
266
+ } catch {
267
+ // Some browsers only allow notifications from a service worker; the in-page pop-up still shows.
268
+ }
269
+ }
270
+ }
271
+
194
272
  async function openNotification(item: Record<string, any>) {
195
273
  if (item.hasRead) return;
196
-
197
- // Marked locally first. The count and the dot are the whole feedback for the
198
- // click, and waiting on a round trip to move them reads as a dead control.
274
+ // Marked locally first: waiting on a round trip to move the dot reads as a dead control.
199
275
  item.hasRead = true;
200
276
  unread.value = Math.max(0, unread.value - 1);
201
-
202
277
  try {
203
278
  await markAsRead(String(item._id), userId.value);
204
279
  } catch {
205
280
  item.hasRead = false;
206
- await refreshUnread();
281
+ unread.value += 1;
282
+ }
283
+ }
284
+
285
+ async function readAll() {
286
+ markingAll.value = true;
287
+ try {
288
+ await markAllAsRead(userId.value);
289
+ items.value.forEach((i) => (i.hasRead = true));
290
+ unread.value = 0;
291
+ } catch {
292
+ // Left as it was; the next check shows the real state.
293
+ } finally {
294
+ markingAll.value = false;
295
+ }
296
+ }
297
+
298
+ async function askDesktop() {
299
+ try {
300
+ desktopState.value = await Notification.requestPermission();
301
+ } catch {
302
+ desktopState.value = "denied";
207
303
  }
208
304
  }
209
305
 
210
- // Fetched when the panel is opened rather than on a timer: a poll in a shared
211
- // header would run on every screen of every app that mounts it.
306
+ function viewFromToast() {
307
+ toast.show = false;
308
+ open.value = true;
309
+ }
310
+
311
+ function onVisible() {
312
+ if (document.visibilityState === "visible") check();
313
+ }
314
+
212
315
  watch(open, (isOpen) => {
213
- if (isOpen) {
214
- refreshList();
215
- refreshUnread();
316
+ if (isOpen) refreshList();
317
+ });
318
+
319
+ watch(userId, (id) => {
320
+ if (id) check();
321
+ });
322
+
323
+ onMounted(() => {
324
+ if (typeof window !== "undefined" && "Notification" in window) {
325
+ desktopState.value = Notification.permission;
216
326
  }
327
+ check();
328
+ timer = setInterval(check, POLL_MS);
329
+ document.addEventListener("visibilitychange", onVisible);
217
330
  });
218
331
 
219
- onMounted(refreshUnread);
332
+ onBeforeUnmount(() => {
333
+ if (timer) clearInterval(timer);
334
+ document.removeEventListener("visibilitychange", onVisible);
335
+ });
220
336
  </script>
221
337
 
222
338
  <style scoped>
339
+ .notif-bell {
340
+ display: inline-flex;
341
+ align-items: center;
342
+ }
343
+
344
+ /* The header's 36px bordered icon button; its rule is scoped to Header.vue. */
345
+ .app-topbar-shell__icon-btn {
346
+ border: 1px solid var(--border);
347
+ border-radius: var(--r-inner);
348
+ }
349
+
223
350
  .notif-panel {
224
351
  border-radius: var(--r-menu);
225
352
  background: var(--card);
@@ -227,11 +354,23 @@ onMounted(refreshUnread);
227
354
  }
228
355
 
229
356
  .notif-panel__head {
357
+ display: flex;
358
+ align-items: center;
359
+ justify-content: space-between;
230
360
  padding: 14px 16px;
231
361
  font-weight: 600;
232
362
  border-bottom: 1px solid var(--border);
233
363
  }
234
364
 
365
+ .notif-panel__desktop {
366
+ display: flex;
367
+ align-items: center;
368
+ gap: 8px;
369
+ padding: 10px 16px;
370
+ font-size: 12.5px;
371
+ background: var(--hover);
372
+ }
373
+
235
374
  .notif-panel__body {
236
375
  max-height: 420px;
237
376
  overflow-y: auto;
@@ -248,6 +387,20 @@ onMounted(refreshUnread);
248
387
  margin: 0;
249
388
  }
250
389
 
390
+ .notif-panel__foot {
391
+ padding: 10px 16px;
392
+ border-top: 1px solid var(--border);
393
+ }
394
+
395
+ .notif-panel__settings {
396
+ display: inline-flex;
397
+ align-items: center;
398
+ gap: 6px;
399
+ font-size: 12.5px;
400
+ color: var(--text2);
401
+ text-decoration: none;
402
+ }
403
+
251
404
  .notif-card {
252
405
  width: 100%;
253
406
  text-align: left;
@@ -274,6 +427,10 @@ onMounted(refreshUnread);
274
427
  font-weight: 500;
275
428
  }
276
429
 
430
+ .notif-card--unread .notif-card__title {
431
+ font-weight: 700;
432
+ }
433
+
277
434
  .notif-card__title--warn {
278
435
  color: var(--warn);
279
436
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.17.1-staging.335",
5
+ "version": "4.17.1-staging.336",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The web notification bell's decisions, kept free of Vue and Nuxt so they are
3
+ * unit-tested directly (`utils/notification-inbox.test.ts`).
4
+ */
5
+
6
+ export type TInboxItem = {
7
+ _id: string;
8
+ title?: string;
9
+ body?: string;
10
+ hasRead?: boolean;
11
+ createdAt?: string;
12
+ };
13
+
14
+ /**
15
+ * Which of the newest unread items have not been announced yet.
16
+ *
17
+ * The first look after sign-in announces nothing: a pop-up for every message
18
+ * that was already waiting is noise, and the badge already says how many there
19
+ * are. After that, anything unread whose id was not seen before is new.
20
+ */
21
+ export function newArrivals(items: TInboxItem[], seen: Set<string>, firstLook: boolean): TInboxItem[] {
22
+ const unread = items.filter((i) => i && i._id && !i.hasRead);
23
+ if (firstLook) return [];
24
+ return unread.filter((i) => !seen.has(i._id));
25
+ }
26
+
27
+ /** "just now", "5 min ago", "3 h ago", "2 days ago", then the date. */
28
+ export function timeAgo(value: string | undefined, now: Date = new Date()): string {
29
+ if (!value) return "";
30
+ const at = new Date(value);
31
+ if (Number.isNaN(at.getTime())) return "";
32
+ const seconds = Math.round((now.getTime() - at.getTime()) / 1000);
33
+ if (seconds < 60) return "just now";
34
+ const minutes = Math.round(seconds / 60);
35
+ if (minutes < 60) return `${minutes} min ago`;
36
+ const hours = Math.round(minutes / 60);
37
+ if (hours < 24) return `${hours} h ago`;
38
+ const days = Math.round(hours / 24);
39
+ if (days < 7) return `${days} day${days === 1 ? "" : "s"} ago`;
40
+ return at.toLocaleDateString("en-SG", { day: "2-digit", month: "short", year: "numeric" });
41
+ }
42
+
43
+ /** The badge text: nothing at 0, the number up to 99, then "99+". */
44
+ export function badgeText(unread: number): string {
45
+ if (!unread || unread < 0) return "";
46
+ return unread > 99 ? "99+" : String(unread);
47
+ }