-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserGroupSync.ts
More file actions
289 lines (240 loc) · 7.81 KB
/
Copy pathuserGroupSync.ts
File metadata and controls
289 lines (240 loc) · 7.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import Papa from "papaparse";
export const USER_EXPORT_HEADERS = [
"Director",
"Senior Manager",
"User Group Member",
"First Name",
"Last Name",
"Colleague ID",
"Email",
"Job Title",
] as const;
type UserExportHeader = (typeof USER_EXPORT_HEADERS)[number];
type RawUserExportRow = Record<UserExportHeader, string | undefined>;
export type UserGroupSyncMode = "add-only" | "exact-sync";
export interface UserExportRow {
rowNumber: number;
director: string;
seniorManager: string;
userGroupMember: string;
firstName: string;
lastName: string;
colleagueId: string;
email: string;
jobTitle: string;
}
export interface ResolvedStackUser {
id: number;
email: string;
name?: string;
}
export interface ExistingUserGroupMember {
id: number;
name?: string;
}
export interface ExistingUserGroup {
id: number;
name: string;
users: ExistingUserGroupMember[];
}
export type UserGroupSyncSkippedRowReason =
| "Missing Senior Manager"
| "Missing Email"
| "Duplicate Email"
| "Email not found in Stack Enterprise";
export interface UserGroupSyncSkippedRow {
rowNumber: number;
email: string;
seniorManager: string;
reason: UserGroupSyncSkippedRowReason;
}
export interface PlannedUserGroupSyncGroup {
manager: string;
groupName: string;
existingGroupId: number | null;
createGroup: boolean;
desiredUserIds: number[];
addUserIds: number[];
removeUserIds: number[];
}
export interface UserGroupSyncPlan {
syncMode: UserGroupSyncMode;
groupNameTemplate: string;
groups: PlannedUserGroupSyncGroup[];
skippedRows: UserGroupSyncSkippedRow[];
blockingErrors: string[];
}
export interface PlanUserGroupSyncInput {
rows: UserExportRow[];
groupNameTemplate: string;
syncMode: UserGroupSyncMode;
existingGroups: ExistingUserGroup[];
resolvedUsers: Record<string, ResolvedStackUser | null | undefined>;
}
interface DesiredGroup {
groupName: string;
managers: Set<string>;
desiredUserIds: Set<number>;
}
export function parseUserExportCsv(csvText: string): UserExportRow[] {
const parsed = Papa.parse<RawUserExportRow>(csvText, {
header: true,
dynamicTyping: false,
skipEmptyLines: true,
});
if (parsed.errors.length > 0) {
throw new Error(parsed.errors.map((error) => error.message).join("; "));
}
const fields = parsed.meta.fields ?? [];
const missingHeaders = USER_EXPORT_HEADERS.filter((header) => !fields.includes(header));
if (missingHeaders.length > 0) {
throw new Error(`User export CSV is missing required column(s): ${missingHeaders.join(", ")}`);
}
return parsed.data.map((row, index) => ({
rowNumber: index + 2,
director: readCell(row, "Director"),
seniorManager: readCell(row, "Senior Manager"),
userGroupMember: readCell(row, "User Group Member"),
firstName: readCell(row, "First Name"),
lastName: readCell(row, "Last Name"),
colleagueId: readCell(row, "Colleague ID"),
email: readCell(row, "Email"),
jobTitle: readCell(row, "Job Title"),
}));
}
export function renderGroupName(template: string, seniorManager: string): string {
return template.split("{Senior Manager}").join(seniorManager).trim();
}
export function planUserGroupSync(input: PlanUserGroupSyncInput): UserGroupSyncPlan {
const existingGroupsByName = new Map(
input.existingGroups.map((group) => [normalizeKey(group.name), group] as const),
);
const resolvedUsersByEmail = new Map(
Object.entries(input.resolvedUsers).map(([email, user]) => [normalizeKey(email), user] as const),
);
const skippedRows: UserGroupSyncSkippedRow[] = [];
const seenEmails = new Set<string>();
const desiredGroupsByName = new Map<string, DesiredGroup>();
for (const row of input.rows) {
const email = row.email.trim();
const seniorManager = row.seniorManager.trim();
if (!email) {
skippedRows.push(toSkippedRow(row, "Missing Email", email, seniorManager));
continue;
}
const emailKey = normalizeKey(email);
const isDuplicateEmail = seenEmails.has(emailKey);
if (!seniorManager) {
skippedRows.push(toSkippedRow(row, "Missing Senior Manager", email, seniorManager));
continue;
}
if (isDuplicateEmail) {
skippedRows.push(toSkippedRow(row, "Duplicate Email", email, seniorManager));
continue;
}
seenEmails.add(emailKey);
const resolvedUser = resolvedUsersByEmail.get(emailKey);
if (!resolvedUser) {
skippedRows.push(toSkippedRow(row, "Email not found in Stack Enterprise", email, seniorManager));
continue;
}
const groupName = renderGroupName(input.groupNameTemplate, seniorManager);
const groupKey = normalizeKey(groupName);
const desiredGroup = desiredGroupsByName.get(groupKey) ?? {
groupName,
managers: new Set<string>(),
desiredUserIds: new Set<number>(),
};
desiredGroup.managers.add(seniorManager);
desiredGroup.desiredUserIds.add(resolvedUser.id);
desiredGroupsByName.set(groupKey, desiredGroup);
}
const blockingErrors = collectBlockingErrors(desiredGroupsByName);
const groups = [...desiredGroupsByName.values()]
.map((desiredGroup) => toPlannedGroup(desiredGroup, existingGroupsByName, input.syncMode))
.sort((left, right) => compareStrings(left.groupName, right.groupName));
return {
syncMode: input.syncMode,
groupNameTemplate: input.groupNameTemplate,
groups,
skippedRows,
blockingErrors,
};
}
function readCell(row: RawUserExportRow, header: UserExportHeader): string {
return String(row[header] ?? "").trim();
}
function normalizeKey(value: string): string {
return value.trim().toLowerCase();
}
function toSkippedRow(
row: UserExportRow,
reason: UserGroupSyncSkippedRowReason,
email: string,
seniorManager: string,
): UserGroupSyncSkippedRow {
return {
rowNumber: row.rowNumber,
email,
seniorManager,
reason,
};
}
function collectBlockingErrors(desiredGroupsByName: Map<string, DesiredGroup>): string[] {
const blockingErrors: string[] = [];
for (const desiredGroup of desiredGroupsByName.values()) {
const managers = [...desiredGroup.managers].sort(compareStrings);
if (!desiredGroup.groupName) {
blockingErrors.push(
`Group name template produced a blank group name for Senior Manager value(s): ${managers.join(", ")}.`,
);
}
if (managers.length > 1) {
blockingErrors.push(
`Group name "${desiredGroup.groupName}" is produced by multiple Senior Manager values: ${managers.join(", ")}.`,
);
}
}
return blockingErrors;
}
function toPlannedGroup(
desiredGroup: DesiredGroup,
existingGroupsByName: Map<string, ExistingUserGroup>,
syncMode: UserGroupSyncMode,
): PlannedUserGroupSyncGroup {
const existingGroup = existingGroupsByName.get(normalizeKey(desiredGroup.groupName)) ?? null;
const existingUserIds = new Set(existingGroup?.users.map((user) => user.id) ?? []);
const desiredUserIds = sortNumbers([...desiredGroup.desiredUserIds]);
return {
manager: [...desiredGroup.managers].sort(compareStrings)[0] ?? "",
groupName: desiredGroup.groupName,
existingGroupId: existingGroup?.id ?? null,
createGroup: existingGroup === null,
desiredUserIds,
addUserIds: desiredUserIds.filter((userId) => !existingUserIds.has(userId)),
removeUserIds:
syncMode === "exact-sync"
? sortNumbers([...existingUserIds].filter((userId) => !desiredGroup.desiredUserIds.has(userId)))
: [],
};
}
function sortNumbers(values: number[]): number[] {
return values.sort((left, right) => left - right);
}
function compareStrings(left: string, right: string): number {
const normalizedLeft = normalizeKey(left);
const normalizedRight = normalizeKey(right);
if (normalizedLeft < normalizedRight) {
return -1;
}
if (normalizedLeft > normalizedRight) {
return 1;
}
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
}