@things-factory/announcement 0.0.0-stage → 10.1.222
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/client/announcement-watch.ts +109 -0
- package/client/bootstrap.ts +9 -0
- package/client/components/announcement-popup.ts +92 -0
- package/client/components/announcement-receipts.ts +196 -0
- package/client/components/announcement-sheet.ts +214 -0
- package/client/components/audience-picker.ts +221 -0
- package/client/index.ts +1 -0
- package/client/pages/announcement-editor.ts +505 -0
- package/client/pages/announcement-list.ts +200 -0
- package/client/pages/announcement-manage-list.ts +113 -0
- package/client/pages/announcement-view.ts +172 -0
- package/client/route.ts +17 -0
- package/client/tsconfig.json +13 -0
- package/client/utils/announcement-api.ts +142 -0
- package/client/utils/announcement-badge.ts +46 -0
- package/client/utils/announcement-words.ts +26 -0
- package/dist-client/announcement-watch.d.ts +6 -0
- package/dist-client/announcement-watch.js +105 -0
- package/dist-client/announcement-watch.js.map +1 -0
- package/dist-client/bootstrap.d.ts +1 -0
- package/dist-client/bootstrap.js +8 -0
- package/dist-client/bootstrap.js.map +1 -0
- package/dist-client/components/announcement-popup.d.ts +20 -0
- package/dist-client/components/announcement-popup.js +98 -0
- package/dist-client/components/announcement-popup.js.map +1 -0
- package/dist-client/components/announcement-receipts.d.ts +30 -0
- package/dist-client/components/announcement-receipts.js +220 -0
- package/dist-client/components/announcement-receipts.js.map +1 -0
- package/dist-client/components/announcement-sheet.d.ts +17 -0
- package/dist-client/components/announcement-sheet.js +224 -0
- package/dist-client/components/announcement-sheet.js.map +1 -0
- package/dist-client/components/audience-picker.d.ts +32 -0
- package/dist-client/components/audience-picker.js +223 -0
- package/dist-client/components/audience-picker.js.map +1 -0
- package/dist-client/index.d.ts +1 -0
- package/dist-client/index.js +2 -0
- package/dist-client/index.js.map +1 -0
- package/dist-client/pages/announcement-editor.d.ts +59 -0
- package/dist-client/pages/announcement-editor.js +523 -0
- package/dist-client/pages/announcement-editor.js.map +1 -0
- package/dist-client/pages/announcement-list.d.ts +54 -0
- package/dist-client/pages/announcement-list.js +209 -0
- package/dist-client/pages/announcement-list.js.map +1 -0
- package/dist-client/pages/announcement-manage-list.d.ts +46 -0
- package/dist-client/pages/announcement-manage-list.js +115 -0
- package/dist-client/pages/announcement-manage-list.js.map +1 -0
- package/dist-client/pages/announcement-view.d.ts +30 -0
- package/dist-client/pages/announcement-view.js +182 -0
- package/dist-client/pages/announcement-view.js.map +1 -0
- package/dist-client/route.d.ts +1 -0
- package/dist-client/route.js +18 -0
- package/dist-client/route.js.map +1 -0
- package/dist-client/tsconfig.tsbuildinfo +1 -0
- package/dist-client/utils/announcement-api.d.ts +149 -0
- package/dist-client/utils/announcement-api.js +52 -0
- package/dist-client/utils/announcement-api.js.map +1 -0
- package/dist-client/utils/announcement-badge.d.ts +4 -0
- package/dist-client/utils/announcement-badge.js +47 -0
- package/dist-client/utils/announcement-badge.js.map +1 -0
- package/dist-client/utils/announcement-words.d.ts +11 -0
- package/dist-client/utils/announcement-words.js +23 -0
- package/dist-client/utils/announcement-words.js.map +1 -0
- package/dist-server/announcement-read.d.ts +6 -0
- package/dist-server/announcement-read.js +45 -0
- package/dist-server/announcement-read.js.map +1 -0
- package/dist-server/attachment-reader.d.ts +1 -0
- package/dist-server/attachment-reader.js +13 -0
- package/dist-server/attachment-reader.js.map +1 -0
- package/dist-server/index.d.ts +2 -0
- package/dist-server/index.js +20 -0
- package/dist-server/index.js.map +1 -0
- package/dist-server/role-tasks.d.ts +2 -0
- package/dist-server/role-tasks.js +13 -0
- package/dist-server/role-tasks.js.map +1 -0
- package/dist-server/service/announcement/announcement-resolver.d.ts +38 -0
- package/dist-server/service/announcement/announcement-resolver.js +664 -0
- package/dist-server/service/announcement/announcement-resolver.js.map +1 -0
- package/dist-server/service/announcement/announcement-rules.d.ts +150 -0
- package/dist-server/service/announcement/announcement-rules.js +227 -0
- package/dist-server/service/announcement/announcement-rules.js.map +1 -0
- package/dist-server/service/announcement/announcement-service.d.ts +54 -0
- package/dist-server/service/announcement/announcement-service.js +248 -0
- package/dist-server/service/announcement/announcement-service.js.map +1 -0
- package/dist-server/service/announcement/announcement-types.d.ts +54 -0
- package/dist-server/service/announcement/announcement-types.js +203 -0
- package/dist-server/service/announcement/announcement-types.js.map +1 -0
- package/dist-server/service/announcement/announcement.d.ts +124 -0
- package/dist-server/service/announcement/announcement.js +462 -0
- package/dist-server/service/announcement/announcement.js.map +1 -0
- package/dist-server/service/announcement/index.d.ts +4 -0
- package/dist-server/service/announcement/index.js +8 -0
- package/dist-server/service/announcement/index.js.map +1 -0
- package/dist-server/service/index.d.ts +7 -0
- package/dist-server/service/index.js +23 -0
- package/dist-server/service/index.js.map +1 -0
- package/dist-server/tsconfig.tsbuildinfo +1 -0
- package/package.json +51 -4
- package/server/announcement-read.ts +44 -0
- package/server/attachment-reader.ts +11 -0
- package/server/index.ts +16 -0
- package/server/role-tasks.ts +12 -0
- package/server/service/announcement/announcement-resolver.ts +506 -0
- package/server/service/announcement/announcement-rules.ts +239 -0
- package/server/service/announcement/announcement-service.ts +240 -0
- package/server/service/announcement/announcement-types.ts +138 -0
- package/server/service/announcement/announcement.ts +367 -0
- package/server/service/announcement/index.ts +5 -0
- package/server/service/index.ts +19 -0
- package/server/tsconfig.json +11 -0
- package/test/announcement-persistence.test.ts +271 -0
- package/test/announcement-read.test.ts +49 -0
- package/test/announcement-rules.test.ts +217 -0
- package/test/open-doors.test.ts +45 -0
- package/test/translations.test.ts +54 -0
- package/things-factory.config.js +13 -0
- package/translations/en.json +169 -0
- package/translations/es.json +169 -0
- package/translations/ja.json +169 -0
- package/translations/ko.json +169 -0
- package/translations/ms.json +169 -0
- package/translations/zh.json +169 -0
- package/README.md +0 -3
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The rules of an announcement (ADR-0163 decisions 3-5) - what may be written, where it stands, what a reader owes it,
|
|
3
|
+
* when it pops up, and what the notice of it says.
|
|
4
|
+
*
|
|
5
|
+
* Pure - the rules are tested without a database. The doors (announcement-resolver.ts) ask them.
|
|
6
|
+
*/
|
|
7
|
+
/** The kinds of announcement - declared by this module, named in its translations (`announcement.category.<code>`). */
|
|
8
|
+
export const ANNOUNCEMENT_CATEGORIES = ['GENERAL', 'HR', 'WELFARE', 'EVENT', 'SYSTEM', 'SECURITY'] as const
|
|
9
|
+
|
|
10
|
+
export const IMPORTANCES = ['NORMAL', 'IMPORTANT', 'URGENT'] as const
|
|
11
|
+
export const MAX_TITLE = 200
|
|
12
|
+
export const MAX_LINKS = 10
|
|
13
|
+
export const MAX_LINK_LABEL = 100
|
|
14
|
+
|
|
15
|
+
export interface AnnouncementFacts {
|
|
16
|
+
status: string
|
|
17
|
+
importance?: string
|
|
18
|
+
pinned?: boolean
|
|
19
|
+
popup?: boolean
|
|
20
|
+
requiresAcknowledgement?: boolean
|
|
21
|
+
startsAt?: Date | string | null
|
|
22
|
+
endsAt?: Date | string | null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ReceiptFacts {
|
|
26
|
+
readAt?: Date | string | null
|
|
27
|
+
acknowledgedAt?: Date | string | null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const time = (value: Date | string | null | undefined) => (value ? new Date(value).getTime() : undefined)
|
|
31
|
+
|
|
32
|
+
/** Out to its audience and not past its end. */
|
|
33
|
+
export function isCurrent(one: AnnouncementFacts, now = new Date()): boolean {
|
|
34
|
+
const end = time(one.endsAt)
|
|
35
|
+
return one.status === 'PUBLISHED' && (end === undefined || end > now.getTime())
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Whether an announcement that is out is still current or past - a reader's list and a dashboard card ask it. */
|
|
39
|
+
export function periodOf(one: AnnouncementFacts, now = new Date()): 'current' | 'past' | undefined {
|
|
40
|
+
if (one.status !== 'PUBLISHED') return undefined
|
|
41
|
+
return isCurrent(one, now) ? 'current' : 'past'
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const PERIODS = ['current', 'past'] as const
|
|
45
|
+
export const READER_STATES = ['unread', 'read', 'to-acknowledge', 'acknowledged'] as const
|
|
46
|
+
|
|
47
|
+
type ListFilter = { name: string; operator?: string; value?: unknown }
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The reader's own narrowing in a list's filters - `period` (current | past) and `readerState` (unread, read,
|
|
51
|
+
* to-acknowledge, acknowledged; one or several) - taken out of the column filters, so the screen and the assistant
|
|
52
|
+
* narrow the one list the same way. Absent, a list is not narrowed by them. An unknown value is refused, not ignored.
|
|
53
|
+
*/
|
|
54
|
+
export function readerNarrowingOf(filters: ListFilter[] | null | undefined): { rest: ListFilter[]; period?: 'current' | 'past'; states?: string[]; refusal?: string } {
|
|
55
|
+
const rest: ListFilter[] = []
|
|
56
|
+
let period: 'current' | 'past' | undefined
|
|
57
|
+
let states: string[] | undefined
|
|
58
|
+
for (const filter of filters ?? []) {
|
|
59
|
+
if (filter?.name === 'period') {
|
|
60
|
+
if (!(PERIODS as readonly string[]).includes(String(filter.value))) return { rest, refusal: 'unknown-period' }
|
|
61
|
+
period = filter.value as 'current' | 'past'
|
|
62
|
+
} else if (filter?.name === 'readerState') {
|
|
63
|
+
const values = [filter.value].flat().map(String)
|
|
64
|
+
if (!values.length || values.some(one => !(READER_STATES as readonly string[]).includes(one))) return { rest, refusal: 'unknown-reader-state' }
|
|
65
|
+
states = values
|
|
66
|
+
} else rest.push(filter)
|
|
67
|
+
}
|
|
68
|
+
return { rest, period, states }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Publishing now goes out at once, or waits for a start still to come. */
|
|
72
|
+
export function publishedStatusOf(startsAt: Date | string | null | undefined, now = new Date()): 'PUBLISHED' | 'SCHEDULED' {
|
|
73
|
+
const start = time(startsAt)
|
|
74
|
+
return start !== undefined && start > now.getTime() ? 'SCHEDULED' : 'PUBLISHED'
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Where it stands for one reader. Reading and acknowledging are apart: one that asks to be acknowledged stays
|
|
79
|
+
* 'to-acknowledge' after it was read.
|
|
80
|
+
*/
|
|
81
|
+
export function readerStateOf(one: AnnouncementFacts, receipt: ReceiptFacts | undefined): 'unread' | 'to-acknowledge' | 'acknowledged' | 'read' {
|
|
82
|
+
if (one.requiresAcknowledgement) {
|
|
83
|
+
if (receipt?.acknowledgedAt) return 'acknowledged'
|
|
84
|
+
return receipt?.readAt ? 'to-acknowledge' : 'unread'
|
|
85
|
+
}
|
|
86
|
+
return receipt?.readAt ? 'read' : 'unread'
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Whether it pops up for the reader (the user, 2026-10-26: 「공지 사항이 있을 때 자동 팝업」): a current popup
|
|
91
|
+
* announcement shows once - seeing it reads it - and one that asks to be acknowledged shows at every sign-in until it
|
|
92
|
+
* is acknowledged.
|
|
93
|
+
*/
|
|
94
|
+
export function popupDue(one: AnnouncementFacts, receipt: ReceiptFacts | undefined, now = new Date()): boolean {
|
|
95
|
+
if (!one.popup || !isCurrent(one, now)) return false
|
|
96
|
+
return one.requiresAcknowledgement ? !receipt?.acknowledgedAt : !receipt?.readAt
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The place in the readers' list - kept as a column so the list is ordered by the database: pinned first, then urgent,
|
|
101
|
+
* important, normal. The newest comes first within each (the list's second order).
|
|
102
|
+
*/
|
|
103
|
+
export function rankOf(one: Pick<AnnouncementFacts, 'pinned' | 'importance'>): number {
|
|
104
|
+
const importance = one.importance === 'URGENT' ? 0 : one.importance === 'IMPORTANT' ? 1 : 2
|
|
105
|
+
return (one.pinned ? 0 : 10) + importance
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A link a reader may follow: a screen of the application by its address (`contract-list?id=…`) or an https page.
|
|
110
|
+
* Nothing that runs (`javascript:`), no other scheme, nothing that leaves through `//`.
|
|
111
|
+
*/
|
|
112
|
+
export function linkRefusal(link: { label?: string; url?: string } | null | undefined): string | undefined {
|
|
113
|
+
const label = String(link?.label ?? '').trim()
|
|
114
|
+
const url = String(link?.url ?? '').trim()
|
|
115
|
+
if (!label || !url) return 'link-incomplete'
|
|
116
|
+
if (label.length > MAX_LINK_LABEL) return 'link-label-too-long'
|
|
117
|
+
if (/\s/.test(url) || url.includes('\\')) return 'bad-link'
|
|
118
|
+
if (/^https:\/\/[^/]/i.test(url)) return undefined
|
|
119
|
+
if (url.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(url)) return 'bad-link'
|
|
120
|
+
return undefined
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface AnnouncementInputFacts {
|
|
124
|
+
title?: string
|
|
125
|
+
category?: string
|
|
126
|
+
importance?: string
|
|
127
|
+
startsAt?: Date | string | null
|
|
128
|
+
endsAt?: Date | string | null
|
|
129
|
+
requiresAcknowledgement?: boolean
|
|
130
|
+
acknowledgeBy?: Date | string | null
|
|
131
|
+
links?: { label?: string; url?: string }[] | null
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Why what was written cannot be kept, or nothing. Asked on every save - a draft is kept to the same rules. */
|
|
135
|
+
export function inputRefusal(input: AnnouncementInputFacts): string | undefined {
|
|
136
|
+
const title = String(input.title ?? '').trim()
|
|
137
|
+
if (!title) return 'no-title'
|
|
138
|
+
if (title.length > MAX_TITLE) return 'title-too-long'
|
|
139
|
+
if (input.category && !(ANNOUNCEMENT_CATEGORIES as readonly string[]).includes(input.category)) return 'unknown-category'
|
|
140
|
+
if (input.importance && !(IMPORTANCES as readonly string[]).includes(input.importance)) return 'unknown-importance'
|
|
141
|
+
const start = time(input.startsAt)
|
|
142
|
+
const end = time(input.endsAt)
|
|
143
|
+
if (start !== undefined && end !== undefined && end <= start) return 'ends-before-start'
|
|
144
|
+
if (input.acknowledgeBy && !input.requiresAcknowledgement) return 'acknowledge-by-without-ask'
|
|
145
|
+
const by = time(input.acknowledgeBy)
|
|
146
|
+
if (by !== undefined && start !== undefined && by < start) return 'acknowledge-by-before-start'
|
|
147
|
+
if ((input.links ?? []).length > MAX_LINKS) return 'too-many-links'
|
|
148
|
+
for (const link of input.links ?? []) {
|
|
149
|
+
const refusal = linkRefusal(link)
|
|
150
|
+
if (refusal) return refusal
|
|
151
|
+
}
|
|
152
|
+
return undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Why it cannot go out, or nothing - it is written to the rules and names someone. */
|
|
156
|
+
export function publishRefusal(status: string, input: AnnouncementInputFacts, audienceCount: number): string | undefined {
|
|
157
|
+
if (status !== 'DRAFT') return 'not-a-draft'
|
|
158
|
+
return inputRefusal(input) ?? (audienceCount > 0 ? undefined : 'no-audience')
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Who on the roster is still owed a reminder: not read yet, or not acknowledged when it asks for that. */
|
|
162
|
+
export function owedReminder(one: Pick<AnnouncementFacts, 'requiresAcknowledgement'>, receipt: ReceiptFacts & { listed?: boolean }): boolean {
|
|
163
|
+
if (!receipt.listed) return false
|
|
164
|
+
return one.requiresAcknowledgement ? !receipt.acknowledgedAt : !receipt.readAt
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The body as one line of plain words - the notice's text, and the list's preview. */
|
|
168
|
+
export function plainSummary(body: string | null | undefined, max = 120): string {
|
|
169
|
+
const text = String(body ?? '')
|
|
170
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
171
|
+
.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
|
|
172
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
173
|
+
.replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, '')
|
|
174
|
+
/* Only the marks that wrap words - a lone ~ (22시~24시), _ or | is part of the text. */
|
|
175
|
+
.replace(/(\*\*|__|~~|`)/g, '')
|
|
176
|
+
.replace(/(^|\s)\*(\S[^*]*?)\*(?=\s|$|[.,!?])/g, '$1$2')
|
|
177
|
+
.replace(/\s+/g, ' ')
|
|
178
|
+
.trim()
|
|
179
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The screen an announcement opens on. */
|
|
183
|
+
export const viewAddressOf = (id: string) => `announcement-view?id=${id}`
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Whether its notice is said once to the whole domain - a Teams channel everyone reads (notification `broadcast`).
|
|
187
|
+
* Only an announcement addressed to the whole domain: one for a department or a role must not land where everyone
|
|
188
|
+
* reads it.
|
|
189
|
+
*/
|
|
190
|
+
export function broadcastOf(audiences: readonly { scope: string; targetId: string }[], domainId: string | undefined): boolean {
|
|
191
|
+
return !!domainId && audiences.some(one => one.scope === 'DOMAIN' && one.targetId === domainId)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Why the people are told: it went out, it changed and they are told again, or they still owe it. */
|
|
195
|
+
export type NoticeKind = 'published' | 'changed' | 'reminder'
|
|
196
|
+
|
|
197
|
+
/** A sentence in one language, with the English one when that language has none. */
|
|
198
|
+
export type Say = (key: string, english: string, params?: Record<string, unknown>) => string
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* What the notice of an announcement says to one person (notification's `NoticeWords`): its title - marked when it is
|
|
202
|
+
* a change or a reminder - the start of its body for the inbox and web push, and the whole body, Markdown, for the mail
|
|
203
|
+
* (ADR-0163 decision 6: the mail carries the announcement, files stay behind the sign-in).
|
|
204
|
+
*/
|
|
205
|
+
export function noticeWordsOf(one: { title: string; body?: string | null }, kind: NoticeKind, say: Say) {
|
|
206
|
+
const subject =
|
|
207
|
+
kind === 'changed'
|
|
208
|
+
? say('announcement.notice.changed-subject', 'Changed: {title}', { title: one.title })
|
|
209
|
+
: kind === 'reminder'
|
|
210
|
+
? say('announcement.notice.reminder-subject', 'Reminder: {title}', { title: one.title })
|
|
211
|
+
: one.title
|
|
212
|
+
return {
|
|
213
|
+
subject,
|
|
214
|
+
summary: plainSummary(one.body),
|
|
215
|
+
body: one.body ?? '',
|
|
216
|
+
action: say('announcement.notice.action', 'Open the announcement'),
|
|
217
|
+
note: say('announcement.notice.note', 'Open Announcements in the application to read it.')
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export type NoticeCount = { receivers: number; email: { sent: number; failed: number }; teams: { sent: number; failed: number } }
|
|
222
|
+
|
|
223
|
+
/** One telling as the announcement keeps it - when, why, and what went out. A send that could not go at all counts its receivers, nothing sent. */
|
|
224
|
+
export function deliveryOf(kind: NoticeKind, result: NoticeCount | undefined, receivers: number, at = new Date()) {
|
|
225
|
+
return {
|
|
226
|
+
at: at.toISOString(),
|
|
227
|
+
kind,
|
|
228
|
+
receivers: result?.receivers ?? receivers,
|
|
229
|
+
email: result?.email ?? { sent: 0, failed: 0 },
|
|
230
|
+
teams: result?.teams ?? { sent: 0, failed: 0 },
|
|
231
|
+
...(result ? {} : { failed: true })
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The record kept on an announcement - the newest tellings, at most `MAX_DELIVERIES`. */
|
|
236
|
+
export const MAX_DELIVERIES = 50
|
|
237
|
+
export function withDelivery<T>(deliveries: T[] | null | undefined, one: T): T[] {
|
|
238
|
+
return [...(deliveries ?? []), one].slice(-MAX_DELIVERIES)
|
|
239
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What the doors of announcements do with the database (ADR-0163 decisions 1-5): who may read one, who is on its roster,
|
|
3
|
+
* sending it out, telling people of it, and publishing the scheduled ones when their start comes.
|
|
4
|
+
*/
|
|
5
|
+
import { EntityManager, In, IsNull, LessThanOrEqual } from 'typeorm'
|
|
6
|
+
|
|
7
|
+
import { checkPermission, User, UserStatus } from '@things-factory/auth-base'
|
|
8
|
+
import { logger } from '@things-factory/env'
|
|
9
|
+
import { translatorFor } from '@things-factory/i18n-base/translator'
|
|
10
|
+
import { noticeLinkOf, sendNotice, sendNoticeWhenCommitted, type Notice, type NoticeResult } from '@things-factory/notification'
|
|
11
|
+
import { audienceMemberOf, audienceUserIds, type AudienceMember } from '@things-factory/organization'
|
|
12
|
+
import { Domain, getDataSource, getRepository } from '@things-factory/shell'
|
|
13
|
+
|
|
14
|
+
import { Announcement, AnnouncementAudience, AnnouncementReceipt, AnnouncementRevision, AnnouncementStatus } from './announcement'
|
|
15
|
+
import { broadcastOf, deliveryOf, noticeWordsOf, viewAddressOf, withDelivery, type NoticeKind, type Say } from './announcement-rules'
|
|
16
|
+
|
|
17
|
+
/** The attachments of an announcement hang on it under this `refType` (attachment-base). */
|
|
18
|
+
export const ANNOUNCEMENT_REF_TYPE = 'Announcement'
|
|
19
|
+
|
|
20
|
+
/** Whether the request writes announcements - the one privilege of the module (`announcement.writing`). */
|
|
21
|
+
export async function isWriter(context: any): Promise<boolean> {
|
|
22
|
+
const state = context?.state ?? {}
|
|
23
|
+
const { domain, user, unsafeIP, prohibitedPrivileges } = state
|
|
24
|
+
if (!domain || !user) return false
|
|
25
|
+
/* Asked once per request - a list asks it for each row. */
|
|
26
|
+
state.__announcementWriter ??= checkPermission({ category: 'announcement', privilege: 'mutation', owner: true } as any, user, domain, unsafeIP, prohibitedPrivileges).then(Boolean)
|
|
27
|
+
return await state.__announcementWriter
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The request's person as an audience sees them - asked once per request. */
|
|
31
|
+
export async function memberOf(context: any): Promise<AudienceMember> {
|
|
32
|
+
const state = context.state
|
|
33
|
+
if (!state.__announcementMember) {
|
|
34
|
+
const { ownDepartments, ...member } = await audienceMemberOf(state.domain, state.user ?? {})
|
|
35
|
+
state.__announcementMember = member
|
|
36
|
+
}
|
|
37
|
+
return state.__announcementMember
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The announcements of the domain whose audience names `member` - by their targets, whatever their status. */
|
|
41
|
+
export async function reachingIds(member: AudienceMember, tx?: EntityManager): Promise<string[]> {
|
|
42
|
+
if (!member.userId || !member.domainId) return []
|
|
43
|
+
const domain = { id: member.domainId }
|
|
44
|
+
const rows = await getRepository(AnnouncementAudience, tx).find({
|
|
45
|
+
where: [
|
|
46
|
+
{ domain, scope: 'DOMAIN', targetId: member.domainId },
|
|
47
|
+
{ domain, scope: 'USER', targetId: member.userId },
|
|
48
|
+
...(member.departmentIds.length ? [{ domain, scope: 'DEPARTMENT', targetId: In([...member.departmentIds]) }] : []),
|
|
49
|
+
...(member.roleIds.length ? [{ domain, scope: 'ROLE', targetId: In([...member.roleIds]) }] : [])
|
|
50
|
+
] as any
|
|
51
|
+
})
|
|
52
|
+
return [...new Set(rows.map(one => one.announcementId!))]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function audiencesOf(announcementId: string, tx?: EntityManager): Promise<AnnouncementAudience[]> {
|
|
56
|
+
return await getRepository(AnnouncementAudience, tx).find({ where: { announcement: { id: announcementId } } as any, order: { createdAt: 'ASC' } as any })
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The announcement as the request may see it, or nothing - one answer for "none", "not yours" and "not out yet".
|
|
61
|
+
* Its audience reads it once it is out; a writer reads every one that is not somebody else's draft.
|
|
62
|
+
*/
|
|
63
|
+
export async function visibleAnnouncement(id: string, context: any, tx?: EntityManager): Promise<{ announcement: Announcement; reader: boolean; writer: boolean } | undefined> {
|
|
64
|
+
const { domain, user } = context?.state ?? {}
|
|
65
|
+
if (!id || !domain || !user || !/^[0-9a-f-]{36}$/i.test(id)) return undefined
|
|
66
|
+
const announcement = await getRepository(Announcement, tx).findOne({ where: { id, domain: { id: domain.id } } as any })
|
|
67
|
+
if (!announcement) return undefined
|
|
68
|
+
const reader = announcement.status === AnnouncementStatus.PUBLISHED && (await reachingIds(await memberOf(context), tx)).includes(id)
|
|
69
|
+
const writer = (announcement.status !== AnnouncementStatus.DRAFT || announcement.creatorId === user.id) && (await isWriter(context))
|
|
70
|
+
return reader || writer ? { announcement, reader, writer } : undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Puts the roster in line with the audience as it stands: everyone it names now is listed, one it no longer names is
|
|
75
|
+
* not (their reading stays). Answers those newly listed - the ones not yet told.
|
|
76
|
+
*/
|
|
77
|
+
export async function alignRoster(announcement: Announcement, domain: Domain, by: { id: string }, tx: EntityManager): Promise<string[]> {
|
|
78
|
+
const named = await audienceUserIds(domain, await audiencesOf(announcement.id, tx), tx)
|
|
79
|
+
const repository = getRepository(AnnouncementReceipt, tx)
|
|
80
|
+
const receipts = await repository.find({ where: { announcement: { id: announcement.id } } as any })
|
|
81
|
+
const byUser = new Map(receipts.map(one => [one.userId, one]))
|
|
82
|
+
const now = new Date()
|
|
83
|
+
const added: string[] = []
|
|
84
|
+
for (const userId of named) {
|
|
85
|
+
const receipt = byUser.get(userId)
|
|
86
|
+
if (receipt?.listed) continue
|
|
87
|
+
added.push(userId)
|
|
88
|
+
if (receipt) await repository.update(receipt.id, { listed: true, notifiedAt: now, updater: by } as any)
|
|
89
|
+
else await repository.save({ domain, announcement: { id: announcement.id }, user: { id: userId }, listed: true, notifiedAt: now, creator: by, updater: by } as any)
|
|
90
|
+
}
|
|
91
|
+
const gone = receipts.filter(one => one.listed && !named.includes(one.userId!))
|
|
92
|
+
if (gone.length) await repository.update({ id: In(gone.map(one => one.id)) } as any, { listed: false, updater: by } as any)
|
|
93
|
+
await getRepository(Announcement, tx).update(announcement.id, { audienceSize: named.length } as any)
|
|
94
|
+
return added
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The version as it stands, kept - the one that went out, and each change after. */
|
|
98
|
+
export async function keepRevision(announcement: Announcement, domain: Domain, by: { id: string }, tx: EntityManager): Promise<void> {
|
|
99
|
+
const audiences = await audiencesOf(announcement.id, tx)
|
|
100
|
+
const { title, body, category, importance, startsAt, endsAt, pinned, requiresAcknowledgement, acknowledgeBy, popup, links } = announcement
|
|
101
|
+
await getRepository(AnnouncementRevision, tx).save({
|
|
102
|
+
domain,
|
|
103
|
+
announcement: { id: announcement.id },
|
|
104
|
+
version: announcement.version,
|
|
105
|
+
title,
|
|
106
|
+
body,
|
|
107
|
+
rest: {
|
|
108
|
+
category,
|
|
109
|
+
importance,
|
|
110
|
+
startsAt,
|
|
111
|
+
endsAt,
|
|
112
|
+
pinned,
|
|
113
|
+
requiresAcknowledgement,
|
|
114
|
+
acknowledgeBy,
|
|
115
|
+
popup,
|
|
116
|
+
links,
|
|
117
|
+
audiences: audiences.map(({ scope, targetId, targetName }) => ({ scope, targetId, targetName }))
|
|
118
|
+
},
|
|
119
|
+
creator: by,
|
|
120
|
+
updater: by
|
|
121
|
+
} as any)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Sends it out: published now, the roster counted, this version kept. Answers the people to tell - the publisher is not
|
|
126
|
+
* told of their own announcement.
|
|
127
|
+
*/
|
|
128
|
+
export async function sendOut(announcement: Announcement, domain: Domain, by: { id: string }, tx: EntityManager): Promise<string[]> {
|
|
129
|
+
const now = new Date()
|
|
130
|
+
await getRepository(Announcement, tx).update(announcement.id, {
|
|
131
|
+
status: AnnouncementStatus.PUBLISHED,
|
|
132
|
+
publishedAt: now,
|
|
133
|
+
startsAt: announcement.startsAt ?? now,
|
|
134
|
+
publisher: by,
|
|
135
|
+
updater: by
|
|
136
|
+
} as any)
|
|
137
|
+
const fresh = await getRepository(Announcement, tx).findOneBy({ id: announcement.id })
|
|
138
|
+
await keepRevision(fresh!, domain, by, tx)
|
|
139
|
+
return (await alignRoster(fresh!, domain, by, tx)).filter(id => id !== by.id)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The sentences in `lng` from this module's translations, the English one where `lng` has none. */
|
|
143
|
+
const sayIn =
|
|
144
|
+
(lng: string): Say =>
|
|
145
|
+
(key, english, params = {}) =>
|
|
146
|
+
translatorFor(lng)(key, { ...params, defaultValue: english.replace(/\{(\w+)\}/g, (_, name) => String(params[name] ?? '')) })
|
|
147
|
+
|
|
148
|
+
/** The people to tell, as notification takes them - only those who can sign in, each with their mail and language. */
|
|
149
|
+
async function receiversOf(userIds: string[], tx?: EntityManager) {
|
|
150
|
+
if (!userIds.length) return []
|
|
151
|
+
const people = await getRepository(User, tx).find({ where: { id: In(userIds) } as any })
|
|
152
|
+
return people.filter(one => one.status === UserStatus.ACTIVATED).map(one => ({ id: one.id, email: one.email, locale: (one as any).locale }))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The notice of an announcement (notification ADR-0164): in the app and by web push always - the `announcement` type is
|
|
157
|
+
* what pops it up - and by mail when the announcement asks for it and the domain has mail on.
|
|
158
|
+
*/
|
|
159
|
+
function noticeOf(one: Announcement, kind: NoticeKind, receivers: Notice['receivers'], broadcast: boolean, link?: string): Notice {
|
|
160
|
+
return {
|
|
161
|
+
type: 'announcement',
|
|
162
|
+
level: one.importance === 'URGENT' ? 'warn' : 'info',
|
|
163
|
+
receivers,
|
|
164
|
+
words: lng => noticeWordsOf(one, kind, sayIn(lng)),
|
|
165
|
+
address: viewAddressOf(one.id),
|
|
166
|
+
link,
|
|
167
|
+
label: `announcement ${kind} ${one.id}`,
|
|
168
|
+
/* The mail carries the whole body, drawn from its Markdown; the inbox and push show the summary. */
|
|
169
|
+
format: 'markdown',
|
|
170
|
+
channels: { email: !!one.sendEmail },
|
|
171
|
+
/* Said once to the domain's Teams channel too - only what is addressed to everyone, and only when it goes out or all are told again. */
|
|
172
|
+
...(broadcast ? { broadcast: true } : {})
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Keeps what one telling sent on the announcement - in its own transaction, the request's being over. */
|
|
177
|
+
async function recordDelivery(id: string, kind: NoticeKind, result: NoticeResult | undefined, receivers: number): Promise<void> {
|
|
178
|
+
try {
|
|
179
|
+
const repository = getRepository(Announcement)
|
|
180
|
+
const one = await repository.findOneBy({ id })
|
|
181
|
+
if (one) await repository.update(id, { deliveries: withDelivery(one.deliveries, deliveryOf(kind, result, receivers)) } as any)
|
|
182
|
+
} catch (error) {
|
|
183
|
+
logger.error(`announcement ${id}: what was sent could not be kept`, error)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Tells `userIds` of it once the request's transaction has committed - a reader told before it would not find it yet -
|
|
189
|
+
* and keeps what went out. A notice that does not arrive does not undo the announcement: its list, badge and popup
|
|
190
|
+
* still reach them.
|
|
191
|
+
*/
|
|
192
|
+
export async function tellWhenCommitted(context: any, one: Announcement, kind: NoticeKind, userIds: string[], toEveryone = false): Promise<void> {
|
|
193
|
+
const receivers = await receiversOf(userIds, context.state.tx)
|
|
194
|
+
if (!receivers.length) return
|
|
195
|
+
const broadcast = toEveryone && broadcastOf(await audiencesOf(one.id, context.state.tx), context.state.domain?.id)
|
|
196
|
+
sendNoticeWhenCommitted(context, noticeOf(one, kind, receivers, broadcast, noticeLinkOf(context, viewAddressOf(one.id))), result =>
|
|
197
|
+
recordDelivery(one.id, kind, result, receivers.length)
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Publishes the scheduled announcements whose start has come. Each is taken by one update from SCHEDULED, so a server
|
|
203
|
+
* among several that loses the race does not send it twice.
|
|
204
|
+
*/
|
|
205
|
+
export async function publishDue(now = new Date()): Promise<number> {
|
|
206
|
+
const due = await getRepository(Announcement).find({
|
|
207
|
+
where: { status: AnnouncementStatus.SCHEDULED, startsAt: LessThanOrEqual(now), deletedAt: IsNull() } as any,
|
|
208
|
+
relations: ['domain', 'publisher', 'creator'],
|
|
209
|
+
take: 50
|
|
210
|
+
})
|
|
211
|
+
let published = 0
|
|
212
|
+
for (const one of due) {
|
|
213
|
+
try {
|
|
214
|
+
const by = { id: one.publisherId ?? one.creatorId! }
|
|
215
|
+
const receivers = await getDataSource().transaction(async tx => {
|
|
216
|
+
const taken = await tx.getRepository(Announcement).update({ id: one.id, status: AnnouncementStatus.SCHEDULED } as any, { status: AnnouncementStatus.DRAFT } as any)
|
|
217
|
+
if (!taken.affected) return undefined
|
|
218
|
+
return await sendOut({ ...one, status: AnnouncementStatus.DRAFT } as Announcement, one.domain!, by, tx)
|
|
219
|
+
})
|
|
220
|
+
if (!receivers) continue
|
|
221
|
+
published++
|
|
222
|
+
/* No request, so no address to put on a mail button - the mail says where to find it instead. */
|
|
223
|
+
const people = await receiversOf(receivers)
|
|
224
|
+
const broadcast = broadcastOf(await audiencesOf(one.id), one.domain?.id)
|
|
225
|
+
if (people.length) await recordDelivery(one.id, 'published', await sendNotice(one.domain, noticeOf(one, 'published', people, broadcast)), people.length)
|
|
226
|
+
} catch (error) {
|
|
227
|
+
logger.error(`announcement ${one.id}: publishing at its start failed`, error)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return published
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let timer: ReturnType<typeof setInterval> | undefined
|
|
234
|
+
|
|
235
|
+
/** Looks for scheduled announcements every minute. The timer never keeps the process alive. */
|
|
236
|
+
export function schedulePublishing(): void {
|
|
237
|
+
if (timer) return
|
|
238
|
+
timer = setInterval(() => void publishDue().catch(error => logger.error('scheduled announcements', error)), 60 * 1000)
|
|
239
|
+
timer.unref?.()
|
|
240
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { Field, InputType, Int, ObjectType } from 'type-graphql'
|
|
2
|
+
|
|
3
|
+
import { Announcement } from './announcement'
|
|
4
|
+
|
|
5
|
+
@InputType({ description: 'A screen an announcement points to.' })
|
|
6
|
+
export class AnnouncementLinkInput {
|
|
7
|
+
@Field({ description: 'What the link is called on the announcement.' })
|
|
8
|
+
label: string
|
|
9
|
+
|
|
10
|
+
@Field({ description: "A screen of the application by its address (`contract-list?id=…`) or an https page." })
|
|
11
|
+
url: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
@InputType({ description: 'One target of an announcement.' })
|
|
15
|
+
export class AnnouncementAudienceInput {
|
|
16
|
+
@Field({ description: 'DOMAIN, DEPARTMENT (with the departments under it), ROLE or USER.' })
|
|
17
|
+
scope: string
|
|
18
|
+
|
|
19
|
+
@Field({ description: 'The domain, department, role or user id.' })
|
|
20
|
+
targetId: string
|
|
21
|
+
|
|
22
|
+
@Field({ nullable: true, description: 'Its name, shown to the writer.' })
|
|
23
|
+
targetName?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
@InputType({ description: 'What an announcement says, to whom and how.' })
|
|
27
|
+
export class AnnouncementInput {
|
|
28
|
+
@Field({ description: 'The title.' })
|
|
29
|
+
title: string
|
|
30
|
+
|
|
31
|
+
@Field({ nullable: true, description: 'The body, in Markdown.' })
|
|
32
|
+
body?: string
|
|
33
|
+
|
|
34
|
+
@Field({ nullable: true, description: 'The kind - one of the codes the module declares; GENERAL when empty.' })
|
|
35
|
+
category?: string
|
|
36
|
+
|
|
37
|
+
@Field({ nullable: true, description: 'NORMAL, IMPORTANT or URGENT; NORMAL when empty.' })
|
|
38
|
+
importance?: string
|
|
39
|
+
|
|
40
|
+
@Field({ nullable: true, description: 'When it starts to be shown - empty publishes it at once.' })
|
|
41
|
+
startsAt?: Date
|
|
42
|
+
|
|
43
|
+
@Field({ nullable: true, description: 'When it stops being a current one.' })
|
|
44
|
+
endsAt?: Date
|
|
45
|
+
|
|
46
|
+
@Field({ nullable: true, description: 'Kept on top of the list while current.' })
|
|
47
|
+
pinned?: boolean
|
|
48
|
+
|
|
49
|
+
@Field({ nullable: true, description: 'Each reader is asked to acknowledge it.' })
|
|
50
|
+
requiresAcknowledgement?: boolean
|
|
51
|
+
|
|
52
|
+
@Field({ nullable: true, description: 'The day by which readers are asked to acknowledge it.' })
|
|
53
|
+
acknowledgeBy?: Date
|
|
54
|
+
|
|
55
|
+
@Field({ nullable: true, description: 'Shown in a popup to its readers.' })
|
|
56
|
+
popup?: boolean
|
|
57
|
+
|
|
58
|
+
@Field({ nullable: true, description: 'Sent by mail too, where the domain has mail on.' })
|
|
59
|
+
sendEmail?: boolean
|
|
60
|
+
|
|
61
|
+
@Field(type => [AnnouncementLinkInput], { nullable: true, description: 'Screens it points to.' })
|
|
62
|
+
links?: AnnouncementLinkInput[]
|
|
63
|
+
|
|
64
|
+
@Field(type => [AnnouncementAudienceInput], { nullable: true, description: 'Whom it is addressed to - the whole list.' })
|
|
65
|
+
audiences?: AnnouncementAudienceInput[]
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
@ObjectType({ description: 'A page of announcements.' })
|
|
69
|
+
export class AnnouncementList {
|
|
70
|
+
@Field(type => [Announcement], { description: 'The announcements of the page.' })
|
|
71
|
+
items: Announcement[]
|
|
72
|
+
|
|
73
|
+
@Field(type => Int, { description: 'How many there are in all.' })
|
|
74
|
+
total: number
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
@ObjectType({ description: "What the reader still owes the announcements addressed to them that are current." })
|
|
78
|
+
export class AnnouncementSummary {
|
|
79
|
+
@Field(type => Int, { description: 'Current announcements the reader has not read.' })
|
|
80
|
+
unread: number
|
|
81
|
+
|
|
82
|
+
@Field(type => Int, { description: 'Current announcements the reader has not acknowledged though they ask for it.' })
|
|
83
|
+
toAcknowledge: number
|
|
84
|
+
|
|
85
|
+
@Field(type => Int, { description: 'Current announcements still owed anything - unread, or read and not yet acknowledged. The menu badge.' })
|
|
86
|
+
pending: number
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
@ObjectType({ description: "One person's reading of an announcement, for its writer." })
|
|
90
|
+
export class AnnouncementReceiptRow {
|
|
91
|
+
@Field({ description: 'The user id.' })
|
|
92
|
+
userId: string
|
|
93
|
+
|
|
94
|
+
@Field({ nullable: true, description: 'The name.' })
|
|
95
|
+
name?: string
|
|
96
|
+
|
|
97
|
+
@Field({ nullable: true, description: 'The e-mail.' })
|
|
98
|
+
email?: string
|
|
99
|
+
|
|
100
|
+
@Field({ description: 'On the roster - addressed when it went out or when its audience changed.' })
|
|
101
|
+
listed: boolean
|
|
102
|
+
|
|
103
|
+
@Field({ nullable: true, description: 'When they were last told of it.' })
|
|
104
|
+
notifiedAt?: Date
|
|
105
|
+
|
|
106
|
+
@Field({ nullable: true, description: 'When they read it.' })
|
|
107
|
+
readAt?: Date
|
|
108
|
+
|
|
109
|
+
@Field({ nullable: true, description: 'When they acknowledged it.' })
|
|
110
|
+
acknowledgedAt?: Date
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
@ObjectType({ description: 'A target the writer may choose.' })
|
|
114
|
+
export class AnnouncementChoice {
|
|
115
|
+
@Field({ description: 'The id.' })
|
|
116
|
+
id: string
|
|
117
|
+
|
|
118
|
+
@Field({ description: 'The name.' })
|
|
119
|
+
name: string
|
|
120
|
+
|
|
121
|
+
@Field({ nullable: true, description: 'The department above, for a department; the e-mail, for a person.' })
|
|
122
|
+
note?: string
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@ObjectType({ description: 'What an announcement may be addressed to in the domain.' })
|
|
126
|
+
export class AnnouncementAudienceChoices {
|
|
127
|
+
@Field({ description: 'The domain - the whole-domain target names it.' })
|
|
128
|
+
domainId: string
|
|
129
|
+
|
|
130
|
+
@Field({ description: 'The domain name.' })
|
|
131
|
+
domainName: string
|
|
132
|
+
|
|
133
|
+
@Field(type => [AnnouncementChoice], { description: 'The departments of the domain, each reaching those under it.' })
|
|
134
|
+
departments: AnnouncementChoice[]
|
|
135
|
+
|
|
136
|
+
@Field(type => [AnnouncementChoice], { description: 'The roles of the domain, the inherited ones included.' })
|
|
137
|
+
roles: AnnouncementChoice[]
|
|
138
|
+
}
|