@speakableio/core 0.1.66 → 0.1.68

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.
@@ -0,0 +1,3234 @@
1
+ // src/providers/SpeakableProvider.tsx
2
+ import { createContext, useContext, useEffect, useState } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ var FsCtx = createContext(null);
5
+ function SpeakableProvider({
6
+ user,
7
+ children,
8
+ queryClient,
9
+ permissions,
10
+ fsClient
11
+ }) {
12
+ const [speakableApi, setSpeakableApi] = useState(null);
13
+ useEffect(() => {
14
+ setSpeakableApi(fsClient);
15
+ }, [fsClient]);
16
+ if (!speakableApi) return null;
17
+ return /* @__PURE__ */ jsx(
18
+ FsCtx.Provider,
19
+ {
20
+ value: {
21
+ speakableApi,
22
+ queryClient,
23
+ user,
24
+ permissions
25
+ },
26
+ children
27
+ }
28
+ );
29
+ }
30
+ function useSpeakableApi() {
31
+ const ctx = useContext(FsCtx);
32
+ if (!ctx) throw new Error("useSpeakableApi must be used within a SpeakableProvider");
33
+ return ctx;
34
+ }
35
+
36
+ // src/utils/error-handler.ts
37
+ var ServiceError = class extends Error {
38
+ constructor(message, originalError, code) {
39
+ super(message);
40
+ this.originalError = originalError;
41
+ this.code = code;
42
+ this.name = "ServiceError";
43
+ }
44
+ };
45
+ function withErrorHandler(fn, serviceName) {
46
+ return async (...args) => {
47
+ try {
48
+ return await fn(...args);
49
+ } catch (error) {
50
+ if (error instanceof Error && "code" in error) {
51
+ const firebaseError = error;
52
+ throw new ServiceError(
53
+ `Error in ${serviceName}: ${firebaseError.message}`,
54
+ error,
55
+ firebaseError.code
56
+ );
57
+ }
58
+ if (error instanceof Error) {
59
+ throw new ServiceError(`Error in ${serviceName}: ${error.message}`, error);
60
+ }
61
+ throw new ServiceError(`Unknown error in ${serviceName}`, error);
62
+ }
63
+ };
64
+ }
65
+
66
+ // src/lib/firebase/api.ts
67
+ var FirebaseAPI = class _FirebaseAPI {
68
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
69
+ constructor() {
70
+ this.config = null;
71
+ }
72
+ static getInstance() {
73
+ if (!_FirebaseAPI.instance) {
74
+ _FirebaseAPI.instance = new _FirebaseAPI();
75
+ }
76
+ return _FirebaseAPI.instance;
77
+ }
78
+ initialize(config) {
79
+ this.config = config;
80
+ }
81
+ get db() {
82
+ if (!this.config) throw new Error("Firebase API not initialized");
83
+ return this.config.db;
84
+ }
85
+ get helpers() {
86
+ if (!this.config) throw new Error("Firebase API not initialized");
87
+ return this.config.helpers;
88
+ }
89
+ get httpsCallable() {
90
+ var _a;
91
+ return (_a = this.config) == null ? void 0 : _a.httpsCallable;
92
+ }
93
+ logEvent(name, data) {
94
+ var _a;
95
+ (_a = this.config) == null ? void 0 : _a.logEvent(name, data);
96
+ }
97
+ accessQueryConstraints() {
98
+ const { query: query2, orderBy: orderBy2, limit: limit2, startAt: startAt2, startAfter: startAfter2, endAt: endAt2, endBefore: endBefore2, where: where2, increment: increment2 } = this.helpers;
99
+ return {
100
+ query: query2,
101
+ orderBy: orderBy2,
102
+ limit: limit2,
103
+ startAt: startAt2,
104
+ startAfter: startAfter2,
105
+ endAt: endAt2,
106
+ endBefore: endBefore2,
107
+ where: where2,
108
+ increment: increment2
109
+ };
110
+ }
111
+ accessHelpers() {
112
+ const { doc: doc2, collection: collection2, writeBatch: writeBatch2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = this.helpers;
113
+ return {
114
+ doc: (path) => doc2(this.db, path),
115
+ collection: (path) => collection2(this.db, path),
116
+ writeBatch: () => writeBatch2(this.db),
117
+ serverTimestamp: serverTimestamp2,
118
+ setDoc: setDoc2
119
+ };
120
+ }
121
+ async getDoc(path) {
122
+ const { getDoc: getDoc2, doc: doc2 } = this.helpers;
123
+ const docRef = doc2(this.db, path);
124
+ const docSnap = await getDoc2(docRef);
125
+ const data = docSnap.exists() ? {
126
+ ...docSnap.data(),
127
+ id: docSnap.id
128
+ } : null;
129
+ return {
130
+ id: docSnap.id,
131
+ data
132
+ };
133
+ }
134
+ async getDocs(path, ...queryConstraints) {
135
+ const { getDocs: getDocs2, query: query2, collection: collection2 } = this.helpers;
136
+ const collectionRef = collection2(this.db, path);
137
+ const q = queryConstraints.length > 0 ? query2(collectionRef, ...queryConstraints) : collectionRef;
138
+ const querySnapshot = await getDocs2(q);
139
+ const data = querySnapshot.docs.map((doc2) => ({
140
+ data: doc2.data(),
141
+ id: doc2.id
142
+ }));
143
+ return {
144
+ data,
145
+ querySnapshot,
146
+ empty: querySnapshot.empty
147
+ };
148
+ }
149
+ async addDoc(path, data) {
150
+ const { addDoc: addDoc2, collection: collection2 } = this.helpers;
151
+ const collectionRef = collection2(this.db, path);
152
+ const docRef = await addDoc2(collectionRef, data);
153
+ return {
154
+ ...data,
155
+ id: docRef.id
156
+ };
157
+ }
158
+ async setDoc(path, data, options = {}) {
159
+ const { setDoc: setDoc2, doc: doc2 } = this.helpers;
160
+ const docRef = doc2(this.db, path);
161
+ await setDoc2(docRef, data, options);
162
+ }
163
+ async updateDoc(path, data) {
164
+ const { updateDoc: updateDoc2, doc: doc2 } = this.helpers;
165
+ const docRef = doc2(this.db, path);
166
+ await updateDoc2(docRef, data);
167
+ }
168
+ async deleteDoc(path) {
169
+ const { deleteDoc: deleteDoc2, doc: doc2 } = this.helpers;
170
+ const docRef = doc2(this.db, path);
171
+ await deleteDoc2(docRef);
172
+ }
173
+ async runTransaction(updateFunction) {
174
+ const { runTransaction: runTransaction2 } = this.helpers;
175
+ return runTransaction2(this.db, updateFunction);
176
+ }
177
+ async runBatch(operations) {
178
+ const { writeBatch: writeBatch2 } = this.helpers;
179
+ const batch = writeBatch2(this.db);
180
+ await Promise.all(operations.map((op) => op()));
181
+ await batch.commit();
182
+ }
183
+ writeBatch() {
184
+ const { writeBatch: writeBatch2 } = this.helpers;
185
+ const batch = writeBatch2(this.db);
186
+ return batch;
187
+ }
188
+ };
189
+ var api = FirebaseAPI.getInstance();
190
+
191
+ // src/domains/assignment/assignment.constants.ts
192
+ var ASSIGNMENT_ANALYTICS_TYPES = [
193
+ "macro" /* Macro */,
194
+ "gradebook" /* Gradebook */,
195
+ "cards" /* Cards */,
196
+ "student" /* Student */,
197
+ "student_summary" /* StudentSummary */
198
+ ];
199
+ var ASSIGNMENTS_COLLECTION = "assignments";
200
+ var ANALYTICS_SUBCOLLECTION = "analytics";
201
+ var SCORES_SUBCOLLECTION = "scores";
202
+ var refsAssignmentFiresotre = {
203
+ allAssignments: () => ASSIGNMENTS_COLLECTION,
204
+ assignment: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}`,
205
+ assignmentAllAnalytics: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${ANALYTICS_SUBCOLLECTION}`,
206
+ assignmentAnalytics: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${ANALYTICS_SUBCOLLECTION}/${params.type}`,
207
+ assignmentScores: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${SCORES_SUBCOLLECTION}/${params.userId}`
208
+ };
209
+
210
+ // src/domains/assignment/services/get-assignments-score.service.ts
211
+ var _getAssignmentScores = async ({
212
+ assignmentId,
213
+ analyticType = "macro" /* Macro */,
214
+ studentId,
215
+ currentUserId
216
+ }) => {
217
+ if (analyticType === "student" /* Student */) {
218
+ const path = refsAssignmentFiresotre.assignmentScores({
219
+ id: assignmentId,
220
+ userId: currentUserId
221
+ });
222
+ const response = await api.getDoc(path);
223
+ return { scores: response.data, id: assignmentId };
224
+ }
225
+ if (analyticType === "student_summary" /* StudentSummary */ && studentId) {
226
+ const path = refsAssignmentFiresotre.assignmentScores({
227
+ id: assignmentId,
228
+ userId: studentId
229
+ });
230
+ const response = await api.getDoc(path);
231
+ return { scores: response.data, id: assignmentId };
232
+ }
233
+ if (analyticType !== "all" /* All */ && ASSIGNMENT_ANALYTICS_TYPES.includes(analyticType)) {
234
+ const ref = refsAssignmentFiresotre.assignmentAnalytics({
235
+ id: assignmentId,
236
+ type: analyticType
237
+ });
238
+ const docData = await api.getDoc(ref);
239
+ return { scores: docData.data, id: assignmentId };
240
+ } else if (analyticType === "all" /* All */) {
241
+ const ref = refsAssignmentFiresotre.assignmentAllAnalytics({ id: assignmentId });
242
+ const response = await api.getDocs(ref);
243
+ const data = response.data.reduce((acc, curr) => {
244
+ acc[curr.id] = curr;
245
+ return acc;
246
+ }, {});
247
+ return { scores: data, id: assignmentId };
248
+ }
249
+ };
250
+ var getAssignmentScores = withErrorHandler(_getAssignmentScores, "getAssignmentScores");
251
+
252
+ // src/domains/assignment/services/attach-score-assignment.service.ts
253
+ var _attachScoresAssignment = async ({
254
+ assignments,
255
+ analyticType,
256
+ studentId,
257
+ currentUserId
258
+ }) => {
259
+ const scoresPromises = assignments.map((a) => {
260
+ return getAssignmentScores({
261
+ assignmentId: a.id,
262
+ analyticType,
263
+ studentId,
264
+ currentUserId
265
+ });
266
+ });
267
+ const scores = await Promise.all(scoresPromises);
268
+ const scoresObject = scores.reduce((acc, curr) => {
269
+ acc[curr.id] = curr.scores;
270
+ return acc;
271
+ }, {});
272
+ const assignmentsWithScores = assignments.map((a) => {
273
+ var _a;
274
+ return {
275
+ ...a,
276
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/ban-ts-comment
277
+ // @ts-ignore
278
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
279
+ scores: (_a = scoresObject[a.id]) != null ? _a : null
280
+ };
281
+ });
282
+ return assignmentsWithScores;
283
+ };
284
+ var attachScoresAssignment = withErrorHandler(
285
+ _attachScoresAssignment,
286
+ "attachScoresAssignment"
287
+ );
288
+
289
+ // src/domains/assignment/services/get-all-assignment.service.ts
290
+ async function _getAllAssignments() {
291
+ const path = refsAssignmentFiresotre.allAssignments();
292
+ const response = await api.getDocs(path);
293
+ return response.data;
294
+ }
295
+ var getAllAssignments = withErrorHandler(_getAllAssignments, "getAllAssignments");
296
+
297
+ // src/domains/assignment/utils/check-assignment-availability.ts
298
+ import dayjs from "dayjs";
299
+ var checkAssignmentAvailability = (scheduledTime) => {
300
+ if (!scheduledTime) return true;
301
+ const scheduledDate = typeof scheduledTime === "string" ? dayjs(scheduledTime) : dayjs(scheduledTime.toDate());
302
+ if (!scheduledDate.isValid()) return true;
303
+ return dayjs().isAfter(scheduledDate);
304
+ };
305
+
306
+ // src/domains/assignment/services/get-assignment.service.ts
307
+ async function _getAssignment(params) {
308
+ var _a;
309
+ const path = refsAssignmentFiresotre.assignment({ id: params.assignmentId });
310
+ const response = await api.getDoc(path);
311
+ if (!response.data) return null;
312
+ const assignment = response.data;
313
+ const isAvailable = checkAssignmentAvailability(assignment.scheduledTime);
314
+ const assignmentWithId = {
315
+ ...assignment,
316
+ isAvailable,
317
+ id: params.assignmentId,
318
+ scheduledTime: (_a = assignment.scheduledTime) != null ? _a : null
319
+ };
320
+ if (params.analyticType) {
321
+ const assignmentsWithScores = await attachScoresAssignment({
322
+ assignments: [assignmentWithId],
323
+ analyticType: params.analyticType,
324
+ currentUserId: params.currentUserId
325
+ });
326
+ return assignmentsWithScores.length > 0 ? assignmentsWithScores[0] : assignmentWithId;
327
+ }
328
+ return assignmentWithId;
329
+ }
330
+ var getAssignment = withErrorHandler(_getAssignment, "getAssignment");
331
+
332
+ // src/domains/assignment/assignment.repo.ts
333
+ var createAssignmentRepo = () => {
334
+ return {
335
+ getAssignment,
336
+ attachScoresAssignment,
337
+ getAssignmentScores,
338
+ getAllAssignments
339
+ };
340
+ };
341
+
342
+ // src/domains/assignment/hooks/assignment.hooks.ts
343
+ import { useQuery } from "@tanstack/react-query";
344
+ var assignmentQueryKeys = {
345
+ all: ["assignments"],
346
+ byId: (id) => [...assignmentQueryKeys.all, id],
347
+ list: () => [...assignmentQueryKeys.all, "list"]
348
+ };
349
+ function useAssignment({
350
+ assignmentId,
351
+ enabled = true,
352
+ analyticType,
353
+ userId
354
+ }) {
355
+ const { speakableApi } = useSpeakableApi();
356
+ return useQuery({
357
+ queryKey: assignmentQueryKeys.byId(assignmentId),
358
+ queryFn: () => speakableApi.assignmentRepo.getAssignment({
359
+ assignmentId,
360
+ analyticType,
361
+ currentUserId: userId
362
+ }),
363
+ enabled
364
+ });
365
+ }
366
+
367
+ // src/domains/assignment/hooks/score-hooks.ts
368
+ import { useMutation, useQuery as useQuery2 } from "@tanstack/react-query";
369
+
370
+ // src/utils/debounce.utils.ts
371
+ function debounce(func, waitFor) {
372
+ let timeoutId;
373
+ return (...args) => new Promise((resolve, reject) => {
374
+ if (timeoutId) {
375
+ clearTimeout(timeoutId);
376
+ }
377
+ timeoutId = setTimeout(async () => {
378
+ try {
379
+ const result = await func(...args);
380
+ resolve(result);
381
+ } catch (error) {
382
+ reject(error);
383
+ }
384
+ }, waitFor);
385
+ });
386
+ }
387
+
388
+ // src/lib/tanstack/handle-optimistic-update-query.ts
389
+ var handleOptimisticUpdate = async ({
390
+ queryClient,
391
+ queryKey,
392
+ newData
393
+ }) => {
394
+ await queryClient.cancelQueries({
395
+ queryKey
396
+ });
397
+ const previousData = queryClient.getQueryData(queryKey);
398
+ if (previousData === void 0) {
399
+ queryClient.setQueryData(queryKey, newData);
400
+ } else {
401
+ queryClient.setQueryData(queryKey, { ...previousData, ...newData });
402
+ }
403
+ return { previousData };
404
+ };
405
+
406
+ // src/constants/speakable-plans.ts
407
+ var FEEDBACK_PLANS = {
408
+ FEEDBACK_TRANSCRIPT: "FEEDBACK_TRANSCRIPT",
409
+ // Transcript from the audio
410
+ FEEDBACK_SUMMARY: "FEEDBACK_SUMMARY",
411
+ // Chatty summary (Free plan)
412
+ FEEDBACK_GRAMMAR_INSIGHTS: "FEEDBACK_GRAMMAR_INSIGHTS",
413
+ // Grammar insights
414
+ FEEDBACK_SUGGESTED_RESPONSE: "FEEDBACK_SUGGESTED_RESPONSE",
415
+ // Suggested Response
416
+ FEEDBACK_RUBRIC: "FEEDBACK_RUBRIC",
417
+ // Suggested Response
418
+ FEEDBACK_GRADING_STANDARDS: "FEEDBACK_GRADING_STANDARDS",
419
+ // ACTFL / WIDA Estimate
420
+ FEEDBACK_TARGET_LANGUAGE: "FEEDBACK_TARGET_LANGUAGE",
421
+ // Ability to set the feedback language to the target language of the student
422
+ FEEDBACK_DISABLE_ALLOW_RETRIES: "FEEDBACK_DISABLE_ALLOW_RETRIES"
423
+ // Turn of allow retries
424
+ };
425
+ var AUTO_GRADING_PLANS = {
426
+ AUTO_GRADING_PASS_FAIL: "AUTO_GRADING_PASS_FAIL",
427
+ // Pass / fail grading
428
+ AUTO_GRADING_RUBRICS: "AUTO_GRADING_RUBRICS",
429
+ // Autograded rubrics
430
+ AUTO_GRADING_STANDARDS_BASED: "AUTO_GRADING_STANDARDS_BASED"
431
+ // Standards based grading
432
+ };
433
+ var AI_ASSISTANT_PLANS = {
434
+ AI_ASSISTANT_DOCUMENT_UPLOADS: "AI_ASSISTANT_DOCUMENT_UPLOADS",
435
+ // Allow document uploading
436
+ AI_ASSISTANT_UNLIMITED_USE: "AI_ASSISTANT_UNLIMITED_USE"
437
+ // Allow unlimited use of AI assistant. Otherwise, limits are used.
438
+ };
439
+ var ASSIGNMENT_SETTINGS_PLANS = {
440
+ ASSESSMENTS: "ASSESSMENTS",
441
+ // Ability to create assessment assignment types
442
+ GOOGLE_CLASSROOM_GRADE_PASSBACK: "GOOGLE_CLASSROOM_GRADE_PASSBACK"
443
+ // Assignment scores can sync with classroom
444
+ };
445
+ var ANALYTICS_PLANS = {
446
+ ANALYTICS_GRADEBOOK: "ANALYTICS_GRADEBOOK",
447
+ // Access to the gradebook page
448
+ ANALYTICS_CLASSROOM_ANALYTICS: "ANALYTICS_CLASSROOM_ANALYTICS",
449
+ // Access to the classroom analytics page
450
+ ANALYTICS_STUDENT_PROGRESS_REPORTS: "ANALYTICS_STUDENT_PROGRESS_REPORTS",
451
+ // Access to the panel that shows an individual student's progress and assignments
452
+ ANALYTICS_ASSIGNMENT_RESULTS: "ANALYTICS_ASSIGNMENT_RESULTS",
453
+ // Access to the assigment RESULTS page
454
+ ANALYTICS_ORGANIZATION: "ANALYTICS_ORGANIZATION"
455
+ // Access to the organization analytics panel (for permitted admins)
456
+ };
457
+ var SPACES_PLANS = {
458
+ SPACES_CREATE_SPACE: "SPACES_CREATE_SPACE",
459
+ // Ability to create spaces
460
+ SPACES_CHECK_POINTS: "SPACES_CHECK_POINTS"
461
+ // Feature not available yet. Ability to create checkpoints for spaces for data aggregation
462
+ };
463
+ var DISCOVER_PLANS = {
464
+ DISCOVER_ORGANIZATION_LIBRARY: "DISCOVER_ORGANIZATION_LIBRARY"
465
+ // Access to the organizations shared library
466
+ };
467
+ var MEDIA_AREA_PLANS = {
468
+ MEDIA_AREA_DOCUMENT_UPLOAD: "MEDIA_AREA_DOCUMENT_UPLOAD",
469
+ MEDIA_AREA_AUDIO_FILES: "MEDIA_AREA_AUDIO_FILES"
470
+ };
471
+ var FREE_PLAN = [];
472
+ var TEACHER_PRO_PLAN = [
473
+ FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
474
+ FEEDBACK_PLANS.FEEDBACK_SUMMARY,
475
+ FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
476
+ AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
477
+ ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
478
+ SPACES_PLANS.SPACES_CREATE_SPACE
479
+ // AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
480
+ ];
481
+ var SCHOOL_STARTER = [
482
+ FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
483
+ FEEDBACK_PLANS.FEEDBACK_SUMMARY,
484
+ FEEDBACK_PLANS.FEEDBACK_GRAMMAR_INSIGHTS,
485
+ FEEDBACK_PLANS.FEEDBACK_SUGGESTED_RESPONSE,
486
+ FEEDBACK_PLANS.FEEDBACK_RUBRIC,
487
+ FEEDBACK_PLANS.FEEDBACK_GRADING_STANDARDS,
488
+ FEEDBACK_PLANS.FEEDBACK_DISABLE_ALLOW_RETRIES,
489
+ FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
490
+ AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
491
+ AUTO_GRADING_PLANS.AUTO_GRADING_RUBRICS,
492
+ AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
493
+ AI_ASSISTANT_PLANS.AI_ASSISTANT_DOCUMENT_UPLOADS,
494
+ AI_ASSISTANT_PLANS.AI_ASSISTANT_UNLIMITED_USE,
495
+ // ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS,
496
+ ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK,
497
+ ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
498
+ ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS,
499
+ ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS,
500
+ // ANALYTICS_PLANS.ANALYTICS_ORGANIZATION,
501
+ SPACES_PLANS.SPACES_CREATE_SPACE,
502
+ SPACES_PLANS.SPACES_CHECK_POINTS,
503
+ // DISCOVER_PLANS.DISCOVER_ORGANIZATION_LIBRARY,
504
+ MEDIA_AREA_PLANS.MEDIA_AREA_DOCUMENT_UPLOAD,
505
+ MEDIA_AREA_PLANS.MEDIA_AREA_AUDIO_FILES
506
+ ];
507
+ var ORGANIZATION_PLAN = [
508
+ FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
509
+ FEEDBACK_PLANS.FEEDBACK_SUMMARY,
510
+ FEEDBACK_PLANS.FEEDBACK_GRAMMAR_INSIGHTS,
511
+ FEEDBACK_PLANS.FEEDBACK_SUGGESTED_RESPONSE,
512
+ FEEDBACK_PLANS.FEEDBACK_RUBRIC,
513
+ FEEDBACK_PLANS.FEEDBACK_GRADING_STANDARDS,
514
+ FEEDBACK_PLANS.FEEDBACK_DISABLE_ALLOW_RETRIES,
515
+ FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
516
+ AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
517
+ AUTO_GRADING_PLANS.AUTO_GRADING_RUBRICS,
518
+ AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
519
+ AI_ASSISTANT_PLANS.AI_ASSISTANT_DOCUMENT_UPLOADS,
520
+ AI_ASSISTANT_PLANS.AI_ASSISTANT_UNLIMITED_USE,
521
+ ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS,
522
+ ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK,
523
+ ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
524
+ ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS,
525
+ ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS,
526
+ ANALYTICS_PLANS.ANALYTICS_ORGANIZATION,
527
+ SPACES_PLANS.SPACES_CREATE_SPACE,
528
+ SPACES_PLANS.SPACES_CHECK_POINTS,
529
+ DISCOVER_PLANS.DISCOVER_ORGANIZATION_LIBRARY,
530
+ MEDIA_AREA_PLANS.MEDIA_AREA_DOCUMENT_UPLOAD,
531
+ MEDIA_AREA_PLANS.MEDIA_AREA_AUDIO_FILES
532
+ ];
533
+ var SpeakablePlanTypes = {
534
+ basic: "basic",
535
+ teacher_pro: "teacher_pro",
536
+ school_starter: "school_starter",
537
+ organization: "organization",
538
+ // OLD PLANS
539
+ starter: "starter",
540
+ growth: "growth",
541
+ professional: "professional"
542
+ };
543
+ var SpeakablePermissionsMap = {
544
+ [SpeakablePlanTypes.basic]: FREE_PLAN,
545
+ [SpeakablePlanTypes.starter]: TEACHER_PRO_PLAN,
546
+ [SpeakablePlanTypes.teacher_pro]: TEACHER_PRO_PLAN,
547
+ [SpeakablePlanTypes.growth]: ORGANIZATION_PLAN,
548
+ [SpeakablePlanTypes.professional]: ORGANIZATION_PLAN,
549
+ [SpeakablePlanTypes.organization]: ORGANIZATION_PLAN,
550
+ [SpeakablePlanTypes.school_starter]: SCHOOL_STARTER
551
+ };
552
+ var SpeakablePlanHierarchy = [
553
+ SpeakablePlanTypes.basic,
554
+ SpeakablePlanTypes.starter,
555
+ SpeakablePlanTypes.teacher_pro,
556
+ SpeakablePlanTypes.growth,
557
+ SpeakablePlanTypes.professional,
558
+ SpeakablePlanTypes.school_starter,
559
+ SpeakablePlanTypes.organization
560
+ ];
561
+
562
+ // src/hooks/usePermissions.ts
563
+ var usePermissions = () => {
564
+ const { permissions } = useSpeakableApi();
565
+ const has = (permission) => {
566
+ var _a;
567
+ return (_a = permissions.permissions) == null ? void 0 : _a.includes(permission);
568
+ };
569
+ return {
570
+ plan: permissions.plan,
571
+ permissionsLoaded: permissions.loaded,
572
+ isStripePlan: permissions.isStripePlan,
573
+ refreshDate: permissions.refreshDate,
574
+ isInstitutionPlan: permissions.isInstitutionPlan,
575
+ subscriptionId: permissions.subscriptionId,
576
+ contact: permissions.contact,
577
+ hasGradebook: has(ANALYTICS_PLANS.ANALYTICS_GRADEBOOK),
578
+ hasGoogleClassroomGradePassback: has(ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK),
579
+ hasAssessments: has(ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS),
580
+ hasSectionAnalytics: has(ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS),
581
+ hasStudentReports: has(ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS),
582
+ permissions: permissions || [],
583
+ hasStudentPortfolios: permissions.hasStudentPortfolios,
584
+ isFreeOrgTrial: permissions.type === "free_org_trial",
585
+ freeOrgTrialExpired: permissions.freeOrgTrialExpired
586
+ };
587
+ };
588
+ var usePermissions_default = usePermissions;
589
+
590
+ // src/domains/notification/notification.constants.ts
591
+ var SPEAKABLE_NOTIFICATIONS = {
592
+ NEW_ASSIGNMENT: "new_assignment",
593
+ ASSESSMENT_SUBMITTED: "assessment_submitted",
594
+ ASSESSMENT_SCORED: "assessment_scored",
595
+ NEW_COMMENT: "NEW_COMMENT"
596
+ };
597
+ var SpeakableNotificationTypes = {
598
+ NEW_ASSIGNMENT: "NEW_ASSIGNMENT",
599
+ FEEDBACK_FROM_TEACHER: "FEEDBACK_FROM_TEACHER",
600
+ MESSAGE_FROM_STUDENT: "MESSAGE_FROM_STUDENT",
601
+ PHRASE_MARKED_CORRECT: "PHRASE_MARKED_CORRECT",
602
+ STUDENT_PROGRESS: "STUDENT_PROGRESS",
603
+ PLAYLIST_FOLLOWERS: "PLAYLIST_FOLLOWERS",
604
+ PLAYLIST_PLAYS: "PLAYLIST_PLAYS",
605
+ // New notifications
606
+ ASSESSMENT_SUBMITTED: "ASSESSMENT_SUBMITTED",
607
+ // Notification FOR TEACHER when student submits assessment
608
+ ASSESSMENT_SCORED: "ASSESSMENT_SCORED",
609
+ // Notification FOR STUDENT when teacher scores assessment
610
+ // Comment
611
+ NEW_COMMENT: "NEW_COMMENT"
612
+ };
613
+
614
+ // src/domains/notification/services/create-notification.service.ts
615
+ import dayjs2 from "dayjs";
616
+
617
+ // src/constants/web.constants.ts
618
+ var WEB_BASE_URL = "https://app.speakable.io";
619
+
620
+ // src/domains/notification/services/send-notification.service.ts
621
+ var _sendNotification = async (sendTo, notification) => {
622
+ var _a, _b, _c;
623
+ const results = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createNotificationV2")) == null ? void 0 : _c({
624
+ sendTo,
625
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
626
+ notification
627
+ }));
628
+ return results;
629
+ };
630
+ var sendNotification = withErrorHandler(_sendNotification, "sendNotification");
631
+
632
+ // src/domains/notification/services/create-notification.service.ts
633
+ var createNotification = async ({
634
+ data,
635
+ type,
636
+ userId,
637
+ profile
638
+ }) => {
639
+ let result;
640
+ switch (type) {
641
+ case SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT:
642
+ result = await handleAssignNotifPromise({ data, profile });
643
+ break;
644
+ case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED:
645
+ result = await createAssessmentSubmissionNotification({
646
+ data,
647
+ profile,
648
+ userId
649
+ });
650
+ break;
651
+ case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED:
652
+ result = await createAssessmentScoredNotification({
653
+ data,
654
+ profile
655
+ });
656
+ break;
657
+ default:
658
+ result = null;
659
+ break;
660
+ }
661
+ return result;
662
+ };
663
+ var handleAssignNotifPromise = async ({
664
+ data: assignments,
665
+ profile
666
+ }) => {
667
+ if (!assignments.length) return;
668
+ try {
669
+ const notifsPromises = assignments.map(async (assignment) => {
670
+ const {
671
+ section,
672
+ section: { members },
673
+ ...rest
674
+ } = assignment;
675
+ if (!section || !members) throw new Error("Invalid assignment data");
676
+ const data = { section, sendTo: members, assignment: { ...rest } };
677
+ return createNewAssignmentNotification({ data, profile });
678
+ });
679
+ await Promise.all(notifsPromises);
680
+ return {
681
+ success: true,
682
+ message: "Assignment notifications sent successfully"
683
+ };
684
+ } catch (error) {
685
+ console.error("Error in handleAssignNotifPromise:", error);
686
+ throw error;
687
+ }
688
+ };
689
+ var createNewAssignmentNotification = async ({
690
+ data,
691
+ profile
692
+ }) => {
693
+ var _a;
694
+ const { assignment, sendTo } = data;
695
+ const teacherName = profile.displayName || "Your teacher";
696
+ const dueDate = assignment.dueDateTimestamp ? dayjs2(assignment.dueDateTimestamp.toDate()).format("MMM Do") : null;
697
+ const results = await sendNotification(sendTo, {
698
+ courseId: assignment.courseId,
699
+ type: SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT,
700
+ senderName: teacherName,
701
+ link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
702
+ messagePreview: `A new assignment "${assignment.name}" is now available. ${dueDate ? `Due ${dueDate}` : ""}`,
703
+ title: "New Assignment Available!",
704
+ imageUrl: (_a = profile.image) == null ? void 0 : _a.url
705
+ });
706
+ return results;
707
+ };
708
+ var createAssessmentSubmissionNotification = async ({
709
+ data: assignment,
710
+ profile,
711
+ userId
712
+ }) => {
713
+ var _a;
714
+ const studentName = profile.displayName || "Your student";
715
+ const results = await sendNotification(assignment.owners, {
716
+ courseId: assignment.courseId,
717
+ type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED,
718
+ link: `${WEB_BASE_URL}/a/${assignment.id}?studentId=${userId}`,
719
+ title: `Assessment Submitted!`,
720
+ senderName: studentName,
721
+ messagePreview: `${studentName} has submitted the assessment "${assignment.name}"`,
722
+ imageUrl: (_a = profile.image) == null ? void 0 : _a.url
723
+ });
724
+ return results;
725
+ };
726
+ var createAssessmentScoredNotification = async ({
727
+ data,
728
+ profile
729
+ }) => {
730
+ var _a, _b, _c, _d, _e;
731
+ const { assignment, sendTo } = data;
732
+ const teacherName = profile.displayName || "Your teacher";
733
+ const title = `${assignment.isAssessment ? "Assessment" : "Assignment"} Reviewed!`;
734
+ const messagePreview = `Your ${assignment.isAssessment ? "assessment" : "assignment"} has been reviewed by your teacher. Click to view the feedback.`;
735
+ const results = await sendNotification(sendTo, {
736
+ courseId: assignment.courseId,
737
+ type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED,
738
+ link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
739
+ title,
740
+ messagePreview,
741
+ imageUrl: (_a = profile.image) == null ? void 0 : _a.url,
742
+ senderName: teacherName
743
+ });
744
+ await ((_e = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "sendAssessmentScoredEmail")) == null ? void 0 : _e({
745
+ assessmentTitle: assignment.name,
746
+ link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
747
+ senderImage: ((_d = profile.image) == null ? void 0 : _d.url) || "",
748
+ studentId: sendTo[0],
749
+ teacherName: profile.displayName
750
+ }));
751
+ return results;
752
+ };
753
+
754
+ // src/domains/notification/hooks/notification.hooks.ts
755
+ var notificationQueryKeys = {
756
+ all: ["notifications"],
757
+ byId: (id) => [...notificationQueryKeys.all, id]
758
+ };
759
+ var useCreateNotification = () => {
760
+ const { user, queryClient } = useSpeakableApi();
761
+ const handleCreateNotifications = async (type, data) => {
762
+ var _a, _b;
763
+ const result = await createNotification({
764
+ type,
765
+ userId: user.auth.uid,
766
+ profile: (_a = user == null ? void 0 : user.profile) != null ? _a : {},
767
+ data
768
+ });
769
+ queryClient.invalidateQueries({
770
+ queryKey: notificationQueryKeys.byId((_b = user == null ? void 0 : user.auth.uid) != null ? _b : "")
771
+ });
772
+ return result;
773
+ };
774
+ return {
775
+ createNotification: handleCreateNotifications
776
+ };
777
+ };
778
+
779
+ // src/hooks/useGoogleClassroom.ts
780
+ var useGoogleClassroom = () => {
781
+ const submitAssignmentToGoogleClassroom = async ({
782
+ assignment,
783
+ scores,
784
+ googleUserId = null
785
+ // optional to override the user's googleUserId
786
+ }) => {
787
+ var _a, _b, _c;
788
+ try {
789
+ const { googleClassroomUserId = null } = scores;
790
+ const googleId = googleUserId || googleClassroomUserId;
791
+ if (!googleId)
792
+ return {
793
+ error: true,
794
+ message: "No Google Classroom ID found"
795
+ };
796
+ const { courseWorkId, maxPoints, owners, courseId } = assignment;
797
+ const draftGrade = (scores == null ? void 0 : scores.score) ? (scores == null ? void 0 : scores.score) / 100 * maxPoints : 0;
798
+ const result = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentToGoogleClassroomV2")) == null ? void 0 : _c({
799
+ teacherId: owners[0],
800
+ courseId,
801
+ courseWorkId,
802
+ userId: googleId,
803
+ draftGrade
804
+ }));
805
+ return result;
806
+ } catch (error) {
807
+ return { error: true, message: error.message };
808
+ }
809
+ };
810
+ return {
811
+ submitAssignmentToGoogleClassroom
812
+ };
813
+ };
814
+
815
+ // src/lib/firebase/firebase-analytics/grading-standard.ts
816
+ var logGradingStandardLog = (data) => {
817
+ var _a, _b, _c;
818
+ if (data.courseId && data.type && data.level) {
819
+ (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
820
+ eventType: data.type || "custom",
821
+ level: data.level,
822
+ courseId: data.courseId
823
+ });
824
+ }
825
+ api.logEvent("logGradingStandard", data);
826
+ };
827
+
828
+ // src/constants/analytics.constants.ts
829
+ var ANALYTICS_EVENT_TYPES = {
830
+ VOICE_SUCCESS: "voice_success",
831
+ VOICE_FAIL: "voice_fail",
832
+ RESPOND_CARD_SUCCESS: "respond_card_success",
833
+ RESPOND_CARD_FAIL: "respond_card_fail",
834
+ RESPOND_WRITE_CARD_SUCCESS: "respond_write_card_success",
835
+ RESPOND_WRITE_CARD_FAIL: "respond_write_card_fail",
836
+ RESPOND_FREE_PLAN: "respond_free_plan",
837
+ RESPOND_WRITE_FREE_PLAN: "respond_write_free_plan",
838
+ SUBMISSION: "assignment_submitted",
839
+ ASSIGNMENT_STARTED: "assignment_started",
840
+ CREATE_ASSIGNMENT: "create_assignment",
841
+ MC_SUCCESS: "multiple_choice_success",
842
+ MC_FAIL: "multiple_choice_fail",
843
+ ACTFL_LEVEL: "actfl_level",
844
+ WIDA_LEVEL: "wida_level"
845
+ };
846
+
847
+ // src/lib/firebase/firebase-analytics/assignment.ts
848
+ var logOpenAssignment = (data = {}) => {
849
+ api.logEvent("open_assignment", data);
850
+ };
851
+ var logOpenActivityPreview = (data = {}) => {
852
+ api.logEvent("open_activity_preview", data);
853
+ };
854
+ var logSubmitAssignment = (data = {}) => {
855
+ var _a, _b, _c;
856
+ (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
857
+ eventType: ANALYTICS_EVENT_TYPES.SUBMISSION,
858
+ ...data
859
+ });
860
+ api.logEvent(ANALYTICS_EVENT_TYPES.SUBMISSION, data);
861
+ };
862
+ var logStartAssignment = (data = {}) => {
863
+ var _a, _b, _c;
864
+ if (data.courseId) {
865
+ (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
866
+ eventType: ANALYTICS_EVENT_TYPES.ASSIGNMENT_STARTED,
867
+ ...data
868
+ });
869
+ }
870
+ api.logEvent(ANALYTICS_EVENT_TYPES.ASSIGNMENT_STARTED, data);
871
+ };
872
+
873
+ // src/domains/assignment/utils/create-default-score.ts
874
+ var defaultScore = (props) => {
875
+ const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
876
+ const score = {
877
+ progress: 0,
878
+ score: 0,
879
+ startDate: serverTimestamp2(),
880
+ status: "IN_PROGRESS",
881
+ submitted: false,
882
+ cards: {},
883
+ lastPlayed: serverTimestamp2(),
884
+ owners: props.owners,
885
+ userId: props.userId
886
+ };
887
+ if (props.googleClassroomUserId) {
888
+ score.googleClassroomUserId = props.googleClassroomUserId;
889
+ }
890
+ if (props.courseId) {
891
+ score.courseId = props.courseId;
892
+ }
893
+ return score;
894
+ };
895
+
896
+ // src/domains/assignment/score-practice.constants.ts
897
+ var SCORES_PRACTICE_COLLECTION = "users";
898
+ var SCORES_PRACTICE_SUBCOLLECTION = "practice";
899
+ var refsScoresPractice = {
900
+ practiceScores: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}`,
901
+ practiceScoreHistoryRefDoc: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}/attempts/${params.date}`
902
+ };
903
+
904
+ // src/domains/assignment/services/create-score.service.ts
905
+ async function _createScore(params) {
906
+ var _a, _b, _c;
907
+ if (params.isAssignment) {
908
+ const ref = refsAssignmentFiresotre.assignmentScores({
909
+ id: params.activityId,
910
+ userId: params.userId
911
+ });
912
+ await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "updateAssignmentGradebookStatus")) == null ? void 0 : _c({
913
+ assignmentId: params.activityId,
914
+ userId: params.userId,
915
+ status: "IN_PROGRESS",
916
+ score: null
917
+ }));
918
+ await api.setDoc(ref, params.scoreData, { merge: true });
919
+ return {
920
+ id: params.userId
921
+ };
922
+ } else {
923
+ const ref = refsScoresPractice.practiceScores({
924
+ userId: params.userId,
925
+ setId: params.activityId
926
+ });
927
+ await api.setDoc(ref, params.scoreData);
928
+ return {
929
+ id: params.userId
930
+ };
931
+ }
932
+ }
933
+ var createScore = withErrorHandler(_createScore, "createScore");
934
+
935
+ // src/domains/assignment/services/get-score.service.ts
936
+ async function getAssignmentScore({
937
+ userId,
938
+ assignment,
939
+ googleClassroomUserId
940
+ }) {
941
+ const path = refsAssignmentFiresotre.assignmentScores({
942
+ id: assignment.id,
943
+ userId
944
+ });
945
+ const response = await api.getDoc(path);
946
+ if (response.data == null) {
947
+ const newScore = {
948
+ ...defaultScore({
949
+ owners: [userId],
950
+ userId,
951
+ courseId: assignment.courseId,
952
+ googleClassroomUserId
953
+ }),
954
+ assignmentId: assignment.id
955
+ };
956
+ logStartAssignment({
957
+ courseId: assignment.courseId
958
+ });
959
+ const result = await createScore({
960
+ activityId: assignment.id,
961
+ userId,
962
+ isAssignment: true,
963
+ scoreData: newScore
964
+ });
965
+ return {
966
+ ...newScore,
967
+ id: result.id
968
+ };
969
+ }
970
+ return response.data;
971
+ }
972
+ async function getPracticeScore({ userId, setId }) {
973
+ const path = refsScoresPractice.practiceScores({ userId, setId });
974
+ const response = await api.getDoc(path);
975
+ if (response.data == null) {
976
+ const newScore = {
977
+ ...defaultScore({
978
+ owners: [userId],
979
+ userId
980
+ }),
981
+ setId
982
+ };
983
+ const result = await createScore({
984
+ activityId: setId,
985
+ userId,
986
+ isAssignment: false,
987
+ scoreData: newScore
988
+ });
989
+ return {
990
+ ...newScore,
991
+ id: result.id
992
+ };
993
+ }
994
+ return response.data;
995
+ }
996
+ async function _getScore(params) {
997
+ if (params.isAssignment) {
998
+ return await getAssignmentScore({
999
+ userId: params.userId,
1000
+ assignment: {
1001
+ id: params.activityId,
1002
+ courseId: params.courseId
1003
+ },
1004
+ googleClassroomUserId: params.googleClassroomUserId
1005
+ });
1006
+ } else {
1007
+ return await getPracticeScore({
1008
+ userId: params.userId,
1009
+ setId: params.activityId
1010
+ });
1011
+ }
1012
+ }
1013
+ var getScore = withErrorHandler(_getScore, "getScore");
1014
+
1015
+ // src/domains/assignment/utils/calculateScoreAndProgress.ts
1016
+ var calculateScoreAndProgress = (scores, cardsList, weights) => {
1017
+ const totalSetPoints = cardsList.reduce((acc, cardId) => {
1018
+ acc += (weights == null ? void 0 : weights[cardId]) || 1;
1019
+ return acc;
1020
+ }, 0);
1021
+ const totalPointsAwarded = Object.keys((scores == null ? void 0 : scores.cards) || {}).reduce((acc, cardId) => {
1022
+ var _a, _b;
1023
+ const cardScores = (_a = scores == null ? void 0 : scores.cards) == null ? void 0 : _a[cardId];
1024
+ if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1025
+ const score2 = (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0 ? Number((_b = cardScores == null ? void 0 : cardScores.score) != null ? _b : 0) : null;
1026
+ const weight = (weights == null ? void 0 : weights[cardId]) || 1;
1027
+ const fraction = (score2 != null ? score2 : 0) / 100;
1028
+ if (score2 || score2 === 0) {
1029
+ acc += weight * fraction;
1030
+ } else {
1031
+ acc += weight;
1032
+ }
1033
+ }
1034
+ return acc;
1035
+ }, 0);
1036
+ const totalCompletedCards = Object.keys((scores == null ? void 0 : scores.cards) || {}).reduce((acc, cardId) => {
1037
+ var _a;
1038
+ const cardScores = (_a = scores == null ? void 0 : scores.cards) == null ? void 0 : _a[cardId];
1039
+ if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1040
+ acc += 1;
1041
+ }
1042
+ return acc;
1043
+ }, 0);
1044
+ const percent = totalPointsAwarded / totalSetPoints;
1045
+ const score = Math.round(percent * 100);
1046
+ const progress = Math.round(totalCompletedCards / (cardsList.length || 1) * 100);
1047
+ return { score, progress };
1048
+ };
1049
+ var calculateScoreAndProgress_default = calculateScoreAndProgress;
1050
+
1051
+ // src/domains/assignment/services/update-score.service.ts
1052
+ async function _updateScore(params) {
1053
+ const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1054
+ id: params.activityId,
1055
+ userId: params.userId
1056
+ }) : refsScoresPractice.practiceScores({
1057
+ setId: params.activityId,
1058
+ userId: params.userId
1059
+ });
1060
+ await api.updateDoc(path, {
1061
+ ...params.data
1062
+ });
1063
+ }
1064
+ var updateScore = withErrorHandler(_updateScore, "updateScore");
1065
+ async function _updateCardScore(params) {
1066
+ const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1067
+ id: params.activityId,
1068
+ userId: params.userId
1069
+ }) : refsScoresPractice.practiceScores({
1070
+ setId: params.activityId,
1071
+ userId: params.userId
1072
+ });
1073
+ const updates = Object.keys(params.updates.cardScore).reduce(
1074
+ (acc, key) => {
1075
+ acc[`cards.${params.cardId}.${key}`] = params.updates.cardScore[key];
1076
+ return acc;
1077
+ },
1078
+ {}
1079
+ );
1080
+ if (params.updates.progress) {
1081
+ updates.progress = params.updates.progress;
1082
+ }
1083
+ if (params.updates.score) {
1084
+ updates.score = params.updates.score;
1085
+ }
1086
+ await api.updateDoc(path, {
1087
+ ...updates
1088
+ });
1089
+ }
1090
+ var updateCardScore = withErrorHandler(_updateCardScore, "updateCardScore");
1091
+
1092
+ // src/domains/assignment/services/clear-score.service.ts
1093
+ import dayjs3 from "dayjs";
1094
+ async function clearScore(params) {
1095
+ var _a, _b, _c, _d, _e;
1096
+ const update = {
1097
+ [`cards.${params.cardId}`]: {
1098
+ attempts: (_a = params.cardScores.attempts) != null ? _a : 1,
1099
+ correct: (_b = params.cardScores.correct) != null ? _b : 0,
1100
+ // save old score history
1101
+ history: [
1102
+ {
1103
+ ...params.cardScores,
1104
+ attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1105
+ correct: (_d = params.cardScores.correct) != null ? _d : 0,
1106
+ retryTime: dayjs3().format("YYYY-MM-DD HH:mm:ss"),
1107
+ history: null
1108
+ },
1109
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1110
+ ...(_e = params.cardScores.history) != null ? _e : []
1111
+ ]
1112
+ }
1113
+ };
1114
+ const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1115
+ id: params.activityId,
1116
+ userId: params.userId
1117
+ }) : refsScoresPractice.practiceScores({
1118
+ setId: params.activityId,
1119
+ userId: params.userId
1120
+ });
1121
+ await api.updateDoc(path, update);
1122
+ return {
1123
+ update,
1124
+ activityId: params.activityId
1125
+ };
1126
+ }
1127
+
1128
+ // src/domains/assignment/services/submit-assignment-score.service.ts
1129
+ import dayjs4 from "dayjs";
1130
+ async function _submitAssignmentScore({
1131
+ cardIds,
1132
+ assignment,
1133
+ weights,
1134
+ userId,
1135
+ status,
1136
+ studentName
1137
+ }) {
1138
+ const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1139
+ const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1140
+ const fieldsUpdated = {
1141
+ submitted: true,
1142
+ progress: 100,
1143
+ submissionDate: serverTimestamp2(),
1144
+ status
1145
+ };
1146
+ if (assignment.isAssessment) {
1147
+ const result = await handleAssessment(
1148
+ assignment,
1149
+ userId,
1150
+ cardIds,
1151
+ weights,
1152
+ fieldsUpdated,
1153
+ studentName
1154
+ );
1155
+ return result;
1156
+ } else if (assignment.courseId) {
1157
+ await handleCourseAssignment(assignment, userId);
1158
+ }
1159
+ await api.updateDoc(path, { ...fieldsUpdated });
1160
+ return { success: true, fieldsUpdated };
1161
+ }
1162
+ var submitAssignmentScore = withErrorHandler(
1163
+ _submitAssignmentScore,
1164
+ "submitAssignmentScore"
1165
+ );
1166
+ async function handleAssessment(assignment, userId, cardIds, weights, fieldsUpdated, studentName) {
1167
+ var _a, _b, _c;
1168
+ const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1169
+ const response = await api.getDoc(path);
1170
+ if (!response.data) {
1171
+ throw new Error("Score not found");
1172
+ }
1173
+ const { score: scoreCalculated } = calculateScoreAndProgress_default(response.data, cardIds, weights);
1174
+ await api.updateDoc(path, { score: scoreCalculated, status: "PENDING_REVIEW" });
1175
+ await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssessment")) == null ? void 0 : _c({
1176
+ assignmentId: assignment.id,
1177
+ assignmentTitle: assignment.name,
1178
+ userId,
1179
+ teacherId: assignment.owners[0],
1180
+ studentName
1181
+ }));
1182
+ fieldsUpdated.status = "PENDING_REVIEW";
1183
+ return { success: true, fieldsUpdated };
1184
+ }
1185
+ async function handleCourseAssignment(assignment, userId) {
1186
+ var _a, _b, _c;
1187
+ await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentV2")) == null ? void 0 : _c({
1188
+ assignmentId: assignment.id,
1189
+ userId
1190
+ }));
1191
+ }
1192
+ async function submitPracticeScore({
1193
+ setId,
1194
+ userId,
1195
+ scores
1196
+ }) {
1197
+ const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1198
+ const date = dayjs4().format("YYYY-MM-DD-HH-mm");
1199
+ const ref = refsScoresPractice.practiceScoreHistoryRefDoc({ setId, userId, date });
1200
+ const fieldsUpdated = {
1201
+ ...scores,
1202
+ submitted: true,
1203
+ progress: 100,
1204
+ submissionDate: serverTimestamp2(),
1205
+ status: "SUBMITTED"
1206
+ };
1207
+ await api.setDoc(ref, { ...fieldsUpdated });
1208
+ const refScores = refsScoresPractice.practiceScores({ userId, setId });
1209
+ await api.deleteDoc(refScores);
1210
+ return { success: true, fieldsUpdated };
1211
+ }
1212
+
1213
+ // src/domains/assignment/hooks/score-hooks.ts
1214
+ var scoreQueryKeys = {
1215
+ all: ["scores"],
1216
+ byId: (id) => [...scoreQueryKeys.all, id],
1217
+ list: () => [...scoreQueryKeys.all, "list"]
1218
+ };
1219
+ function useScore({
1220
+ isAssignment,
1221
+ activityId,
1222
+ userId = "",
1223
+ courseId,
1224
+ enabled = true,
1225
+ googleClassroomUserId
1226
+ }) {
1227
+ return useQuery2({
1228
+ queryFn: () => getScore({
1229
+ userId,
1230
+ courseId,
1231
+ activityId,
1232
+ googleClassroomUserId,
1233
+ isAssignment
1234
+ }),
1235
+ queryKey: scoreQueryKeys.byId(activityId),
1236
+ enabled
1237
+ });
1238
+ }
1239
+ var debounceUpdateScore = debounce(updateScore, 1e3);
1240
+ function useUpdateScore() {
1241
+ const { queryClient } = useSpeakableApi();
1242
+ const mutation = useMutation({
1243
+ mutationFn: debounceUpdateScore,
1244
+ onMutate: (variables) => {
1245
+ return handleOptimisticUpdate({
1246
+ queryClient,
1247
+ queryKey: scoreQueryKeys.byId(variables.activityId),
1248
+ newData: variables.data
1249
+ });
1250
+ },
1251
+ onError: (_, variables, context) => {
1252
+ if (context == null ? void 0 : context.previousData)
1253
+ queryClient.setQueryData(scoreQueryKeys.byId(variables.activityId), context.previousData);
1254
+ },
1255
+ onSettled: (_, err, variables) => {
1256
+ queryClient.invalidateQueries({
1257
+ queryKey: scoreQueryKeys.byId(variables.activityId)
1258
+ });
1259
+ }
1260
+ });
1261
+ return {
1262
+ mutationUpdateScore: mutation
1263
+ };
1264
+ }
1265
+ function useUpdateCardScore({
1266
+ isAssignment,
1267
+ activityId,
1268
+ userId,
1269
+ cardIds,
1270
+ weights
1271
+ }) {
1272
+ const { queryClient } = useSpeakableApi();
1273
+ const queryKey = scoreQueryKeys.byId(activityId);
1274
+ const mutation = useMutation({
1275
+ mutationFn: async ({ cardId, cardScore }) => {
1276
+ const previousScores = queryClient.getQueryData(queryKey);
1277
+ const { progress, score, newScoreUpdated, updatedCardScore } = getScoreUpdated({
1278
+ previousScores: previousScores != null ? previousScores : {},
1279
+ cardId,
1280
+ cardScore,
1281
+ cardIds,
1282
+ weights
1283
+ });
1284
+ await updateCardScore({
1285
+ userId,
1286
+ cardId,
1287
+ isAssignment,
1288
+ activityId,
1289
+ updates: {
1290
+ cardScore: updatedCardScore,
1291
+ progress,
1292
+ score
1293
+ }
1294
+ });
1295
+ return { cardId, scoresUpdated: newScoreUpdated };
1296
+ },
1297
+ onMutate: ({ cardId, cardScore }) => {
1298
+ queryClient.setQueryData(queryKey, (previousScore) => {
1299
+ const updates = handleOptimisticScore({
1300
+ score: previousScore,
1301
+ cardId,
1302
+ cardScore,
1303
+ cardIds,
1304
+ weights
1305
+ });
1306
+ return {
1307
+ ...previousScore,
1308
+ ...updates
1309
+ };
1310
+ });
1311
+ },
1312
+ // eslint-disable-next-line no-unused-vars
1313
+ onError: (error) => {
1314
+ console.log(error.message);
1315
+ const previousData = queryClient.getQueryData(queryKey);
1316
+ if (previousData) {
1317
+ queryClient.setQueryData(queryKey, previousData);
1318
+ }
1319
+ }
1320
+ });
1321
+ return {
1322
+ mutationUpdateCardScore: mutation
1323
+ };
1324
+ }
1325
+ var getScoreUpdated = ({
1326
+ cardId,
1327
+ cardScore,
1328
+ previousScores,
1329
+ cardIds,
1330
+ weights
1331
+ }) => {
1332
+ var _a, _b;
1333
+ const previousCard = (_a = previousScores.cards) == null ? void 0 : _a[cardId];
1334
+ const newCardScore = {
1335
+ ...previousCard != null ? previousCard : {},
1336
+ ...cardScore
1337
+ };
1338
+ const newScores = {
1339
+ ...previousScores,
1340
+ cards: {
1341
+ ...(_b = previousScores.cards) != null ? _b : {},
1342
+ [cardId]: newCardScore
1343
+ }
1344
+ };
1345
+ const { score, progress } = calculateScoreAndProgress_default(newScores, cardIds, weights);
1346
+ return {
1347
+ newScoreUpdated: newScores,
1348
+ updatedCardScore: cardScore,
1349
+ score,
1350
+ progress
1351
+ };
1352
+ };
1353
+ var handleOptimisticScore = ({
1354
+ score,
1355
+ cardId,
1356
+ cardScore,
1357
+ cardIds,
1358
+ weights
1359
+ }) => {
1360
+ var _a;
1361
+ let cards = { ...(_a = score == null ? void 0 : score.cards) != null ? _a : {} };
1362
+ cards = {
1363
+ ...cards,
1364
+ [cardId]: {
1365
+ ...cards[cardId],
1366
+ ...cardScore
1367
+ }
1368
+ };
1369
+ const { score: scoreValue, progress } = calculateScoreAndProgress_default(
1370
+ // @ts-ignore
1371
+ {
1372
+ ...score != null ? score : {},
1373
+ cards
1374
+ },
1375
+ cardIds,
1376
+ weights
1377
+ );
1378
+ return { cards, score: scoreValue, progress };
1379
+ };
1380
+ function useClearScore() {
1381
+ const { queryClient } = useSpeakableApi();
1382
+ const mutation = useMutation({
1383
+ mutationFn: clearScore,
1384
+ onSettled: (result) => {
1385
+ var _a;
1386
+ queryClient.invalidateQueries({
1387
+ queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1388
+ });
1389
+ }
1390
+ });
1391
+ return {
1392
+ mutationClearScore: mutation
1393
+ };
1394
+ }
1395
+ function useSubmitAssignmentScore({
1396
+ onAssignmentSubmitted,
1397
+ studentName
1398
+ }) {
1399
+ const { queryClient } = useSpeakableApi();
1400
+ const { hasGoogleClassroomGradePassback } = usePermissions_default();
1401
+ const { submitAssignmentToGoogleClassroom } = useGoogleClassroom();
1402
+ const { createNotification: createNotification2 } = useCreateNotification();
1403
+ const mutation = useMutation({
1404
+ mutationFn: async ({
1405
+ assignment,
1406
+ userId,
1407
+ cardIds,
1408
+ weights,
1409
+ scores,
1410
+ status
1411
+ }) => {
1412
+ try {
1413
+ const scoreUpdated = await submitAssignmentScore({
1414
+ assignment,
1415
+ userId,
1416
+ cardIds,
1417
+ weights,
1418
+ status,
1419
+ studentName
1420
+ });
1421
+ if (assignment.courseWorkId != null && !assignment.isAssessment && hasGoogleClassroomGradePassback) {
1422
+ await submitAssignmentToGoogleClassroom({
1423
+ assignment,
1424
+ scores
1425
+ });
1426
+ }
1427
+ if (assignment.isAssessment) {
1428
+ createNotification2(SpeakableNotificationTypes.ASSESSMENT_SUBMITTED, assignment);
1429
+ }
1430
+ if (assignment == null ? void 0 : assignment.id) {
1431
+ logSubmitAssignment({
1432
+ courseId: assignment == null ? void 0 : assignment.courseId
1433
+ });
1434
+ }
1435
+ onAssignmentSubmitted(assignment.id);
1436
+ queryClient.setQueryData(scoreQueryKeys.byId(assignment.id), {
1437
+ ...scores,
1438
+ ...scoreUpdated.fieldsUpdated
1439
+ });
1440
+ return {
1441
+ success: true,
1442
+ message: "Score submitted successfully"
1443
+ };
1444
+ } catch (error) {
1445
+ return {
1446
+ success: false,
1447
+ error
1448
+ };
1449
+ }
1450
+ }
1451
+ });
1452
+ return {
1453
+ submitAssignmentScore: mutation.mutateAsync,
1454
+ isLoading: mutation.isPending
1455
+ };
1456
+ }
1457
+ function useSubmitPracticeScore() {
1458
+ const { queryClient } = useSpeakableApi();
1459
+ const mutation = useMutation({
1460
+ mutationFn: async ({
1461
+ setId,
1462
+ userId,
1463
+ scores
1464
+ }) => {
1465
+ try {
1466
+ await submitPracticeScore({
1467
+ setId,
1468
+ userId,
1469
+ scores
1470
+ });
1471
+ queryClient.invalidateQueries({
1472
+ queryKey: scoreQueryKeys.byId(setId)
1473
+ });
1474
+ return {
1475
+ success: true,
1476
+ message: "Score submitted successfully"
1477
+ };
1478
+ } catch (error) {
1479
+ return {
1480
+ success: false,
1481
+ error
1482
+ };
1483
+ }
1484
+ }
1485
+ });
1486
+ return {
1487
+ submitPracticeScore: mutation.mutateAsync,
1488
+ isLoading: mutation.isPending
1489
+ };
1490
+ }
1491
+
1492
+ // src/domains/cards/card.hooks.ts
1493
+ import { useMutation as useMutation2, useQueries, useQuery as useQuery3 } from "@tanstack/react-query";
1494
+ import { useMemo } from "react";
1495
+
1496
+ // src/domains/cards/card.constants.ts
1497
+ var FeedbackTypesCard = /* @__PURE__ */ ((FeedbackTypesCard2) => {
1498
+ FeedbackTypesCard2["SuggestedResponse"] = "suggested_response";
1499
+ FeedbackTypesCard2["Wida"] = "wida";
1500
+ FeedbackTypesCard2["GrammarInsights"] = "grammar_insights";
1501
+ FeedbackTypesCard2["Actfl"] = "actfl";
1502
+ FeedbackTypesCard2["ProficiencyLevel"] = "proficiency_level";
1503
+ return FeedbackTypesCard2;
1504
+ })(FeedbackTypesCard || {});
1505
+ var LeniencyCard = /* @__PURE__ */ ((LeniencyCard2) => {
1506
+ LeniencyCard2["CONFIDENCE"] = "confidence";
1507
+ LeniencyCard2["EASY"] = "easy";
1508
+ LeniencyCard2["NORMAL"] = "normal";
1509
+ LeniencyCard2["HARD"] = "hard";
1510
+ return LeniencyCard2;
1511
+ })(LeniencyCard || {});
1512
+ var LENIENCY_OPTIONS = [
1513
+ {
1514
+ label: "Build Confidence - most lenient",
1515
+ value: "confidence" /* CONFIDENCE */
1516
+ },
1517
+ {
1518
+ label: "Very Lenient",
1519
+ value: "easy" /* EASY */
1520
+ },
1521
+ {
1522
+ label: "Normal",
1523
+ value: "normal" /* NORMAL */
1524
+ },
1525
+ {
1526
+ label: "No leniency - most strict",
1527
+ value: "hard" /* HARD */
1528
+ }
1529
+ ];
1530
+ var STUDENT_LEVELS_OPTIONS = [
1531
+ {
1532
+ label: "Beginner",
1533
+ description: "Beginner Level: Just starting out. Can say a few basic words and phrases.",
1534
+ value: "beginner"
1535
+ },
1536
+ {
1537
+ label: "Elementary",
1538
+ description: "Elementary Level: Can understand simple sentences and have very basic conversations.",
1539
+ value: "elementary"
1540
+ },
1541
+ {
1542
+ label: "Intermediate",
1543
+ description: "Intermediate Level: Can talk about everyday topics and handle common situations.",
1544
+ value: "intermediate"
1545
+ },
1546
+ {
1547
+ label: "Advanced",
1548
+ description: "Advanced Level: Can speak and understand with ease, and explain ideas clearly.",
1549
+ value: "advanced"
1550
+ },
1551
+ {
1552
+ label: "Fluent",
1553
+ description: "Fluent Level: Speaks naturally and easily. Can use the language in work or school settings.",
1554
+ value: "fluent"
1555
+ },
1556
+ {
1557
+ label: "Native-like",
1558
+ description: "Native-like Level: Understands and speaks like a native. Can discuss complex ideas accurately.",
1559
+ value: "nativeLike"
1560
+ }
1561
+ ];
1562
+ var BASE_RESPOND_FIELD_VALUES = {
1563
+ title: "",
1564
+ allowRetries: true,
1565
+ respondTime: 180,
1566
+ maxCharacters: 1e3
1567
+ };
1568
+ var BASE_REPEAT_FIELD_VALUES = {
1569
+ repeat: 1
1570
+ };
1571
+ var BASE_MULTIPLE_CHOICE_FIELD_VALUES = {
1572
+ MCQType: "single",
1573
+ answer: ["A"],
1574
+ choices: [
1575
+ { option: "A", value: "Option A" },
1576
+ { option: "B", value: "Option B" },
1577
+ { option: "C", value: "Option C" }
1578
+ ]
1579
+ };
1580
+ var VerificationCardStatus = /* @__PURE__ */ ((VerificationCardStatus2) => {
1581
+ VerificationCardStatus2["VERIFIED"] = "VERIFIED";
1582
+ VerificationCardStatus2["WARNING"] = "WARNING";
1583
+ VerificationCardStatus2["NOT_RECOMMENDED"] = "NOT_RECOMMENDED";
1584
+ VerificationCardStatus2["NOT_WORKING"] = "NOT_WORKING";
1585
+ VerificationCardStatus2["NOT_CHECKED"] = "NOT_CHECKED";
1586
+ return VerificationCardStatus2;
1587
+ })(VerificationCardStatus || {});
1588
+ var CARDS_COLLECTION = "flashcards";
1589
+ var refsCardsFiresotre = {
1590
+ allCards: CARDS_COLLECTION,
1591
+ card: (id) => `${CARDS_COLLECTION}/${id}`
1592
+ };
1593
+
1594
+ // src/domains/cards/services/get-card.service.ts
1595
+ async function _getCard(params) {
1596
+ const ref = refsCardsFiresotre.card(params.cardId);
1597
+ const response = await api.getDoc(ref);
1598
+ if (!response.data) return null;
1599
+ return response.data;
1600
+ }
1601
+ var getCard = withErrorHandler(_getCard, "getCard");
1602
+
1603
+ // src/domains/cards/services/create-card.service.ts
1604
+ import { v4 } from "uuid";
1605
+
1606
+ // src/domains/cards/card.model.ts
1607
+ var ActivityPageType = /* @__PURE__ */ ((ActivityPageType2) => {
1608
+ ActivityPageType2["READ_REPEAT"] = "READ_REPEAT";
1609
+ ActivityPageType2["VIDEO"] = "VIDEO";
1610
+ ActivityPageType2["TEXT"] = "TEXT";
1611
+ ActivityPageType2["READ_RESPOND"] = "READ_RESPOND";
1612
+ ActivityPageType2["FREE_RESPONSE"] = "FREE_RESPONSE";
1613
+ ActivityPageType2["REPEAT"] = "REPEAT";
1614
+ ActivityPageType2["RESPOND"] = "RESPOND";
1615
+ ActivityPageType2["RESPOND_WRITE"] = "RESPOND_WRITE";
1616
+ ActivityPageType2["TEXT_TO_SPEECH"] = "TEXT_TO_SPEECH";
1617
+ ActivityPageType2["MULTIPLE_CHOICE"] = "MULTIPLE_CHOICE";
1618
+ ActivityPageType2["PODCAST"] = "PODCAST";
1619
+ ActivityPageType2["MEDIA_PAGE"] = "MEDIA_PAGE";
1620
+ ActivityPageType2["WRITE"] = "WRITE";
1621
+ ActivityPageType2["SHORT_ANSWER"] = "SHORT_ANSWER";
1622
+ ActivityPageType2["SHORT_STORY"] = "SHORT_STORY";
1623
+ ActivityPageType2["SPEAK"] = "SPEAK";
1624
+ ActivityPageType2["CONVERSATION"] = "CONVERSATION";
1625
+ ActivityPageType2["CONVERSATION_WRITE"] = "CONVERSATION_WRITE";
1626
+ ActivityPageType2["DIALOGUE"] = "DIALOGUE";
1627
+ ActivityPageType2["INSTRUCTION"] = "INSTRUCTION";
1628
+ ActivityPageType2["LISTEN"] = "LISTEN";
1629
+ ActivityPageType2["READ"] = "READ";
1630
+ ActivityPageType2["ANSWER"] = "ANSWER";
1631
+ return ActivityPageType2;
1632
+ })(ActivityPageType || {});
1633
+ var RESPOND_PAGE_ACTIVITY_TYPES = [
1634
+ "READ_RESPOND" /* READ_RESPOND */,
1635
+ "RESPOND" /* RESPOND */,
1636
+ "RESPOND_WRITE" /* RESPOND_WRITE */,
1637
+ "FREE_RESPONSE" /* FREE_RESPONSE */
1638
+ ];
1639
+ var MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES = ["MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */];
1640
+ var REPEAT_PAGE_ACTIVITY_TYPES = ["READ_REPEAT" /* READ_REPEAT */, "REPEAT" /* REPEAT */];
1641
+ var RESPOND_WRITE_PAGE_ACTIVITY_TYPES = [
1642
+ "RESPOND_WRITE" /* RESPOND_WRITE */,
1643
+ "FREE_RESPONSE" /* FREE_RESPONSE */
1644
+ ];
1645
+ var RESPOND_AUDIO_PAGE_ACTIVITY_TYPES = [
1646
+ "RESPOND" /* RESPOND */,
1647
+ "READ_RESPOND" /* READ_RESPOND */
1648
+ ];
1649
+
1650
+ // src/utils/text-utils.ts
1651
+ import sha1 from "js-sha1";
1652
+ var purify = (word) => {
1653
+ return word.normalize("NFD").replace(/\/([^" "]*)/g, "").replace(/\([^()]*\)/g, "").replace(/([^()]*)/g, "").replace(/[\u0300-\u036f]/g, "").replace(/[-]/g, " ").replace(/[.,/#!¡¿?؟。,.?$%^&*;:{}=\-_`~()’'…\s]/g, "").replace(/\s\s+/g, " ").toLowerCase().trim();
1654
+ };
1655
+ var cleanString = (words) => {
1656
+ const splitWords = words == null ? void 0 : words.split("+");
1657
+ if (splitWords && splitWords.length === 1) {
1658
+ const newWord = purify(words);
1659
+ return newWord;
1660
+ } else if (splitWords && splitWords.length > 1) {
1661
+ const split = splitWords.map((w) => purify(w));
1662
+ return split;
1663
+ } else {
1664
+ return "";
1665
+ }
1666
+ };
1667
+ var getWordHash = (word, language) => {
1668
+ const cleanedWord = cleanString(word);
1669
+ const wordHash = sha1(`${language}-${cleanedWord}`);
1670
+ console.log("wordHash core library", wordHash);
1671
+ return wordHash;
1672
+ };
1673
+ function getPhraseLength(phrase, input) {
1674
+ if (Array.isArray(phrase) && phrase.includes(input)) {
1675
+ return phrase[phrase.indexOf(input)].split(" ").length;
1676
+ } else {
1677
+ return phrase ? phrase.split(" ").length : 0;
1678
+ }
1679
+ }
1680
+
1681
+ // src/domains/cards/services/get-card-verification-status.service.ts
1682
+ var charactarLanguages = ["zh", "ja", "ko"];
1683
+ var getVerificationStatus = async (target_text, language) => {
1684
+ if ((target_text == null ? void 0 : target_text.length) < 3 && !charactarLanguages.includes(language)) {
1685
+ return "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1686
+ }
1687
+ const hash = getWordHash(target_text, language);
1688
+ const response = await api.getDoc(`checked-pronunciations/${hash}`);
1689
+ try {
1690
+ if (response.data) {
1691
+ return processRecord(response.data);
1692
+ } else {
1693
+ return "NOT_CHECKED" /* NOT_CHECKED */;
1694
+ }
1695
+ } catch (e) {
1696
+ return "NOT_CHECKED" /* NOT_CHECKED */;
1697
+ }
1698
+ };
1699
+ var processRecord = (data) => {
1700
+ const { pronunciations = 0, fails = 0 } = data;
1701
+ const attempts = pronunciations + fails;
1702
+ const successRate = attempts > 0 ? pronunciations / attempts * 100 : 0;
1703
+ let newStatus = null;
1704
+ if (attempts < 6) {
1705
+ return "NOT_CHECKED" /* NOT_CHECKED */;
1706
+ }
1707
+ if (successRate > 25) {
1708
+ newStatus = "VERIFIED" /* VERIFIED */;
1709
+ } else if (successRate > 10) {
1710
+ newStatus = "WARNING" /* WARNING */;
1711
+ } else if (fails > 20 && successRate < 10 && pronunciations > 1) {
1712
+ newStatus = "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1713
+ } else if (pronunciations === 0 && fails > 20) {
1714
+ newStatus = "NOT_WORKING" /* NOT_WORKING */;
1715
+ } else {
1716
+ newStatus = "NOT_CHECKED" /* NOT_CHECKED */;
1717
+ }
1718
+ return newStatus;
1719
+ };
1720
+
1721
+ // src/domains/cards/services/create-card.service.ts
1722
+ async function _createCard({ data }) {
1723
+ const response = await api.addDoc(refsCardsFiresotre.allCards, data);
1724
+ return response;
1725
+ }
1726
+ var createCard = withErrorHandler(_createCard, "createCard");
1727
+ async function _createCards({ cards }) {
1728
+ const { writeBatch: writeBatch2, doc: doc2 } = api.accessHelpers();
1729
+ const batch = writeBatch2();
1730
+ const cardsWithId = [];
1731
+ for (const card of cards) {
1732
+ const cardId = v4();
1733
+ const ref = doc2(refsCardsFiresotre.card(cardId));
1734
+ const newCardObject = {
1735
+ ...card,
1736
+ id: cardId
1737
+ };
1738
+ if (card.type === "READ_REPEAT" /* READ_REPEAT */ && card.target_text && card.language) {
1739
+ const verificationStatus = await getVerificationStatus(card.target_text, card.language);
1740
+ newCardObject.verificationStatus = verificationStatus || null;
1741
+ }
1742
+ cardsWithId.push(newCardObject);
1743
+ batch.set(ref, newCardObject);
1744
+ }
1745
+ await batch.commit();
1746
+ return cardsWithId;
1747
+ }
1748
+ var createCards = withErrorHandler(_createCards, "createCards");
1749
+
1750
+ // src/domains/cards/card.hooks.ts
1751
+ var cardsQueryKeys = {
1752
+ all: ["cards"],
1753
+ one: (params) => [...cardsQueryKeys.all, params.cardId]
1754
+ };
1755
+ function useCards({
1756
+ cardIds,
1757
+ enabled = true,
1758
+ asObject
1759
+ }) {
1760
+ const queries = useQueries({
1761
+ queries: cardIds.map((cardId) => ({
1762
+ enabled: enabled && cardIds.length > 0,
1763
+ queryKey: cardsQueryKeys.one({
1764
+ cardId
1765
+ }),
1766
+ queryFn: () => getCard({ cardId })
1767
+ }))
1768
+ });
1769
+ const cards = queries.map((query2) => query2.data).filter(Boolean);
1770
+ const cardsObject = useMemo(() => {
1771
+ if (!asObject) return null;
1772
+ return cards.reduce((acc, card) => {
1773
+ acc[card.id] = card;
1774
+ return acc;
1775
+ }, {});
1776
+ }, [asObject, cards]);
1777
+ return {
1778
+ cards,
1779
+ cardsObject,
1780
+ cardsQueries: queries
1781
+ };
1782
+ }
1783
+ function useCreateCard() {
1784
+ const { queryClient } = useSpeakableApi();
1785
+ const mutationCreateCard = useMutation2({
1786
+ mutationFn: createCard,
1787
+ onSuccess: (cardCreated) => {
1788
+ queryClient.invalidateQueries({ queryKey: cardsQueryKeys.one({ cardId: cardCreated.id }) });
1789
+ }
1790
+ });
1791
+ return {
1792
+ mutationCreateCard
1793
+ };
1794
+ }
1795
+ function useCreateCards() {
1796
+ const mutationCreateCards = useMutation2({
1797
+ mutationFn: createCards
1798
+ });
1799
+ return {
1800
+ mutationCreateCards
1801
+ };
1802
+ }
1803
+ function getCardFromCache({
1804
+ cardId,
1805
+ queryClient
1806
+ }) {
1807
+ return queryClient.getQueryData(cardsQueryKeys.one({ cardId }));
1808
+ }
1809
+ function updateCardInCache({
1810
+ cardId,
1811
+ card,
1812
+ queryClient
1813
+ }) {
1814
+ queryClient.setQueryData(cardsQueryKeys.one({ cardId }), card);
1815
+ }
1816
+ function useGetCard({ cardId, enabled = true }) {
1817
+ const query2 = useQuery3({
1818
+ queryKey: cardsQueryKeys.one({ cardId }),
1819
+ queryFn: () => getCard({ cardId }),
1820
+ enabled: enabled && !!cardId
1821
+ });
1822
+ return query2;
1823
+ }
1824
+
1825
+ // src/domains/cards/card.repo.ts
1826
+ var createCardRepo = () => {
1827
+ return {
1828
+ createCard,
1829
+ createCards,
1830
+ getCard
1831
+ };
1832
+ };
1833
+
1834
+ // src/domains/cards/utils/check-page-type.ts
1835
+ function checkIsRepeatPage(cardType) {
1836
+ if (cardType === void 0) return false;
1837
+ return REPEAT_PAGE_ACTIVITY_TYPES.includes(cardType);
1838
+ }
1839
+ function checkIsMCPage(cardType) {
1840
+ if (cardType === void 0) return false;
1841
+ return MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES.includes(cardType);
1842
+ }
1843
+ function checkIsRespondPage(cardType) {
1844
+ if (cardType === void 0) return false;
1845
+ return RESPOND_PAGE_ACTIVITY_TYPES.includes(cardType);
1846
+ }
1847
+ function checkIsRespondWrittenPage(cardType) {
1848
+ if (cardType === void 0) return false;
1849
+ return RESPOND_WRITE_PAGE_ACTIVITY_TYPES.includes(cardType);
1850
+ }
1851
+ function checkIsRespondAudioPage(cardType) {
1852
+ if (cardType === void 0) return false;
1853
+ return RESPOND_AUDIO_PAGE_ACTIVITY_TYPES.includes(cardType);
1854
+ }
1855
+ var checkIsMediaPage = (cardType) => {
1856
+ if (cardType === void 0) return false;
1857
+ return cardType === "MEDIA_PAGE" /* MEDIA_PAGE */;
1858
+ };
1859
+ var checkIsShortAnswerPage = (cardType) => {
1860
+ if (cardType === void 0) return false;
1861
+ return cardType === "SHORT_ANSWER" /* SHORT_ANSWER */;
1862
+ };
1863
+ var checkTypePageActivity = (cardType) => {
1864
+ const isRespondAudio = checkIsRespondAudioPage(cardType);
1865
+ const isRespondWritten = checkIsRespondWrittenPage(cardType);
1866
+ const isRespond = checkIsRespondPage(cardType);
1867
+ const isMC = checkIsMCPage(cardType);
1868
+ const isRepeat = checkIsRepeatPage(cardType);
1869
+ const isMediaPage = checkIsMediaPage(cardType);
1870
+ const isShortAnswer = checkIsShortAnswerPage(cardType);
1871
+ return {
1872
+ isRespondAudio,
1873
+ isRespondWritten,
1874
+ isRespond,
1875
+ isMC,
1876
+ isRepeat,
1877
+ isMediaPage,
1878
+ isShortAnswer
1879
+ };
1880
+ };
1881
+
1882
+ // src/domains/cards/utils/get-page-prompt.ts
1883
+ function getPagePrompt(card) {
1884
+ if (!card) return { has: false, text: "" };
1885
+ const { isMC, isRepeat, isRespond, isShortAnswer } = checkTypePageActivity(card == null ? void 0 : card.type);
1886
+ const hidePrompt = (card == null ? void 0 : card.hidePrompt) === true;
1887
+ if (isRepeat) {
1888
+ return {
1889
+ has: true,
1890
+ text: card == null ? void 0 : card.target_text
1891
+ };
1892
+ }
1893
+ if (isRespond && !hidePrompt) {
1894
+ return {
1895
+ has: true,
1896
+ text: card == null ? void 0 : card.prompt
1897
+ };
1898
+ }
1899
+ if (isMC) {
1900
+ return {
1901
+ has: true,
1902
+ text: card == null ? void 0 : card.question
1903
+ };
1904
+ }
1905
+ if (isShortAnswer && !hidePrompt) {
1906
+ return {
1907
+ has: true,
1908
+ text: card == null ? void 0 : card.prompt
1909
+ };
1910
+ }
1911
+ return {
1912
+ has: false,
1913
+ text: ""
1914
+ };
1915
+ }
1916
+
1917
+ // src/domains/sets/set.hooks.ts
1918
+ import { useQuery as useQuery4 } from "@tanstack/react-query";
1919
+
1920
+ // src/domains/sets/set.constants.ts
1921
+ var SETS_COLLECTION = "sets";
1922
+ var refsSetsFirestore = {
1923
+ allSets: SETS_COLLECTION,
1924
+ set: (id) => `${SETS_COLLECTION}/${id}`
1925
+ };
1926
+
1927
+ // src/domains/sets/services/get-set.service.ts
1928
+ async function _getSet({ setId }) {
1929
+ const response = await api.getDoc(refsSetsFirestore.set(setId));
1930
+ return response.data;
1931
+ }
1932
+ var getSet = withErrorHandler(_getSet, "getSet");
1933
+
1934
+ // src/domains/sets/set.hooks.ts
1935
+ var setsQueryKeys = {
1936
+ all: ["sets"],
1937
+ one: (params) => [...setsQueryKeys.all, params.setId]
1938
+ };
1939
+ var useSet = ({ setId, enabled }) => {
1940
+ return useQuery4({
1941
+ queryKey: setsQueryKeys.one({ setId }),
1942
+ queryFn: () => getSet({ setId }),
1943
+ enabled: setId !== void 0 && setId !== "" && enabled
1944
+ });
1945
+ };
1946
+ function getSetFromCache({
1947
+ setId,
1948
+ queryClient
1949
+ }) {
1950
+ if (!setId) return null;
1951
+ return queryClient.getQueryData(setsQueryKeys.one({ setId }));
1952
+ }
1953
+ function updateSetInCache({
1954
+ set,
1955
+ queryClient
1956
+ }) {
1957
+ const { id, ...setData } = set;
1958
+ queryClient.setQueryData(setsQueryKeys.one({ setId: id }), setData);
1959
+ }
1960
+
1961
+ // src/domains/sets/set.repo.ts
1962
+ var createSetRepo = () => {
1963
+ return {
1964
+ getSet
1965
+ };
1966
+ };
1967
+
1968
+ // src/constants/all-langs.json
1969
+ var all_langs_default = {
1970
+ af: "Afrikaans",
1971
+ sq: "Albanian",
1972
+ am: "Amharic",
1973
+ ar: "Arabic",
1974
+ hy: "Armenian",
1975
+ az: "Azerbaijani",
1976
+ eu: "Basque",
1977
+ be: "Belarusian",
1978
+ bn: "Bengali",
1979
+ bs: "Bosnian",
1980
+ bg: "Bulgarian",
1981
+ ca: "Catalan",
1982
+ ceb: "Cebuano",
1983
+ zh: "Chinese",
1984
+ co: "Corsican",
1985
+ hr: "Croatian",
1986
+ cs: "Czech",
1987
+ da: "Danish",
1988
+ nl: "Dutch",
1989
+ en: "English",
1990
+ eo: "Esperanto",
1991
+ et: "Estonian",
1992
+ fi: "Finnish",
1993
+ fr: "French",
1994
+ fy: "Frisian",
1995
+ gl: "Galician",
1996
+ ka: "Georgian",
1997
+ de: "German",
1998
+ el: "Greek",
1999
+ gu: "Gujarati",
2000
+ ht: "Haitian Creole",
2001
+ ha: "Hausa",
2002
+ haw: "Hawaiian",
2003
+ he: "Hebrew",
2004
+ hi: "Hindi",
2005
+ hmn: "Hmong",
2006
+ hu: "Hungarian",
2007
+ is: "Icelandic",
2008
+ ig: "Igbo",
2009
+ id: "Indonesian",
2010
+ ga: "Irish",
2011
+ it: "Italian",
2012
+ ja: "Japanese",
2013
+ jv: "Javanese",
2014
+ kn: "Kannada",
2015
+ kk: "Kazakh",
2016
+ km: "Khmer",
2017
+ ko: "Korean",
2018
+ ku: "Kurdish",
2019
+ ky: "Kyrgyz",
2020
+ lo: "Lao",
2021
+ la: "Latin",
2022
+ lv: "Latvian",
2023
+ lt: "Lithuanian",
2024
+ lb: "Luxembourgish",
2025
+ mk: "Macedonian",
2026
+ mg: "Malagasy",
2027
+ ms: "Malay",
2028
+ ml: "Malayalam",
2029
+ mt: "Maltese",
2030
+ mi: "Maori",
2031
+ mr: "Marathi",
2032
+ mn: "Mongolian",
2033
+ my: "Myanmar (Burmese)",
2034
+ ne: "Nepali",
2035
+ no: "Norwegian",
2036
+ ny: "Nyanja (Chichewa)",
2037
+ ps: "Pashto",
2038
+ fa: "Persian",
2039
+ pl: "Polish",
2040
+ pt: "Portuguese",
2041
+ pa: "Punjabi",
2042
+ ro: "Romanian",
2043
+ ru: "Russian",
2044
+ sm: "Samoan",
2045
+ gd: "Scots Gaelic",
2046
+ sr: "Serbian",
2047
+ st: "Sesotho",
2048
+ sn: "Shona",
2049
+ sd: "Sindhi",
2050
+ si: "Sinhala (Sinhalese)",
2051
+ sk: "Slovak",
2052
+ sl: "Slovenian",
2053
+ so: "Somali",
2054
+ es: "Spanish",
2055
+ su: "Sundanese",
2056
+ sw: "Swahili",
2057
+ sv: "Swedish",
2058
+ tl: "Tagalog (Filipino)",
2059
+ tg: "Tajik",
2060
+ ta: "Tamil",
2061
+ te: "Telugu",
2062
+ th: "Thai",
2063
+ tr: "Turkish",
2064
+ uk: "Ukrainian",
2065
+ ur: "Urdu",
2066
+ uz: "Uzbek",
2067
+ vi: "Vietnamese",
2068
+ cy: "Welsh",
2069
+ xh: "Xhosa",
2070
+ yi: "Yiddish",
2071
+ yo: "Yoruba",
2072
+ zu: "Zulu"
2073
+ };
2074
+
2075
+ // src/utils/ai/get-respond-card-tool.ts
2076
+ var getRespondCardTool = ({
2077
+ language,
2078
+ standard = "actfl"
2079
+ }) => {
2080
+ const lang = all_langs_default[language] || "English";
2081
+ const tool = {
2082
+ tool_choice: {
2083
+ type: "function",
2084
+ function: { name: "get_feedback" }
2085
+ },
2086
+ tools: [
2087
+ {
2088
+ type: "function",
2089
+ function: {
2090
+ name: "get_feedback",
2091
+ description: "Get feedback on a student's response",
2092
+ parameters: {
2093
+ type: "object",
2094
+ required: [
2095
+ "success",
2096
+ "score",
2097
+ "score_justification",
2098
+ "errors",
2099
+ "improvedResponse",
2100
+ "compliments"
2101
+ ],
2102
+ properties: {
2103
+ success: {
2104
+ type: "boolean",
2105
+ description: "Mark true if the student's response was on-topic and generally demonstrated understanding. A few grammar mistakes are acceptable. Mark false if the student's response was off-topic or did not demonstrate understanding."
2106
+ },
2107
+ errors: {
2108
+ type: "array",
2109
+ items: {
2110
+ type: "object",
2111
+ required: ["error", "grammar_error_type", "correction", "justification"],
2112
+ properties: {
2113
+ error: {
2114
+ type: "string",
2115
+ description: "The grammatical error in the student's response."
2116
+ },
2117
+ correction: {
2118
+ type: "string",
2119
+ description: "The suggested correction to the error"
2120
+ },
2121
+ justification: {
2122
+ type: "string",
2123
+ description: `An explanation of the rationale behind the suggested correction. WRITE THIS IN ${lang}!`
2124
+ },
2125
+ grammar_error_type: {
2126
+ type: "string",
2127
+ enum: [
2128
+ "subjVerbAgree",
2129
+ "tenseErrors",
2130
+ "articleMisuse",
2131
+ "prepositionErrors",
2132
+ "adjNounAgree",
2133
+ "pronounErrors",
2134
+ "wordOrder",
2135
+ "verbConjugation",
2136
+ "pluralization",
2137
+ "negationErrors",
2138
+ "modalVerbMisuse",
2139
+ "relativeClause",
2140
+ "auxiliaryVerb",
2141
+ "complexSentenceAgreement",
2142
+ "idiomaticExpression",
2143
+ "registerInconsistency",
2144
+ "voiceMisuse"
2145
+ ],
2146
+ description: "The type of grammatical error found. It should be one of the following categories: subject-verb agreement, tense errors, article misuse, preposition errors, adjective-noun agreement, pronoun errors, word order, verb conjugation, pluralization errors, negation errors, modal verb misuse, relative clause errors, auxiliary verb misuse, complex sentence agreement, idiomatic expression, register inconsistency, or voice misuse"
2147
+ }
2148
+ }
2149
+ },
2150
+ description: "An array of objects, each representing a grammatical error in the student's response. Each object should have the following properties: error, grammar_error_type, correction, and justification. If there were no errors, return an empty array."
2151
+ },
2152
+ compliments: {
2153
+ type: "array",
2154
+ items: {
2155
+ type: "string"
2156
+ },
2157
+ description: `An array of strings, each representing something the student did well. Each string should be WRITTEN IN ${lang}!`
2158
+ },
2159
+ improvedResponse: {
2160
+ type: "string",
2161
+ description: "An improved response with proper grammar and more detail, if applicable."
2162
+ },
2163
+ score: {
2164
+ type: "number",
2165
+ description: "A score between 0 and 100, reflecting the overall quality of the response"
2166
+ },
2167
+ score_justification: {
2168
+ type: "string",
2169
+ description: "An explanation of the rationale behind the assigned score, considering both accuracy and fluency"
2170
+ }
2171
+ }
2172
+ }
2173
+ }
2174
+ }
2175
+ ]
2176
+ };
2177
+ if (standard === "wida") {
2178
+ const wida_level = {
2179
+ type: "number",
2180
+ enum: [1, 2, 3, 4, 5, 6],
2181
+ description: `The student's WIDA (World-Class Instructional Design and Assessment) proficiency level. Choose one of the following options: 1, 2, 3, 4, 5, 6 which corresponds to
2182
+
2183
+ 1 - Entering
2184
+ 2 - Emerging
2185
+ 3 - Developing
2186
+ 4 - Expanding
2187
+ 5 - Bridging
2188
+ 6 - Reaching
2189
+
2190
+ This is an estimate based on the level of the student's response. Use the descriptions of the WIDA speaking standards to guide your decision.
2191
+ `
2192
+ };
2193
+ const wida_justification = {
2194
+ type: "string",
2195
+ description: `An explanation of the rationale behind the assigned WIDA level of the response, considering both accuracy and fluency. WRITE THIS IN ENGLISH!`
2196
+ };
2197
+ tool.tools[0].function.parameters.required.push("wida_level");
2198
+ tool.tools[0].function.parameters.required.push("wida_justification");
2199
+ tool.tools[0].function.parameters.properties.wida_level = wida_level;
2200
+ tool.tools[0].function.parameters.properties.wida_justification = wida_justification;
2201
+ } else {
2202
+ const actfl_level = {
2203
+ type: "string",
2204
+ enum: ["NL", "NM", "NH", "IL", "IM", "IH", "AL", "AM", "AH", "S", "D"],
2205
+ description: "The student's ACTFL (American Council on the Teaching of Foreign Languages) proficiency level. Choose one of the following options: NL, NM, NH, IL, IM, IH, AL, AM, AH, S, or D"
2206
+ };
2207
+ const actfl_justification = {
2208
+ type: "string",
2209
+ description: "An explanation of the rationale behind the assigned ACTFL level, considering both accuracy and fluency"
2210
+ };
2211
+ tool.tools[0].function.parameters.required.push("actfl_level");
2212
+ tool.tools[0].function.parameters.required.push("actfl_justification");
2213
+ tool.tools[0].function.parameters.properties.actfl_level = actfl_level;
2214
+ tool.tools[0].function.parameters.properties.actfl_justification = actfl_justification;
2215
+ }
2216
+ return tool;
2217
+ };
2218
+
2219
+ // src/hooks/useActivity.ts
2220
+ import { useEffect as useEffect2 } from "react";
2221
+
2222
+ // src/services/add-grading-standard.ts
2223
+ var addGradingStandardLog = async (gradingStandard, userId) => {
2224
+ logGradingStandardLog(gradingStandard);
2225
+ const path = `users/${userId}/grading_standard_logs`;
2226
+ await api.addDoc(path, gradingStandard);
2227
+ };
2228
+
2229
+ // src/hooks/useActivityTracker.ts
2230
+ import { v4 as v42 } from "uuid";
2231
+ function useActivityTracker({ userId }) {
2232
+ const trackActivity = async ({
2233
+ activityName,
2234
+ activityType,
2235
+ id = v42(),
2236
+ language = ""
2237
+ }) => {
2238
+ if (userId) {
2239
+ const { doc: doc2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = api.accessHelpers();
2240
+ const activityRef = doc2(`users/${userId}/activity/${id}`);
2241
+ const timestamp = serverTimestamp2();
2242
+ await setDoc2(activityRef, {
2243
+ name: activityName,
2244
+ type: activityType,
2245
+ lastSeen: timestamp,
2246
+ id,
2247
+ language
2248
+ });
2249
+ }
2250
+ };
2251
+ return {
2252
+ trackActivity
2253
+ };
2254
+ }
2255
+
2256
+ // src/hooks/useActivity.ts
2257
+ function useActivity({
2258
+ id,
2259
+ isAssignment,
2260
+ onAssignmentSubmitted,
2261
+ ltiData
2262
+ }) {
2263
+ var _a, _b;
2264
+ const { queryClient, user } = useSpeakableApi();
2265
+ const userId = user.auth.uid;
2266
+ const assignmentQuery = useAssignment({
2267
+ assignmentId: id,
2268
+ userId,
2269
+ enabled: isAssignment
2270
+ });
2271
+ const activeAssignment = assignmentQuery.data;
2272
+ const setId = isAssignment ? (_a = activeAssignment == null ? void 0 : activeAssignment.setId) != null ? _a : "" : id;
2273
+ const querySet = useSet({ setId });
2274
+ const setData = querySet.data;
2275
+ const assignmentContent = activeAssignment == null ? void 0 : activeAssignment.content;
2276
+ const assignmentWeights = activeAssignment == null ? void 0 : activeAssignment.weights;
2277
+ const setContent = setData == null ? void 0 : setData.content;
2278
+ const setWeights = setData == null ? void 0 : setData.weights;
2279
+ const contentCardsToUse = isAssignment ? assignmentContent != null ? assignmentContent : setContent : setContent;
2280
+ const weightsToUse = isAssignment ? assignmentWeights != null ? assignmentWeights : setWeights : setWeights;
2281
+ const activityId = isAssignment ? (_b = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b : "" : setId;
2282
+ const { cardsObject, cardsQueries, cards } = useCards({
2283
+ cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2284
+ enabled: querySet.isSuccess,
2285
+ asObject: true
2286
+ });
2287
+ const scoreQuery = useScore({
2288
+ isAssignment,
2289
+ activityId: id,
2290
+ userId,
2291
+ courseId: activeAssignment == null ? void 0 : activeAssignment.courseId,
2292
+ googleClassroomUserId: user.profile.googleClassroomUserId,
2293
+ enabled: isAssignment ? assignmentQuery.isSuccess : querySet.isSuccess
2294
+ });
2295
+ const { mutationUpdateScore } = useUpdateScore();
2296
+ const { mutationUpdateCardScore } = useUpdateCardScore({
2297
+ activityId,
2298
+ isAssignment,
2299
+ userId,
2300
+ cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2301
+ weights: weightsToUse != null ? weightsToUse : {}
2302
+ });
2303
+ const { mutationClearScore } = useClearScore();
2304
+ const { submitAssignmentScore: submitAssignmentScore2 } = useSubmitAssignmentScore({
2305
+ onAssignmentSubmitted,
2306
+ studentName: user.profile.displayName
2307
+ });
2308
+ const { submitPracticeScore: submitPracticeScore2 } = useSubmitPracticeScore();
2309
+ const handleUpdateScore = (data) => {
2310
+ mutationUpdateScore.mutate({
2311
+ data,
2312
+ isAssignment,
2313
+ activityId,
2314
+ userId
2315
+ });
2316
+ };
2317
+ const handleUpdateCardScore = (cardId, cardScore) => {
2318
+ mutationUpdateCardScore.mutate({ cardId, cardScore });
2319
+ if (cardScore.proficiency_level) {
2320
+ logGradingStandardEntry({
2321
+ type: cardScore.proficiency_level.standardId,
2322
+ cardId,
2323
+ gradingStandard: cardScore.proficiency_level
2324
+ });
2325
+ } else if (cardScore.wida || cardScore.actfl) {
2326
+ logGradingStandardEntry({
2327
+ type: cardScore.wida ? "wida" : "actfl",
2328
+ cardId,
2329
+ gradingStandard: cardScore.wida || cardScore.actfl || { level: "", justification: "" }
2330
+ });
2331
+ }
2332
+ };
2333
+ const onClearScore = ({
2334
+ cardId,
2335
+ wasCompleted = true
2336
+ }) => {
2337
+ var _a2, _b2;
2338
+ const currentCard = cardsObject == null ? void 0 : cardsObject[cardId];
2339
+ if ((currentCard == null ? void 0 : currentCard.type) === "MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */ || (currentCard == null ? void 0 : currentCard.type) === "READ_REPEAT" /* READ_REPEAT */) {
2340
+ return;
2341
+ }
2342
+ const queryKeys = scoreQueryKeys.byId(activityId);
2343
+ const activeCardScores = (_b2 = (_a2 = queryClient.getQueryData(queryKeys)) == null ? void 0 : _a2.cards) == null ? void 0 : _b2[cardId];
2344
+ if (activeCardScores === void 0) return;
2345
+ mutationClearScore.mutate({
2346
+ isAssignment,
2347
+ activityId,
2348
+ cardScores: activeCardScores,
2349
+ cardId,
2350
+ userId
2351
+ });
2352
+ };
2353
+ const onSubmitScore = async () => {
2354
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
2355
+ try {
2356
+ let results;
2357
+ if (isAssignment) {
2358
+ const cardScores = ((_a2 = scoreQuery.data) == null ? void 0 : _a2.cards) || {};
2359
+ const hasPendingReview = Object.values(cardScores).some(
2360
+ (cardScore) => cardScore.status === "pending_review"
2361
+ );
2362
+ results = await submitAssignmentScore2({
2363
+ assignment: assignmentQuery.data,
2364
+ userId,
2365
+ cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2366
+ scores: scoreQuery.data,
2367
+ weights: weightsToUse != null ? weightsToUse : {},
2368
+ status: hasPendingReview ? "PENDING_REVIEW" : "FINALIZED"
2369
+ });
2370
+ if ((_b2 = assignmentQuery.data) == null ? void 0 : _b2.ltiDeeplink) {
2371
+ submitLTIScore({
2372
+ maxPoints: (_c = assignmentQuery.data) == null ? void 0 : _c.maxPoints,
2373
+ score: (_e = (_d = scoreQuery.data) == null ? void 0 : _d.score) != null ? _e : 0,
2374
+ SERVICE_KEY: (_f = ltiData == null ? void 0 : ltiData.serviceKey) != null ? _f : "",
2375
+ lineItemId: (_g = ltiData == null ? void 0 : ltiData.lineItemId) != null ? _g : "",
2376
+ lti_id: (_h = ltiData == null ? void 0 : ltiData.lti_id) != null ? _h : ""
2377
+ });
2378
+ }
2379
+ } else {
2380
+ results = await submitPracticeScore2({
2381
+ setId: (_j = (_i = querySet.data) == null ? void 0 : _i.id) != null ? _j : "",
2382
+ userId,
2383
+ scores: scoreQuery.data
2384
+ });
2385
+ }
2386
+ return results;
2387
+ } catch (error) {
2388
+ return {
2389
+ success: false,
2390
+ error
2391
+ };
2392
+ }
2393
+ };
2394
+ const logGradingStandardEntry = ({
2395
+ cardId,
2396
+ gradingStandard,
2397
+ type
2398
+ }) => {
2399
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
2400
+ const card = cardsObject == null ? void 0 : cardsObject[cardId];
2401
+ const scoresObject = queryClient.getQueryData(scoreQueryKeys.byId(activityId));
2402
+ const cardScore = (_a2 = scoresObject == null ? void 0 : scoresObject.cards) == null ? void 0 : _a2[cardId];
2403
+ const serverTimestamp2 = api.helpers.serverTimestamp;
2404
+ addGradingStandardLog(
2405
+ {
2406
+ assignmentId: (_b2 = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b2 : "",
2407
+ courseId: (_c = activeAssignment == null ? void 0 : activeAssignment.courseId) != null ? _c : "",
2408
+ teacherId: (_d = activeAssignment == null ? void 0 : activeAssignment.owners[0]) != null ? _d : "",
2409
+ setId: (_e = setData == null ? void 0 : setData.id) != null ? _e : "",
2410
+ cardId,
2411
+ level: gradingStandard.level,
2412
+ justification: gradingStandard.justification,
2413
+ transcript: (_f = cardScore == null ? void 0 : cardScore.transcript) != null ? _f : "",
2414
+ audioUrl: (_g = cardScore == null ? void 0 : cardScore.audio) != null ? _g : "",
2415
+ prompt: (_h = card == null ? void 0 : card.prompt) != null ? _h : "",
2416
+ responseType: (card == null ? void 0 : card.type) === "RESPOND_WRITE" /* RESPOND_WRITE */ ? "written" : "spoken",
2417
+ type,
2418
+ dateMade: serverTimestamp2(),
2419
+ language: (_i = card == null ? void 0 : card.language) != null ? _i : ""
2420
+ },
2421
+ userId
2422
+ );
2423
+ };
2424
+ useEffect2(() => {
2425
+ if (isAssignment) {
2426
+ logOpenAssignment({ assignmentId: id });
2427
+ } else {
2428
+ logOpenActivityPreview({ setId: id });
2429
+ }
2430
+ }, []);
2431
+ useInitActivity({
2432
+ assignment: activeAssignment != null ? activeAssignment : void 0,
2433
+ set: setData != null ? setData : void 0,
2434
+ enabled: !!setData,
2435
+ userId
2436
+ });
2437
+ return {
2438
+ set: {
2439
+ data: setData,
2440
+ query: querySet
2441
+ },
2442
+ cards: {
2443
+ data: cardsObject,
2444
+ query: cardsQueries,
2445
+ cardsArray: cards
2446
+ },
2447
+ assignment: {
2448
+ data: isAssignment ? activeAssignment : void 0,
2449
+ query: assignmentQuery
2450
+ },
2451
+ scores: {
2452
+ data: scoreQuery.data,
2453
+ query: scoreQuery,
2454
+ actions: {
2455
+ update: handleUpdateScore,
2456
+ clear: onClearScore,
2457
+ submit: onSubmitScore,
2458
+ updateCard: handleUpdateCardScore,
2459
+ logGradingStandardEntry
2460
+ }
2461
+ }
2462
+ };
2463
+ }
2464
+ var useInitActivity = ({
2465
+ assignment,
2466
+ set,
2467
+ enabled,
2468
+ userId
2469
+ }) => {
2470
+ const { trackActivity } = useActivityTracker({ userId });
2471
+ const init = () => {
2472
+ var _a, _b, _c, _d, _e, _f, _g;
2473
+ if (!enabled) return;
2474
+ if (!assignment) {
2475
+ trackActivity({
2476
+ activityName: (_a = set == null ? void 0 : set.name) != null ? _a : "",
2477
+ activityType: "set",
2478
+ id: set == null ? void 0 : set.id,
2479
+ language: set == null ? void 0 : set.language
2480
+ });
2481
+ } else if (assignment.name) {
2482
+ trackActivity({
2483
+ activityName: assignment.name,
2484
+ activityType: assignment.isAssessment ? "assessment" : "assignment",
2485
+ id: assignment.id,
2486
+ language: set == null ? void 0 : set.language
2487
+ });
2488
+ }
2489
+ if (set == null ? void 0 : set.public) {
2490
+ (_d = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "onSetOpened")) == null ? void 0 : _d({
2491
+ setId: set.id,
2492
+ language: set.language
2493
+ });
2494
+ }
2495
+ (_g = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "updateAlgoliaIndex")) == null ? void 0 : _g({
2496
+ updatePlays: true,
2497
+ objectID: set == null ? void 0 : set.id
2498
+ });
2499
+ };
2500
+ useEffect2(() => {
2501
+ init();
2502
+ }, [set]);
2503
+ };
2504
+ var submitLTIScore = async ({
2505
+ maxPoints,
2506
+ score,
2507
+ SERVICE_KEY,
2508
+ lineItemId,
2509
+ lti_id
2510
+ }) => {
2511
+ var _a, _b, _c;
2512
+ try {
2513
+ if (!SERVICE_KEY || !lineItemId || !lti_id) {
2514
+ throw new Error("Missing required LTI credentials");
2515
+ }
2516
+ const earnedPoints = score ? score / 100 * maxPoints : 0;
2517
+ const { data } = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitLTIAssignmentScore")) == null ? void 0 : _c({
2518
+ SERVICE_KEY,
2519
+ scoreData: {
2520
+ lineItemId,
2521
+ userId: lti_id,
2522
+ maxPoints,
2523
+ earnedPoints
2524
+ }
2525
+ }));
2526
+ return { success: true, data };
2527
+ } catch (error) {
2528
+ console.error("Failed to submit LTI score:", error);
2529
+ return {
2530
+ success: false,
2531
+ error: error instanceof Error ? error : new Error("Unknown error occurred")
2532
+ };
2533
+ }
2534
+ };
2535
+
2536
+ // src/hooks/useCredits.ts
2537
+ import { useQuery as useQuery5 } from "@tanstack/react-query";
2538
+ var creditQueryKeys = {
2539
+ userCredits: (uid) => ["userCredits", uid]
2540
+ };
2541
+ var useUserCredits = () => {
2542
+ const { user } = useSpeakableApi();
2543
+ const email = user.auth.email;
2544
+ const uid = user.auth.uid;
2545
+ const query2 = useQuery5({
2546
+ queryKey: creditQueryKeys.userCredits(uid),
2547
+ queryFn: () => fetchUserCredits({ uid, email }),
2548
+ enabled: !!uid,
2549
+ refetchInterval: 1e3 * 60 * 5
2550
+ });
2551
+ return {
2552
+ ...query2
2553
+ };
2554
+ };
2555
+ var fetchUserCredits = async ({ uid, email }) => {
2556
+ if (!uid) {
2557
+ throw new Error("User ID is required");
2558
+ }
2559
+ const contractSnap = await api.getDoc(`creditContracts/${uid}`);
2560
+ if (contractSnap.data == null) {
2561
+ return {
2562
+ id: uid,
2563
+ userId: uid,
2564
+ email,
2565
+ effectivePlanId: "free_tier",
2566
+ status: "inactive",
2567
+ isUnlimited: false,
2568
+ creditsAvailable: 100,
2569
+ creditsAllocatedThisPeriod: 100,
2570
+ topOffCreditsAvailable: 0,
2571
+ topOffCreditsTotal: 0,
2572
+ allocationSource: "free_tier",
2573
+ sourceDetails: {},
2574
+ periodStart: null,
2575
+ periodEnd: null,
2576
+ planTermEndTimestamp: null,
2577
+ ownerType: "individual",
2578
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2579
+ lastUpdatedAt: (/* @__PURE__ */ new Date()).toISOString()
2580
+ };
2581
+ }
2582
+ const contractData = contractSnap.data;
2583
+ const monthlyCredits = (contractData == null ? void 0 : contractData.creditsAvailable) || 0;
2584
+ const topOffCredits = (contractData == null ? void 0 : contractData.topOffCreditsAvailable) || 0;
2585
+ const totalCredits = monthlyCredits + topOffCredits;
2586
+ return {
2587
+ id: contractSnap.id,
2588
+ ...contractData,
2589
+ // Add computed total for convenience
2590
+ totalCreditsAvailable: totalCredits
2591
+ };
2592
+ };
2593
+
2594
+ // src/hooks/useOrganizationAccess.ts
2595
+ import { useQuery as useQuery6 } from "@tanstack/react-query";
2596
+ var useOrganizationAccess = () => {
2597
+ const { user } = useSpeakableApi();
2598
+ const email = user.auth.email;
2599
+ const query2 = useQuery6({
2600
+ queryKey: ["organizationAccess", email],
2601
+ queryFn: async () => {
2602
+ if (!email) {
2603
+ return {
2604
+ hasUnlimitedAccess: false,
2605
+ subscriptionId: null,
2606
+ organizationId: null,
2607
+ organizationName: null,
2608
+ subscriptionEndDate: null,
2609
+ accessType: "individual"
2610
+ };
2611
+ }
2612
+ return getOrganizationAccess(email);
2613
+ },
2614
+ enabled: !!email,
2615
+ // Only run query if we have a user email
2616
+ staleTime: 5 * 60 * 1e3,
2617
+ // Consider data fresh for 5 minutes
2618
+ gcTime: 10 * 60 * 1e3,
2619
+ // Keep in cache for 10 minutes
2620
+ retry: 2
2621
+ // Retry failed requests twice
2622
+ });
2623
+ return {
2624
+ ...query2
2625
+ };
2626
+ };
2627
+ var getOrganizationAccess = async (email) => {
2628
+ const { limit: limit2, where: where2 } = api.accessQueryConstraints();
2629
+ try {
2630
+ const organizationSnapshot = await api.getDocs(
2631
+ "organizations",
2632
+ where2("members", "array-contains", email),
2633
+ where2("masterSubscriptionStatus", "==", "active"),
2634
+ limit2(1)
2635
+ );
2636
+ if (!organizationSnapshot.empty) {
2637
+ const orgData = organizationSnapshot.data[0];
2638
+ return {
2639
+ hasUnlimitedAccess: true,
2640
+ subscriptionId: orgData == null ? void 0 : orgData.masterSubscriptionId,
2641
+ organizationId: orgData.id,
2642
+ organizationName: orgData.name || "Unknown Organization",
2643
+ subscriptionEndDate: orgData.masterSubscriptionEndDate || null,
2644
+ accessType: "organization"
2645
+ };
2646
+ }
2647
+ const institutionSnapshot = await api.getDocs(
2648
+ "institution_subscriptions",
2649
+ where2("users", "array-contains", email),
2650
+ where2("active", "==", true),
2651
+ limit2(1)
2652
+ );
2653
+ if (!institutionSnapshot.empty) {
2654
+ const institutionData = institutionSnapshot.data[0];
2655
+ const isUnlimited = (institutionData == null ? void 0 : institutionData.plan) === "organization" || (institutionData == null ? void 0 : institutionData.plan) === "school_starter";
2656
+ return {
2657
+ hasUnlimitedAccess: isUnlimited,
2658
+ subscriptionId: institutionData.id,
2659
+ organizationId: institutionData == null ? void 0 : institutionData.institutionId,
2660
+ organizationName: institutionData.name || institutionData.institutionId || "Legacy Institution",
2661
+ subscriptionEndDate: institutionData.endDate || null,
2662
+ accessType: "institution_subscriptions"
2663
+ };
2664
+ }
2665
+ return {
2666
+ hasUnlimitedAccess: false,
2667
+ subscriptionId: null,
2668
+ organizationId: null,
2669
+ organizationName: null,
2670
+ subscriptionEndDate: null,
2671
+ accessType: "individual"
2672
+ };
2673
+ } catch (error) {
2674
+ console.error("Error checking organization access:", error);
2675
+ return {
2676
+ hasUnlimitedAccess: false,
2677
+ subscriptionId: null,
2678
+ organizationId: null,
2679
+ organizationName: null,
2680
+ subscriptionEndDate: null,
2681
+ accessType: "individual"
2682
+ };
2683
+ }
2684
+ };
2685
+
2686
+ // src/hooks/useUpdateStudentVoc.ts
2687
+ var useUpdateStudentVocab = (page) => {
2688
+ const { user } = useSpeakableApi();
2689
+ const currentUserId = user == null ? void 0 : user.auth.uid;
2690
+ if (!page || !currentUserId || !page.target_text || !page.language) {
2691
+ return {
2692
+ studentVocabMarkVoiceSuccess: void 0,
2693
+ studentVocabMarkVoiceFail: void 0
2694
+ };
2695
+ }
2696
+ const getDataObject = () => {
2697
+ var _a, _b;
2698
+ const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2699
+ const language = (_a = page.language) != null ? _a : "en";
2700
+ const word = (_b = page.target_text) != null ? _b : "";
2701
+ const phrase_length = getPhraseLength(word);
2702
+ const wordHash = getWordHash(word, language);
2703
+ const docPath = `users/${currentUserId}/vocab/${wordHash}`;
2704
+ const communityPath = `checked-pronunciations/${wordHash}`;
2705
+ const id = `${language}-${cleanString(word)}`;
2706
+ const data = {
2707
+ id,
2708
+ word,
2709
+ words: (word == null ? void 0 : word.split(" ")) || [],
2710
+ wordHash,
2711
+ language,
2712
+ lastSeen: serverTimestamp2(),
2713
+ phrase_length
2714
+ };
2715
+ return {
2716
+ docPath,
2717
+ communityPath,
2718
+ data
2719
+ };
2720
+ };
2721
+ const markVoiceSuccess = async () => {
2722
+ const { docPath, communityPath, data } = getDataObject();
2723
+ const { increment: increment2 } = api.accessQueryConstraints();
2724
+ const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2725
+ data.voiceSuccess = increment2(1);
2726
+ try {
2727
+ await api.updateDoc(docPath, data);
2728
+ } catch (error) {
2729
+ if (error instanceof Error && error.message === "not-found") {
2730
+ data.firstSeen = serverTimestamp2();
2731
+ await api.setDoc(docPath, data);
2732
+ } else {
2733
+ console.log(error);
2734
+ }
2735
+ }
2736
+ try {
2737
+ data.pronunciations = increment2(1);
2738
+ await api.setDoc(communityPath, data, { merge: true });
2739
+ } catch (error) {
2740
+ console.log(error);
2741
+ }
2742
+ };
2743
+ const markVoiceFail = async () => {
2744
+ const { docPath, communityPath, data } = getDataObject();
2745
+ const { increment: increment2 } = api.accessQueryConstraints();
2746
+ const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2747
+ data.voiceFail = increment2(1);
2748
+ try {
2749
+ await api.updateDoc(docPath, data);
2750
+ } catch (error) {
2751
+ if (error instanceof Error && error.message === "not-found") {
2752
+ data.firstSeen = serverTimestamp2();
2753
+ await api.setDoc(docPath, data);
2754
+ } else {
2755
+ console.log(error);
2756
+ }
2757
+ }
2758
+ try {
2759
+ data.fails = increment2(1);
2760
+ await api.setDoc(communityPath, data, { merge: true });
2761
+ } catch (error) {
2762
+ console.log(error);
2763
+ }
2764
+ };
2765
+ return {
2766
+ studentVocabMarkVoiceSuccess: markVoiceSuccess,
2767
+ studentVocabMarkVoiceFail: markVoiceFail
2768
+ };
2769
+ };
2770
+
2771
+ // src/hooks/useActivityFeedbackAccess.ts
2772
+ import { useQuery as useQuery7 } from "@tanstack/react-query";
2773
+ var activityFeedbackAccessQueryKeys = {
2774
+ activityFeedbackAccess: (args) => ["activityFeedbackAccess", ...Object.values(args)]
2775
+ };
2776
+ var useActivityFeedbackAccess = ({
2777
+ aiEnabled = false,
2778
+ isActivityRoute = false
2779
+ }) => {
2780
+ var _a, _b, _c;
2781
+ const { user } = useSpeakableApi();
2782
+ const uid = user.auth.uid;
2783
+ const isTeacher = (_a = user.profile) == null ? void 0 : _a.isTeacher;
2784
+ const isStudent = (_b = user.profile) == null ? void 0 : _b.isStudent;
2785
+ const userRoles = ((_c = user.profile) == null ? void 0 : _c.roles) || [];
2786
+ const query2 = useQuery7({
2787
+ queryKey: activityFeedbackAccessQueryKeys.activityFeedbackAccess({
2788
+ aiEnabled,
2789
+ isActivityRoute
2790
+ }),
2791
+ queryFn: async () => {
2792
+ var _a2, _b2, _c2;
2793
+ if (!uid) {
2794
+ return {
2795
+ canAccessFeedback: false,
2796
+ reason: "Missing user ID",
2797
+ isUnlimited: false,
2798
+ accessType: "none"
2799
+ };
2800
+ }
2801
+ try {
2802
+ if (aiEnabled) {
2803
+ return {
2804
+ canAccessFeedback: true,
2805
+ reason: "AI feedback enabled",
2806
+ isUnlimited: true,
2807
+ accessType: "ai_enabled"
2808
+ };
2809
+ }
2810
+ if (isTeacher || userRoles.includes("ADMIN")) {
2811
+ return {
2812
+ canAccessFeedback: true,
2813
+ reason: "Teacher preview access",
2814
+ isUnlimited: true,
2815
+ accessType: "teacher_preview"
2816
+ };
2817
+ }
2818
+ if (isStudent && isActivityRoute) {
2819
+ try {
2820
+ const result = await ((_c2 = (_b2 = (_a2 = api).httpsCallable) == null ? void 0 : _b2.call(_a2, "checkStudentTeacherPlan")) == null ? void 0 : _c2({
2821
+ studentId: uid
2822
+ }));
2823
+ const planCheckResult = result.data;
2824
+ if (planCheckResult.canAccessFeedback) {
2825
+ return {
2826
+ canAccessFeedback: true,
2827
+ reason: planCheckResult.reason || "Student access via teacher with active plan",
2828
+ isUnlimited: planCheckResult.hasTeacherWithUnlimitedAccess,
2829
+ accessType: "student_with_teacher_plan"
2830
+ };
2831
+ } else {
2832
+ return {
2833
+ canAccessFeedback: false,
2834
+ reason: planCheckResult.reason || "No teacher with active plan found",
2835
+ isUnlimited: false,
2836
+ accessType: "none"
2837
+ };
2838
+ }
2839
+ } catch (error) {
2840
+ console.error("Error checking student teacher plan:", error);
2841
+ return {
2842
+ canAccessFeedback: false,
2843
+ reason: "Error checking teacher plans",
2844
+ isUnlimited: false,
2845
+ accessType: "none"
2846
+ };
2847
+ }
2848
+ }
2849
+ return {
2850
+ canAccessFeedback: false,
2851
+ reason: "No access permissions found for current context",
2852
+ isUnlimited: false,
2853
+ accessType: "none"
2854
+ };
2855
+ } catch (error) {
2856
+ console.error("Error checking activity feedback access:", error);
2857
+ return {
2858
+ canAccessFeedback: false,
2859
+ reason: "Error checking access permissions",
2860
+ isUnlimited: false,
2861
+ accessType: "none"
2862
+ };
2863
+ }
2864
+ },
2865
+ enabled: !!uid,
2866
+ staleTime: 5 * 60 * 1e3,
2867
+ // 5 minutes
2868
+ gcTime: 10 * 60 * 1e3
2869
+ // 10 minutes
2870
+ });
2871
+ return {
2872
+ ...query2
2873
+ };
2874
+ };
2875
+
2876
+ // src/hooks/useOpenAI.ts
2877
+ var useBaseOpenAI = ({
2878
+ onTranscriptSuccess,
2879
+ onTranscriptError,
2880
+ onCompletionSuccess,
2881
+ onCompletionError,
2882
+ aiEnabled,
2883
+ submitAudioResponse,
2884
+ uploadAudioAndGetTranscript
2885
+ }) => {
2886
+ const { user, queryClient } = useSpeakableApi();
2887
+ const currentUserId = user.auth.uid;
2888
+ const { data: feedbackAccess } = useActivityFeedbackAccess({
2889
+ aiEnabled
2890
+ });
2891
+ const getTranscript = async (audioUrl, language) => {
2892
+ var _a, _b;
2893
+ try {
2894
+ const getAssemblyAITranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "transcribeAssemblyAIAudio");
2895
+ const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
2896
+ audioUrl,
2897
+ language
2898
+ }));
2899
+ console.log("response (getTranscript) from getAssemblyAITranscript", {
2900
+ response,
2901
+ audioUrl,
2902
+ language,
2903
+ getAssemblyAITranscript
2904
+ });
2905
+ const transcript = response == null ? void 0 : response.data;
2906
+ onTranscriptSuccess(transcript);
2907
+ return transcript;
2908
+ } catch (error) {
2909
+ console.log("error", error);
2910
+ onTranscriptError({
2911
+ type: "TRANSCRIPT",
2912
+ message: (error == null ? void 0 : error.message) || "Error getting transcript"
2913
+ });
2914
+ throw new Error(error);
2915
+ }
2916
+ };
2917
+ const getFreeResponseCompletion = async (messages, isFreeResponse, feedbackLanguage, gradingStandard = "actfl") => {
2918
+ var _a, _b, _c, _d, _e;
2919
+ const responseTool = getRespondCardTool({
2920
+ language: feedbackLanguage,
2921
+ standard: gradingStandard
2922
+ });
2923
+ try {
2924
+ const createChatCompletion = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createChatCompletion");
2925
+ const {
2926
+ data: {
2927
+ response,
2928
+ prompt_tokens = 0,
2929
+ completion_tokens = 0,
2930
+ success: aiSuccess = false
2931
+ // the AI was able to generate a response
2932
+ }
2933
+ } = await (createChatCompletion == null ? void 0 : createChatCompletion({
2934
+ chat: {
2935
+ model: isFreeResponse ? "gpt-4-1106-preview" : "gpt-3.5-turbo-1106",
2936
+ messages,
2937
+ temperature: 0.7,
2938
+ ...responseTool
2939
+ },
2940
+ type: isFreeResponse ? "LONG_RESPONSE" : "SHORT_RESPONSE"
2941
+ }));
2942
+ const functionArguments = JSON.parse(((_e = (_d = (_c = response == null ? void 0 : response.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function) == null ? void 0 : _e.arguments) || "{}");
2943
+ const result = {
2944
+ ...functionArguments,
2945
+ prompt_tokens,
2946
+ completion_tokens,
2947
+ aiSuccess
2948
+ };
2949
+ onCompletionSuccess(result);
2950
+ return result;
2951
+ } catch (error) {
2952
+ onCompletionError({
2953
+ type: "COMPLETION",
2954
+ message: (error == null ? void 0 : error.message) || "Error getting completion"
2955
+ });
2956
+ throw new Error(error);
2957
+ }
2958
+ };
2959
+ const getFeedback = async ({
2960
+ cardId,
2961
+ language = "en",
2962
+ // required
2963
+ writtenResponse = null,
2964
+ // if the type = RESPOND_WRITE
2965
+ audio = null,
2966
+ autoGrade = true,
2967
+ file = null
2968
+ }) => {
2969
+ try {
2970
+ if (!(feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback)) {
2971
+ const result = {
2972
+ noFeedbackAvailable: true,
2973
+ success: true,
2974
+ reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
2975
+ accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
2976
+ };
2977
+ onCompletionSuccess(result);
2978
+ return result;
2979
+ }
2980
+ let transcript;
2981
+ if (writtenResponse) {
2982
+ transcript = writtenResponse;
2983
+ onTranscriptSuccess(writtenResponse);
2984
+ } else if (typeof audio === "string" && file) {
2985
+ if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
2986
+ transcript = await getTranscript(audio, language);
2987
+ onTranscriptSuccess(transcript);
2988
+ } else {
2989
+ console.info(
2990
+ `Transcript not available: ${(feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access"}`
2991
+ );
2992
+ }
2993
+ } else {
2994
+ transcript = await uploadAudioAndGetTranscript(audio || "", language);
2995
+ }
2996
+ if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
2997
+ const results = await getAIResponse({
2998
+ cardId,
2999
+ transcript: transcript || ""
3000
+ });
3001
+ let output = results;
3002
+ if (!autoGrade) {
3003
+ output = {
3004
+ ...output,
3005
+ noFeedbackAvailable: true,
3006
+ success: true
3007
+ };
3008
+ }
3009
+ onCompletionSuccess(output);
3010
+ return output;
3011
+ } else {
3012
+ const result = {
3013
+ noFeedbackAvailable: true,
3014
+ success: true,
3015
+ reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3016
+ accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3017
+ };
3018
+ onCompletionSuccess(result);
3019
+ return result;
3020
+ }
3021
+ } catch (error) {
3022
+ console.error("Error getting feedback:", error);
3023
+ throw new Error(error);
3024
+ }
3025
+ };
3026
+ const getAIResponse = async ({ cardId, transcript }) => {
3027
+ var _a, _b, _c, _d, _e;
3028
+ try {
3029
+ const getGeminiFeedback = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "callGetFeedback");
3030
+ const getProficiencyEstimate = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "getProficiencyEstimate");
3031
+ const card = getCardFromCache({
3032
+ cardId,
3033
+ queryClient
3034
+ });
3035
+ let feedbackData;
3036
+ let proficiencyData = {};
3037
+ if (card && card.grading_method === "manual") {
3038
+ } else if (card && card.grading_method !== "standards_based") {
3039
+ const [geminiResult, proficiencyResult] = await Promise.all([
3040
+ getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3041
+ cardId,
3042
+ studentId: currentUserId,
3043
+ studentResponse: transcript
3044
+ }),
3045
+ getProficiencyEstimate == null ? void 0 : getProficiencyEstimate({
3046
+ cardId,
3047
+ studentId: currentUserId,
3048
+ studentResponse: transcript
3049
+ })
3050
+ ]);
3051
+ proficiencyData = (proficiencyResult == null ? void 0 : proficiencyResult.data) || {};
3052
+ feedbackData = {
3053
+ ...(_e = geminiResult == null ? void 0 : geminiResult.data) != null ? _e : {},
3054
+ // @ts-ignore
3055
+ proficiency_level: (proficiencyData == null ? void 0 : proficiencyData.proficiency_level) || null
3056
+ };
3057
+ } else {
3058
+ const geminiResult = await (getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3059
+ cardId,
3060
+ studentId: currentUserId,
3061
+ studentResponse: transcript
3062
+ }));
3063
+ feedbackData = geminiResult == null ? void 0 : geminiResult.data;
3064
+ }
3065
+ const results = {
3066
+ ...feedbackData,
3067
+ // ...proficiencyData,
3068
+ aiSuccess: true,
3069
+ promptSuccess: (feedbackData == null ? void 0 : feedbackData.success) || false,
3070
+ transcript
3071
+ };
3072
+ return results;
3073
+ } catch (error) {
3074
+ onCompletionError({
3075
+ type: "AI_FEEDBACK",
3076
+ message: (error == null ? void 0 : error.message) || "Error getting ai feedback"
3077
+ });
3078
+ throw new Error(error);
3079
+ }
3080
+ };
3081
+ return {
3082
+ submitAudioResponse,
3083
+ uploadAudioAndGetTranscript,
3084
+ getTranscript,
3085
+ getFreeResponseCompletion,
3086
+ getFeedback
3087
+ };
3088
+ };
3089
+
3090
+ // src/lib/create-firebase-client-web.ts
3091
+ import {
3092
+ getDoc,
3093
+ getDocs,
3094
+ addDoc,
3095
+ setDoc,
3096
+ updateDoc,
3097
+ deleteDoc,
3098
+ runTransaction,
3099
+ writeBatch,
3100
+ doc,
3101
+ collection,
3102
+ query,
3103
+ serverTimestamp,
3104
+ orderBy,
3105
+ limit,
3106
+ startAt,
3107
+ startAfter,
3108
+ endAt,
3109
+ endBefore,
3110
+ where,
3111
+ increment
3112
+ } from "firebase/firestore";
3113
+
3114
+ // src/lib/create-firebase-client.ts
3115
+ function createFsClientBase({
3116
+ db,
3117
+ helpers,
3118
+ httpsCallable,
3119
+ logEvent
3120
+ }) {
3121
+ const dbAsFirestore = db;
3122
+ api.initialize({
3123
+ db: dbAsFirestore,
3124
+ helpers,
3125
+ httpsCallable,
3126
+ logEvent
3127
+ });
3128
+ return {
3129
+ assignmentRepo: createAssignmentRepo(),
3130
+ cardRepo: createCardRepo()
3131
+ };
3132
+ }
3133
+
3134
+ // src/lib/create-firebase-client-web.ts
3135
+ var createFsClientWeb = ({ db, httpsCallable, logEvent }) => {
3136
+ return createFsClientBase({
3137
+ db,
3138
+ httpsCallable,
3139
+ logEvent,
3140
+ helpers: {
3141
+ getDoc,
3142
+ getDocs,
3143
+ addDoc,
3144
+ setDoc,
3145
+ updateDoc,
3146
+ deleteDoc,
3147
+ runTransaction,
3148
+ writeBatch,
3149
+ doc,
3150
+ collection,
3151
+ query,
3152
+ serverTimestamp,
3153
+ orderBy,
3154
+ limit,
3155
+ startAt,
3156
+ startAfter,
3157
+ endAt,
3158
+ endBefore,
3159
+ where,
3160
+ increment
3161
+ }
3162
+ });
3163
+ };
3164
+ export {
3165
+ ActivityPageType,
3166
+ BASE_MULTIPLE_CHOICE_FIELD_VALUES,
3167
+ BASE_REPEAT_FIELD_VALUES,
3168
+ BASE_RESPOND_FIELD_VALUES,
3169
+ FeedbackTypesCard,
3170
+ FsCtx,
3171
+ LENIENCY_OPTIONS,
3172
+ LeniencyCard,
3173
+ MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES,
3174
+ REPEAT_PAGE_ACTIVITY_TYPES,
3175
+ RESPOND_AUDIO_PAGE_ACTIVITY_TYPES,
3176
+ RESPOND_PAGE_ACTIVITY_TYPES,
3177
+ RESPOND_WRITE_PAGE_ACTIVITY_TYPES,
3178
+ SPEAKABLE_NOTIFICATIONS,
3179
+ STUDENT_LEVELS_OPTIONS,
3180
+ SpeakableNotificationTypes,
3181
+ SpeakableProvider,
3182
+ VerificationCardStatus,
3183
+ assignmentQueryKeys,
3184
+ cardsQueryKeys,
3185
+ checkIsMCPage,
3186
+ checkIsMediaPage,
3187
+ checkIsRepeatPage,
3188
+ checkIsRespondAudioPage,
3189
+ checkIsRespondPage,
3190
+ checkIsRespondWrittenPage,
3191
+ checkIsShortAnswerPage,
3192
+ checkTypePageActivity,
3193
+ cleanString,
3194
+ createAssignmentRepo,
3195
+ createCardRepo,
3196
+ createFsClientWeb as createFsClient,
3197
+ createSetRepo,
3198
+ creditQueryKeys,
3199
+ debounce,
3200
+ getCardFromCache,
3201
+ getPagePrompt,
3202
+ getPhraseLength,
3203
+ getRespondCardTool,
3204
+ getSetFromCache,
3205
+ getWordHash,
3206
+ purify,
3207
+ refsCardsFiresotre,
3208
+ refsSetsFirestore,
3209
+ scoreQueryKeys,
3210
+ setsQueryKeys,
3211
+ updateCardInCache,
3212
+ updateSetInCache,
3213
+ useActivity,
3214
+ useActivityFeedbackAccess,
3215
+ useAssignment,
3216
+ useBaseOpenAI,
3217
+ useCards,
3218
+ useClearScore,
3219
+ useCreateCard,
3220
+ useCreateCards,
3221
+ useCreateNotification,
3222
+ useGetCard,
3223
+ useOrganizationAccess,
3224
+ useScore,
3225
+ useSet,
3226
+ useSpeakableApi,
3227
+ useSubmitAssignmentScore,
3228
+ useSubmitPracticeScore,
3229
+ useUpdateCardScore,
3230
+ useUpdateScore,
3231
+ useUpdateStudentVocab,
3232
+ useUserCredits
3233
+ };
3234
+ //# sourceMappingURL=index.web.mjs.map