@7365admin1/layer-common 4.188.2 → 4.188.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.188.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 1d2983a: Bulletin Board list shows Date Created, Start Date and End Date as DD/MM/YYYY, the same as the bulletin's details.
8
+ - ee09e41: Visitor Management: the HID QR Code option is hidden from the Pass Type picker for now.
9
+
10
+ ## 4.188.3
11
+
12
+ ### Patch Changes
13
+
14
+ - 6fc06d5: Super Admin Client List / Client Details: a nature is now spelt the way the Invite Client dropdown spells it. `formatNature` title-cased the stored slug, so `mechanical_electrical_services` showed as "Mechanical Electrical Services" (no "&") and `estate_ranger_services` as "Estate Ranger Services"; they now read "Mechanical & Electrical Services" and "iRanger365". The stored value was always the correct slug - no API or data change. Workspace #1860.
15
+ - 6f6ffb8: Delete Role lists each person once, with one Reassign role field that moves all of their memberships on the role (Organisation and the app). It used to list the same e-mail twice (DV-1858).
16
+ - a1f8b08: Invitations: when the invite API saves the invitation but its e-mail could not be sent (`emailSent: false`, needs `@7365admin1/core` with the #1416 fix), Invite member closes as usual and the page shows the server's warning ("Invitation created, but the email could not be sent: ... Use Resend ..."); Resend shows the same warning instead of "Invitation re-sent". `InvitationForm` emits `email-not-sent` with that text. Workspace #1416.
17
+ - d115901: Members (all apps): the organisation owner's row no longer offers Assign Role, Suspend, Activate or Delete - to anybody, the owner included - and your own row no longer offers Suspend or Delete. The owner is the server's own test (core `hasOrgOwnership`): the organisation's `createdBy`, or its e-mail. The server already refused every one of these; the menu offered them anyway, and suspending or deleting the owner risks locking the organisation out. Every other row is unchanged. No API or data change. Workspace #1859.
18
+ - 1b9b278: Create Role: Submit stays off until at least one permission is ticked, and the footer says "Select at least one permission." A role with no permission was saved as full access (DV-1847).
19
+
3
20
  ## 4.188.2
4
21
 
5
22
  ### Patch Changes
@@ -4119,11 +4136,11 @@ Monthly report: a month that had patrols opens the list of that month's patrol r
4119
4136
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
4120
4137
  own rule from two endpoints the console already calls, unprojected:
4121
4138
 
4122
- GET /api/members/user/:user/app/admin the Seven365 staff membership
4123
- GET /api/roles/id/:role that membership's role document
4139
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
4140
+ GET /api/roles/id/:role that membership's role document
4124
4141
 
4125
- owner = member.type === "admin" && role.type === "admin" && role.default === true
4126
- staff = member.type === "admin" && role.type === "admin"
4142
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
4143
+ staff = member.type === "admin" && role.type === "admin"
4127
4144
 
4128
4145
  `role.default` is the marker because it is the only property of a platform
4129
4146
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -230,7 +230,8 @@ function toRoute(status: any) {
230
230
 
231
231
  function toLocalDate(utcString: string) {
232
232
  if (!utcString) return ""
233
- return new Date(utcString).toLocaleString("en-US", {
233
+ // DD/MM/YYYY, the same as the bulletin's details (BulletinBoardView).
234
+ return new Date(utcString).toLocaleDateString("en-GB", {
234
235
  year: "numeric",
235
236
  month: "2-digit",
236
237
  day: "2-digit",
@@ -366,8 +366,10 @@ const { getAvailableContractorCards, generateQrVms } = useAccessManagement();
366
366
  const { debounce } = useUtils();
367
367
 
368
368
  const nfcEnabled = computed(() => props.settings?.data?.settings?.nfcPass ?? false);
369
+ // HID QR Code pass type is hidden for now. Set to true to show it again.
370
+ const SHOW_HID_QR_PASS_TYPE = false;
369
371
  const hidQrCodeEnabled = computed(() => {
370
- return props.hidQrCodeEnabled && ["guest", "contractor", "walk-in"].includes(String(props.visitorType || ""));
372
+ return SHOW_HID_QR_PASS_TYPE && props.hidQrCodeEnabled &&["guest", "contractor", "walk-in"].includes(String(props.visitorType || ""));
371
373
  });
372
374
  const printer = computed(() => props.settings?.data?.settings?.printer ?? { vendorId: null, productId: null });
373
375
  const hasPrinter = computed(() => !!printer.value.vendorId && !!printer.value.productId);
@@ -175,6 +175,7 @@ import useRole from '../composables/useRole';
175
175
  import useSite from '../composables/useSite';
176
176
  import { inviteRoleOptions } from '../utils/invite-role-options';
177
177
  import { roleSiteFor } from '../utils/invite-sites';
178
+ import { inviteNotEmailedNotice } from '../utils/invite-email-notice';
178
179
  import useUser from '../composables/useUser';
179
180
  import useUtils from '../composables/useUtils';
180
181
 
@@ -260,7 +261,7 @@ const props = defineProps({
260
261
  }
261
262
  });
262
263
 
263
- const emit = defineEmits(["cancel", "success", "success:create-more"]);
264
+ const emit = defineEmits(["cancel", "success", "success:create-more", "email-not-sent"]);
264
265
 
265
266
  const validForm = ref(false);
266
267
  const form = ref<HTMLFormElement | null>(null);
@@ -586,11 +587,15 @@ async function submit() {
586
587
  loading.submittingForm = true;
587
588
 
588
589
  try {
589
- if (props.inviteMember) {
590
- await inviteMemberClient(invite.value);
591
- } else {
592
- await inviteUser(invite.value);
593
- }
590
+ const res = props.inviteMember
591
+ ? await inviteMemberClient(invite.value)
592
+ : await inviteUser(invite.value);
593
+
594
+ // Saved, but its e-mail did not go out (#1416): still a success - the
595
+ // invitation is listed and can be re-sent - so close as usual and let the
596
+ // page warn.
597
+ const notice = inviteNotEmailedNotice(res);
598
+ if (notice) emit("email-not-sent", notice);
594
599
 
595
600
  if (createMore.value) {
596
601
  form.value?.reset();
@@ -187,6 +187,7 @@
187
187
  :invite-member="true"
188
188
  @cancel="dialogMember = false"
189
189
  @success="handleSuccess"
190
+ @email-not-sent="showMessage($event, 'warning')"
190
191
  @invited="getVerifications()"
191
192
  :app="props.app"
192
193
  />
@@ -198,6 +199,7 @@
198
199
  <script setup lang="ts">
199
200
  // Relative import: this layer's `utils/` is not auto-imported into consumers.
200
201
  import { invitationsEmptyText } from "../utils/invitations-empty-text";
202
+ import { inviteNotEmailedNotice } from "../utils/invite-email-notice";
201
203
  import {
202
204
  groupIds,
203
205
  resendArgs,
@@ -432,8 +434,11 @@ async function onResend(item: any) {
432
434
  if (resending.value) return;
433
435
  resending.value = true;
434
436
  try {
435
- await inviteMemberClient(args);
436
- showMessage("Invitation re-sent (one e-mail).", "success");
437
+ const res = await inviteMemberClient(args);
438
+ // The invitation is re-issued either way; say when its e-mail failed (#1416).
439
+ const notice = inviteNotEmailedNotice(res);
440
+ if (notice) showMessage(notice, "warning");
441
+ else showMessage("Invitation re-sent (one e-mail).", "success");
437
442
  await getVerifications();
438
443
  } catch (error: any) {
439
444
  showMessage(error?.data?.message || error?.message || "Failed to resend invitation", "error");
@@ -224,14 +224,10 @@
224
224
  `members:assign-member-role` and nothing else got no menu at all,
225
225
  and the permission was unreachable.
226
226
  -->
227
+ <!-- #1859: the organisation owner's row offers none of them, and
228
+ your own row no Suspend / Delete (`utils/member-row-actions`). -->
227
229
  <v-menu
228
- v-if="!isLimited(item) && (
229
- props.assignRole ||
230
- (currentStatus === 'active' &&
231
- (canSuspendMembers || canDeleteMembers)) ||
232
- (currentStatus === 'suspended' &&
233
- (canActivateMembers || canDeleteMembers)))
234
- "
230
+ v-if="!isLimited(item) && rowActions(item).menu"
235
231
  v-model="item.menuOpen"
236
232
  :close-on-content-click="false"
237
233
  offset-y
@@ -249,7 +245,7 @@
249
245
  <!-- Highlighted when the row's role chip is a warning (no /
250
246
  deleted / other org / other site role): this is the fix. -->
251
247
  <v-list-item
252
- v-if="props.assignRole"
248
+ v-if="rowActions(item).assignRole"
253
249
  :class="{
254
250
  'text-warning font-weight-bold':
255
251
  memberRoleChip(item)?.tone === 'warn',
@@ -280,19 +276,19 @@
280
276
  </v-list-item>
281
277
 
282
278
  <v-list-item
283
- v-if="currentStatus === 'active' && canSuspendMembers"
279
+ v-if="rowActions(item).suspend"
284
280
  @click="openUpdateDialog(item._id, 'suspended')"
285
281
  >
286
282
  Suspend
287
283
  </v-list-item>
288
284
  <v-list-item
289
- v-if="currentStatus === 'suspended' && canActivateMembers"
285
+ v-if="rowActions(item).activate"
290
286
  @click="openUpdateDialog(item._id, 'active')"
291
287
  >
292
288
  Activate
293
289
  </v-list-item>
294
290
  <v-list-item
295
- v-if="canDeleteMembers"
291
+ v-if="rowActions(item).delete"
296
292
  @click="openUpdateDialog(item._id, 'deleted')"
297
293
  >
298
294
  Delete
@@ -440,6 +436,7 @@ import {
440
436
  } from "../utils/role";
441
437
  import { formatLastActive } from "../utils/last-active";
442
438
  import { formatMemberDate, memberAccess, memberPerson } from "../utils/member-row";
439
+ import { memberRowActions } from "../utils/member-row-actions";
443
440
 
444
441
  const props = defineProps({
445
442
  /** The design's page title. Every app that mounts this screen calls it
@@ -707,6 +704,35 @@ const siteAccessAllowed = computed(() => props.assignRole && !props.siteId);
707
704
  one-membership actions (Assign Role, Suspend, Delete) are not offered on it;
708
705
  Site access manages them. */
709
706
  const isLimited = (item: Record<string, any>) => orgLevel.value && limitedSites(item).length > 0;
707
+ /*
708
+ * #1859: the organisation owner's row offered Assign Role, Suspend and Delete
709
+ * (all seven apps). The organisation's record names its owner - `createdBy`
710
+ * and its e-mail, the server's own test (core `hasOrgOwnership`) - and the
711
+ * signed-in user is the viewer. A failed or name-only read names no owner;
712
+ * the server still refuses, as it always did.
713
+ */
714
+ const { currentUser } = useLocalAuth();
715
+ const { data: ownerOrg } = useAsyncData(
716
+ `member-owner-org-${props.orgId}`,
717
+ () =>
718
+ props.orgId
719
+ ? useNuxtApp()
720
+ .$api<Record<string, any>>(`/api/organizations/id/${props.orgId}`)
721
+ .catch(() => null)
722
+ : Promise.resolve(null),
723
+ { watch: [() => props.orgId] }
724
+ );
725
+ const rowActions = (item: Record<string, any>) =>
726
+ memberRowActions({
727
+ item,
728
+ org: ownerOrg.value,
729
+ viewerId: String(currentUser.value?._id ?? ""),
730
+ status: currentStatus.value,
731
+ assignRole: props.assignRole,
732
+ canSuspend: props.canSuspendMembers,
733
+ canActivate: props.canActivateMembers,
734
+ canDelete: props.canDeleteMembers,
735
+ });
710
736
  /* Keep the actions column on screen however wide the table gets. */
711
737
  const actionLast = computed(() => props.headers[props.headers.length - 1]?.value === "action-table");
712
738
  const siteAccessDialog = ref(false);
@@ -262,6 +262,10 @@
262
262
  <div v-if="message" class="role-create__save-error" role="alert">
263
263
  Couldn't save: {{ message }}
264
264
  </div>
265
+ <!-- DV-1847: a role with no permission was saved as full access. -->
266
+ <div v-else-if="!hasPermission" class="role-create__save-error" role="status">
267
+ Select at least one permission.
268
+ </div>
265
269
 
266
270
  <div class="role-create__footer">
267
271
  <AppButton
@@ -278,7 +282,7 @@
278
282
  </AppButton>
279
283
 
280
284
  <AppButton variant="ghost" @click="cancel">{{ props.cancelText }}</AppButton>
281
- <AppButton :disabled="!validForm || disable" @click="submit">Submit</AppButton>
285
+ <AppButton :disabled="!validForm || !hasPermission || disable" @click="submit">Submit</AppButton>
282
286
  </div>
283
287
  </v-card>
284
288
  </template>
@@ -294,7 +298,7 @@ import useRole from "../composables/useRole";
294
298
  import useUtils from "../composables/useUtils";
295
299
  import useSite from "../composables/useSite";
296
300
  import { readApiError } from "../utils/subscription-form";
297
- import { withSecurityMarker } from "../utils/security-catalogue";
301
+ import { countRealPermissions, withSecurityMarker } from "../utils/security-catalogue";
298
302
  import { isTradeCatalogue, withTradeMarker } from "../utils/trade-catalogue";
299
303
  import { applyRolePreset, ROLE_PRESETS, type TRolePreset } from "../utils/inventory-presets";
300
304
 
@@ -393,6 +397,11 @@ const catalogueSize = computed(() =>
393
397
  )
394
398
  );
395
399
 
400
+ // DV-1847: the catalogue marker is not a permission.
401
+ const hasPermission = computed(
402
+ () => countRealPermissions(permState.value.selected) > 0
403
+ );
404
+
396
405
  const totalLabel = computed(() => {
397
406
  const selected = permState.value.selected.length;
398
407
  return catalogueSize.value > 0
@@ -541,6 +550,7 @@ watch(
541
550
  );
542
551
 
543
552
  async function submit() {
553
+ if (!hasPermission.value) return;
544
554
  disable.value = true;
545
555
  message.value = "";
546
556
  try {
@@ -155,26 +155,33 @@
155
155
  <p class="mb-4">
156
156
  There are currently
157
157
  <span class="text-error font-weight-bold">
158
- {{ deletionPreview.members.length }}
159
- {{ deletionPreview.members.length === 1 ? "user" : "users" }}
158
+ {{ deletionPeople.length }}
159
+ {{ deletionPeople.length === 1 ? "user" : "users" }}
160
160
  </span>
161
161
  assigned to this role. Reassign each user before deleting it so
162
162
  they do not lose access.
163
163
  </p>
164
164
 
165
+ <!-- DV-1858: one row per person; their memberships move together. -->
165
166
  <v-row
166
- v-for="member in deletionPreview.members"
167
- :key="member._id"
167
+ v-for="person in deletionPeople"
168
+ :key="person.key"
168
169
  no-gutters
169
170
  class="mb-3 pa-3 border rounded-lg"
170
171
  align="center"
171
172
  >
172
173
  <v-col cols="12" sm="5" class="mb-2 mb-sm-0">
173
- {{ member.name || member.user }}
174
+ {{ person.name || person.email || person.key }}
175
+ <div
176
+ v-if="person.name && person.email && person.name !== person.email"
177
+ class="text-caption text-medium-emphasis"
178
+ >
179
+ {{ person.email }}
180
+ </div>
174
181
  </v-col>
175
182
  <v-col cols="12" sm="7">
176
183
  <v-select
177
- v-model="memberReassignments[member._id]"
184
+ v-model="memberReassignments[person.key]"
178
185
  :items="deletionPreview.replacementRoles"
179
186
  :item-title="props.siteId ? sitePickerRoleLabel : roleLabel"
180
187
  item-value="_id"
@@ -219,6 +226,7 @@
219
226
  import { roleAppLabel, roleLabel, safeReturnTo, showSiteField, sitePickerRoleLabel } from "../utils/role";
220
227
  import { holdsPermission } from "../utils/permission-spellings";
221
228
  import { countRealPermissions } from "../utils/security-catalogue";
229
+ import { groupDeletionMembers, reassignmentsFor } from "../utils/role-deletion-people";
222
230
  import {
223
231
  catalogueForOrg,
224
232
  catalogueForOwnerGrant,
@@ -728,9 +736,14 @@ const hasAssignedMembers = computed(
728
736
  () => deletionPreview.value.members.length > 0
729
737
  );
730
738
 
739
+ // DV-1858: a person has a membership per scope (Organisation and the app).
740
+ const deletionPeople = computed(() =>
741
+ groupDeletionMembers(deletionPreview.value.members)
742
+ );
743
+
731
744
  const canConfirmDeletion = computed(() =>
732
- deletionPreview.value.members.every(
733
- (member) => Boolean(memberReassignments.value[member._id])
745
+ deletionPeople.value.every((person) =>
746
+ Boolean(memberReassignments.value[person.key])
734
747
  )
735
748
  );
736
749
 
@@ -773,10 +786,10 @@ async function handleDeleteRole() {
773
786
  if (!selectedRoleId.value) return;
774
787
  deleteLoading.value = true;
775
788
  try {
776
- const reassignments = deletionPreview.value.members.map((member) => ({
777
- memberId: member._id,
778
- roleId: memberReassignments.value[member._id],
779
- }));
789
+ const reassignments = reassignmentsFor(
790
+ deletionPeople.value,
791
+ memberReassignments.value
792
+ );
780
793
  const res = hasAssignedMembers.value
781
794
  ? await deleteWithReassignments(selectedRoleId.value, reassignments)
782
795
  : await deleteRole(selectedRoleId.value);
@@ -316,8 +316,25 @@ export default function useUtils() {
316
316
  return `${day}/${month}/${year}`;
317
317
  }
318
318
 
319
+ /*
320
+ * A nature is stored as a slug (`mechanical_electrical_services`), so
321
+ * title-casing it cannot bring back what the slug never held: the "&" of
322
+ * "Mechanical & Electrical Services", or the product name "iRanger365".
323
+ * Natures whose name is not their slug in words are spelt here exactly as
324
+ * the Invite Client dropdown spells them (`InvitationClientForm.vue`
325
+ * APP_LIST); every other value - including ones the model does not list,
326
+ * like `property_owner` - is still title-cased.
327
+ */
328
+ const NATURE_LABELS: Readonly<Record<string, string>> = {
329
+ mechanical_electrical_services: "Mechanical & Electrical Services",
330
+ estate_ranger_services: "iRanger365",
331
+ };
332
+
319
333
  function formatNature(value: string): string {
320
334
  if (!value) return "";
335
+ if (Object.prototype.hasOwnProperty.call(NATURE_LABELS, value)) {
336
+ return NATURE_LABELS[value];
337
+ }
321
338
  return value
322
339
  .split("_")
323
340
  .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
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.188.2",
5
+ "version": "4.188.4",
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,16 @@
1
+ /**
2
+ * Workspace #1416: Invite member / Resend used to get a 500 when the
3
+ * invitation was saved but its e-mail failed, so the dialog stayed open over
4
+ * an invitation that already existed. The API now answers 201 with
5
+ * `emailSent: false` and a message; this is the warning to show, or "" when
6
+ * the e-mail went out (or the API is older and does not say).
7
+ */
8
+ export function inviteNotEmailedNotice(
9
+ res: { message?: string; emailSent?: boolean } | null | undefined,
10
+ ): string {
11
+ if (res?.emailSent !== false) return "";
12
+ return (
13
+ res.message ||
14
+ "Invitation created, but the email could not be sent. Use Resend on the invitation to try again."
15
+ );
16
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Which actions one row of the Members table offers (#1859).
3
+ *
4
+ * The organisation owner's row offered Assign Role, Suspend and Delete - in all
5
+ * seven apps, to the owner looking at their own row too. Suspending or deleting
6
+ * the owner can lock the organisation out. The server already refuses each of
7
+ * them (core `requireNotOwnerUnlessOwner`, and "You cannot suspend or remove
8
+ * your own access." in `requireMemberStatusChanger`); the screen offered them
9
+ * anyway, so pressing one ended in a red error.
10
+ *
11
+ * - The owner's row: no Assign Role, Suspend, Activate or Delete, for anybody.
12
+ * - Your own row: no Suspend or Delete.
13
+ * - Every other row: exactly what the permissions gave it before.
14
+ */
15
+
16
+ type TRow = Record<string, any> | null | undefined;
17
+
18
+ function idOf(value: unknown): string {
19
+ if (typeof value === "string") return value.trim();
20
+ const hex = (value as any)?.toHexString;
21
+ return typeof hex === "function" ? String(hex.call(value)).trim() : "";
22
+ }
23
+
24
+ function emailOf(value: unknown): string {
25
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
26
+ }
27
+
28
+ /**
29
+ * Is this the organisation owner's row? The same test the server applies
30
+ * (core `hasOrgOwnership`): the account that created the organisation
31
+ * (`createdBy`), or the organisation's own e-mail. A name-only organisation
32
+ * record (no `createdBy`, no `email`) names nobody.
33
+ */
34
+ export function isOrgOwnerRow(item: TRow, org: TRow): boolean {
35
+ const user = idOf(item?.user);
36
+ const owner = idOf(org?.createdBy);
37
+ if (user && owner && user === owner) return true;
38
+ const email = emailOf(item?.email);
39
+ const orgEmail = emailOf(org?.email);
40
+ return !!email && !!orgEmail && email === orgEmail;
41
+ }
42
+
43
+ export type TMemberRowActions = {
44
+ /** Whether the row's three-dot menu is drawn at all. */
45
+ menu: boolean;
46
+ assignRole: boolean;
47
+ suspend: boolean;
48
+ activate: boolean;
49
+ delete: boolean;
50
+ };
51
+
52
+ export function memberRowActions(input: {
53
+ item: TRow;
54
+ org: TRow;
55
+ /** The signed-in user's id. */
56
+ viewerId?: string;
57
+ /** The tab: "active", "suspended", or an app's extra tab. */
58
+ status: string;
59
+ assignRole: boolean;
60
+ canSuspend: boolean;
61
+ canActivate: boolean;
62
+ canDelete: boolean;
63
+ }): TMemberRowActions {
64
+ const owner = isOrgOwnerRow(input.item, input.org);
65
+ const viewer = idOf(input.viewerId);
66
+ const self = !!viewer && idOf(input.item?.user) === viewer;
67
+ const locked = owner || self;
68
+
69
+ const assignRole = input.assignRole && !owner;
70
+ const suspend = input.status === "active" && input.canSuspend && !locked;
71
+ const activate = input.status === "suspended" && input.canActivate && !owner;
72
+ const del = input.canDelete && !locked;
73
+ // As before: Delete alone opens the menu only on Active / Inactive.
74
+ const onStatusTab = input.status === "active" || input.status === "suspended";
75
+ const menu = assignRole || (onStatusTab && (suspend || activate || del));
76
+
77
+ return { menu, assignRole, suspend, activate, delete: del };
78
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * DV-1858: who holds a role, one entry per PERSON.
3
+ *
4
+ * The deletion preview returns one row per membership, and a person usually
5
+ * has two on the same role (Organisation and the app), so Delete Role listed
6
+ * them twice with two Reassign fields. Group by `user`; keep every membership
7
+ * id so one choice reassigns all of them (the API refuses a reassignment that
8
+ * leaves any membership on the deleted role).
9
+ */
10
+ export type TDeletionPerson = {
11
+ key: string;
12
+ name: string;
13
+ email: string;
14
+ memberIds: string[];
15
+ };
16
+
17
+ const idOf = (v: unknown) => String((v as any)?.toString?.() ?? v ?? "").trim();
18
+
19
+ export function groupDeletionMembers(
20
+ members: ReadonlyArray<Record<string, any>> | null | undefined,
21
+ ): TDeletionPerson[] {
22
+ const people = new Map<string, TDeletionPerson>();
23
+ for (const m of members ?? []) {
24
+ const memberId = idOf(m?._id);
25
+ const key = idOf(m?.user) || `member:${memberId}`;
26
+ const found = people.get(key);
27
+ if (found) {
28
+ found.memberIds.push(memberId);
29
+ if (!found.name && m?.name) found.name = String(m.name);
30
+ if (!found.email && m?.email) found.email = String(m.email);
31
+ continue;
32
+ }
33
+ people.set(key, {
34
+ key,
35
+ name: String(m?.name ?? ""),
36
+ email: String(m?.email ?? ""),
37
+ memberIds: [memberId],
38
+ });
39
+ }
40
+ return [...people.values()];
41
+ }
42
+
43
+ export function reassignmentsFor(
44
+ people: ReadonlyArray<TDeletionPerson>,
45
+ choice: Record<string, string>,
46
+ ): Array<{ memberId: string; roleId: string }> {
47
+ return people.flatMap((p) => p.memberIds.map((memberId) => ({ memberId, roleId: choice[p.key] })));
48
+ }