-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcypress.config.ts
More file actions
396 lines (325 loc) · 12.4 KB
/
Copy pathcypress.config.ts
File metadata and controls
396 lines (325 loc) · 12.4 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/// <reference types="node" />
import dotenv from "dotenv";
import { defineConfig } from "cypress";
import { createClient } from "@supabase/supabase-js";
dotenv.config();
type RoleType = "superadmin" | "manager" | "hr" | "regular" | "employee";
type AddUserPayload = {
name: string;
email: string;
password: string;
roleType?: RoleType;
employeeId?: string | null;
employmentStatus?: string | null;
contactDetails?: string | null;
homeAddress?: string | null;
tinId?: string | null;
sssId?: string | null;
pagibigId?: string | null;
};
type AddBadgePayload = {
name: string;
description?: string | null;
points?: number;
awardAtInterval?: "none" | "daily" | "monthly" | "anually";
createdByEmail?: string | null;
};
function getRequiredEnv(key: string): string {
const value = process.env[key]?.trim();
if (!value) {
throw new Error(`Missing required Cypress env var: ${key}`);
}
return value;
}
function getProjectRefFromUrl(url: string): string {
try {
const hostname = new URL(url).hostname;
return hostname.split(".")[0] || "";
} catch {
return "";
}
}
function normalizeEmail(raw: string): string {
return raw.trim().toLowerCase();
}
function createServiceRoleClient() {
return createClient(
getRequiredEnv("SUPABASE_URL"),
getRequiredEnv("SUPABASE_SERVICE_ROLE_KEY"),
{
auth: {
persistSession: false,
autoRefreshToken: false,
detectSessionInUrl: false,
},
}
);
}
function createPublicClient() {
const publishableKey =
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY?.trim() ||
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_DEFAULT_KEY?.trim();
if (!publishableKey) {
throw new Error(
"Missing required Cypress env var: NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY"
);
}
return createClient(
getRequiredEnv("NEXT_PUBLIC_SUPABASE_URL"),
publishableKey,
{
auth: {
persistSession: false,
autoRefreshToken: false,
detectSessionInUrl: false,
},
}
);
}
export default defineConfig({
allowCypressEnv: false,
e2e: {
baseUrl: "http://localhost:3008",
setupNodeEvents(on, config) {
// implement node event listeners here
on("task", {
// define the tasks here so that they can be used in the commands.ts
// use direct Supabase client logic (do not import server actions)
async login({ email, password }: { email: string; password: string }) {
console.log("[task:login] Starting login for", email);
const supabase = createPublicClient();
const normalizedEmail = normalizeEmail(email);
const { data, error } = await supabase.auth.signInWithPassword({
email: normalizedEmail,
password,
});
if (error || !data.session) {
console.log("[task:login] Failed:", error?.message ?? "No session");
throw error ?? new Error("Failed to sign in user");
}
console.log("[task:login] Success; returning session");
return data.session;
},
async addUser(payload: AddUserPayload) {
console.log("[task:addUser] Creating user", payload.email);
const supabase = createServiceRoleClient();
const normalizedEmail = normalizeEmail(payload.email);
const roleType = (payload.roleType ?? "superadmin").trim().toLowerCase();
const { data: existingUser } = await supabase
.from("User")
.select("id, email")
.eq("email", normalizedEmail)
.maybeSingle();
let roleId: string | null = null;
const roleQuery = await supabase
.from("Role")
.select("id")
.eq("type", roleType)
.limit(1)
.maybeSingle();
if (roleQuery.data?.id) {
roleId = roleQuery.data.id;
} else if (roleQuery.error) {
throw new Error(
`Failed to lookup role (${roleType}): ${roleQuery.error?.message || "not found"}`
);
}
if (!roleId) {
console.log("[task:addUser] Role not found; creating role", roleType);
const { data: roleInsert, error: roleInsertError } = await supabase
.from("Role")
.insert([{ type: roleType }])
.select("id")
.single();
if (roleInsertError || !roleInsert?.id) {
throw new Error(
`Failed to create role (${roleType}): ${roleInsertError?.message || "unknown"}`
);
}
roleId = roleInsert.id;
}
let authUser = null as null | { id: string; email?: string | null };
const { data: existingAuthUsers, error: listError } = await supabase.auth.admin.listUsers({
page: 1,
perPage: 1000,
});
if (listError) {
throw new Error(`Failed to list auth users: ${listError.message}`);
}
authUser =
existingAuthUsers?.users?.find(
(user) => user.email?.toLowerCase() === normalizedEmail
) ?? null;
if (!authUser) {
const { data: createData, error: createError } = await supabase.auth.admin.createUser({
email: normalizedEmail,
password: payload.password,
email_confirm: true,
user_metadata: { name: payload.name ?? null },
app_metadata: { user_role: roleType },
});
if (createError || !createData?.user) {
throw new Error(createError?.message || "Failed to create auth user");
}
authUser = createData.user;
} else {
await supabase.auth.admin
.updateUserById(authUser.id, {
password: payload.password,
user_metadata: { name: payload.name ?? null },
app_metadata: { user_role: roleType },
})
.catch(() => undefined);
}
if (existingUser?.id && authUser && existingUser.id !== authUser.id) {
console.log(
"[task:addUser] Found public user row with mismatched id; recreating",
existingUser.id,
authUser.id
);
await supabase.from("User").delete().eq("id", existingUser.id);
}
const normalizedEmploymentStatus = payload.employmentStatus?.trim().toLowerCase();
const insertPayload = {
id: authUser.id,
email: normalizedEmail,
name: payload.name ?? authUser.email ?? null,
date_added: new Date().toISOString(),
employee_id: payload.employeeId || null,
contact_details: payload.contactDetails || null,
home_address: payload.homeAddress || null,
tin_id: payload.tinId || null,
sss_id: payload.sssId || null,
pagibig_id: payload.pagibigId || null,
employment_status: normalizedEmploymentStatus || null,
role_id: roleId,
};
const { error: insertError } = await supabase
.from("User")
.upsert([insertPayload], { onConflict: "id" });
if (insertError) {
throw new Error(`Failed to insert user row: ${insertError.message}`);
}
console.log("[task:addUser] Created user", authUser.id);
return { userId: authUser.id, email: normalizedEmail, existed: false };
},
async deleteUser({ email }: { email: string }) {
console.log("[task:deleteUser] Deleting user", email);
const supabase = createServiceRoleClient();
const normalizedEmail = normalizeEmail(email);
const { data: userRow, error: userRowError } = await supabase
.from("User")
.select("id")
.eq("email", normalizedEmail)
.maybeSingle();
if (userRowError) {
throw new Error(`Failed to lookup user row: ${userRowError.message}`);
}
let userId = userRow?.id ?? null;
if (!userId) {
const { data: authUsers, error: listError } = await supabase.auth.admin.listUsers({
page: 1,
perPage: 1000,
});
if (listError) {
throw new Error(`Failed to list auth users: ${listError.message}`);
}
const matchedUser = authUsers?.users?.find(
(user) => user.email?.toLowerCase() === normalizedEmail
);
userId = matchedUser?.id ?? null;
}
if (!userId) {
console.log("[task:deleteUser] User not found; nothing to delete");
return { deleted: false };
}
if (userRow?.id) {
const { error: rowDeleteError } = await supabase
.from("User")
.delete()
.eq("id", userRow.id);
if (rowDeleteError) {
throw new Error(`Failed to delete user row: ${rowDeleteError.message}`);
}
}
const { error: authDeleteError } = await supabase.auth.admin.deleteUser(userId);
if (authDeleteError && !/user not found/i.test(authDeleteError.message ?? "")) {
throw new Error(`Failed to delete auth user: ${authDeleteError.message}`);
}
console.log("[task:deleteUser] Deleted user", userId);
return { deleted: true };
},
async addBadge(payload: AddBadgePayload) {
console.log("[task:addBadge] Creating badge", payload.name);
const supabase = createServiceRoleClient();
const badgeName = payload.name.trim();
const description = payload.description?.trim() || null;
const points = payload.points ?? 10;
const awardAtInterval = payload.awardAtInterval ?? "none";
let createdBy: string | null = null;
if (payload.createdByEmail) {
const { data: creatorRow } = await supabase
.from("User")
.select("id")
.eq("email", normalizeEmail(payload.createdByEmail))
.maybeSingle();
createdBy = creatorRow?.id ?? null;
}
const { data: existingBadge, error: existingBadgeError } = await supabase
.from("Badges")
.select("id")
.eq("name", badgeName)
.maybeSingle();
if (existingBadgeError) {
throw new Error(`Failed to lookup badge by name: ${existingBadgeError.message}`);
}
if (existingBadge?.id) {
const { error: updateError } = await supabase
.from("Badges")
.update({
description,
points,
award_at_interval: awardAtInterval,
img_link: null,
created_by: createdBy,
})
.eq("id", existingBadge.id);
if (updateError) {
throw new Error(`Failed to update badge: ${updateError.message}`);
}
console.log("[task:addBadge] Updated existing badge", existingBadge.id);
return { badgeId: existingBadge.id };
}
const { data: badgeRow, error: badgeError } = await supabase
.from("Badges")
.insert({
name: badgeName,
description,
points,
award_at_interval: awardAtInterval,
img_link: null,
created_by: createdBy,
})
.select("id")
.single();
if (badgeError || !badgeRow?.id) {
throw new Error(`Failed to add badge: ${badgeError?.message || "Unknown error"}`);
}
console.log("[task:addBadge] Created badge", badgeRow.id);
return { badgeId: badgeRow.id };
},
async deleteBadge({ badgeId }: { badgeId: string }) {
console.log("[task:deleteBadge] Deleting badge", badgeId);
const supabase = createServiceRoleClient();
await supabase.from("BadgeRequirements").delete().eq("badge_id", badgeId);
const { error } = await supabase.from("Badges").delete().eq("id", badgeId);
if (error) {
throw new Error(`Failed to delete badge: ${error.message}`);
}
console.log("[task:deleteBadge] Deleted badge", badgeId);
return { deleted: true };
},
});
},
},
});