@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.
Files changed (122) hide show
  1. package/client/announcement-watch.ts +109 -0
  2. package/client/bootstrap.ts +9 -0
  3. package/client/components/announcement-popup.ts +92 -0
  4. package/client/components/announcement-receipts.ts +196 -0
  5. package/client/components/announcement-sheet.ts +214 -0
  6. package/client/components/audience-picker.ts +221 -0
  7. package/client/index.ts +1 -0
  8. package/client/pages/announcement-editor.ts +505 -0
  9. package/client/pages/announcement-list.ts +200 -0
  10. package/client/pages/announcement-manage-list.ts +113 -0
  11. package/client/pages/announcement-view.ts +172 -0
  12. package/client/route.ts +17 -0
  13. package/client/tsconfig.json +13 -0
  14. package/client/utils/announcement-api.ts +142 -0
  15. package/client/utils/announcement-badge.ts +46 -0
  16. package/client/utils/announcement-words.ts +26 -0
  17. package/dist-client/announcement-watch.d.ts +6 -0
  18. package/dist-client/announcement-watch.js +105 -0
  19. package/dist-client/announcement-watch.js.map +1 -0
  20. package/dist-client/bootstrap.d.ts +1 -0
  21. package/dist-client/bootstrap.js +8 -0
  22. package/dist-client/bootstrap.js.map +1 -0
  23. package/dist-client/components/announcement-popup.d.ts +20 -0
  24. package/dist-client/components/announcement-popup.js +98 -0
  25. package/dist-client/components/announcement-popup.js.map +1 -0
  26. package/dist-client/components/announcement-receipts.d.ts +30 -0
  27. package/dist-client/components/announcement-receipts.js +220 -0
  28. package/dist-client/components/announcement-receipts.js.map +1 -0
  29. package/dist-client/components/announcement-sheet.d.ts +17 -0
  30. package/dist-client/components/announcement-sheet.js +224 -0
  31. package/dist-client/components/announcement-sheet.js.map +1 -0
  32. package/dist-client/components/audience-picker.d.ts +32 -0
  33. package/dist-client/components/audience-picker.js +223 -0
  34. package/dist-client/components/audience-picker.js.map +1 -0
  35. package/dist-client/index.d.ts +1 -0
  36. package/dist-client/index.js +2 -0
  37. package/dist-client/index.js.map +1 -0
  38. package/dist-client/pages/announcement-editor.d.ts +59 -0
  39. package/dist-client/pages/announcement-editor.js +523 -0
  40. package/dist-client/pages/announcement-editor.js.map +1 -0
  41. package/dist-client/pages/announcement-list.d.ts +54 -0
  42. package/dist-client/pages/announcement-list.js +209 -0
  43. package/dist-client/pages/announcement-list.js.map +1 -0
  44. package/dist-client/pages/announcement-manage-list.d.ts +46 -0
  45. package/dist-client/pages/announcement-manage-list.js +115 -0
  46. package/dist-client/pages/announcement-manage-list.js.map +1 -0
  47. package/dist-client/pages/announcement-view.d.ts +30 -0
  48. package/dist-client/pages/announcement-view.js +182 -0
  49. package/dist-client/pages/announcement-view.js.map +1 -0
  50. package/dist-client/route.d.ts +1 -0
  51. package/dist-client/route.js +18 -0
  52. package/dist-client/route.js.map +1 -0
  53. package/dist-client/tsconfig.tsbuildinfo +1 -0
  54. package/dist-client/utils/announcement-api.d.ts +149 -0
  55. package/dist-client/utils/announcement-api.js +52 -0
  56. package/dist-client/utils/announcement-api.js.map +1 -0
  57. package/dist-client/utils/announcement-badge.d.ts +4 -0
  58. package/dist-client/utils/announcement-badge.js +47 -0
  59. package/dist-client/utils/announcement-badge.js.map +1 -0
  60. package/dist-client/utils/announcement-words.d.ts +11 -0
  61. package/dist-client/utils/announcement-words.js +23 -0
  62. package/dist-client/utils/announcement-words.js.map +1 -0
  63. package/dist-server/announcement-read.d.ts +6 -0
  64. package/dist-server/announcement-read.js +45 -0
  65. package/dist-server/announcement-read.js.map +1 -0
  66. package/dist-server/attachment-reader.d.ts +1 -0
  67. package/dist-server/attachment-reader.js +13 -0
  68. package/dist-server/attachment-reader.js.map +1 -0
  69. package/dist-server/index.d.ts +2 -0
  70. package/dist-server/index.js +20 -0
  71. package/dist-server/index.js.map +1 -0
  72. package/dist-server/role-tasks.d.ts +2 -0
  73. package/dist-server/role-tasks.js +13 -0
  74. package/dist-server/role-tasks.js.map +1 -0
  75. package/dist-server/service/announcement/announcement-resolver.d.ts +38 -0
  76. package/dist-server/service/announcement/announcement-resolver.js +664 -0
  77. package/dist-server/service/announcement/announcement-resolver.js.map +1 -0
  78. package/dist-server/service/announcement/announcement-rules.d.ts +150 -0
  79. package/dist-server/service/announcement/announcement-rules.js +227 -0
  80. package/dist-server/service/announcement/announcement-rules.js.map +1 -0
  81. package/dist-server/service/announcement/announcement-service.d.ts +54 -0
  82. package/dist-server/service/announcement/announcement-service.js +248 -0
  83. package/dist-server/service/announcement/announcement-service.js.map +1 -0
  84. package/dist-server/service/announcement/announcement-types.d.ts +54 -0
  85. package/dist-server/service/announcement/announcement-types.js +203 -0
  86. package/dist-server/service/announcement/announcement-types.js.map +1 -0
  87. package/dist-server/service/announcement/announcement.d.ts +124 -0
  88. package/dist-server/service/announcement/announcement.js +462 -0
  89. package/dist-server/service/announcement/announcement.js.map +1 -0
  90. package/dist-server/service/announcement/index.d.ts +4 -0
  91. package/dist-server/service/announcement/index.js +8 -0
  92. package/dist-server/service/announcement/index.js.map +1 -0
  93. package/dist-server/service/index.d.ts +7 -0
  94. package/dist-server/service/index.js +23 -0
  95. package/dist-server/service/index.js.map +1 -0
  96. package/dist-server/tsconfig.tsbuildinfo +1 -0
  97. package/package.json +51 -4
  98. package/server/announcement-read.ts +44 -0
  99. package/server/attachment-reader.ts +11 -0
  100. package/server/index.ts +16 -0
  101. package/server/role-tasks.ts +12 -0
  102. package/server/service/announcement/announcement-resolver.ts +506 -0
  103. package/server/service/announcement/announcement-rules.ts +239 -0
  104. package/server/service/announcement/announcement-service.ts +240 -0
  105. package/server/service/announcement/announcement-types.ts +138 -0
  106. package/server/service/announcement/announcement.ts +367 -0
  107. package/server/service/announcement/index.ts +5 -0
  108. package/server/service/index.ts +19 -0
  109. package/server/tsconfig.json +11 -0
  110. package/test/announcement-persistence.test.ts +271 -0
  111. package/test/announcement-read.test.ts +49 -0
  112. package/test/announcement-rules.test.ts +217 -0
  113. package/test/open-doors.test.ts +45 -0
  114. package/test/translations.test.ts +54 -0
  115. package/things-factory.config.js +13 -0
  116. package/translations/en.json +169 -0
  117. package/translations/es.json +169 -0
  118. package/translations/ja.json +169 -0
  119. package/translations/ko.json +169 -0
  120. package/translations/ms.json +169 -0
  121. package/translations/zh.json +169 -0
  122. package/README.md +0 -3
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@things-factory/announcement",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "10.1.222",
4
+ "main": "dist-server/index.js",
5
+ "browser": "dist-client/index.js",
6
+ "things-factory": true,
7
+ "license": "MIT",
8
+ "author": "heartyoh <heartyoh@hatiolab.com>",
9
+ "description": "Announcements - written once, addressed to an audience, read and acknowledged by each of its people",
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "@things-factory:registry": "https://registry.npmjs.org"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/hatiolab/things-factory.git",
17
+ "directory": "packages/announcement"
18
+ },
19
+ "scripts": {
20
+ "build": "npm run build:server && npm run build:client",
21
+ "copy:files": "copyfiles -e \"./client/**/*.{ts,js,json}\" -u 1 \"./client/**/*\" dist-client",
22
+ "build:client": "npm run clean:client && npm run copy:files && npx tsc --p ./client/tsconfig.json",
23
+ "build:server": "npm run clean:server && npx tsc --p ./server/tsconfig.json",
24
+ "clean:server": "rm -rf dist-server",
25
+ "clean:client": "rm -rf dist-client",
26
+ "clean": "npm run clean:server && npm run clean:client"
27
+ },
28
+ "dependencies": {
29
+ "@material/web": "^2.0.0",
30
+ "@operato/data-grist": "^10.0.0",
31
+ "@operato/graphql": "^10.29.39",
32
+ "@operato/i18n": "^10.0.0",
33
+ "@operato/input": "^10.29.43",
34
+ "@operato/layout": "^10.29.49",
35
+ "@operato/popup": "^10.29.39",
36
+ "@operato/shell": "^10.29.39",
37
+ "@operato/styles": "^10.29.1",
38
+ "@operato/utils": "^10.0.0",
39
+ "@things-factory/ai-assistant": "^10.1.222",
40
+ "@things-factory/attachment-base": "^10.1.218",
41
+ "@things-factory/auth-base": "^10.1.218",
42
+ "@things-factory/env": "^10.1.149",
43
+ "@things-factory/i18n-base": "^10.1.218",
44
+ "@things-factory/notification": "^10.1.222",
45
+ "@things-factory/organization": "^10.1.222",
46
+ "@things-factory/shell": "^10.1.208",
47
+ "graphql-scalars": "^1.22.0",
48
+ "graphql-tag": "^2.12.6",
49
+ "graphql-upload": "^15.0.2",
50
+ "lit": "^3.1.2"
51
+ },
52
+ "gitHead": "afdd6a9b1c8b440e39d4fec48bfbad1a0c02fccc"
53
+ }
@@ -0,0 +1,44 @@
1
+ import { listReadTarget, registerReadTarget, type ListRead } from '@things-factory/ai-assistant'
2
+
3
+ import { READER_STATES } from './service/announcement/announcement-rules'
4
+
5
+ /*
6
+ * 공지사항 as the assistant reads it (ADR-0163 decision 8) - the readers' own list query, as the person: only what is
7
+ * addressed to them and out, with their own reading of each. So it is `mine` - a card made of it shows each viewer
8
+ * their own announcements - and it is a source for 나의 대시보드 cards (ADR-0160) as every read target is.
9
+ *
10
+ * `status` narrows by the reader's state (unread, to acknowledge …), which the server works out from the reader's own
11
+ * receipts; `period` (current | past) is a column, a card's match keeps the current ones.
12
+ */
13
+ export const ANNOUNCEMENT_LIST_READ: ListRead = {
14
+ key: 'announcement.list',
15
+ title: 'announcement.title.list',
16
+ name: 'Announcements (공지사항) addressed to the person - current and past, each with their own reading state (unread, read, to-acknowledge, acknowledged)',
17
+ listQuery: 'announcements',
18
+ selection: 'id title body category importance pinned requiresAcknowledgement acknowledgeBy publishedAt endsAt period readerState publisher { name }',
19
+ columns: [
20
+ { name: 'title', type: 'string', labelKey: 'announcement.field.title' },
21
+ { name: 'category', type: 'string', labelKey: 'announcement.field.category', words: 'announcement.category.' },
22
+ { name: 'importance', type: 'string', labelKey: 'announcement.field.importance', words: 'announcement.importance.' },
23
+ { name: 'readerState', type: 'string', labelKey: 'announcement.field.reader-state', words: 'announcement.reader-state.' },
24
+ { name: 'period', type: 'string', labelKey: 'announcement.text.period', words: 'announcement.period.' },
25
+ { name: 'publishedAt', type: 'date', labelKey: 'announcement.field.published-at' },
26
+ { name: 'endsAt', type: 'date', labelKey: 'announcement.field.ends-at' },
27
+ { name: 'acknowledgeBy', type: 'date', labelKey: 'announcement.field.acknowledge-by' },
28
+ { name: 'publisher', path: 'publisher.name', type: 'string', labelKey: 'announcement.field.publisher' },
29
+ { name: 'body', type: 'string' }
30
+ ],
31
+ dateField: 'publishedAt',
32
+ status: { field: 'readerState', values: [...READER_STATES] },
33
+ search: 'fields title, body, category',
34
+ route: 'announcement-list',
35
+ mine: true
36
+ }
37
+
38
+ /** The keys an application's assistant mode names in its `readTargets` to read announcements. */
39
+ export const ANNOUNCEMENT_READ_TARGETS = [ANNOUNCEMENT_LIST_READ.key]
40
+
41
+ /** At boot: the assistant may read the announcements, in a mode that names them. */
42
+ export function registerAnnouncementReads(): void {
43
+ registerReadTarget(listReadTarget(ANNOUNCEMENT_LIST_READ))
44
+ }
@@ -0,0 +1,11 @@
1
+ /*
2
+ * Who may open an announcement's file by its path - whoever may see the announcement (ADR-0163 decision 2): its audience
3
+ * once it is out, its writers. attachment-base has already checked the file is of the request's domain.
4
+ */
5
+ import { registerAttachmentReader } from '@things-factory/attachment-base'
6
+
7
+ import { ANNOUNCEMENT_REF_TYPE, visibleAnnouncement } from './service/announcement/announcement-service'
8
+
9
+ export function registerAnnouncementFiles(): void {
10
+ registerAttachmentReader(ANNOUNCEMENT_REF_TYPE, async (attachment, context) => !!attachment.refBy && !!(await visibleAnnouncement(attachment.refBy, context)))
11
+ }
@@ -0,0 +1,16 @@
1
+ export * from './service'
2
+ export { ANNOUNCEMENT_LIST_READ, ANNOUNCEMENT_READ_TARGETS } from './announcement-read'
3
+
4
+ import { registerRoleTask } from '@things-factory/auth-base'
5
+
6
+ import { registerAnnouncementReads } from './announcement-read'
7
+ import { registerAnnouncementFiles } from './attachment-reader'
8
+ import { ROLE_TASKS } from './role-tasks'
9
+ import { schedulePublishing } from './service/announcement/announcement-service'
10
+
11
+ for (const task of ROLE_TASKS) registerRoleTask(task)
12
+ registerAnnouncementFiles()
13
+ registerAnnouncementReads()
14
+
15
+ /* Scheduled announcements go out at their start (ADR-0163 decision 4). */
16
+ process.on('bootstrap-module-start' as any, () => schedulePublishing())
@@ -0,0 +1,12 @@
1
+ /*
2
+ * The work this module names, for the seats applications build (ADR-0139 decision 11).
3
+ *
4
+ * Reading announcements is no task: an announcement is read by the people it names (ADR-0163 decision 2). Writing,
5
+ * publishing, withdrawing and seeing who read them is `announcement.writing`.
6
+ *
7
+ * Data only - `server/index.ts` registers it - so an application's tests read it without starting the framework.
8
+ */
9
+
10
+ import type { RoleTask } from '@things-factory/auth-base'
11
+
12
+ export const ROLE_TASKS: RoleTask[] = [{ id: 'announcement.writing', grants: [{ category: 'announcement', axes: ['mutation'] }] }]
@@ -0,0 +1,506 @@
1
+ /*
2
+ * The doors of announcements (ADR-0163 decisions 2-5).
3
+ *
4
+ * Reading is not a privilege: an announcement is read by the people it names, so the reader's doors are open to anyone
5
+ * signed in to the domain and each asks the audience itself (announcement-service.ts). Writing, managing and the
6
+ * reading record of others are `announcement:mutation` - the module's task `announcement.writing`.
7
+ */
8
+ import type { FileUpload } from 'graphql-upload/GraphQLUpload.js'
9
+ import GraphQLUpload from 'graphql-upload/GraphQLUpload.js'
10
+ import { Arg, Args, Ctx, Directive, FieldResolver, Int, Mutation, Query, Resolver, Root } from 'type-graphql'
11
+ import { In, IsNull, MoreThan, Not } from 'typeorm'
12
+
13
+ import { Attachment, createAttachment, deleteAttachment, deleteAttachmentsByRef } from '@things-factory/attachment-base'
14
+ import { getDomainAssignees, User } from '@things-factory/auth-base'
15
+ import { audienceTargetRefusal, audienceUserIds, Department, departmentTreeOf, domainRolesOf } from '@things-factory/organization'
16
+ import { getQueryBuilderFromListParams, getRepository, ListParam } from '@things-factory/shell'
17
+
18
+ import { Announcement, AnnouncementAudience, AnnouncementImportance, AnnouncementReceipt, AnnouncementRevision, AnnouncementStatus } from './announcement'
19
+ import { inputRefusal, isCurrent, owedReminder, periodOf, popupDue, publishedStatusOf, publishRefusal, rankOf, readerNarrowingOf, readerStateOf } from './announcement-rules'
20
+ import {
21
+ alignRoster,
22
+ ANNOUNCEMENT_REF_TYPE,
23
+ audiencesOf,
24
+ isWriter,
25
+ keepRevision,
26
+ memberOf,
27
+ reachingIds,
28
+ sendOut,
29
+ tellWhenCommitted,
30
+ visibleAnnouncement
31
+ } from './announcement-service'
32
+ import {
33
+ AnnouncementAudienceChoices,
34
+ AnnouncementAudienceInput,
35
+ AnnouncementChoice,
36
+ AnnouncementInput,
37
+ AnnouncementList,
38
+ AnnouncementReceiptRow,
39
+ AnnouncementSummary
40
+ } from './announcement-types'
41
+
42
+ const WRITE = '@privilege(category: "announcement", privilege: "mutation", domainOwnerGranted: true)'
43
+
44
+ /** A refusal said in the reader's words, with a code the screen may read. */
45
+ function refuse(context: ResolverContext, code: string, fallback: string): never {
46
+ const message = context.t ? String(context.t(`announcement.refusal.${code}`, { defaultValue: fallback })) : fallback
47
+ const error: any = new Error(message)
48
+ error.extensions = { code: `announcement.${code}` }
49
+ throw error
50
+ }
51
+
52
+ const NOT_FOUND = 'there is no such announcement.'
53
+
54
+ /** The announcement the request may see, refused otherwise. */
55
+ async function visibleOrRefuse(id: string, context: ResolverContext, tx?: any) {
56
+ const visible = await visibleAnnouncement(id, context, tx)
57
+ if (!visible) refuse(context, 'unknown-announcement', NOT_FOUND)
58
+ return visible
59
+ }
60
+
61
+ /** One the writer may change: any that is not somebody else's draft, and not withdrawn. */
62
+ async function changeable(id: string, context: ResolverContext, tx: any): Promise<Announcement> {
63
+ const visible = await visibleOrRefuse(id, context, tx)
64
+ if (!visible.writer) refuse(context, 'unknown-announcement', NOT_FOUND)
65
+ if (visible.announcement.status === AnnouncementStatus.WITHDRAWN) refuse(context, 'withdrawn', 'a withdrawn announcement is not changed.')
66
+ return visible.announcement
67
+ }
68
+
69
+ /** The fields of the input as stored, checked against the rules. */
70
+ function fieldsOf(input: AnnouncementInput, context: ResolverContext) {
71
+ const refusal = inputRefusal(input)
72
+ if (refusal) refuse(context, refusal, `the announcement cannot be kept (${refusal}).`)
73
+ const importance = (input.importance as AnnouncementImportance) || AnnouncementImportance.NORMAL
74
+ const pinned = !!input.pinned
75
+ return {
76
+ title: input.title.trim(),
77
+ body: input.body ?? null,
78
+ category: input.category || 'GENERAL',
79
+ importance,
80
+ startsAt: input.startsAt ?? null,
81
+ endsAt: input.endsAt ?? null,
82
+ pinned,
83
+ rank: rankOf({ pinned, importance }),
84
+ requiresAcknowledgement: !!input.requiresAcknowledgement,
85
+ acknowledgeBy: input.requiresAcknowledgement ? (input.acknowledgeBy ?? null) : null,
86
+ popup: !!input.popup,
87
+ sendEmail: !!input.sendEmail,
88
+ links: (input.links ?? []).map(({ label, url }) => ({ label: label.trim(), url: url.trim() }))
89
+ }
90
+ }
91
+
92
+ /** Sets the whole audience - each target checked against the domain - and answers whether it changed. */
93
+ async function setAudiences(announcement: Announcement, wanted: AnnouncementAudienceInput[], context: ResolverContext, tx: any): Promise<boolean> {
94
+ const { domain, user } = context.state
95
+ const scopes = new Set(wanted.map(one => one.scope))
96
+ const departmentIds = scopes.has('DEPARTMENT') ? [...(await departmentTreeOf(domain, tx)).keys()] : []
97
+ const roleIds = scopes.has('ROLE') ? (await domainRolesOf(domain, undefined, tx)).map(one => one.id) : []
98
+ const people = scopes.has('USER') ? new Set((await getDomainAssignees(domain as any, tx)).map(one => one.id)) : new Set<string>()
99
+ const byKey = new Map<string, AnnouncementAudienceInput>()
100
+ for (const target of wanted) {
101
+ const refusal = audienceTargetRefusal(target, { domainId: domain.id, departmentIds, roleIds }) ?? (target.scope === 'USER' && !people.has(target.targetId) ? 'unknown-person' : undefined)
102
+ if (refusal) refuse(context, `audience-${refusal}`, `this target cannot be given (${refusal}).`)
103
+ byKey.set(`${target.scope}:${target.targetId}`, target)
104
+ }
105
+ const repository = getRepository(AnnouncementAudience, tx)
106
+ const current = await audiencesOf(announcement.id, tx)
107
+ const gone = current.filter(one => !byKey.has(`${one.scope}:${one.targetId}`))
108
+ if (gone.length) await repository.softRemove(gone)
109
+ let added = 0
110
+ for (const [key, target] of byKey) {
111
+ if (current.some(one => `${one.scope}:${one.targetId}` === key)) continue
112
+ added++
113
+ await repository.save({ domain, announcement: { id: announcement.id }, scope: target.scope, targetId: target.targetId, targetName: target.targetName?.slice(0, 100), creator: user, updater: user } as any)
114
+ }
115
+ return gone.length + added > 0
116
+ }
117
+
118
+ async function attachFiles(announcementId: string, attach: FileUpload[] | undefined, remove: string[] | undefined, context: ResolverContext) {
119
+ for (const id of remove ?? []) {
120
+ const file = await getRepository(Attachment, context.state.tx).findOne({ where: { id, domain: { id: context.state.domain.id }, refType: ANNOUNCEMENT_REF_TYPE, refBy: announcementId } as any })
121
+ if (file) await deleteAttachment(null, { id }, context)
122
+ }
123
+ for (const file of attach ?? []) {
124
+ await createAttachment(null, { attachment: { file, refType: ANNOUNCEMENT_REF_TYPE, refBy: announcementId } } as any, context)
125
+ }
126
+ }
127
+
128
+ /** The reader's own receipts of `ids`, by announcement. */
129
+ async function myReceipts(ids: string[], userId: string, tx?: any): Promise<Map<string, AnnouncementReceipt>> {
130
+ if (!ids.length) return new Map()
131
+ const rows = await getRepository(AnnouncementReceipt, tx).find({ where: { announcement: { id: In(ids) }, user: { id: userId } } as any })
132
+ return new Map(rows.map(one => [one.announcementId!, one]))
133
+ }
134
+
135
+ /** The current announcements addressed to the request's person, with their receipts. */
136
+ async function currentForReader(context: ResolverContext) {
137
+ const { domain, user } = context.state
138
+ const ids = await reachingIds(await memberOf(context))
139
+ if (!ids.length) return { items: [] as Announcement[], receipts: new Map<string, AnnouncementReceipt>() }
140
+ const now = new Date()
141
+ const items = await getRepository(Announcement).find({
142
+ where: [
143
+ { id: In(ids), domain: { id: domain.id }, status: AnnouncementStatus.PUBLISHED, endsAt: IsNull() },
144
+ { id: In(ids), domain: { id: domain.id }, status: AnnouncementStatus.PUBLISHED, endsAt: MoreThan(now) }
145
+ ] as any,
146
+ order: { rank: 'ASC', publishedAt: 'DESC' } as any
147
+ })
148
+ return { items, receipts: await myReceipts(items.map(one => one.id), user.id) }
149
+ }
150
+
151
+ @Resolver(Announcement)
152
+ export class AnnouncementResolver {
153
+ /* ---------------------------------------------------------------- reading - the audience */
154
+
155
+ @Query(returns => AnnouncementList, {
156
+ description:
157
+ "The announcements addressed to the request's person that are out. Two filters are the reader's own: `period` (current | past) and `readerState` (unread, read, to-acknowledge, acknowledged - one or several, with `in`). The current ones come pinned, urgent and important first; otherwise the newest first."
158
+ })
159
+ async announcements(@Args(type => ListParam) params: ListParam, @Ctx() context: ResolverContext): Promise<AnnouncementList> {
160
+ const { domain, user } = context.state
161
+ const { rest, period, states, refusal } = readerNarrowingOf(params.filters as any)
162
+ if (refusal) refuse(context, refusal, `the list cannot be narrowed so (${refusal}).`)
163
+ let ids = await reachingIds(await memberOf(context))
164
+ if (states && ids.length) {
165
+ const candidates = await getRepository(Announcement).find({ where: { id: In(ids), status: AnnouncementStatus.PUBLISHED } as any })
166
+ const receipts = await myReceipts(
167
+ candidates.map(one => one.id),
168
+ user.id
169
+ )
170
+ ids = candidates.filter(one => states.includes(readerStateOf(one, receipts.get(one.id)))).map(one => one.id)
171
+ }
172
+ if (!ids.length) return { items: [], total: 0 }
173
+ const now = new Date()
174
+ const qb = getQueryBuilderFromListParams({
175
+ domain,
176
+ params: { ...params, filters: rest as any, sortings: [] },
177
+ repository: getRepository(Announcement),
178
+ alias: 'A',
179
+ searchables: ['title', 'body', 'category']
180
+ })
181
+ .andWhere('A.id IN (:...ids)', { ids })
182
+ .andWhere('A.status = :published', { published: AnnouncementStatus.PUBLISHED })
183
+ if (period === 'past') qb.andWhere('A.endsAt <= :now', { now })
184
+ if (period === 'current') qb.andWhere('(A.endsAt IS NULL OR A.endsAt > :now)', { now }).orderBy('A.rank', 'ASC').addOrderBy('A.publishedAt', 'DESC')
185
+ else qb.orderBy('A.publishedAt', 'DESC')
186
+ const [items, total] = await qb.getManyAndCount()
187
+ const receipts = await myReceipts(
188
+ items.map(one => one.id),
189
+ user.id
190
+ )
191
+ for (const one of items) (one as any).__mine = receipts.get(one.id) ?? null
192
+ return { items, total }
193
+ }
194
+
195
+ @Query(returns => Announcement, { nullable: true, description: 'One announcement - to its audience once it is out, to a writer whatever its status (not somebody else\'s draft).' })
196
+ async announcement(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<Announcement | undefined> {
197
+ return (await visibleAnnouncement(id, context))?.announcement
198
+ }
199
+
200
+ @Query(returns => AnnouncementSummary, { description: 'How many current announcements addressed to the person are unread, and how many await their acknowledgement.' })
201
+ async announcementSummary(@Ctx() context: ResolverContext): Promise<AnnouncementSummary> {
202
+ const { items, receipts } = await currentForReader(context)
203
+ let unread = 0
204
+ let toAcknowledge = 0
205
+ let pending = 0
206
+ for (const one of items) {
207
+ const state = readerStateOf(one, receipts.get(one.id))
208
+ if (state === 'unread') unread++
209
+ if (one.requiresAcknowledgement && state !== 'acknowledged') toAcknowledge++
210
+ if (state === 'unread' || state === 'to-acknowledge') pending++
211
+ }
212
+ return { unread, toAcknowledge, pending }
213
+ }
214
+
215
+ @Query(returns => [Announcement], { description: 'The announcements that pop up for the person now - unread popup ones, and those still to be acknowledged.' })
216
+ async announcementPopups(@Ctx() context: ResolverContext): Promise<Announcement[]> {
217
+ const { items, receipts } = await currentForReader(context)
218
+ const now = new Date()
219
+ return items.filter(one => popupDue(one, receipts.get(one.id), now)).map(one => Object.assign(one, { __mine: receipts.get(one.id) ?? null }))
220
+ }
221
+
222
+ @Directive('@transaction')
223
+ @Mutation(returns => Announcement, { description: 'Records that the person read the announcement - once; reading it again changes nothing.' })
224
+ async readAnnouncement(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<Announcement> {
225
+ return await this.receive(id, context, false)
226
+ }
227
+
228
+ @Directive('@transaction')
229
+ @Mutation(returns => Announcement, { description: 'Records that the person acknowledged an announcement that asks for it - reading it too.' })
230
+ async acknowledgeAnnouncement(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<Announcement> {
231
+ return await this.receive(id, context, true)
232
+ }
233
+
234
+ private async receive(id: string, context: ResolverContext, acknowledge: boolean): Promise<Announcement> {
235
+ const { domain, user, tx } = context.state as any
236
+ const visible = await visibleOrRefuse(id, context, tx)
237
+ /* Only its audience reads it into the record - a writer looking at one addressed to others leaves no trace. */
238
+ if (!visible.reader) return visible.announcement
239
+ if (acknowledge && !visible.announcement.requiresAcknowledgement) refuse(context, 'no-acknowledgement', 'this announcement does not ask to be acknowledged.')
240
+ const repository = getRepository(AnnouncementReceipt, tx)
241
+ const now = new Date()
242
+ const receipt = await repository.findOne({ where: { announcement: { id }, user: { id: user.id } } as any })
243
+ const patch: any = {}
244
+ if (!receipt?.readAt) patch.readAt = now
245
+ if (acknowledge && !receipt?.acknowledgedAt) patch.acknowledgedAt = now
246
+ if (!receipt) await repository.save({ domain, announcement: { id }, user: { id: user.id }, listed: false, ...patch, creator: user, updater: user } as any)
247
+ else if (Object.keys(patch).length) await repository.update(receipt.id, { ...patch, updater: user })
248
+ return visible.announcement
249
+ }
250
+
251
+ /* ---------------------------------------------------------------- writing and managing */
252
+
253
+ @Directive(WRITE)
254
+ @Query(returns => AnnouncementList, { description: "Every announcement of the domain for its writers - all that are out, scheduled or withdrawn, and the writer's own drafts." })
255
+ async managedAnnouncements(@Args(type => ListParam) params: ListParam, @Ctx() context: ResolverContext): Promise<AnnouncementList> {
256
+ const { domain, user } = context.state
257
+ const qb = getQueryBuilderFromListParams({
258
+ domain,
259
+ params,
260
+ repository: getRepository(Announcement),
261
+ alias: 'A',
262
+ searchables: ['title', 'body', 'category']
263
+ }).andWhere('(A.status != :draft OR A.creator = :me)', { draft: AnnouncementStatus.DRAFT, me: user.id })
264
+ if (!params.sortings?.length) qb.orderBy('A.updatedAt', 'DESC')
265
+ const [items, total] = await qb.getManyAndCount()
266
+ return { items, total }
267
+ }
268
+
269
+ @Directive(WRITE)
270
+ @Query(returns => [AnnouncementReceiptRow], { description: 'Who on the roster read and acknowledged it, and who came to it later - for its writers.' })
271
+ async announcementReceipts(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<AnnouncementReceiptRow[]> {
272
+ const visible = await visibleOrRefuse(id, context)
273
+ if (!visible.writer) refuse(context, 'unknown-announcement', NOT_FOUND)
274
+ const receipts = await getRepository(AnnouncementReceipt).find({ where: { announcement: { id } } as any, relations: ['user'] })
275
+ return receipts
276
+ .map(one => ({
277
+ userId: one.userId!,
278
+ name: one.user?.name,
279
+ email: one.user?.email,
280
+ listed: one.listed,
281
+ notifiedAt: one.notifiedAt,
282
+ readAt: one.readAt,
283
+ acknowledgedAt: one.acknowledgedAt
284
+ }))
285
+ .sort((a, b) => Number(!!a.readAt) - Number(!!b.readAt) || String(a.name ?? '').localeCompare(String(b.name ?? '')))
286
+ }
287
+
288
+ @Directive(WRITE)
289
+ @Query(returns => [AnnouncementRevision], { description: 'The versions of an announcement since it went out, newest first - for its writers.' })
290
+ async announcementRevisions(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<AnnouncementRevision[]> {
291
+ const visible = await visibleOrRefuse(id, context)
292
+ if (!visible.writer) refuse(context, 'unknown-announcement', NOT_FOUND)
293
+ return await getRepository(AnnouncementRevision).find({ where: { announcement: { id } } as any, order: { version: 'DESC' } as any, relations: ['creator'] })
294
+ }
295
+
296
+ @Directive(WRITE)
297
+ @Query(returns => AnnouncementAudienceChoices, { description: 'What an announcement may be addressed to - the domain, its departments and its roles.' })
298
+ async announcementAudienceChoices(@Ctx() context: ResolverContext): Promise<AnnouncementAudienceChoices> {
299
+ const domain: any = context.state.domain
300
+ const tree = await departmentTreeOf(domain)
301
+ const departments = tree.size ? await getRepository(Department).find({ where: { id: In([...tree.keys()]) } as any, order: { name: 'ASC' } as any }) : []
302
+ const nameOf = new Map(departments.map(one => [one.id, one.name]))
303
+ return {
304
+ domainId: domain.id,
305
+ domainName: domain.name ?? domain.subdomain ?? domain.id,
306
+ departments: departments.map(one => ({ id: one.id, name: one.name, note: nameOf.get(tree.get(one.id) ?? '') ?? undefined })),
307
+ roles: (await domainRolesOf(domain)).map(one => ({ id: one.id, name: one.name, note: one.description ?? undefined }))
308
+ }
309
+ }
310
+
311
+ @Directive(WRITE)
312
+ @Query(returns => [AnnouncementChoice], { description: 'People of the domain an announcement may be addressed to, found by name or e-mail.' })
313
+ async announcementPeople(@Arg('text') text: string, @Ctx() context: ResolverContext): Promise<AnnouncementChoice[]> {
314
+ const words = (text ?? '').trim().toLowerCase()
315
+ if (!words) return []
316
+ return (await getDomainAssignees(context.state.domain as any))
317
+ .filter(one => `${one.name ?? ''} ${one.email ?? ''}`.toLowerCase().includes(words))
318
+ .slice(0, 20)
319
+ .map(one => ({ id: one.id, name: one.name || one.email, note: one.email }))
320
+ }
321
+
322
+ @Directive(WRITE)
323
+ @Query(returns => Int, { description: 'How many people an audience names now - shown before it is sent.' })
324
+ async announcementAudienceSize(@Arg('audiences', type => [AnnouncementAudienceInput]) audiences: AnnouncementAudienceInput[], @Ctx() context: ResolverContext): Promise<number> {
325
+ return (await audienceUserIds(context.state.domain, audiences ?? [])).length
326
+ }
327
+
328
+ @Directive(WRITE)
329
+ @Directive('@transaction')
330
+ @Mutation(returns => Announcement, { description: 'Writes a new announcement as a draft, with its files.' })
331
+ async createAnnouncement(
332
+ @Arg('input', type => AnnouncementInput) input: AnnouncementInput,
333
+ @Arg('attach', type => [GraphQLUpload], { nullable: true }) attach: FileUpload[],
334
+ @Ctx() context: ResolverContext
335
+ ): Promise<Announcement> {
336
+ const { domain, user, tx } = context.state as any
337
+ const saved = await getRepository(Announcement, tx).save({ ...fieldsOf(input, context), domain, status: AnnouncementStatus.DRAFT, version: 1, creator: user, updater: user } as any)
338
+ await setAudiences(saved, input.audiences ?? [], context, tx)
339
+ await attachFiles(saved.id, attach, [], context)
340
+ return saved
341
+ }
342
+
343
+ @Directive(WRITE)
344
+ @Directive('@transaction')
345
+ @Mutation(returns => Announcement, {
346
+ description:
347
+ 'Changes an announcement. Once out, each change is a new version; people the audience now names who were not told are told, and `notifyAgain` tells everyone on the roster again.'
348
+ })
349
+ async updateAnnouncement(
350
+ @Arg('id') id: string,
351
+ @Arg('input', type => AnnouncementInput) input: AnnouncementInput,
352
+ @Arg('attach', type => [GraphQLUpload], { nullable: true }) attach: FileUpload[],
353
+ @Arg('remove', type => [String], { nullable: true, description: 'Ids of its files to take off.' }) remove: string[],
354
+ @Arg('notifyAgain', { nullable: true, description: 'Tell everyone on the roster of the change.' }) notifyAgain: boolean,
355
+ @Ctx() context: ResolverContext
356
+ ): Promise<Announcement> {
357
+ const { domain, user, tx } = context.state as any
358
+ const announcement = await changeable(id, context, tx)
359
+ const fields = fieldsOf(input, context)
360
+ const out = announcement.status === AnnouncementStatus.PUBLISHED
361
+ /* Once out, its start is the moment it went out - a start set later would hide it again. */
362
+ if (out) fields.startsAt = announcement.startsAt
363
+ const repository = getRepository(Announcement, tx)
364
+ await repository.update(id, { ...fields, ...(out ? { version: announcement.version + 1 } : {}), updater: user } as any)
365
+ const audienceChanged = await setAudiences(announcement, input.audiences ?? [], context, tx)
366
+ if (out && !(input.audiences ?? []).length) refuse(context, 'no-audience', 'an announcement that is out names someone.')
367
+ await attachFiles(id, attach, remove, context)
368
+ const fresh = (await repository.findOneBy({ id }))!
369
+ if (!out) return fresh
370
+ await keepRevision(fresh, domain, user, tx)
371
+ const added = audienceChanged ? await alignRoster(fresh, domain, user, tx) : []
372
+ const receivers = notifyAgain
373
+ ? (await getRepository(AnnouncementReceipt, tx).find({ where: { announcement: { id }, listed: true } as any })).map(one => one.userId!)
374
+ : added
375
+ if (notifyAgain) await getRepository(AnnouncementReceipt, tx).update({ announcement: { id }, listed: true } as any, { notifiedAt: new Date() } as any)
376
+ /* Told again, everyone hears it - the channel too; people the audience newly names are told one by one. */
377
+ await tellWhenCommitted(context, fresh, notifyAgain ? 'changed' : 'published', receivers.filter(one => one !== user.id), !!notifyAgain)
378
+ return fresh
379
+ }
380
+
381
+ @Directive(WRITE)
382
+ @Directive('@transaction')
383
+ @Mutation(returns => Announcement, { description: 'Sends a draft out to its audience - at once, or at its start when that is still to come.' })
384
+ async publishAnnouncement(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<Announcement> {
385
+ const { domain, user, tx } = context.state as any
386
+ const announcement = await changeable(id, context, tx)
387
+ const audiences = await audiencesOf(id, tx)
388
+ const refusal = publishRefusal(announcement.status, announcement, audiences.length)
389
+ if (refusal) refuse(context, refusal, `the announcement cannot go out (${refusal}).`)
390
+ const repository = getRepository(Announcement, tx)
391
+ if (publishedStatusOf(announcement.startsAt) === 'SCHEDULED') {
392
+ await repository.update(id, { status: AnnouncementStatus.SCHEDULED, publisher: user, updater: user } as any)
393
+ return (await repository.findOneBy({ id }))!
394
+ }
395
+ const receivers = await sendOut(announcement, domain, user, tx)
396
+ const fresh = (await repository.findOneBy({ id }))!
397
+ await tellWhenCommitted(context, fresh, 'published', receivers, true)
398
+ return fresh
399
+ }
400
+
401
+ @Directive(WRITE)
402
+ @Directive('@transaction')
403
+ @Mutation(returns => Announcement, { description: 'Takes back an announcement that is out or scheduled, with the reason. Its audience no longer sees it; its record stays.' })
404
+ async withdrawAnnouncement(@Arg('id') id: string, @Arg('reason') reason: string, @Ctx() context: ResolverContext): Promise<Announcement> {
405
+ const { user, tx } = context.state as any
406
+ const announcement = await changeable(id, context, tx)
407
+ if (announcement.status === AnnouncementStatus.DRAFT) refuse(context, 'not-out', 'a draft is deleted, not withdrawn.')
408
+ if (!reason?.trim()) refuse(context, 'no-reason', 'say why it is withdrawn.')
409
+ const repository = getRepository(Announcement, tx)
410
+ await repository.update(id, { status: AnnouncementStatus.WITHDRAWN, withdrawnAt: new Date(), withdrawReason: reason.trim().slice(0, 500), updater: user } as any)
411
+ return (await repository.findOneBy({ id }))!
412
+ }
413
+
414
+ @Directive(WRITE)
415
+ @Directive('@transaction')
416
+ @Mutation(returns => Boolean, { description: "Deletes one's own draft and its files. An announcement that went out is withdrawn instead." })
417
+ async deleteAnnouncement(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<boolean> {
418
+ const { tx } = context.state as any
419
+ const announcement = await changeable(id, context, tx)
420
+ if (announcement.status !== AnnouncementStatus.DRAFT) refuse(context, 'not-a-draft', 'an announcement that went out is withdrawn, not deleted.')
421
+ await deleteAttachmentsByRef(null, { refBys: [id], refType: ANNOUNCEMENT_REF_TYPE }, context)
422
+ await getRepository(Announcement, tx).softDelete(id)
423
+ return true
424
+ }
425
+
426
+ @Directive(WRITE)
427
+ @Directive('@transaction')
428
+ @Mutation(returns => Int, { description: 'Tells again those on the roster who have not read it - or not acknowledged it, when it asks for that. Answers how many were told.' })
429
+ async remindAnnouncement(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<number> {
430
+ const { user, tx } = context.state as any
431
+ const announcement = await changeable(id, context, tx)
432
+ if (!isCurrent(announcement)) refuse(context, 'not-current', 'only a current announcement is reminded.')
433
+ const repository = getRepository(AnnouncementReceipt, tx)
434
+ const owed = (await repository.find({ where: { announcement: { id } } as any })).filter(one => owedReminder(announcement, one))
435
+ if (owed.length) await repository.update({ id: In(owed.map(one => one.id)) } as any, { notifiedAt: new Date(), updater: user } as any)
436
+ await tellWhenCommitted(
437
+ context,
438
+ announcement,
439
+ 'reminder',
440
+ owed.map(one => one.userId!)
441
+ )
442
+ return owed.length
443
+ }
444
+
445
+ /* ---------------------------------------------------------------- fields */
446
+
447
+ @FieldResolver(type => [AnnouncementAudience], { description: 'Whom it is addressed to.' })
448
+ async audiences(@Root() one: Announcement): Promise<AnnouncementAudience[]> {
449
+ return await audiencesOf(one.id)
450
+ }
451
+
452
+ @FieldResolver(type => [Attachment], { description: 'Its files.' })
453
+ async attachments(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<Attachment[]> {
454
+ return await getRepository(Attachment).find({ where: { domain: { id: context.state.domain.id }, refType: ANNOUNCEMENT_REF_TYPE, refBy: one.id } as any, order: { createdAt: 'ASC' } as any })
455
+ }
456
+
457
+ @FieldResolver(type => AnnouncementReceipt, { nullable: true, description: "The request's person's own reading of it." })
458
+ async mine(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<AnnouncementReceipt | null> {
459
+ if ('__mine' in (one as any)) return (one as any).__mine
460
+ return (await myReceipts([one.id], context.state.user.id)).get(one.id) ?? null
461
+ }
462
+
463
+ @FieldResolver(type => Boolean, { description: "Whether it is addressed to the request's person and out - the one who reads and acknowledges it." })
464
+ async addressed(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<boolean> {
465
+ return one.status === AnnouncementStatus.PUBLISHED && (await reachingIds(await memberOf(context))).includes(one.id)
466
+ }
467
+
468
+ @FieldResolver(type => String, { nullable: true, description: 'Whether it is still current or past - for one that is out.' })
469
+ period(@Root() one: Announcement): string | undefined {
470
+ return periodOf(one)
471
+ }
472
+
473
+ @FieldResolver(type => String, { description: "Where it stands for the request's person: unread, read, to-acknowledge or acknowledged." })
474
+ async readerState(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<string> {
475
+ return readerStateOf(one, (await this.mine(one, context)) ?? undefined)
476
+ }
477
+
478
+ @FieldResolver(type => Int, { nullable: true, description: 'How many on the roster read it - for its writers.' })
479
+ async readCount(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<number | null> {
480
+ if (!(await isWriter(context))) return null
481
+ return await getRepository(AnnouncementReceipt).count({ where: { announcement: { id: one.id }, listed: true, readAt: Not(IsNull()) } as any })
482
+ }
483
+
484
+ @FieldResolver(type => Int, { nullable: true, description: 'How many on the roster acknowledged it - for its writers.' })
485
+ async acknowledgedCount(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<number | null> {
486
+ if (!(await isWriter(context))) return null
487
+ return await getRepository(AnnouncementReceipt).count({ where: { announcement: { id: one.id }, listed: true, acknowledgedAt: Not(IsNull()) } as any })
488
+ }
489
+
490
+ @FieldResolver(type => Boolean, { description: 'Whether the request may change it.' })
491
+ async editable(@Root() one: Announcement, @Ctx() context: ResolverContext): Promise<boolean> {
492
+ if (one.status === AnnouncementStatus.WITHDRAWN) return false
493
+ if (one.status === AnnouncementStatus.DRAFT && one.creatorId !== context.state.user.id) return false
494
+ return await isWriter(context)
495
+ }
496
+
497
+ @FieldResolver(type => User, { nullable: true, description: 'Who published it.' })
498
+ async publisher(@Root() one: Announcement): Promise<User | null> {
499
+ return one.publisherId ? await getRepository(User).findOneBy({ id: one.publisherId }) : null
500
+ }
501
+
502
+ @FieldResolver(type => User, { nullable: true, description: 'Who wrote it.' })
503
+ async creator(@Root() one: Announcement): Promise<User | null> {
504
+ return one.creatorId ? await getRepository(User).findOneBy({ id: one.creatorId }) : null
505
+ }
506
+ }